##^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
##PlotRow.py
##
##PURPOSE: 
##To plot the a row of a given frame, or a subrow
##
##INPUTS:
##	FitsFileName - The name of the fits file to be used to 
##	Row	     - The Row of the pixel
## 	ReadNum	     - The Read of the exposure from which to take the row
##KEYWORDS:
##	SaveImg      - 0 - Don't save the image
##		       1 - Save the image
##	UseRef	     - 0 - Don't include the reference pixel ramp plot
##		     - 1 - Include the reference pixel ramp plot
##      XSTART    = X start coordinate for region of interest
##      XSTOP     = X stop coordinate for region of interest
##
##CALLING SEQUENCE:
##________
##      run PlotRamp.py [FitsFileName] Row Col
##
##EXAMPLES:
##H1RG
##run PlotRow.py /nfs/slac/g/ki/ki03/lances/H1RG-022/LEACH/2007Nov14/Flat/G_Flat_2.fits 200 --UseRef=1
##H2RG
##run PlotRow.py '/nfs/slac/g/ki/ki03/lances/H2RG-32-147/ASIC/07Dec19/HD82780/ForwardBiasedResets_Blank_H2RG_SIPIN_1_Reads_Dec20_2007_05_15_47.fits' 712 0 --XStart=960 --XStop=1200

##
##//////////////////////////////////////////////////////////////
##SETUP:
execfile('/afs/slac/u/ki/lances/python/python_HxRG/HxRG_Setup.py')
from HxRG_Class import *
from PathFromFileName import *

#Set Up for plotting
PlotFile='/afs/slac/u/ki/lances/python/SPIEPlotSettings.py'
if os.path.exists(PlotFile) : execfile(PlotFile)

#Get the filename and options from command line
FitsFileName = sys.argv[1]
Row          = int(sys.argv[2])
ReadNum	     = int(sys.argv[3])

#Figure out some parameters based on the file name
BaseName  = os.path.basename(FitsFileName)
DirName   = os.path.dirname(FitsFileName)
Fullpath  = os.getcwd()
BaseParts = BaseName.split('.')
BaseKey   = BaseParts[0]
CFac, DetSt, ElecSt, RootDir, ReducedDir = PathFromFile(FitsFileName)
PlotDir      = '/nfs/slac/g/ki/ki03/lances/'+DetSt+'/Plots/Ramps/'

#Form the class that will contain the necessary info
HxRG = HxRG_C(FitsFileName=FitsFileName)
HxRG.Get_Raw_Header(FitsFileName)

##PARSE KEYWORDS
keywords    = ['SaveImg=','UseRef=', 'XStart=', 'XStop=']
XStart      = 0
XStop	    = HxRG.NAxis1
SaveImg     = 0
UseRef      = 0
opts, extraparams = getopt.getopt(sys.argv[4:],'',keywords)
for o,p in opts:
  if o in ['--SaveImg']:
    SaveImage =int(p)
  elif o in ['--UseRef']:
    UseRef = int(p)
  elif o in ['--XStart']:
    XStart =int(p)
  elif o in ['--XStop']:
    XStop  =int(p)

##OPEN THE FITS FILE AND GET THE PIXEL VALUES
FitsHDU      = pyfits.open(FitsFileName)
FitsHeader   = FitsHDU[0].header
HxRG.Get_Raw_Header(FitsFileName)

##Get Just the Row 
if HxRG.NAxis == 2:
  ThisRow = FitsHDU[0].section[Row,XStart:XStop]+HxRG.BZero
else:
  ThisRow = FitsHDU[0].section[ReadNum,Row,XStart:XStop]+HxRG.BZero

##Plot the ramp
if UseRef == 0 :
  mplot.clf()
  mplot.plot(ThisRow, 'k')
  mplot.title(strip_sc(BaseName), fontsize=10)

