#!/usr/bin/env python3
#
#
'''
.. module:: mhfit
   :synopsis: holzerfit on summed spectrum  
.. moduleauthor:: Cor de Vries <c.p.de.vries@sron.nl>

'''

import sys,os
import numpy

import matplotlib
if __name__ == "__main__":
   matplotlib.use('GTK3Agg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

from tesfdmtools.utils.widgets.filechooser import getfile
from tesfdmtools.methods.holzerv import holzerfit,holzer
from tesfdmtools.utils.fiterrplot import fiterrplot
from tesfdmtools.utils.tesfdm_defaults import Tesfdm_Defaults

def readspectrum(fnam):
   ff=open(fnam,'r')
   nn=1000
   energy=numpy.zeros(nn,dtype=float)
   counts=numpy.zeros(nn)
   i=0
   for line in ff:
      ll=line.strip(' \n')
      if ll[0] != '#':
         its=ll.split()
         energy[i]=its[0]
         counts[i]=its[1]
         i=i+1
   ff.close()
   energy=energy[:i]
   counts=counts[:i]
   return (energy,counts)

#=======================================================================
if __name__ == "__main__":

   defs=Tesfdm_Defaults() 

   sfile=getfile(path=defs.get_filepath('lst'),pattern='Summed_spectrum_*.txt')
   if sfile == '':
      sys.exit()
   defs.set_filepath(sfile)
   fnam=os.path.basename(sfile).rsplit('.',1)[0]
   
   energy,counts=readspectrum(sfile)
   
   ppp=holzerfit(energy,counts.astype(int))                           # fit total spectrum
   holy=holzer(ppp,energy)                                           # fitted function
   yrr=numpy.sqrt(counts)                                          # 1-sigma errors
   yerr=numpy.where(yrr <= 0.0,1.0,yrr)                           # for zero counts insert one-count error
   gfwhmtxt="%5.5s %12.4g +/- %12.4g (eV)" % ("Gfwhm: ",(ppp[4]*1000.0),(ppp[11]*1000.0))  # FWHM + 1-sigma error
   lfwhmtxt="%5.5s %12.4g +/- %12.4g (eV)" % ("Lfwhm: ",(ppp[3]*1000.0),(ppp[10]*1000.0))  # FWHM + 1-sigma error
#   sttt="Average resolution for all pixels %5.5s %12.4g +/- %12.4g (eV)" % \
#        ("FWHM: ",(ppp[3]*1000.0),(ppp[9]*1000.0))
#   sfiletxt['total']='\n\n'+' '.join(sttt.split())
#   sfiletxt['totct']='\nTotal counts: %d' % (numpy.sum(counts))
   ptxt=' '.join(gfwhmtxt.split())+'\n'
   ptxt=ptxt+' '.join(lfwhmtxt.split())+'\n'
   ptxt=ptxt+( "%d counts\n" % (numpy.sum(counts)) )
   ptxt=ptxt+( "C-stat: %5.1f\n" % ppp[5] )
   ptxt=ptxt+( "degs of frdm: %d\n" % ppp[6] )
   
   pdf=PdfPages(fnam+'.pdf')
   plt.suptitle(fnam,size=12)
   splot=plt.subplot2grid((2,1), (0,0) )
   fiterrplot(energy,counts,yerr,holy,\
              xtitle="Energy (keV)",ytitle="Counts",ptitle="Holzerfit",ptxt=ptxt,pltax=splot)
              
   fpage = plt.gcf()
   fpage.set_size_inches(8.27, 10.75)
   plt.tight_layout()
   plt.subplots_adjust(top=0.94)
   plt.savefig(pdf,format='pdf',papertype='a4')
   plt.show()
   plt.close('all') 
   pdf.close() 
      
