##^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
#Astrometry_DAOFind.py
#
#PURPOSE:
#  To locate sources in a slopefitted file from one of the HxRG 
#  detectors as an alternative to StarFind 
#
#  The text file contains the positions of the stars found and can be used as 
#  input to Astrometry_CCXYMatch.py after 3 reference points have been picked
#  and put into [FitsFileName]RefPoints.txt.
#
#  Also, if TvFlag==1, interactive mode is entered and you can use the 
#  examine functions from IRAF to looks at the FWHM of the stars.  If 
#  you do this, make sure ds9 is already open.
#
#INPUTS:
#  FitsFileName: string
#     The full path to the fits file that will be examined.
#
#OUTPUTS:
#  CoordFileName: string
#     The coordinates are written to a file called [FitsFileName].coo
# 
#KEYWORDS:
#  TvFlag: int
#          0 - Don't plot or display
#          1 - Display and offer user imexamine
#  OverRide: int    
#	   0 - Don't overwrite the existing .coo or .mag files
#          1 - Overwrite the files
#  OverWrite: int   
#	   0 - Read the paramters from the existing .par files
#          1 - Rewrite the parameter files with the values in this file
#  FWHM: float
#    Full Width at Half Max 
#  Sky:float
#    Average value of the sky
#  DataMin: float                    
#    Minimum value for acceptable data
#  DataMax: float
#    Maximum value for acceptable data
#  Gain: float
#    e-/ADU
#  ReadNoise: float
#    Readnoise for a single
#  BackSig: float
#    Background Sigma
#  NumReads: int                     
#    Number of reads in the ramp
#  NumFiles: int
#    Number of files used to make dither 
#
#NOTE:
#  It seems that giving a small FWHM is preferable to a large one in order
#  to identify a wide range of stars.
#
#EXAMPLES:
#  from Astrometry_DAOFIND import *
#
#  R=Astrometry_DAOFind('/nfs/slac/g/ki/ki04/lances/H2RG-32-147/ASIC/Reduced/07Dec18/NGC2395/SaturationRamp_I_H2RG_SIPIN_20_Reads_Dec19_2007_04_44_16_I_RPS_SlopeFlatFielded.fits[0]')
#
##SETUP:
execfile('/afs/slac/u/ki/lances/python/python_HxRG/HxRG_Setup.py')
from HxRG_Class import *
import pdb

def Astrometry_DAOFind(FitsFileName, TvFlag=0, OverRide=0, OverWrite=0,\ 
  FWHM=5.5                   #Full Width at Half Max 
  Sky       = 35.0                #Average value of the sky
  DataMin   = 10                    #Minimum value for acceptable data
  DataMax   = 20000               #Maximum value for acceptable data
  Gain      = 5.8                   #e-/ADU
  ReadNoise = 8.00                  #Readnoise for a single
  BackSig   = 10.00                  #Background Signal
  NumReads  = 1                     #Number of reads in the ramp
  NumFiles  = 1.0                   #Number of files used to make dither 
  Gain      = NumFiles*Gain         #If N images are averaged, Gain=N*Gain
  print 'Using FWHM of ' + str(FWHM)

  
  #Form the class that will contain the necessary info
  HxRG = HxRG_C(FitsFileName=FitsFileName)
  
  #Read in the array
  HxRG.Get_Raw_Header(FitsFileName.replace('[0]',''))
  Im = pyfits.getdata(FitsFileName.replace('[0]',''))
  
  #Create Names for the Output Files
  CoordListName      = HxRG.RedObjectDir+'Astrometry/'+HxRG.RawObjectKey+'.coo'
  CenterParsFileName = HxRG.RedObjectDir+'Astrometry/'+HxRG.RawObjectKey+\
                       '_Center.par'
  FitSkyParsFileName = HxRG.RedObjectDir+'Astrometry/'+HxRG.RawObjectKey+\
                       '_FitSky.par'
  FindParsFileName   = HxRG.RedObjectDir+'Astrometry/'+HxRG.RawObjectKey+\
                       '_Find.par'
  DataParsFileName   = HxRG.RedObjectDir+'Astrometry/'+HxRG.RawObjectKey+\
                       '_DataPar.par'
  DAOFindFileName    = HxRG.RedObjectDir+'Astrometry/'+HxRG.RawObjectKey+\
                       'DAOFind.coo'
  
  #Import the good packages from IRAF
  iraf.digiphot(_doprint=0)
  iraf.daophot(_doprint=0)
  iraf.apphot(_doprint=0)
  
  #PARAMETERS in the various files
  datapars   = iraf.datapars.getParList()
  daopars    = iraf.daopars.getParList()
  findpars   = iraf.findpars.getParList()
  centerpars = iraf.centerpars.getParList()
  
  #KEY PARAMETERS Paramters to use
  FWHM      = 5.5                   #Full Width at Half Max 
  Sky       = 35.0		  #Average value of the sky
  DataMin   = 10                    #Minimum value for acceptable data
  DataMax   = 20000		  #Maximum value for acceptable data
  Gain      = 5.8                   #e-/ADU
  ReadNoise = 8.00                  #Readnoise for a single
  BackSig   = 10.00                  #Background Signal
  NumReads  = 1                     #Number of reads in the ramp
  NumFiles  = 1.0                   #Number of files used to make dither 
  Gain      = NumFiles*Gain         #If N images are averaged, Gain=N*Gain
  print 'Using FWHM of ' + str(FWHM)
  
  #CENTERPARS #############################################################
  if OverWrite == 1 or not os.path.exists(CenterParsFileName) :
    iraf.centerpars.setParam('calgorithm','centroid')  #Recommended for first pass
    iraf.centerpars.setParam('cbox', 3.5*FWHM)      #Centroiding box
    iraf.centerpars.setParam('cthreshold','0')
    iraf.centerpars.saveParList(filename=CenterParsFileName)
  else :
    iraf.centerpars.setParList(ParList=CenterParsFileName)
  
  #SkyPARS ################################################################
  if OverWrite == 1 or not os.path.exists(FitSkyParsFileName) :
    iraf.fitskypars.setParam('salgorithm','mode')
    iraf.fitskypars.setParam('skyvalue', Sky)
    iraf.fitskypars.setParam('annulus',  4.*FWHM)
    iraf.fitskypars.setParam('dannulus', 2.*FWHM)
    iraf.fitskypars.saveParList(filename=FitSkyParsFileName)
  else:
    iraf.fitskypars.setParList(ParList=FitSkyParsFileName)
  
  #FINDPARS ##############################################################
  if OverWrite == 1 or not os.path.exists(FindParsFileName) :
    iraf.findpars.setParam('threshold',  5.0)
    iraf.findpars.setParam('sharphi',    0.5)	#0.5-1.0 likely cosmic ray, bad
    iraf.findpars.setParam('roundhi',    0.8)
    iraf.findpars.setParam('roundlo',   -0.8)
    iraf.findpars.saveParList(filename=FindParsFileName)
  else :
    iraf.findpars.setParList(ParList = FindParsFileName)
  
  #DATAPARS -#############################################################
  if OverWrite == 1 or not os.path.exists(DataParsFileName) :
    iraf.datapars.setParam('fwhmpsf', FWHM)       #FWHM of biggest star
    iraf.datapars.setParam('sigma',   BackSig)    #Std. Dev of sky pixels
    iraf.datapars.setParam('datamin', DataMin)    #Min good data value ~Sky-3Sigma
    iraf.datapars.setParam('datamax', DataMax)    #Max good data value
    iraf.datapars.setParam('epadu',   Gain)       #e- per ADU; calculated above
    iraf.datapars.setParam('readnoise', ReadNoise)#readnoise
    #KEYWORDS IN FITSHEADER
    iraf.datapars.setParam('exposure','ITIME')    #Integration time
    iraf.datapars.setParam('airmass', 'AIRMASS')  #Airmass at middle
    iraf.datapars.setParam('filter', 'FILTER')    #Filter used
    iraf.datapars.setParam('obstime','UTMID')     #UT at middle
    iraf.datapars.saveParList(filename=DataParsFileName)
  else:
    iraf.datapars.setParList(ParList=DataParsFileName)
  
  ########################################################################
  ########################################################DAOFIND
  #Set up daofind to go without prompting for input
  iraf.daofind.setParam('image',FitsFileName)             #Set ImageName
  iraf.daofind.setParam('verify','no')                    #Don't verify
  iraf.daofind.setParam('interactive','no')               #Interactive
  iraf.daofind.saveParList(filename=HxRG.PhotDir+HxRG.ObjectName+'_'+HxRG.Filter+\
       '_daofind.par')
  
  #If the output file exists, overwrite it
  if os.path.isfile(DAOFindFileName) and OverRide==1:
     os.remove(DAOFindFileName);
  iraf.daofind.setParam('output',DAOFindFileName)  #Output File
  
  #Run DAOFIND once unless OverRide = 1
  #iraf.daofind.setParam('graphics', 'stdgraph')
  #iraf.daofind.setParam('display', 'display(image=\'$1\',frame=$2)')
  print 'Running DAOFIND'
  daostring=iraf.daofind(mode='h',Stdout=1)
  
  #Mark the centroids on the image if TvFlag = 1
  if TvFlag >= 1:
    MaxDisp = Im.mean()+3*Im.std()
    if long(MaxDisp) == 0: MaxDisp = 50
    iraf.set(stdimage=HxRG.StdImage)
    iraf.display(FitsFileName,1,z1=0,z2=MaxDisp,zrange='no')
    if os.path.exists(DAOFindFileName):
       iraf.tvmark(1, DAOFindFileName, color=205)
       #iraf.tvmark(1, CoordListName, color=204)
       iraf.imexamine()

  return 1
