/*===========================================================================
  Copyright (C) 1995-2009 European Southern Observatory (ESO)
 
  This program is free software; you can redistribute it and/or 
  modify it under the terms of the GNU General Public License as 
  published by the Free Software Foundation; either version 2 of 
  the License, or (at your option) any later version.
 
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
 
  You should have received a copy of the GNU General Public 
  License along with this program; if not, write to the Free 
  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, 
  MA 02139, USA.
 
  Correspondence concerning ESO-MIDAS should be addressed as follows:
	Internet e-mail: midas@eso.org
	Postal address: European Southern Observatory
			Data Management Division 
			Karl-Schwarzschild-Strasse 2
			D 85748 Garching bei Muenchen 
			GERMANY
===========================================================================*/

/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++
.IDENTIFICATION     aglgraph.c
.MODULE             application
.LANGUAGE           C
.AUTHOR             Jean-Paul Kneib - Eso La Silla
.KEYWORD            X11-Midas ESO filters handling.
.COMMENTS           xfilters .
.ENVIRONMENT        Unix

.VERSION            1.0.0, 1-MAY-94

090422		last modif
--------------------------------------------------------*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <sys/wait.h>
#include <sys/stat.h>

#include <midas_def.h>
#include <tbldef.h>

#include <gl_defs.h>

#include <globaldef.h>
#include <modeldef.h>
#include <UxLib.h>

#define GDE0	"graph_wnd0:"
#define GDNEMA0	"graph_wnd0/n:/a"

#define LABELPLT "filterl.plt"
#define LABELADD "filterl.plt/a"
#define DRAW "color=1"
#define DRAWCOL "color=2"
#define NODRAW "color=0"
#define PLOTNAME "filter.plt"
#define PLOTAPP "filter.plt/a"
#define PLOTMODE        0
#define OVERMODE        1

#define MAXLEAKS	10

float	Clip[4];
void endname();
int	read_spec_table();
int	file_exists(), graphwin_exists();
int	read_atmos(), read_trans();
int	read_grism(), read_sky(), init_gr();

int	AppendDialogText();


extern struct s_trans	T;

extern int	Nccd;
extern float	Xccd[MAXCCDAT];
extern float	Yccd[MAXCCDAT];

extern int	Nfilter;
extern float	Xfilt[];
extern float	Yfilt[];

extern int	Nsky;
extern float	Xsky[];
extern float	Ysky[];

extern int	Nspec;
extern float	Xspec[];
extern float	Yspec[];

extern int	Ngrism;
extern float	Xgrism[];
extern float	Ygrism[];

extern int	Natmos;
extern float	Xatmos[];
extern float	Yatmos[];

extern int	Noptics;
extern float	Xoptics[];
extern float	Yoptics[];

extern int	Nmir;
extern float	Xmir[];
extern float	Ymir[];

extern int nc_ovplt;
 
extern int pltgr, ovpltgr, pltneso;
extern float cw1, cw2;
extern float cw1p, cw2p;

extern int ltrimx;
extern int ltrimy;

int	gnfilt;

float	Sxmi,Sxma,Symi,Syma;
float	Oxmi,Oxma,Oymi,Oyma;
int	Slmode,Snp;
char	Sstr[200];
float	*Sxx,*Syy;

float	YY[6000];

float goffx1, goffx2, goffy1, goffy2;

extern int lfirstp;

/***************************
     Local functions
 ***************************/

void vdef_wspec();
void clear_graphic();
void end_graphic();
void end_viewp();
void end_graphic1();
int read_ccd_table();
int read_filt_table();
void c_minmax();
void rg_minmax();
void set_minmax();
void plot_xy();
void Trim();
void Unzoom();
void plot1filter();
void plot1ccd();
void plot4filter();
void plot4ccd();
void plot9filter();
void plot19filter();

/* =================================================================== */

#include <aglerror.h>
#include <agl_defs.h>

int      InitGraphic = FALSE;
int      InitGraphic2 = FALSE;

/* devices for AG_VDEF */
char     gdevice[21]="graph_wnd0";
char     DevErase[80], DevNoErase[80], DevMAppend[80],DevEMAppend[80];

/* viewport identification in AGL */
int pviewp, sviewp,vwp1, vwp2, vwp3, vwp4;

void get_agldev();

void open_plotfile();
void opena_plotfile();

void plot_ccd();
void plot_ovfilters();
void plot_ovccds();

/* ------------------------------------------------------------------- */
void plot_ccd(nccd)
int nccd;
{
 char str[300], str1[200];
 float xmi,ymi,xma,yma;

/* read CCD Table  if not return */

if(!read_ccd_table(nccd))
   {
     SCTPUT("ERROR: CCD curve not found.");
   }
else
   {
   sprintf(str1,"\1CCD# %2d   Quantum Efficiency",nccd);
   sprintf(str,
     "TITLE=%20s;DTITL=%4.1f;LABX=%12s;LABY=%12s;DLABL=%4.1f;NGEOM;USER;BOLD;GRID;TIME;XSPACE=%1d;",
     str1, 2.0, "\1Lambda [nm]", "\1QE [%]",1.0,0);

   xmi=300.0; xma=1000.0;
   ymi=0.0;  yma=1.0;

   cw1p=300.; cw2p=1000.0;

   plot_xy(str,-19,Xccd,Yccd,Nccd,xmi,xma,ymi,yma);
   end_graphic1();
   Oxmi=xmi;
   Oxma=xma;
   Oymi=ymi;
   Oyma=yma;
   };

}

/* ------------------------------------------------------------------- */
void plot_spec(filepath,spectrum)
char	spectrum[];
char	filepath[];
{
char str[100], str1[50];
float xmi,ymi,xma,yma;
char end[10];
int	rd,read_spec_table(),read_spec();

endname(spectrum,end);
if (!strncmp(end,"tbl",3))
	{
	rd=read_spec_table(filepath,spectrum);
	T.ispectra=1;
	}
else
	{
	rd=read_spec(spectrum);
	T.ispectra=2;
	}

/* read Spectrum Table  if not return */


if(!rd)
   {
     SCTPUT("ERROR: SPECTRUM curve not found.");
   }
else
   {
   sprintf(str1,"\1Spectrum %s   Flux",spectrum);
   sprintf(str,
     "TITLE=%20s;DTITL=%4.1f;LABX=%12s;LABY=%12s;DLABL=%4.1f;NGEOM;USER;BOLD;GRID;TIME;XSPACE=%1d;",
     str1, 2.0, "\1Lambda [nm]", "\1Flux [1e-16 erg/cm2/A/s]",1.0,0);

   c_minmax(Xspec,Yspec,Nspec,&xmi,&xma,&ymi,&yma);
   plot_xy(str,0,Xspec,Yspec,Nspec,xmi,xma,ymi,yma);
   end_graphic1();

   Oxmi=xmi;
   Oxma=xma;
   Oymi=ymi;
   Oyma=yma;

   };
}

/* ------------------------------------------------------------------- */
void plot_spec2(filepath,spectrum)
char	spectrum[];
char	filepath[];
{
char str[100], str1[50];
float xmi,ymi,xma,yma;
char end[10];
int	rd,read_spec();

endname(spectrum,end);
if (!strncmp(end,"tbl",3))
	{
	rd=read_spec_table(filepath,spectrum);
	T.ispectra=1;
	}
else
	{
	rd=read_spec(spectrum);
	T.ispectra=2;
	}

/* read Spectrum Table  if not return */


if(!rd)
   {
     SCTPUT("ERROR: SPECTRUM curve not found.");
   }
else
   {
   sprintf(str1,"\1Spectrum %s   Flux",spectrum);
   sprintf(str,
     "TITLE=%20s;DTITL=%4.1f;LABX=%12s;LABY=%12s;DLABL=%4.1f;NGEOM;USER;BOLD;GRID;TIME;XSPACE=%1d;",
     str1, 2.0, "\1Lambda [nm]", "\1Flux [1e-16 erg/cm2/A/s]",1.0,0);

   c_minmax(Xspec,Yspec,Nspec,&xmi,&xma,&ymi,&yma);
   plot_xy(str,0,Xspec,Yspec,Nspec,xmi,xma,ymi,yma);
   end_graphic1();

   Oxmi=xmi;
   Oxma=xma;
   Oymi=ymi;
   Oyma=yma;

   };
}

/* ------------------------------------------------------------------- */
void plot_sky(sky)
char	sky[];
{
char str[120], str1[50],sky_nm[30];
float xmi,ymi,xma,yma;
int	i,l;

/* read sky Table  if not return */

if(!read_sky(sky))
   {
     SCTPUT("ERROR: sky curve not found.");
   }
else
   {
   l=strlen(sky);
   for(i=l-15;i<l;i++) sky_nm[i+15-l]=sky[i];
   sky_nm[15]='\0';
   sprintf(str1,"\1 FLux of the sky %s",sky_nm);
   sprintf(str,
     "TITLE=%20s;DTITL=%4.1f;LABX=%12s;LABY=%12s;DLABL=%4.1f;NGEOM;USER;BOLD;GRID;TIME;XSPACE=%1d;",
     str1, 2.0, "\1Lambda [nm]", "\1Flux [e-16 erg/cm2/A/s]",1.0,0);

   c_minmax(Xsky,Ysky,Nsky,&xmi,&xma,&ymi,&yma);

   if (ymi==yma)
	{
	ymi*=.9;
	yma*=1.1;
	}
   plot_xy(str,0,Xsky,Ysky,Nsky,xmi,xma,ymi,yma);
   end_graphic1();
   Oxmi=xmi;
   Oxma=xma;
   Oymi=ymi;
   Oyma=yma;
   };
}

/* ------------------------------------------------------------------- */
void plot_grism(grism)
char	grism[];
{
char str[120], str1[50],grism_nm[30];
float xmi,ymi,xma,yma;
int	i,l;

/* read grism Table  if not return */

if(!read_grism(grism))
   {
     fprintf(stderr,"GRISM curve %s not found!",grism);
   }
else
   {
   l=strlen(grism);
   for(i=l-15;i<l;i++) grism_nm[i+15-l]=grism[i];
   grism_nm[15]='\0';
   sprintf(str1,"\1Grism %s Transmission",grism_nm);
   sprintf(str,
     "TITLE=%20s;DTITL=%4.1f;LABX=%12s;LABY=%12s;DLABL=%4.1f;NGEOM;USER;BOLD;GRID;TIME;XSPACE=%1d;",
     str1, 2.0, "\1Lambda [nm]", "\1Transmission [%]",1.0,0);

   c_minmax(Xgrism,Ygrism,Ngrism,&xmi,&xma,&ymi,&yma);
   ymi=0.; yma=1.;

   plot_xy(str,0,Xgrism,Ygrism,Ngrism,xmi,xma,ymi,yma);
   end_graphic1();
   Oxmi=xmi;
   Oxma=xma;
   Oymi=ymi;
   Oyma=yma;
   };
}

/* ------------------------------------------------------------------- */
void plot_mirror(mirror)

char	mirror[];
{
char str[120], str1[50],mirror_nm[30];
float xmi,ymi,xma,yma;
int	i,l;

ymi=0.;
yma=1.;

/* read mirror file  if not return */

if(!read_trans(mirror,Xmir,Ymir,&Nmir,&T.mirmin,&T.mirmax))
   {
     fprintf(stderr,"ERROR: OPTICS curve %s not found.\r\n",mirror);
   }
else
   {
   l=strlen(mirror);
   for(i=l-15;i<l;i++) mirror_nm[i+15-l]=mirror[i];
   mirror_nm[15]='\0';
   sprintf(str1,"\1Optics %s Transmission",mirror_nm);
   sprintf(str,
     "TITLE=%20s;DTITL=%4.1f;LABX=%12s;LABY=%12s;DLABL=%4.1f;NGEOM;USER;BOLD;GRID;TIME;XSPACE=%1d;",
     str1, 2.0, "\1Lambda [nm]", "\1Transmission [%]",1.0,0);


   xmi=T.mirmin;
   xma=T.mirmax;
   plot_xy(str,0,Xmir,Ymir,Nmir,xmi,xma,ymi,yma);
   end_graphic1();
   Oxmi=xmi;
   Oxma=xma;
   Oymi=ymi;
   Oyma=yma;
   };
}

/* ------------------------------------------------------------------- */
void plot_optics(optics)

char	optics[];
{
char str[120], str1[50],optics_nm[30];
float xmi,ymi,xma,yma;
int	i,l;

ymi=0.;
yma=1.;

/* read optics file  if not return */

if(!read_trans(optics,Xoptics,Yoptics,&Noptics,&T.optmin,&T.optmax))
   {
     fprintf(stderr,"ERROR: OPTICS curve %s not found.\r\n",optics);
   }
else
   {
   l=strlen(optics);
   for(i=l-15;i<l;i++) optics_nm[i+15-l]=optics[i];
   optics_nm[15]='\0';
   sprintf(str1,"\1Optics %s Transmission",optics_nm);
   sprintf(str,
     "TITLE=%20s;DTITL=%4.1f;LABX=%12s;LABY=%12s;DLABL=%4.1f;NGEOM;USER;BOLD;GRID;TIME;XSPACE=%1d;",
     str1, 2.0, "\1Lambda [nm]", "\1Transmission [%]",1.0,0);


   xmi=T.optmin;
   xma=T.optmax;
   plot_xy(str,0,Xoptics,Yoptics,Noptics,xmi,xma,ymi,yma);
   end_graphic1();
   Oxmi=xmi;
   Oxma=xma;
   Oymi=ymi;
   Oyma=yma;
   };
}

/* ------------------------------------------------------------------- */
void plot_atmos(atmos)
char	atmos[];
{
register int	i;
char str[120], str1[50];
float xmi,ymi,xma,yma;

/* read atmos Table  if not return */

if(!read_atmos(atmos))
   {
     SCTPUT("ERROR: ATMOS curve not found.");
   }
else
   {
   if (T.airmass!=1.)
  	 for(i=0;i<Natmos;i++)
                YY[i]=pow(Yatmos[i],T.airmass);

   sprintf(str1,"\1Atmospheric Transmission");
   sprintf(str,
     "TITLE=%20s;DTITL=%4.1f;LABX=%12s;LABY=%12s;DLABL=%4.1f;NGEOM;USER;BOLD;GRID;TIME;XSPACE=%1d;",
     str1, 2.0, "\1Lambda [nm]", "\1Transmission [%]",1.0,0);

   c_minmax(Xatmos,Yatmos,Natmos,&xmi,&xma,&ymi,&yma);
   ymi=0.; yma=1.;

   if (T.airmass!=1.)
	plot_xy(str,0,Xatmos,YY,Natmos,xmi,xma,ymi,yma);
   else
   	plot_xy(str,0,Xatmos,Yatmos,Natmos,xmi,xma,ymi,yma);
   end_graphic1();
   Oxmi=xmi;
   Oxma=xma;
   Oymi=ymi;
   Oyma=yma;
   };
}

/* ------------------------------------------------------------------- */
void plot_filters(nfilt)
int nfilt;
{
float xmi,ymi,xma,yma,xbias;
char str[150], str1[50];

/* read Filter Table if not return */
if(!read_filt_table(nfilt)){
     SCTPUT("ERROR: FILTER curve not found.");
     return;
    }
else
    {
    sprintf(str1,"\1FILTER %2d  Transmission Curve",nfilt);
    sprintf(str,
     "TITLE=%18s;DTITL=%4.1f;LABX=%12s;LABY=%12s;DLABL=%4.1f;NGEOM;USER;GRID;XSPACE=%1d",
    str1, 2.0, "\1Lambda [nm]", "\1Transmission",1.0,0);

     c_minmax(Xfilt,Yfilt,Nfilter,&xmi,&xma,&ymi,&yma);

     xbias=(xma-xmi)/16.;
     xmi-=xbias;
     xma+=xbias;
     ymi=-0.05;  
     yma=1.0;

     plot_xy(str,0,Xfilt, Yfilt, Nfilter,xmi,xma,ymi,yma);
   end_graphic1();
   Oxmi=xmi;
   Oxma=xma;
   Oymi=ymi;
   Oyma=yma;
     };

}

/* ------------------------------------------------------------------- */
int read_ccd_table(nccd)
int nccd;
{
 int i, id ;
 int ncols, nrows, nul, sortcol, aw, ar;
 int cwave, crqe;
 char str[200], table[80];
 float x,y;
char    *dirdata;

dirdata=(char *) getenv("MID_FILTERS");
if (dirdata==NULL)
   {
   fprintf(stderr,"ERROR: cannot find MID_FILTERS environment variable\r\n");
   return(0);
   }


if(nccd<10)
	sprintf(table,"%s/ccd/ccd%1d.tbl",dirdata,nccd);
else
	sprintf(table,"%s/ccd/ccd%2d.tbl",dirdata,nccd);

if(!file_exists(table,".tbl")) {
    sprintf(str, "ERROR: Table %s could not be opened.", table);
    SCTPUT(str);
    return(0);
}
TCTOPN(table,F_I_MODE,&id);

TCIGET(id,&ncols,&nrows,&sortcol,&aw,&ar); 
TCCSER(id, ":wave",  &cwave);
TCCSER(id, ":rqe",   &crqe);

Nccd=nrows;

for(i=0;i<nrows;i++)
    {
      TCERDR(id,i+1,cwave,&x,&nul);
      Xccd[i]=x;
      TCERDR(id,i+1,crqe,&y,&nul);
      Yccd[i]=y;
    }

TCTCLO(id);

set_minmax(Xccd,Nccd,&T.ccdmin,&T.ccdmax);

return(1);
}

/* ------------------------------------------------------------------- */
int read_filt_table(nfilt)
int nfilt;
{
int id, unit, nleak, npleak;
int i, ncols, nrows, nul, sortcol, aw, ar;
int ndum, clamda, cflux;
char table[80], rleak[21], news_text[24*40], news_line[256];
char dtype[2];
float x,y;
float rleak0, rleak1, pleak_nm[MAXLEAKS], pleak_t[MAXLEAKS];
double dpleak_nm[MAXLEAKS], dpleak_t[MAXLEAKS];

char    *dirdata;

dirdata=(char *) getenv("MID_FILTERS");
if (dirdata==NULL)
	{
	fprintf(stderr,
	"ERROR: cannot find MID_FILTERS environment variable\r\n");
	return(0);
	}

sprintf(table,"%s/filters/eso%5.5d",dirdata,nfilt);

if(!file_exists(table,".tbl")) {
	 SCTPUT("ERROR: Transmission curve does not exist.");
	 return(0);
	 }

TCTOPN(table,F_I_MODE,&id);
TCIGET(id,&ncols,&nrows,&sortcol,&aw,&ar); 

TCCSER(id, ":LAMBDA",  &clamda);
TCCSER(id, ":FLUX", &cflux);

Nfilter=nrows;

for ( i = 0L; i < nrows; i++)
	{
	TCERDR(id,i+1,clamda,&x,&nul);
	Xfilt[i]=x;
	TCERDR(id,i+1,cflux,&y,&nul);
	Yfilt[i]=y;
	}

/* Now we read the leak information */
SCDGETC( id, "RLEAK", 1, 20, &ar, rleak );
SCDRDI( id, "NLEAK", 1, 1, &ar, &nleak, &unit, &nul);
SCDRDI( id, "NPLEAK", 1, 1, &ar, &npleak, &unit, &nul);

news_text[0] = '\0';

if ( nleak == 0 )
    strcat(news_text, "\n********* NO RED LEAKS **********\n");
else {
    strcat(news_text, "\n********* RED LEAKS **********\n");
    strcat(news_text, "\n       NM         T%%\n");
    strcat(news_text, "-----------------------------\n");
}

if ( nleak == 1 || nleak == 3 ) {
    (void) SCDFND( id, "PLEAK_NM", dtype, &ndum, &ndum );
    if (*dtype == 'r') 
       SCDRDR( id, "PLEAK_NM", 1, npleak, &ar, pleak_nm, &unit, &nul);
    else if  (*dtype == 'd') 
       {
       SCDRDD( id, "PLEAK_NM", 1, npleak, &ar, dpleak_nm, &unit, &nul);
       for (i = 0; i < npleak; i++) pleak_nm[i] = (float) dpleak_nm[i];
       } 
 
    (void) SCDFND( id, "PLEAK_T", dtype, &ndum, &ndum );  
    if (*dtype == 'r') 
       SCDRDR( id, "PLEAK_T", 1, npleak, &ar, pleak_t, &unit, &nul);
    else if  (*dtype == 'd') 
       {
       SCDRDD( id, "PLEAK_T", 1, npleak, &ar, dpleak_t, &unit, &nul);
       for (i = 0; i < npleak; i++) pleak_t[i] = (float) dpleak_t[i];
       } 

    for ( i = 0; i < npleak; i++ ) {
        sprintf(news_line, "%10.0f %10.2f\n", pleak_nm[i], pleak_t[i]);
        strcat(news_text, news_line);
    }
}

if ( nleak > 1 ) {
    for ( i = 0; rleak[i] != '\0'; i++ )
	if ( rleak[i] != ' ' ) {
	    sscanf(rleak+i, "%f / %f", &rleak0, &rleak1);
	    break;
	}
    if ( nleak != 2 )
        strcat(news_text, "\n.............................\n");
    sprintf(news_line, "%10.0f %10.2f\n%10.0f %10.2f\n", 1100., rleak0,
	    1200., rleak1);
    strcat(news_text, news_line);
}

if ( nleak > 0 ) {
    strcat(news_text, "\n-----------------------------\n");
    strcat(news_text, "\n** Please use the \"Frame\" menu to see **\n");
    strcat(news_text, "** the leaks in the graphic window **\n");
}
UxPopupInterface(UxFindSwidget("LeaksShell"), no_grab);
UxPutText(UxFindSwidget("tx_red_leaks"), news_text);

TCTCLO(id);

set_minmax(Xfilt,Nfilter,&T.filtmin,&T.filtmax);
if ((T.specmin>1500.)||(T.specmax>2000.))
	{
	for(i=0;i<Nfilter;i++)
		Xfilt[i]*=.1;
	T.filtmin*=.1;
	T.filtmax*=.1;
	}

return (1);
}

/* ------------------------------------------------------------------- */
int	read_spec_table(filepath,specname)
char	specname[];
char	filepath[];
{
int	id;
int	i,ncols,nrows,nul,sortcol,aw,ar;
int	clamda,cflux;
char	str[200], table[80];
float	x,y;

sprintf(table,"%s/%s",filepath,specname);

if(!file_exists(table,".tbl")) {
    sprintf(str, "ERROR: Table %s could not be opened.", table);
    SCTPUT(str);
    return(0);
}
TCTOPN(table,F_I_MODE,&id);

TCIGET(id,&ncols,&nrows,&sortcol,&aw,&ar);
TCCSER(id,":WAVE",&clamda);
TCCSER(id,":FLUX_W",&cflux);
if ( clamda == -1 || cflux == -1 ) {
    SCTPUT( "ERROR: Wrong table columns. Correct names are:" );
    SCTPUT( "      :WAVE    (wavelength)" );
    SCTPUT( "      :FLUX_W  (flux in wavelength units)" );
    return 0;
}

for(i=0L;i<nrows;i++)
    {
    TCERDR(id,i+1,clamda,&x,&nul);
    Xspec[i]=x;
    TCERDR(id,i+1,cflux,&y,&nul);
    Yspec[i]=y;
    }

Nspec=nrows;

TCTCLO(id);

set_minmax(Xspec,Nspec,&T.specmin,&T.specmax);
if ((T.specmin>1500.)||(T.specmax>2000.))
	{
	for(i=0;i<Nspec;i++)
		Xspec[i]*=.1;
	T.specmin*=.1;
	T.specmax*=.1;
	}

return(1);
}

/* ------------------------------------------------------------------- */
int	read_spec(name)
char	name[];
{
return(read_trans(name,Xspec,Yspec,&Nspec,&T.specmin,&T.specmax));
}

/* ------------------------------------------------------------------- */
int	read_sky(sky)
char	sky[];
{
char	*dirdata;
char	name[80];

dirdata=(char *) getenv("MID_FILTERS");
if (dirdata==NULL)
   {
   fprintf(stderr,"ERROR: cannot find MID_FILTERS environment variable\r\n");
   return(0);
   }

sprintf(name,"%s/atmos/%s",dirdata,sky);

return(read_trans(name,Xsky,Ysky,&Nsky,&T.skymin,&T.skymax));
}

/* ------------------------------------------------------------------- */
int	read_grism(name)
char	name[];
{
return(read_trans(name,Xgrism,Ygrism,&Ngrism,&T.grismmin,&T.grismmax));
}

/* ------------------------------------------------------------------- */
int	read_atmos(name)
char	name[];
{
int	check;
check=read_trans(name,Xatmos,Yatmos,&Natmos,&T.atmosmin,&T.atmosmax);
return(check);
}

/* ------------------------------------------------------------------- */

void	c_minmax(xxx,yyy,np,xmi,xma,ymi,yma)

int	np;
float	xxx[],yyy[],*xmi,*xma,*ymi,*yma;
{
register int	i;
float	xmin,xmax,ymin,ymax;

xmin=xmax=xxx[0];
ymin=ymax=yyy[0];

for(i=0;i<np;i++)
	{
	xmin=Min(xmin,xxx[i]);
	xmax=Max(xmax,xxx[i]);
	ymin=Min(ymin,yyy[i]);
	ymax=Max(ymax,yyy[i]);
	}
*xmi=xmin;
*xma=xmax;
*ymi=ymin;
*yma=ymax;
}
/* --------------------------------------------------------- */
void	plot_xy(title,lmode,xx,yy,np,xmi,xma,ymi,yma)

int	lmode,np;
float	xx[],yy[],xmi,xma,ymi,yma;
char	title[];
{
extern	int	tracemode;
register int	i;

init_gr(DEV_ERASE,1);

if ((ovpltgr==TRUE)&&(lfirstp==FALSE))
	{
	nc_ovplt++;
	vdef_wspec();
	AG_MOPN(PLOTAPP);

/*
 	ncol=(nc_ovplt+1)&0x7;
	if(ncol==0)
		ncol++;
	fprintf(stderr,"ncol=%d (%d) \r\n",ncol,nc_ovplt);
	sprintf(str,"COLOR=%1d",ncol);
	AG_SSET(str);
*/
 	AG_SSET("color=red");
	}
else
	{
	lfirstp=FALSE;
	nc_ovplt=0;
	
	AG_VDEF("graph_wnd0:", 0.0, 1.0, 0.0, 1.0, 0.0, 0.0);
	AG_MOPN(PLOTNAME);
	AG_SSET("FONT=1;CHDI=1.2,1.2");
	AG_SSET("COLOR=black");
	AG_AXES(xmi, xma, ymi, yma, title);
	AG_RGET("CLPL", Clip);
	
	/* save current data in case of zoom */
	Sxmi=xmi;
	Sxma=xma;
	Symi=ymi;
	Syma=yma;
	Slmode=lmode;
	Snp=np;
	strcpy(Sstr,title);
	Sxx=(float *)malloc((size_t)(Snp*sizeof(float)));
	Syy=(float *)malloc((size_t)(Snp*sizeof(float)));
	for(i=0;i<Snp;i++)
		{
		Sxx[i]=xx[i];
		Syy[i]=yy[i];
		};
 	AG_SSET("color=red");
	}
	
	
if (lmode<=0)
 {
 lmode*=-1;
 if (tracemode==FALSE)
	 AG_GPLL(xx, yy, np);
 else
	 AG_HIST(xx, yy, np, 0, 0);
 };


if (lmode!=0)
 {
 AG_SSET("color=magent");
 AG_GPLM(xx, yy, np,lmode); 
 }

 AG_SSET("color=black");
 AG_VUPD();
 AG_MCLS();

}

/* ------------------------------------------------------------------- */

int init_gr( devtype, viewp )
int devtype, viewp;
{
  if( InitGraphic && viewp==1 )
    return(TRUE); 
  if( InitGraphic2 && viewp==2 )
    return(TRUE);

  if ( !graphwin_exists() ) {
    SCTPUT( "*** Creating the graphic window ***" );
    AppendDialogText( "reset/display" );
    AppendDialogText( "create/graphic" );
    AppendDialogText( "SET/GCURSOR ? C_HAIR" );
    }

  if(viewp==1)
    InitGraphic = TRUE;
  if(viewp==2)
    InitGraphic2 = TRUE;

  return(TRUE);
}


/* ------------------------------------------------------------------- */
void end_graphic()
{
    if ( InitGraphic && graphwin_exists() ) { 
       AG_CLS();
       InitGraphic = FALSE;
       InitGraphic2 = FALSE;  }
}

/* ------------------------------------------------------------------- */
void end_viewp()
{
    if ( InitGraphic && graphwin_exists() )
	    AG_VKIL();

    InitGraphic = FALSE;
    InitGraphic2 = FALSE;
}

/* ------------------------------------------------------------------- */
void end_graphic1()
{
    if ( InitGraphic )
	    AG_CLS();

    InitGraphic = FALSE;
}

/* ------------------------------------------------------------------- */
void open_plotfile(n)
int n;
{
    AG_SSET("MFHARD");  /*  metafile in hard mode to multi-viewp */

   if(n==0)
    AG_MOPN( PLOTNAME );
   else
    AG_MOPN( PLOTAPP );

}

/* ------------------------------------------------------------------- */
void opena_plotfile()
{
    AG_MOPN( PLOTAPP );
}


/* ------------------------------------------------------------------- */
void clear_graphic()
 {
   if ( InitGraphic && graphwin_exists() ) {
	AG_VERS();
	AG_VUPD();
    }
}

/* ------------------------------------------------------------------- */
/*********************************************************
* get_agldev(): translate IDI device to devices erasable
* and non-erasable suitable for AG_VDEF calls.
*********************************************************/
void get_agldev()
 {

    /* now make the AGL device names */
    strcpy( DevErase, gdevice );
    strcat( DevErase, "/n:" ); /* see AG_VDEF definition */

    strcpy( DevNoErase, gdevice );
    strcat( DevNoErase, "/n:" ); /* see AG_VDEF definition */

    strcpy( DevEMAppend, gdevice );
    strcat( DevEMAppend, ":/a" ); /* see AG_VDEF definition */

    strcpy( DevMAppend, gdevice );
    strcat( DevMAppend, "/n:/a" ); /* see AG_VDEF definition */
}


/* ------------------------------------------------------------------- */
void Unzoom()
{
plot_xy(Sstr,Slmode,Sxx,Syy,Snp,Oxmi,Oxma,Oymi,Oyma);
end_graphic1();
}

void Trim()
{
float cpx, cpy, ox, oy, viewpsz[4];
int key, valpix;
char msg[30];
float	tmp;

  if ( ! graphwin_exists() ) {
	SCTPUT("*** Graphics system must be restarted with reset/display ***");
   	return;
  }

  AppendDialogText( "SET/GCURSOR ? C_HAIR" );

  ox=Sxmi;
  oy=Symi;


  plot_xy(Sstr,Slmode,Sxx,Syy,Snp,Sxmi,Sxma,Symi,Syma);

  AG_VSEL(pviewp); 
  AG_SSET("cursor=0");
  AG_RGET("WNDLimits",viewpsz);
  AG_VUPD();
  AG_VLOC( &cpx, &cpy, &key, &valpix );
  if ( key == 'D')
       return; 

  SCTPUT(" ");
  SCTPUT("    X-axis       Y-axis");
  SCTPUT("---------------------------");

  if(ltrimx)
      Sxmi=cpx;
  if(ltrimy) 
      Symi=cpy;

  sprintf( msg, "%10.2f %10.2f", cpx, cpy);
  SCTPUT( msg );

  AG_VLOC( &cpx, &cpy, &key, &valpix );
  if(key=='B')
     {
     if(ltrimx)
       Sxmi=ox;
     if(ltrimy)
       Symi=oy;
     return;
     }

    if(ltrimx)
      Sxma=cpx;
    if(ltrimy)
      Syma=cpy;

    sprintf( msg, "%10.2f %10.2f", cpx, cpy);
    SCTPUT( msg );

   end_graphic1();

   lfirstp=TRUE;

   if (Sxmi>Sxma)
	{tmp=Sxmi;Sxmi=Sxma;Sxma=tmp;};

   if (Symi>Syma)
	{tmp=Symi;Symi=Syma;Syma=tmp;};

    plot_xy(Sstr,Slmode,Sxx,Syy,Snp,Sxmi,Sxma,Symi,Syma);
   end_graphic1();

}

/* ------------------------------------------------------------------- */
void plot4filter(f)
int f[4];
{
  int i;
 
  for(i=0;i<4;i++){
    plot1filter(i+1,f[i]);
  }
  end_graphic();
}

/* ------------------------------------------------------------------- */
void plot9filter(f)
int f[9];
{
  int i;
 
  for(i=1;i <= 9 ;i++){
    plot19filter(i,f[i-1]);
  }
  end_graphic();
}

/* ------------------------------------------------------------------- */
void plot4ccd(f)
int f[4];
{
  int i;
 
  for(i=0;i<4 ;i++){
#ifdef DEBUG
    sprintf(str,"ccd # %d -> %d ",i+1,f[i]);
    SCTPUT(str);
#endif
    plot1ccd(i+1,f[i]);
  }
  end_graphic();
}

/* ------------------------------------------------------------------- */
void plot1filter(vp, filt)
int vp, filt;
{
 char str[150];
 char str1[50];
 float xmin,ymin,xmax,ymax,xbias,ybias;
 float xmi, xma, ymi, yma;
  
 if(vp==1){
   vwp1=AG_VDEF(GDE0, 0.05, 0.45, 0.05, 0.45, 0.0, 0.0);
   InitGraphic=TRUE;
   clear_graphic();
   open_plotfile(0);
  }
 else if(vp==2){
   vwp2=AG_VDEF(GDNEMA0, 0.55, 0.95, 0.05, 0.45, 0.0, 0.0);
   opena_plotfile();
   }
 else if(vp==3){
   vwp3=AG_VDEF(GDNEMA0, 0.55, 0.95, 0.55, 0.95, 0.0, 0.0);
   opena_plotfile();
   }
 else if(vp==4){
   vwp4=AG_VDEF(GDNEMA0, 0.05, 0.45, 0.55, 0.95, 0.0, 0.0);
   opena_plotfile();
   }
 
  if(!read_filt_table(filt)){
    SCTPUT("ERROR: Transmission curve does not exist. ");
    return;
   }


 AG_VUPD();

 sprintf(str1,"\1FILTER #%2d TRANSMISSION CURVE ",filt);
 sprintf(str,
     "TITLE=%18s;LABX=%12s;LABY=%12s;NGEOM;USER;XSPACE=%1d;GRID",
     str1, "\1Lambda [nm]", "\1Flux[%1]",0);

 c_minmax(Xfilt,Yfilt,Nfilter,&xmin,&xmax,&ymin,&ymax);
 xbias=(xmax-xmin)/16;
 ybias=(ymax-ymin)/16;

 xmi=xmin-xbias;
 xma=xmax+xbias;
 ymi=ymin-ybias;
 yma=ymax+ybias;

 AG_SSET("color=1");
 AG_AXES(xmi, xma, ymi, yma, str);

 AG_SSET("color=2");
 AG_GPLL(Xfilt, Yfilt, Nfilter);
 AG_VUPD();

 AG_VKIL();

}

/* ------------------------------------------------------------------- */
void plot19filter(vp, filt)
int vp, filt;
{
 int i;
 char str[150];
 char str1[50];
 float xmin,ymin,xmax,ymax,xbias,ybias;
 float xmi, xma, ymi, yma;
  
 if(vp==1){
   vwp1=AG_VDEF(GDE0, 0.02, 0.31, 0.02, 0.31, 0.0, 0.0);
   InitGraphic=TRUE;
   clear_graphic();
   open_plotfile(0);
  }
 else if(vp==2){
   vwp2=AG_VDEF(GDNEMA0, 0.35, 0.64, 0.02, 0.31, 0.0, 0.0);
   opena_plotfile();
   }
 else if(vp==3){
   vwp3=AG_VDEF(GDNEMA0, 0.68, 0.98, 0.02, 0.31, 0.0, 0.0);
   opena_plotfile();
   }
 else if(vp==4){
   vwp4=AG_VDEF(GDNEMA0, 0.68, 0.98, 0.35, 0.64, 0.0, 0.0);
   opena_plotfile();
   }
 else if(vp==5){
   vwp2=AG_VDEF(GDNEMA0, 0.68, 0.98, 0.68, 0.98, 0.0, 0.0);
   opena_plotfile();
   }
 else if(vp==6){
   vwp3=AG_VDEF(GDNEMA0, 0.35, 0.64, 0.68, 0.98, 0.0, 0.0);
   opena_plotfile();
   }
 else if(vp==7){
   vwp4=AG_VDEF(GDNEMA0, 0.02, 0.31, 0.68, 0.98, 0.0, 0.0);
   opena_plotfile();
   }
 else if(vp==8){
   vwp3=AG_VDEF(GDNEMA0, 0.02, 0.31, 0.35, 0.64, 0.0, 0.0);
   opena_plotfile();
   }
 else if(vp==9){
   vwp4=AG_VDEF(GDNEMA0, 0.35, 0.64, 0.35, 0.64, 0.0, 0.0);
   opena_plotfile();
   }
 
  if(!read_filt_table(filt)){
    SCTPUT("ERROR: Transmission curve does not exist.");
    return;
   }

  /* det Xmax and Xmin   */
  xmin=xmax=Xfilt[0];
  ymin=ymax=Yfilt[0];
  for(i=0; i<Nfilter; i++) {
   if(Xfilt[i]>xmax)
     xmax=Xfilt[i];
   if(Xfilt[i]<xmin)
     xmin=Xfilt[i];
   if(Yfilt[i]>ymax)
     ymax=Yfilt[i];
   if(Yfilt[i]<ymin)
     ymin=Yfilt[i];
  }

 AG_VUPD();

 sprintf(str1,"\1FILTER #%2d TRANSMISSION CURVE ",filt);
 sprintf(str,
     "TITLE=%18s;LABX=%12s;LABY=%12s;NGEOM;USER;XSPACE=%1d;GRID",
     str1, "\1Lambda [nm]", "\1Flux[%1]",0);
 xbias=(xmax-xmin)/16;
 ybias=(ymax-ymin)/16;

 xmi=xmin-xbias;
 xma=xmax+xbias;
 ymi=ymin-ybias;
 yma=ymax+ybias;

 AG_SSET("color=1");
 AG_AXES(xmi, xma, ymi, yma, str);

 AG_SSET("color=2");
 AG_GPLL(Xfilt, Yfilt, Nfilter);
 AG_VUPD();

 AG_VKIL();

}

/* ------------------------------------------------------------------- */
void plot1ccd(vp, filt)
int vp, filt;
{
 int i;
 char str[150];
 char str1[50];
 float xmin,ymin,xmax,ymax,xbias,ybias;
 float xmi, xma, ymi, yma;
  
 if(vp==1){
   vwp1=AG_VDEF(GDE0, 0.05, 0.45, 0.05, 0.45, 0.0, 0.0);
   InitGraphic=TRUE;
   clear_graphic();
   open_plotfile(0);
  }
 else if(vp==2){
   vwp2=AG_VDEF(GDNEMA0, 0.55, 0.95, 0.05, 0.45, 0.0, 0.0);
   opena_plotfile();
   }
 else if(vp==3){
   vwp3=AG_VDEF(GDNEMA0, 0.55, 0.95, 0.55, 0.95, 0.0, 0.0);
   opena_plotfile();
   }
 else if(vp==4){
   vwp4=AG_VDEF(GDNEMA0, 0.05, 0.45, 0.55, 0.95, 0.0, 0.0);
   opena_plotfile();
   }
 
  if(!read_ccd_table(filt)){
    SCTPUT("ERROR: Efficiency curve does not exist.");
    return;
   }

  /* det Xmax and Xmin   */
  xmin=xmax=Xccd[0];
  ymin=ymax=Yccd[0];
  for(i=0; i< Nccd; i++) {
   if(Xccd[i]>xmax)
     xmax=Xccd[i];
   if(Xccd[i]<xmin)
     xmin=Xccd[i];
   if(Yccd[i]>ymax)
     ymax=Yccd[i];
   if(Yccd[i]<ymin)
     ymin=Yccd[i];
  }

 sprintf(str," xmin-> %10.2f xmax-> %10.2f ",xmin,xmax);
 sprintf(str1,"\1CCD #%2d Responsive Quatum Efficiency ",filt);
 sprintf(str,
     "TITLE=%18s;LABX=%12s;LABY=%12s;NGEOM;USER;XSPACE=%1d;GRID",
     str1, "\1Lambda [nm]", "\1RQE[%]",0);
 xbias=(xmax-xmin)/16;
 ybias=(ymax-ymin)/16;

 xmi=xmin-xbias;
 xma=xmax+xbias;
 ymi=ymin-ybias;
 ymi=0.;
 yma=ymax+ybias;
 yma=1.;

 AG_SSET("color=1");
 AG_AXES(xmi, xma, ymi, yma, str);

 AG_SSET("color=2");
 AG_GPLL(Xccd, Yccd, Nccd);
 AG_VUPD();

 AG_VKIL();

}

/*-------------------------------------------------------------------------
  vdef_wspec() : define the Midas window limits.
--------------------------------------------------------------------------*/
void	vdef_wspec()
{
  AG_VDEF("graph_wnd0/n:", 0.0, 1.0, 0.0, 1.0, 0.0, 0.0);
  AG_CDEF(Clip[0], Clip[1], Clip[2], Clip[3]);
  AG_WDEF(Sxmi, Sxma, Symi, Syma);
  AG_SSET("FONT=1;CHDI=1.2,1.2");
}

void	set_minmax(xx,n,xmin,xmax)
float	xx[],*xmin,*xmax;
int	n;
{
register int	i;
float	amin,amax;

amin=xx[0];
amax=xx[0];
for(i=1;i<n;i++)
	{
	amin=Min(amin,xx[i]);
        amax=Max(amax,xx[i]);
	};
*xmin=amin;
*xmax=amax;
}

void	rg_minmax(xx,n,xmin,xmax)
float	xx[],*xmin,*xmax;
int	n;
{
register int	i;
float	amin,amax;

amin=xx[0];
amax=xx[0];
for(i=1;i<n;i++)
	{
	amin=Min(amin,xx[i]);
        amax=Max(amax,xx[i]);
	};
if (*xmin==-1.)
         *xmin=amin;
else
         *xmin=Max(*xmin,amin);
if( *xmax==-1.)
         *xmax=amax;
else
         *xmax=Min(*xmax,amax);
}

