/* A simple program that plots the position and relative strength of
 * lines in a line list. The line list should take the form;
 *		...					...
 * Wavlength(Angstroms)		Flux
 *		...					...
 *
 * Fraser Clarke (fclarke@ast.cam.ac.uk)
 * January 2000
 */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <wctype.h>
#include <cpgplot.h>
#include <ada.h>

#define DEFAULT_LINE_FILE "./cirpass-lines.dat"

void plotlinelist(Spectrum *list) {

	int i;
	float maxx, minx, maxy, miny, diff;

	// Find out the limits of the data in each axis.
	
	maxx = maxy = -1.0E30;
	minx = miny = 1.0E30;
	for(i=0;i<list->np;i++) {
		if(list->wave[i]>maxy) maxy=list->wave[i];
		if(list->wave[i]<miny) miny=list->wave[i];
		if(list->flux[i]>maxx) maxx=list->flux[i];
		if(list->flux[i]<minx) minx=list->flux[i];
	}
	
	diff = maxx-minx;
	maxx+=0.1*diff;
	minx-=0.1*diff;
	diff = maxy-miny;
	maxy+=0.1*diff;
	miny-=0.1*diff;
	
	cpgsci(1);
	cpgenv(miny, maxy, 0, maxx,0,1);
	cpgsci(2);
	for(i=0;i<list->np;i++) {
		cpgmove((float)list->wave[i],1);
		cpgdraw((float)list->wave[i],(float)list->flux[i]);
	}
	
	cpgsci(1);

}

int main (int argc, char *argv[]) {
	
	char filename[255];
	char cwave[255],cflux[255];
	char tmp[255];
	FILE *file;
	Spectrum *skyspec;
	int i;
	
	if(argc<2) {
		strcpy(filename,DEFAULT_LINE_FILE);
		printf("Loading data from %s\n",filename);
	}
	else 
		strcpy(filename,argv[1]);
	
	file = fopen(filename,"r");
	if(!file)
		adaerr("Can't open specified line file!");// %s!\n",filename);
		
	// Allocate space to for the spectrum.
	
	skyspec = specalloc(linesinfile(file));
	
	// Load the data into the spectrum. The format is expected to be 
	// one entry per line of; Wavelength	Strength
	
	rewind(file);
	i=0;
	
	for(;;) {
		fscanf(file,"%s%s",cwave,cflux);
		if(feof(file))
			break;
		if(cflux[0]<=57 && cflux[0]>=48) {
			// Convert the wavelength to microns
			skyspec->wave[i] = atof(cwave)/10000.0;
			skyspec->flux[i] = atof(cflux);
			i++;
		}
	}
	
	fclose(file);
	
	skyspec->np = i;

	// Open the PGPLOT device and start plotting...

	cpgopen("?");	

	plotlinelist(skyspec);
	
	sprintf(tmp,"Lines in %s",filename);

	cpglab("Wavelength (microns)", "Relative Strength (arbitrary units)", tmp);
	
	cpgclos();
	
	freespec(skyspec);
	
	return 0;
}