import pyfits
import os,sys
import time

#source pour Python 2.7

# recuperer Python 2.7 ici:   http://www.python.org/download/releases/2.7.6/
# attention, il faut garder la coherence entre python et les package. C'est 32 bit ou 63 bit au choix.
# aller ici pour recuperer pyfits:   http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyfits


# return  [min,max]  entre les longeur d onde xmin,xmax
def foundMinMax(data,start,step,xmin,xmax):
	ixmin=int((xmin-start)/step)
	ixmax=int((xmax-start)/step)
	n=len(data)
	if (ixmin<0):
		ixmin=0
	if (ixmax<0):
		ixmax=0
	if (ixmin>=n):
		ixmin=0
	if (ixmax>=n):
		ixmax=n
	return [min(data[ixmin:ixmax]),max(data[ixmin:ixmax])]

def WriteDatFile(data,start,step):
	f=open(PathFileTmpDat,'w')
	wave=start
	for intensity in data:
		l=str(wave)+" "+str(intensity)+"\n"
		f.write(l)
		wave+=step
	f.close()
	
def WritePngFile(DstFile,title,xmin,xmax,ymin,ymax):
	print("DstFile: "+DstFile)
	print("Title: "+title)

	f=open(PathGnuplot+'gnuplotcmd.txt','w')
	l1="call 'C:\\\\gnuplot\\\\std.gnu' '"+PathFileTmpDat+"' '"+title+"' '"
	l1+=str(xmin)+":"+str(xmax)+"' '"+str(ymin)+":"+str(ymax)+"' '800,400' '"+DstFile+"'\n"
	l2="pause -1"
	f.write(l1)
#	f.write(l2)
	f.close()

	cmd=PathGnuplot+"binary\\pgnuplot.exe C:\gnuplot\gnuplotcmd.txt"
	print ("CMD = "+cmd)
	sortie=os.system(cmd)
	print(sortie)

# le programme commence ici	
#le repertoire contenant les fichiers .fits au format bess est dans le chemin courant et s apelle   web-xxxxx	
# verifie le nombre d'argument
if len(sys.argv)==2:
        filename=sys.argv[1]
        print "nom du repertoire: "+filename
else:
        print "nombre d'argument incorrect"
        print "utiliser un arguments 'nom de repertoire'"
        exit(1)

StatusDic={\
'BD+64 106':['Already publish<br>not in Bess','emission line signaled in Catalogue of Stellar Spectral Classifications (Skiff, 2009-2014)<br>a high resolution spectrum R=50k was acquired by C.Buil'],\
'HR 8107':['already in Bess as HD201836','discovered in 1989'],\
'BD+28 4177':['','a high resolution spectrum R=50k was acquired by C.Buil'],\
'BD+60 133':['','a high resolution spectrum R=50kwas acquired by C.Buil'],\
'BD+60 2523':['','a high resolution spectrum R=50k was acquired by C.Buil'],\
'HD 237126':['','a high resolution spectrum R=50k was acquired by C.Buil'],\

}

AltNameDic={'HR 8107':'HD201836'}
		
BasePath=sys.path[0].replace("\\","\\\\")+"\\\\"
dbSourcePath=BasePath+"web-"+filename
PathWeb=BasePath+"web-"+filename+"\\\\"
PathFileTmpDat=BasePath+"@.dat"

PathGnuplot="C:\\gnuplot\\"
WebPageFileName="auto-"+filename+".html"
WebTitle="Spectroscopic observation of "+filename

dirList= os.listdir(dbSourcePath)
dirList=sorted(dirList)
#efface les fichier .png present
for file in dirList:
	if (file.endswith(".png")):
		print "remove " + file
		os.remove(dbSourcePath+"\\"+file)


#la generation du code html commence ici
f=open(PathWeb+WebPageFileName,'w')
f.write("<html>\n<head>\n<title>Be search, Be candidate</title>\n")
f.write("""<meta http-equiv="content-type" content=" Text / html; Charset = ISO - 8859 - 1">""")
f.write("</head>\n<body>\n")
f.write("<H1>Be search survey</H1>\n")

f.write("Last update at "+time.strftime("%d/%m/%Y  %H:%M")+" from fits files. ")
f.write("Contact: thierry  dot  lemoult  arobase  gmail dot com<br>\n")
f.write("<H2>Introduction</H2>\n")
f.write('This page in a first attenpt to make a synthesis of a new Field: Be Search</br>')
f.write('<a href="http://www.spectro-aras.com/forum/viewforum.php?f=32"> ARAS Spectroscopy sub forum dedicated to Be Search</a><br>\n')
f.write("<H2>Be candidate list</H2>\n")

# tri des fichiers suivant la date d'observation
ListOrder=[]
for file in dirList:
	if (file.endswith(".fits") or file.endswith(".fit")):
		hdulist = pyfits.open(dbSourcePath+'/'+file)
		prihdr  = hdulist[0].header
		ListOrder=ListOrder+[(file,prihdr['OBJNAME']+prihdr['DATE-OBS'])]
ListOrder=sorted(ListOrder,key=lambda ListOrder:ListOrder[1])
dirList=[a[0] for a in ListOrder]
# fin du tri des fichiers


# creer un tableau resumant les observations
f.write("""<table border="1"cellpadding="0"cellspacing="1">\n""")
f.write("<tr><td>Name</td><td>Name2</td><td>Observation Date in UT</td><td>Status</td><td>Comment</td><td>Exposure</td><td>Instrument</td><td>fits file</td></tr>\n")
for file in dirList:
	hdulist = pyfits.open(dbSourcePath+'/'+file)
	prihdr  = hdulist[0].header
	try:
		exptime2=prihdr['EXPTIME2']
	except KeyError:
                try:
                        exptime2=str(prihdr['EXPTIME'])+"s"
                except KeyError:
                        exptime2='undefine'
	try:
		instrument=prihdr['BSS_INST']
	except KeyError:
		instrument=''
	
	f.write("<tr><td>"+prihdr['OBJNAME']+"</td>")
	
	# nom alternatif si definit
	try:
		altName=AltNameDic[prihdr['OBJNAME']]
	except KeyError:
		altName=''
	f.write("<td>"+altName+"</td>")

	f.write("<td>"+prihdr['DATE-OBS']+"</td>")

	# commentaire et statut si definit
	try:
		status=StatusDic[prihdr['OBJNAME']][0]
		comment=StatusDic[prihdr['OBJNAME']][1]
	except KeyError:
		status=''
		comment=''
	f.write("<td>"+status+"</td>")

	f.write("<td>"+comment+"</td>")
	f.write("<td>"+exptime2+"</td><td>"+instrument+"</td><td><a href=\""+file+"\">"+file+"</a></td><tr>\n")
	
f.write("<tr><td>HD 189847</td><td>HIP 98525</td><td></td><td>Already publish<br>not in Bess</td>\n")
f.write("<td>Robin , C.Buil realised HR<br>published here http://arxiv.org/abs/1409.4668</td><td></td><td></td><td>Waiting for Andrew spectrum</td>\n")

f.write("<tr><td>HD 181751</td><td>HIP 95109</td><td>2014-09-21</td><td></td>\n")
f.write("<td>Robin realised HR</td><td></td><td></td><td>Waiting for Andrew spectrum</td>\n")

f.write("<tr><td>HD192445</td><td>HIP99667</td><td></td><td></td>\n")
f.write("<td></td><td></td><td></td><td>Waiting for Andrew spectrum</td>\n")

f.write("</tr>")
f.write("</table><p>\n")

f.write('<h2>Biblio</h2>\n')
f.write('<li>The frequency of Be Stars, Jaschek, 1983 <a href="http://adsabs.harvard.edu/abs/1983A%26A...117..357J"> http://adsabs.harvard.edu/abs/1983A%26A...117..357J</a><br>\n')
f.write('<li>Classification of Be Stars, Jaschek, 1980 <a href="http://adsabs.harvard.edu/abs/1980A%26AS...42..103J"> http://adsabs.harvard.edu/abs/1980A%26AS...42..103J</a><br>\n')
f.write('<li> To be completed...\n')
f.write('\n')
f.write('<h2>Complete scan List</h2>\n')
f.write('<li><a href="BeCandidateFiles/B_list_Mag6-11_v1.00.xlsx">List currently used by Thierry Lemoult automated telescope, extracted from SIMBAD 6&lt;B mag &lt; 10.9</a>\n')
f.write('<li>List of non giant B stars ( V &lt; 10) from Simbad <a href="http://www.astronomie-amateur.fr/Documents%20Spectro/B_Cibles.xlsm"> http://www.astronomie-amateur.fr/Documents%20Spectro/B_Cibles.xlsm</a>\n')
f.write('<h2>List of already observed stars</h2>\n')
f.write('<li><a href="BeCandidateFiles/full_list_observed_star.txt">Thierry Lemoult automated telescope</a>\n')
f.write('<h2>Be Candidate spectrum plot</h2>\n')
#genere les graphiques	
f.write("""<table border="1"cellpadding="0"cellspacing="10">\n""")
i=0  #index unique pour les nom de fichier
for file in dirList:   # boucle sur les fichiers fits
	#recuperation des mots clef du fichier fits
	print "File name: "+file
	hdulist = pyfits.open(dbSourcePath+'/'+file)
	prihdr  = hdulist[0].header
	name=prihdr['OBJNAME']
 	dateObs=prihdr['DATE-OBS']
 	try:
                Instrument=prihdr['BSS_INST']
        except KeyError:
                Instrument='undefine'
	
	try:
		exptime2=prihdr['EXPTIME2']
	except KeyError:
		try:
                        exptime2=str(prihdr['EXPTIME'])+"s"
                except KeyError:
                        exptime2='undefine'
	
	try:
		resolStr=str(prihdr['BSS_ITRP'])
		
	except KeyError:
		resolStr="non definie"
		
	start=prihdr['CRVAL1']
	step=prihdr['CDELT1']
	nstep=prihdr['NAXIS1']
	print "longueur d onde [" + str(start) + " ... " +str(start+step*nstep)+"] "+prihdr['CUNIT1']
	print "************"

	#genere resume dans la premiere colonne.
	f.write("<tr>\n<td>\n")
	f.write("	<h3>"+name+"</h3>\n")
	f.write("	<ul><li>Date: "+dateObs[0:10]+" a "+dateObs[11:13]+"h"+dateObs[14:16]+" TU</li>\n")
	f.write("	<li>Exposure time: "+exptime2+"</li>\n")
	f.write("	<li>Instrument:"+Instrument+"</li>\n")
	f.write("	<li>Resolution: "+resolStr+"</li>\n")
        try:
                Site=prihdr['BSS_SITE']
        except KeyError:
                Site='undefined'
	f.write("	<li>Site: "+Site+"</li></ul>\n")
	f.write("	<p>Spectrum fits file link:<br><a href=\""+file+"\">"+file+"</a>\n</td>\n\n")
	

	
	WriteDatFile(hdulist[0].data,start,step)	
	titre=name+"   "+dateObs[0:10]+" "+dateObs[11:22]+"  "+Instrument+"  "+exptime2
	
	if (nstep*step>1000):  # si on couvre une large bande spectral, on fait des zoom...
		#definition des bandes a tracer
		graph=[[start+step*nstep/2.0,step*nstep/2.0,""],[6560,90,"Region Ha"]]
	else: # sinon on affiche juste tout le spectre
		graph=[[start+step*nstep/2.0,step*nstep/2.0,""]]
	
	for zoom in graph:
		i+=1
		lmin=zoom[0]-zoom[1]
		lmax=zoom[0]+zoom[1]
		regionTitle=zoom[2]
		if (lmin>=start*0.98 and lmax<=(start+step*nstep)*1.02):
			[Imin,Imax]=foundMinMax(hdulist[0].data,start,step,lmin,lmax)
			if (Imin<-1):
				Imin=0
			pngFileName=name+"_"+dateObs[0:10]+"_"+dateObs[11:13]+"h"+dateObs[14:16]+"m_"+regionTitle+"_"+str(i)+".png"
			#genere image
			WritePngFile(PathWeb+pngFileName,titre+" "+regionTitle,lmin,lmax,Imin,Imax)
			#insere le lien dans le  html
			f.write("	<td><img src = \""+pngFileName+"\" border=\"0\"></td>\n")

	f.write("</tr>\n\n\n")

# ferme le fichier html
f.write("</table></body>\n</html>\n")	
f.close()
	
