/* Calculates the plate seperation & order required to observe a given
 * wavelength with a given bandpass. Command line input should be wavelength 
 * and then the bandpass, both in angstroms.
 *
 * DAZLE parameters are defined at the top.
 *
 * Fraser Clarke (fclarke@ast.cam.ac.uk)
 * 25/01/2000
 *
 * TODO - Turn this into a Java applet...
 */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define R 0.939			// Reflectance (INTENSITY!!!! (amplitude^2))
#define T 1.0			// Transmission
#define mu 1.0			// Refractive index
#define costheta 1.0	// (cosine of) Angle of incidence

int main(int argc, char *argv[]) {
	
	char tmp[255];
	double wavelength, bandpass;
	double bp1, bp2;
	double coF;
	double sep,o;			// Seperation and order.
	int orderlo, orderhi, order;
	
	if(argc<3) {
		do {
			printf("Enter central wavelength (Angstroms) > ");
			fgets(tmp,255,stdin);
		} while(tmp[0]=='\n');
		wavelength=atof(tmp)*1E-10;
		do {
			printf("Enter desired width of bandpass (Angstroms) > ");
			fgets(tmp,255,stdin);
		} while(tmp[0]=='\n');
		bandpass=atof(tmp)*1E-10;
	}
	else {
		wavelength=atof(argv[1])*1E-10;
		bandpass=atof(argv[2])*1E-10;
	}

	coF = M_PI*sqrt(R)/(1.0-R);
	
	// Calculate the order needed to give the nearest bandpass and wavelength.
	
	o = wavelength/(bandpass*coF);
	orderlo = floor(o);
	orderhi = ceil(o);
	if(orderlo==0) orderlo++;
	
	bp1 = wavelength/(coF*(double)orderlo);
	bp2 = wavelength/(coF*(double)orderhi);

	if(fabs(bp1-bandpass) < fabs(bp2-bandpass)) {
		bandpass=bp1;
		order=orderlo;
	}
	else {
		bandpass=bp2;
		order=orderhi;
	}

	// Use this to calculate the plate seperation needed, as well as the
	// nearest bandpass possible

	sep = (double)order*wavelength/(2.0*mu*costheta);
	
	printf("\nPlate seperation : %.2f microns\n",sep*1.0E6);
	printf("FP Order : %d\n", order);
	printf("Closest bandpass : %.1f Angstroms\n",bandpass*1e10);
	
	return 1;
}
