#! /usr/bin/python
# coding: latin-1

import string, os, math
from html_elements import *
Content = []
Rows=0

def output_header(Web, Title, Error):
	if Web < 2:
		Output={}
		Ini_read=open('output.ini','r')
		Data=Ini_read.readline()
		while Data <> "":
			Raw=string.split(Data)
			Output[Raw[0]]=Raw[2]
			Data=Ini_read.readline()
		Ini_read.close()
		Table_web = Output["web"] + "table.csv"
		Table_abs = Output["abs"] + "table.csv"
		Picture_web = Output["web"] + "plot.png"
		Picture_abs = Output["abs"] + "plot.png"
		Gnuplot = Output["abs"] + "plot.plt"
		Output["help_web"] = Output["help_web"] + "index.html"

		#------------------------------------web output-------------------------------------
		Rows=0
		header(Title, Output["css"])
		body()
		headline(Title, '1')
		headline("Based on a Gauss-function", '5')
		hline('100%', "left", 4)
#		body()
	else:
		#--------------------------------monitor output-------------------------------------
		print
		print
		print Title
		Table_abs = "table.csv"
	if Error == 0:
		Table_write=open(Table_abs,'w')
		Table_write.write(Title+"\n")
		Table_write.write("\n")
		Table_write.close()


def output_summary(Web, Source, Object_choice_0, Object_choice_1, Object_choice_2, Filter_mag, Object_brightness_choice, Detector, Hawaii_conditions, Filter_choice, Camera_choice, Slit_width, Dispersion_choice, Water_vapor, Airmass, Background_choice, Sky_brightness, Strehl, Seeing, Central_wavelength, Lpmm, SN, DIT, Tau, Scale, Mode, Error):
	
	if Web < 2:
		Output={}
		Ini_read=open('output.ini','r')
		Data=Ini_read.readline()
		while Data <> "":
			Raw=string.split(Data)
			Output[Raw[0]]=Raw[2]
			Data=Ini_read.readline()
		Ini_read.close()
		Table_web = Output["web"] + "table.csv"
		Table_abs = Output["abs"] + "table.csv"
		Picture_web = Output["web"] + "plot.png"
		Picture_abs = Output["abs"] + "plot.png"
		Gnuplot = Output["abs"] + "plot.plt"
		Output["help_web"] = Output["help_web"] + "index.html"

		#------------------------------------web output-------------------------------------
		Rows=0
		headline_left("headline_object", "Object characteristics")
		headline_right("headline_hardware", "Hardware characteristics")
		par("object_left")
		print "Source geometry:"
		newline()
		print "Source type:"
		newline()
		if Object_choice_0 == 'b' or Object_choice_0 == 't':
			print "Source magnitude (%s-filter):" % Filter_mag
			newline()
		if Object_choice_0 == "b":
			print "Temperature:"
			newline()
		if Object_choice_0 <> 'b' and Object_choice_0 <> 't':
			print "Line wavelength:"
			newline()
			print "Line flux:"
			newline()
			print "Line width:"
			newline()
		coda_par()
		par("object_right")
		emph(Source)
		newline()
		if Object_choice_0 == "t":
			emph("Template spectrum, ")
			emph(Object_choice_1)
			if Object_choice_1.find('galaxy') <> -1:
				emph(", z= ")
				emph(Object_choice_2)
			newline()
		if Object_choice_0 == "b":
			emph("Blackbody")
			newline()
		if Object_choice_0 == "b" or Object_choice_0 == 't':
			emph(str(Object_brightness_choice)+" mag")
			newline()
		if Object_choice_0 == "b":
			emph(Object_choice_1+" K")
			newline()
		if Object_choice_0 <> 'b' and Object_choice_0 <> 't':
			emph("Single line")
			newline()
			emph(Object_choice_0+' micron')
			newline()
			emph(Object_choice_1+' erg/s/cm&sup2')
			newline()
			emph(Object_choice_2+' &Aring')
			newline()
#		coda_par()
#		par("clear")
#		coda_par()
#		headline_right("Hardware characteristics")
		par("hardware_left")
		print "LUCIFER No.:"
		newline()
		if Error == 0:
			print "Detector full well:"
			newline()
			print "Detector Readout Noise:"
			newline()
		print "Filter:"
		newline()
		print "Camera:"
		newline()
		if (Mode%2)==0:
			print "Slit width:"
			newline()
			print "Central Wavelength of the grating unit:"
			newline()
			print "Number of lines per milimeter:"
			newline()	
			print "Dispersion:"
			newline()	
		print "Plate scale:"
		newline()

		coda_par()
		par("hardware_right")
		emph(Detector)
		newline()
		if Error == 0:
			emph("%.0f e-" % (Hawaii_conditions['Fullwell_%d' % int(Detector)]))
			newline()
			emph("%.0f e- rms" % (Hawaii_conditions['RON_%d' % int(Detector)]))
			newline()
		emph(Filter_choice)
		newline()
		emph(Camera_choice)
		newline()
		if (Mode%2)==0:
			emph(str(Slit_width)+' arcsec')
			newline()
			emph(str(Central_wavelength)+' micron')
			newline()
			emph(str(Lpmm)+' l/mm')
			newline()
			String = "%4.2f" % (Dispersion_choice*10000.)
			emph(String+'  &Aring/pixel')
			#print  "%4.2f &Aring/pixel" % (Dispersion_choice*10000.)
			newline()
		emph(str(Scale)+' arcsec/pixel')
		newline()
			
		coda_par()
		par("clear")		
		coda_par()
		
		hline('80%', "center", 2)
		
		headline_left("headline_atmosphere","Atmospheric conditions")
		headline_right("headline_exposure","Parameters of exposure")
		par("atmosphere_left")
		print "Water vapor:"
		newline()
		print "Airmass:"
		newline()
		if Background_choice=="0":
			print "Sky brightness:"
			newline()
		elif Sky_brightness==-27:
			print "Sky background:"
			newline()
		elif Sky_brightness==-17:
			print "Sky background:"
			newline()
		print "Seeing:"
		newline()
		if Strehl<>'-1':
			print "Strehl:"
			newline()
		coda_par()
		
		par("atmosphere_right")
		emph(str(Water_vapor)+' mm')
		newline()
		emph(str(Airmass))
		newline()
		if Background_choice=="0":
			emph(str(Sky_brightness)+' mag')
			newline()
		elif Sky_brightness==-27:
			emph("File")
			newline()
		elif Sky_brightness==-17:
			emph("Theoretical")
			newline()
		emph(str(Seeing)+" arcsec")
		newline()
		if Strehl<>'-1':
			emph(str(Strehl))
			newline()
		coda_par()
#		par("clear")
#		coda_par()
		
#		hline('80%', "center", 2)
		
		par("exposure_left")
		print "DIT: "
		newline()
		if (Mode==1) or (Mode==3):
			print "SNR:"
			newline()
		else:
			print "Total exposure time:"
			newline()
		coda_par()
		par("exposure_right")
		emph(str(DIT)+' sec')
		newline()
		if (Mode==1) or (Mode==3):
			String = "%.1f" % SN
			emph(String)
			newline()
		else:
			emph(str(Tau)+" sec")
			newline()
		coda_par()
		par("clear")
		coda_par()

#		hline('100%', "left", 3)

	else:
		#---------------------Monitor output-------------------------------
		
		Table_abs = "table.csv"
		Picture_abs = "plot.png"
		Gnuplot = "plot.plt"

		print "Source geometry:", Source
		if Object_choice_0 =="t":
			print "Source type: Template spectrum,",Object_choice_1
		if Object_choice_0 =="b":
			print "Blackbody"
			print "Blackbody Temperature:", Object_choice_1,"K"
		if Object_choice_0 <> 'b' and Object_choice_0 <> 't':
			print "Single line"
			print "Line_wavelength:", Object_choice_0,"micron"
			print "Line_flux:", Object_choice_1,"erg/s/cm^2"
			print "Line_width:", Object_choice_2,"A"
		else:
			print "Source magnitude (%s-filter): %.2f mag" % (Filter_mag, Object_brightness_choice)
		print "LUCIFER No.:", Detector
		print "Filter of LUCIFER:", Filter_choice
		print "Camera:", Camera_choice
		if (Mode % 2) == 0:
			print "Slit width:", Slit_width,"arcsec"
			print "Central Wavelength of the grating unit:", Central_wavelength,"micron"
			print "Number of lines per milimeter:", Lpmm,"l/mm"
			print "Plate scale:", Scale,"arcsec/pixel"
		print "Water vapour:", Water_vapor,"mm"
		print "Airmass:", Airmass
		if Background_choice =="0":
			print "Sky brightness:", Sky_brightness,"mag"
		elif Sky_brightness==-27:
			print "Sky background: File"
		elif Sky_brightness==-17:
			print "Sky background: Theoretical"
		if Strehl<>'-1':
			print "Strehl:", Strehl
		print "Seeing:", Seeing,"arcsec"
		print "DIT:", DIT
		if (Mode==1) or (Mode==3):
			print "SNR: %.2f\n" % SN
		else:
			print "Total exposure time: %.2f\n" % Tau

	#---------------------File output-----------------------------------
	if Error == 0:
		Table_write=open(Table_abs,'a')
		Table_write.write("Source geometry: "+Source+"\n")
		if Object_choice_0 =="t":
			Table_write.write("Source type: Template spectrum, "+Object_choice_1+"\n")
		if Object_choice_0 =="b":
			Table_write.write("Blackbody"+"\n")
			Table_write.write("Blackbody Temperature: "+Object_choice_1+" K\n")
		if Object_choice_0 <> 'b' and Object_choice_0 <> 't':
			Table_write.write("Single line"+"\n")
			Table_write.write("Line_wavelength: "+Object_choice_0+" micron\n")
			Table_write.write("Line_flux: "+Object_choice_1+" erg/s/cm^2\n")
			Table_write.write("Line_width: "+Object_choice_2+" A")
		else:
			Table_write.write("Source magnitude (%s-filter): %.2f mag\n" % (Filter_mag, Object_brightness_choice))
		Table_write.write("LUCIFER No.: %s\n" % Detector)
		Table_write.write("Filter used in LUCIFER: "+Filter_choice+"\n")
		Table_write.write("Camera: "+Camera_choice+"\n")
		if (Mode % 2) == 0:
			Table_write.write("Slit width: %s arcsec\n" % Slit_width)
			Table_write.write("Central Wavelength of the grating unit: %.2f micron\n" % Central_wavelength)
			Table_write.write("Number of lines per milimeter: %s l/mm\n"  % Lpmm)
			Table_write.write("Plate scale: %.2f arcsec/pixel\n" % Scale)
		Table_write.write("Water vapor: %.1f mm\n" % Water_vapor)
		Table_write.write("Airmass: %.2f\n" % Airmass)
		if Background_choice =="0":
			Table_write.write("Sky brightness: %.1f mag\n" % Sky_brightness)
		elif Sky_brightness==-27:
			Table_write.write("Sky background: File\n")
		elif Sky_brightness==-17:
			Table_write.write("Sky background: Theoretical\n")
		if Strehl<>'-1':
			Table_write.write("Strehl: %.2f\n" % Strehl)
		Table_write.write("Seeing: %.2f arcsec\n" % Seeing)
		Table_write.write("DIT: %.2e sec\n" % DIT)
		if (Mode==1) or (Mode==3):
			Table_write.write("SNR: %.2f\n\n" % SN)
		else:
			Table_write.write("Total exposure time: %.2e sec\n\n" % Tau)
		Table_write.close()

def output_imaging(Web, Source, Detector, Hawaii_conditions, Photons_object_tau, Photons_sky_tau, Center_pixel_tau, SN, SN_center_tau, DIT, SN_DIT, Tau, Mode, N_pix, Seeing):
	
	if Web < 2:
# --------------------------- web output ---------------------	
		Output={}
		Ini_read=open('output.ini','r')
		Data=Ini_read.readline()
		while Data <> "":
			Raw=string.split(Data)
			Output[Raw[0]]=Raw[2]
			Data=Ini_read.readline()
		Ini_read.close()
		Table_web = Output["web"] + "table.csv"
		Table_abs = Output["abs"] + "table.csv"
		Picture_web = Output["web"] + "plot.png"
		Picture_abs = Output["abs"] + "plot.png"
		Gnuplot = Output["abs"] + "plot.plt"
		Output["help_web"] = Output["help_web"] + "index.html"
		hline("80%","center",2)
		headline("Calculated values", "2")
#		hline("100%", "left", 2)
		par("five")
		coda_par()
		
		par("output_left")
		#if Source == "Point source":
			#print "Number of pixel in PSF area:"
		#newline()
		if (Mode==1) or (Mode==3):
			print "Exposure time:"
		else:
			print "SNR:"
		newline()
		print "Total object flux:"
		newline()
		print "Total sky flux:"
		newline()
		print "Electrons from object+sky inside the central pixel:"
		newline()
		print "Electrons from object+sky inside the central pixel per DIT:"
		newline()
		print "Object central pixel:"
		newline()
		print "Sky background:"
		coda_par()
		
		par("output_right")
		############ number of pixels in PSF area ##########################
		#if Source == "Point source":
			#print "%d" % N_pix
		#newline()
		########### Exposure time or SNR ###################################
		if (Mode==1) or (Mode==3):
			Temp = "%.2f" % Tau
			emph(Temp+' sec')
		else:
			Temp = "%.2f" % SN
			emph(Temp)
		newline()
		############ total object flux #####################################
		Temp = "%.2f" % Photons_object_tau
		if Source == "Point source":
			emph(Temp+' e-')
		else:
			emph(Temp+' e-/pixel')
		newline()
		############ total sky flux ########################################
		Temp = Photons_sky_tau*N_pix
		if Source == "Point source":
			emph('%0.2f e-' % Temp)
		else:
			emph('%0.2f e-/pixel' % Temp)
		newline()
		#### Electrons from object+sky inside the central pixel ############
		Temp1 = Center_pixel_tau + Photons_sky_tau
		Temp = "%.2f e-" % (Temp1)
		emph(Temp)
		newline()
		#### Electrons from object+sky inside the central pixel per DIT ####
		Temp = 'Fullwell_%s' % Detector
		Temp = Hawaii_conditions[Temp]
		Temp4 = 'Linearity_start_%s' % Detector
		Temp2 = Hawaii_conditions[Temp4]
		Temp4 = 'Linearity_end_%s' % Detector
		Temp3 = Hawaii_conditions[Temp4]
		Temp1 = ((Center_pixel_tau + Photons_sky_tau) / Tau * DIT)
		if Temp1 > Temp:
			Temp1 = "%.2f e-/DIT" % ((Center_pixel_tau + Photons_sky_tau) / Tau * DIT)
			Temp = "%s <font color=red>!! saturated !!</font>" % (Temp1)
		elif Temp1 > Temp*Temp3 or Temp1 < Temp*Temp2:
			Temp1 = "%.2f e-/DIT" % ((Center_pixel_tau + Photons_sky_tau) / Tau * DIT)
			Temp = "%s <font color=red>!! Linearity is not within 5%% !!</font>" % (Temp1)
		else:
			Temp1 = "%.2f e-/DIT" % ((Center_pixel_tau + Photons_sky_tau) / Tau * DIT)
			Temp = Temp1
		emph(Temp)
		newline()
		########### Object central pixel ###################################
		Temp = "%.2f e-/pix/DIT" % (Center_pixel_tau/Tau*DIT)
		emph(Temp)
		newline()
		########### Sky background #########################################
		Temp = "%.2f e-/pix/DIT" % (Photons_sky_tau/Tau*DIT)
		emph(Temp)
		coda_par()
		par("clear")
		coda_par()
		#hline("80%","center",2)
		
	else:
# -------------------------- monitor output --------------------
		Table_abs = "table.csv"
		Picture_abs = "plot.png"
		Gnuplot = "plot.plt"
		print "Total number of electrons from source: %.2e e-" % Photons_object_tau
		if (Mode==1) or (Mode==3):
			print "Exposure time: %.2e sec" % Tau
		else:
			print "SNR: %.2e" % SN
		print "Electrons from object+sky inside the central pixel: %.2e e-" % (Center_pixel_tau + Photons_sky_tau)
		print "SNR for the central pixel: %.2e" % SN_center_tau
		print "Background: %.2e e-/pixel/sec" % (Photons_sky_tau/Tau)
# -------------------------- file output -----------------------
	Table_write=open(Table_abs,'a')
	Temp =  "Total number of electrons from source: %.2f e-\n" % Photons_object_tau
	Table_write.write(Temp)
	if (Mode==1) or (Mode==3):
		Temp =  "Exposure time: %.2f sec\n" % Tau
	else:
		Temp = "SNR: %.2f\n" % SN
	Table_write.write(Temp)
	Temp =  "Electrons from object+sky inside the central pixel: %.2e e-\n" % (Center_pixel_tau + Photons_sky_tau)
	Table_write.write(Temp)
	Temp =  "SNR for the central pixel: %.2f\n" % SN_center_tau
	Table_write.write(Temp)
	Temp =  "Background: %.2f e-/pixel/sec\n" % (Photons_sky_tau/Tau)
	Table_write.write(Temp)
	Temp = "\n"
	Table_write.write(Temp)
	Temp = "exposure time / sec\tSNR\n"
	Table_write.write(Temp)
	i = 0.25*Tau
	while i <= 1.75*Tau:
		#print i, SN[i]
		String="%.2e\t%.7f\n" % (i, math.sqrt(i/DIT)*SN_DIT)
		Table_write.write(String)
		i = i + 1.5*Tau/20.
	Table_write.close()
	Gnuplot_write = open(Gnuplot, 'w')
	Gnuplot_write.write("set output '"+Picture_abs+"'\n")
	Gnuplot_write.write("set term png\n")
	Gnuplot_write.write("set style data lines\n")
	Gnuplot_write.write("set xlabel 'exposure time [sec]'\n")
	Gnuplot_write.write("set ylabel 'SNR'\n")
	Temp=math.sqrt((i + 1.5*Tau/20.)/DIT)*SN_DIT
	Gnuplot_write.write("set yrange[*:%s]\n" % Temp)
	Gnuplot_write.write("plot '" + Table_abs + "' using ($1):($2) ")
	Gnuplot_write.write("title 'LUCIFER-ETC SNR'\n")
	Gnuplot_write.close()
	String="gnuplot "+Gnuplot
	os.system(String)
	
	if Web < 2:
		par("center")
		print "The SNR is calculated over %d pixels in the PSF area including  93.8 &#37 of the total flux." % (N_pix + 0.5)
		#print "The SNR (%d sec) is calculated for %d pixel in the PSF area of a Moffat-function with beta=2.5 and a FWHM of 4.1*Seeing=%0.2f''." % (Tau, N_pix, 4.1*Seeing)
		coda_par()
		headline ('Signal-To-Noise plot', "1")
		image(Picture_web)
		par("clear")
		coda_par()
		par("ascii")
		link(Table_web, "ASCII-file")
#		coda_par()

#def output_spectrum(Web, SN, Photons_object_dit, Photons_sky_dit, Pixel_start, Pixel_end, Dispersion_choice, Pixel, N_pix, Central_wavelength, DIT, Tau):
def output_spectrum(Web, Detector, Hawaii_conditions, SN, Photons_object_dit, Photons_sky_dit, Dispersion_choice, Pixel, N_pix, Central_wavelength, DIT, Tau, Photons_max_dit):
	Pixel_shift = 500
	Wavelength_start = 0.0
	Wavelength_end = 0.0
	if Web < 2:
		Output={}
		Ini_read=open('output.ini','r')
		Data=Ini_read.readline()
		while Data <> "":
			Raw=string.split(Data)
			Output[Raw[0]]=Raw[2]
			Data=Ini_read.readline()
		Ini_read.close()
		Table_web = Output["web"] + "table.csv"
		Table_abs = Output["abs"] + "table.csv"
		Picture_web = Output["web"] + "plot.png"
		Picture_abs = Output["abs"] + "plot.png"
		Gnuplot = Output["abs"] + "plot.plt"
		Output["help_web"] = Output["help_web"] + "index.html"

	else:
		Table_abs = "table.csv"
		Picture_abs = "plot.png"
		Gnuplot = "plot.plt"
	Gnuplot_write = open(Gnuplot, 'w')
	Table_write=open(Table_abs,'a')
	Liste=SN.keys()
	Liste.sort()
	Photons_sky_max = 0.0
	Table_write.write("WL/micron\tSN\tPixel\n")
	for i in Liste:
		j =  int((string.atof(i)-Central_wavelength+Dispersion_choice*1024.)/Dispersion_choice+0.5)
		if j > (-1.)*Pixel_shift and j < Pixel + Pixel_shift:
			if Photons_sky_max < Photons_sky_dit[i] and j > 0 and j < Pixel:
				Photons_sky_max = Photons_sky_dit[i]
				Wavelength_sky_max = string.atof(i)
		String="%s\t%.4f\t%d\n" % (i, SN[i],j)
		Table_write.write(String)
		if j == Pixel / 2.:
			Photons_object_cw = Photons_object_dit[i]#/DIT*Tau
			Photons_sky_cw = Photons_sky_dit[i]#/DIT*Tau
			SN_cw = SN[i]
	Table_write.close()
	Photons_max_dit = Photons_max_dit + Photons_sky_max
	#if Wavelength_end == 0.0:
		#Wavelength_end = i
	#print Wavelength_start,Wavelength_end
	Wavelength_start = (-1.)*Dispersion_choice*(Pixel_shift + Pixel / 2.)+Central_wavelength
	Wavelength_end = Dispersion_choice*(Pixel_shift + Pixel / 2.)+Central_wavelength
	Wavelength_step = (string.atof(Wavelength_end) - string.atof(Wavelength_start)) / 5.
	
	Gnuplot_write.write("set output '"+Picture_abs+"'\n")
	Gnuplot_write.write("set term png\n")
	Gnuplot_write.write("set style data lines\n")
	#Gnuplot_write.write("set xlabel 'wavelength [micron]'\n")
	#Gnuplot_write.write("set x2label 'Pixel'\n")
	#Gnuplot_write.write("set x2tics -20000,"+str(Pixel_step)+"\n")
	#Gnuplot_write.write("set x2range["+str(Pixel_start)+":"+str(Pixel_end)+"]\n")
	Gnuplot_write.write("set xlabel 'Pixel'\n")
	Gnuplot_write.write("set x2label 'wavelength [micron]'\n")
	Gnuplot_write.write("set ylabel 'SNR (total exposure time)'\n")
	Gnuplot_write.write("set x2tics 0,"+str(Wavelength_step)+"\n")
	Gnuplot_write.write("set x2range["+str(Wavelength_start)+":"+str(Wavelength_end)+"]\n")
	Gnuplot_write.write("set xtics nomirror\n")
	Gnuplot_write.write("set xrange[-%s:%s]\n" % (Pixel_shift,Pixel + Pixel_shift))
	#Gnuplot_write.write("set xrange[-500:2500]\n")
	Gnuplot_write.write("set yrange[0:*]\n")
	Gnuplot_write.write("plot '" + Table_abs + "' using ($3):($2) title 'LUCIFER-ETC SNR'\n")
	Gnuplot_write.close()
	String="gnuplot "+Gnuplot
	os.system(String)
	
	if Web < 2:
		hline("80%","center",2)
		headline("Calculated values", "2")
		#hline("100%", "left", 2)
		par("five")
		coda_par()
		par("output_left")
		print "Object signal at %4.2f micron:" % Central_wavelength
		newline()
		print "SNR at %4.2f micron:" % Central_wavelength
		newline()
		print "Maximum count rate from object + sky:"
		newline()
		print "Maximum sky level at %4.4f micron:" % Wavelength_sky_max
		coda_par()
		
		par("output_right")
		print "%3.2f e-/DIT" % (Photons_object_cw)
		newline()
		print "%3.2f" % (SN_cw)
		newline()
		print "%3.2f e-/DIT/pix" % (Photons_max_dit)
		newline()
		print "%3.2f e-/DIT/pix" % (Photons_sky_max)
		coda_par()
		
		par("center")
		Temp = 'Fullwell_%s' % Detector
		Temp = Hawaii_conditions[Temp]
		#Temp1 = (Photons_object_cw + Photons_sky_cw)
		Temp1 = Photons_max_dit
		if Temp1 > Temp:
			Temp = "<font color=red>!! saturated !!</font>"
			emph(Temp)
		coda_par()
		
		par("center")
		print "The SNR and the object signal is calculated for one pixel in dispersion direction and %d pixel in spatial direction." % (N_pix + 0.5)
		coda_par()
		headline ('Signal-To-Noise plot', "1")
		image(Picture_web)
		par("ascii")
		link(Table_web, "ASCII-file")
#		coda_par()
		
