;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
;plot_neg_persistence
;
;PURPOSE:
;  To plot areas of the HxRG detector that have been afflicted by 
;  negative persistence. This script accepts a .fits file that 
;  contains the negative persistence effect as well as a .fits file
;  that contains the saturation area that caused it 
;
;INPUTS:
;  NegFileName: string
;	The name of the .fits file that contains the persistence
;  SatFileName: string
;	The name of the .fits file that contains the saturation that induced
;	the persistencein NegFileName
; 
;KEYWORDS:
;  MODE:
;	0 - Plot both persistence ramp with negative persistence (NP), positive 
;	    persistence (PP), and sky (Sk) pixels
;	1 - Plot 9 pixels out from the central persistence core
;
;  XPPPIX, YPPPIX: int
;	  - the x and y pixel values that contain positive persistence
;  XNPPIX, YNPPIX: int
;	  - the x and y pixel values that contain negative persistence
;  XSKPIX, YSKPIX: int
;         - the x and y pixel values that contain sky values persistence
;  BIASSUB: int
;	0 - Don't subtract the first read
;	1 - Subtract the first read
;  ATTFIT: int
;       0 - Don't attempt to fit the persistence curve
;       1 - Attempt to fit the persistence curve
;  LASTREAD: int
;       The last read to include on the plot.
;  HORIZONTAL: int
;       0 - Plot a row of pixel in mode 1
;       1 - Plot a column of pixels in mode 0
;  LEGENDLOC: int
;       0 - Legend in top left
;       1 - Legend in bottom left
; 	  	
;EXAMPLES:
;m36=============
;plot_neg_persistence_xRG, '/nfs/slac/g/ki/ki04/lances/H1RG-022/LEACH/2007Nov13_2/M36/M36_Yfilter_200_1_0_-20_20.fits', '', xpppix = 532, ypppix = 685, xnppix = 540, ynppix = 683, mode=0
;plot_neg_persistence_xRG, '/nfs/slac/g/ki/ki04/lances/H1RG-022/LEACH/2007Nov13_2/M36/M36_Yfilter_200_1_0_-20_20.fits', '', xpppix = 532, ypppix = 685, xnppix = 523, ynppix = 684, mode=0,tvflag=1
;
;SUPER LONG RAMP ======================
;plot_neg_persistence_xRG, '/nfs/slac/g/ki/ki04/lances/H1RG-022/ASIC/07Nov19/SAO5417_I_NegPerDark_H1RG_SIPIN_2500_Reads_Nov19_2007_22_45_50.fits','', mode = 0, date='07Nov19'
;plot_neg_persistence_xRG, '/nfs/slac/g/ki/ki04/lances/H1RG-022/ASIC/07Nov19/SAO5417_I_NegPerDark_H1RG_SIPIN_2500_Reads_Nov19_2007_22_45_50.fits','',mode=0
;plot_neg_persistence_xRG, '/nfs/slac/g/ki/ki04/lances/H1RG-022/ASIC/07Nov19/SAO5417_I_NegPerDark_H1RG_SIPIN_2500_Reads_Nov19_2007_22_45_50.fits','',mode=0, xnppix = 343, ynppix=266, xpppix=336, ypppix = 261,xskpix=336,yskpix=260
;
;plot_neg_persistence_xRG, '/nfs/slac/g/ki/ki04/lances/H1RG-022/ASIC/07Nov19/SAO5417_I_NegPerDark_H1RG_SIPIN_2500_Reads_Nov19_2007_22_45_50.fits','',mode=1, xpppix=336, ypppix = 261, horizontal=1
;plot_neg_persistence_xRG, '/nfs/slac/g/ki/ki04/lances/H1RG-022/ASIC/07Nov19/SAO5417_I_NegPerAfterDark_H1RG_SIPIN_2500_Reads_Nov19_2007_23_20_46.fits','',mode=1, xpppix=336, ypppix = 261, horizontal=1

;GREAT COSMIC RAY CHARGE LOSS!!!
;plot_neg_persistence_xRG, '/nfs/slac/g/ki/ki04/lances/H1RG-022/ASIC/07Nov19/SAO5417_I_NegPerDark_H1RG_SIPIN_2500_Reads_Nov19_2007_22_45_50.fits','', mode = 0, date='07Nov19', xnppix = 4, ynppix = 645, xpppix = 8, ypppix = 644 ,xskpix=4,yskpix=644
;
;Last - Minus - First files
;ds9 /nfs/slac/g/ki/ki04/lances/H1RG-022/ASIC/Reduced/07Nov19/SAO5417/SAO5417_I_NegPerDark_H1RG_SIPIN_2500_Reads_Nov19_2007_22_45_50LMF.fits &
;
;NGC419=================================
;plot_neg_persistence_xRG, '/nfs/slac/g/ki/ki04/lances/H1RG-022/ASIC/07Nov19/NGC7419_I_Dither2_20ArcSecondsEast_20ArcSecondsNorth_H1RG_SIPIN_100_Reads_Nov19_2007_21_02_37.fits', '', xpppix=399, ypppix = 469, xnppix= 402, ynppix = 466, xskpix = 396, yskpix=469, mode=0
;
;NGC956
;plot_neg_persistence_xrg, '/nfs/slac/g/ki/ki04/lances/H2RG-32-147/ASIC/07Dec19/NGC956/DarksAfter_20_ReadsSaturation_G_1Rsts_H2RG_SIPIN_10_Reads_Dec19_2007_21_04_38.fits', '', xpppix=887, 370, mode=1, tvflag=1
;
;WINDOW FILES==========================
;plot_neg_persistence_xRG, '/nfs/slac/g/ki/ki04/lances/H2RG-32-147/ASIC/07Dec19/HD53791/HD53791_Dark_H2RG_SIPIN_OneWindow2000_Reads_Dec20_2007_00_54_25.fits', '', xpppix=79, ypppix=65, mode=1, tvflag=1
;plot_neg_persistence_xRG, '/nfs/slac/g/ki/ki04/lances/H2RG-32-147/ASIC/07Dec19/HD53791/HD53791_Dark_H2RG_SIPIN_OneWindow500_Reads_Dec20_2007_02_57_22.fits', '', xpppix=75, ypppix=64, mode=1, tvflag=1, horizontal=1
;
;THESIS PLOT RADIAL PERSISTENCE:
;  plot_neg_persistence_xRG, '/nfs/slac/g/ki/ki04/lances/H1RG-022/ASIC/07Nov19/SAO5417_I_NegPerDark_H1RG_SIPIN_2500_Reads_Nov19_2007_22_45_50.fits','',mode=1, horizontal=1,tvflag=2, xpppix=336, ypppix=271, /savefig 
pro plot_neg_persistence_xrg, NegFileName, SatFileName, $
	XNPPix=XNPPix, YNPPix = YNPPix, $
	XPPPix=XPPPix, YPPPix = YPPPix, $
        XSkPix=XSkPix, YSkPix = YSkPix, $
	TvFlag = TvFlag, Mode = Mode, Date = Date,$
	BiasSub = BiasSub, AttFit=AttFit, $
        UseRef = UseRef, LastRead=LastRead, $
        Horizontal = Horizontal, LegendLoc=LegendLoc, SaveFig=SaveFig

;Include all the keywords from the KeywordStruct.pro file
FitsFileName = NegFileName

Common KeyParams, KeyStr
@KeywordStruct_xRG.pro
@PlotSettings_xRG.pro

;Declare the pixel values that will be used for the positive and negative persistence  
If N_Elements(XNPPix)     eq 0  then XNPPix     = 512
If N_Elements(YNPPix)     eq 0  then YNPPix     = 450
If N_Elements(XPPPix)     eq 0  then XPPPix     = 771
If N_Elements(YPPPix)     eq 0  then YPPPix     = 852
If N_Elements(XSkPix)     eq 0  then XSkPix     = 690
If N_Elements(YSkPix)     eq 0  then YSkPix     = 400
If N_Elements(Mode)       eq 0  then Mode       = 1
If N_Elements(TvFlag)     eq 0  then TvFlag     = 0
If N_Elements(Leach)	  eq 0  then Leach      = 0
If N_Elements(BiasSub)    eq 0  then BiasSub    = 0
If N_Elements(AttFit)     eq 0  then AttFit     = 0
If N_Elements(UseRef)     eq 0  then UseRef     = 0
If N_Elements(Horizontal) eq 0  then Horizontal = 0
If N_Elements(LegendLoc)  eq 0  then LegendLoc  = 0 
If N_Elements(SaveFig)    eq 0  then SaveFig    = 0
If SatFileName		eq '' then PlotSat  = 0 $
   			      else PlotSat = 1
;Make the Common Block
Common KeyParams, KeyStr

;Read the Negative persistence file and get some info
Fits_Read, KeyStr.RawObjectPath, NoData, NH, /header_only
FileParams = Return_File_Params_xRG(KeyStr.RawObjectPath)

;Get the absolute coordinates if a window mode file is used
If KeyStr.WindowMode then begin
   XNPix = XPPPix - KeyStr.XWindowStart(0)
   YNPix = YPPPix - KeyStr.YWindowStart(0)
EndIf

;Get the exposure time in the negative persistence image
FrameNTime = KeyStr.FrameTime
INTime     = KeyStr.ITime

;*********************************************************************************
;DETERMINE MODE ******************************************************************
Case Mode of 
  0: begin ;**************************************PLOT THREE RAMPS, SKY, NEG, POS.

    ;Ramp of pixel exhibiting positive persistence
    Fits_read_datacube, KeyStr.RawObjectPath, ImPP, NH, $
	XStart = XPPPix, XStop = XPPPix, $
        YStart = YPPPix, YStop = YPPPix
    ;Ramp of pixel exhibiting negative persistence 
    Fits_read_datacube, KeyStr.RawObjectPath, ImNP, NH, $
        XStart = XNPPix, XStop = XNPPix, $
        YStart = YNPPix, YStop = YNPPix
    ;Ramp of pixel integrating skyflux 
    Fits_read_datacube, KeyStr.RawObjectPath, ImSk, NH, $
        XStart = XSkPix, XStop = XSkPix, $
        YStart = YSkPix, YStop = YSkPix
    
    ;subtract the bias if BiasSub==1
    If BiasSub then begin
       ImPP = Long(ImPP) - ImPP(0)
       ImNP = Long(ImNP) - ImNP(0)
       ImSk = Long(ImSk) - ImSk(0)
    EndIf

    ;If the Saturating image is requested, get the values
    If PlotSat then begin
      ;Get the info for the saturated ramp
      Fits_read_datacube, SatFileName, ImSPP, SH, $
        XStart = XPPPix, XStop = XPPPix, $ 
        YStart = YPPPix, YStop = YPPPix 
      Fits_read_datacube, SatFileName, ImSNP, SH, $ 
        XStart = XNPPix, XStop = XNPPix, $ 
        YStart = YNPPix, YStop = YNPPix 
      ;Ramp of pixel integrating skyflux  
      Fits_read_datacube, SatFileName, ImSSk, SH, $
        XStart = XSkPix, XStop = XSkPix, $ 
        YStart = YSkPix, YStop = YSkPix 
      ;Get the exposure and frame time for the saturation ramp 
      ISTime      = Double(SxPar(SH, 'ITIME'))
      SNaxis3     = Long(SxPar(SH, 'NAXIS3'))
      FrameSTime  = ISTime/SNaxis3
      STime       = IndGen(N_Elements(ImS))*FrameSTime
    EndIf
    
    ;Plot the Sky, PP, and NP pixels
    erase
    MinPlot   = Min([min(ImPP), min(ImNP), min(ImSk)])
    MinBSPlot = Min([min(ImPP-long(ImPP(0))), min(ImNP-long(ImNP(0))), $
		     min(ImSk-long(ImSk(0)))]) 
    MaxPlot   = Max([max(ImPP), max(ImNP), max(ImSk)])
    MaxBSPlot = Max([max(ImPP-long(ImPP(0))), max(ImNP-long(ImNP(0))), $
		     max(ImSk-long(ImSk(0)))])

    If BiasSub eq 1 then begin
       YTitle = 'Bias Subtracted ADU'
    endif else begin
       YTitle = 'ADU'
    endelse
    Plot, ImPP, Yrange = [MinPlot, MaxPlot], $
          XTitle = 'Read Number', $
          YTitle = YTitle , background = fsc_color('white'), $
          color=fsc_color('black'), position = [0.175, 0.10, 0.9250, 0.90], $
          /normal, xstyle = 8
    OPlot, ImNP, color=fsc_color('red')
    OPlot, ImSk, color=fsc_color('blue') 
    !p.noerase=1
    Axis, XAxis = 1, color=fsc_color('black'), xrange=[0, INTime], $
	  XStyle = 1, xtitle = 'Seconds'
    ItemsN = [Strtrim(XPPPix,2)+','+Strtrim(YPPPix,2), $
	     Strtrim(XNPPix,2)+','+Strtrim(YNPPix,2), $
	     Strtrim(XSkPix,2)+','+Strtrim(YSkPix,2)]
    ColorsN = [fsc_color('black'), fsc_color('red'), fsc_color('blue')]
    TextColorsN =[fsc_color('black'),fsc_color('black'),fsc_color('black')]
    PSymsN = [0,0,0]
    If LegendLoc eq 0 then begin 
      legend, ItemsN, PSym=PSymsN, Color=ColorsN, TextColors = TextColorsN 
    endif else begin
      legend, ItemsN, PSym=PSymsN, Color=ColorsN, TextColors = TextColorsN, $
      position = [0.7,0.25], /normal
    endelse
    if AttFit eq 1 then begin
       ReadTimes = (INTime/Keystr.NAxis3) * findgen(KeyStr.NAxis3) 
       Fit = 200.*(1-exp(-ReadTimes/10))+1000.*(1-exp(-ReadTimes/240))
       oplot, Fit, color = fsc_color('green'), linestyle = 2
     endif

    ;Write a .tif if TvFLAG == 1
    If KeyStr.TvFlag eq 1 then begin
       Img  = tvrd(true=3)
       Img24=reverse(Img,2)
       TVLCT, R, G, B, /Get
       Write_Tiff, KeyStr.PlotDir+KeyStr.RawObjectKey+'_3Curves.tif', $
         red=Img24(*,*,0), green=Img24(*,*,1), blue=Img24(*,*,2), $
         planarconfig=2, orientation=1, compression=0
    EndIf

    ;Plot the saturating ramps
    If PlotSat then begin
      Plot, ImS, Yrange = [Min(ImS)-100, Max(Ims)+100], $
	  xstyle = 4, ystyle = 4, $
          color = fsc_color('black'), background = fsc_color('white'), $
          position = [0.125, 0.10, 0.90, 0.90], $
          /normal, XRange = [0, INTime]
      Axis, YAxis = 1, color=fsc_color('black'), $
	  yrange=[Min(ImS)-100, Max(ImS)+100], $
          ystyle =1, YTitle = 'ADU in First Ramp'
    EndIf 

    ;Write a PNG if KeyStr.TvFLAG == 3
    !P.Noerase = 0
    If KeyStr.TvFlag eq 3 then begin
           PNGFileName = KeyStr.PlotDir+KeyStr.RawObjectKey+'_3Curves.png'
           PNGImg      = tvrd()
           tvlct, reds, greens, blues, /get
           write_png, PNGFileName, PNGImg, Reds, Greens, Blues
           stop
     EndIf
 
  end
  1: begin ;**************************PLOT 9 pixels out from core
    if KeyStr.TvFlag eq 2 then begin
      EPSName = KeyStr.PlotDir+KeyStr.RawObjectKey+$
         'RadialNegPersistPlot'+strtrim(XPPPix,2)+'_'+$
          strtrim(YPPPix,2)+'.eps'
      device, filename=EPSName, $
      bits_per_pixel=8, /encapsul, ysize=5.00, xsize=8.0,/inches
      !p.charsize=1.4
      !p.charthick=3.8
      device, set_font='Times-Roman'
    endif
    if KeyStr.TvFlag eq 1 then begin
      !p.charsize=1.5
      !p.charthick=3
    endif 
    ;Ramp of pixel exhibiting positive persistence
    if Horizontal eq 1 then begin
      NumPix     = 10
      Fits_read_datacube, KeyStr.RawObjectPath, Im, NH, $
        XStart = XPPPix, XStop = XPPPix+NumPix-1, $
        YStart = YPPPix, YStop = YPPPix
      ImB      = Long(Im(*,0,0))
      XPixVals = Indgen(NumPix)+XPPPix
      YPixVals = Intarr(NumPix)+YPPPix
    endif else if Horizontal eq 0 then begin
      NumPix     = 10
      Fits_read_datacube, KeyStr.RawObjectPath, Im, NH, $
        XStart = XPPPix, XStop = XPPPix, $
        YStart = YPPPix, YStop = YPPPix+NumPix-1
      ImB      = Long(Im(0,*,0))     
      XPixVals = Intarr(NumPix)+XPPPix
      YPixVals = Indgen(NumPix)+YPPPix     
    endif else begin
      Fits_read_datacube, KeyStr.RawObjectPath, Im, NH, $
        XStart = XPPPix-1, XStop = XPPPix+1, $
        YStart = YPPPix-1, YStop = YPPPix+1
      ImB      = Long(Im(*,*,0))
      NumPix   = 9
      XPixVals = XPPPix+(Indgen(NumPix) mod 3) - 1
      YPixVals = YPPPix+(Indgen(NumPix)/3) - 1
    endelse

    NumReads = Long(SxPar(NH, 'NAXIS3'))
    if N_Elements(LastRead) eq 0 then LastRead = NumReads
    ImMB     = LonArr(NumPix,1,NumReads)

    ;Subtract the bias if necessary
    if BiasSub eq 0 then ImB(*,*,*)= 0

    For ReadNum = 0, NumReads-1 do begin
      If Horizontal eq 1 then begin
        For PixNum = 0, NumPix-1 do begin
          ImMB(PixNum,0,ReadNum) = Im(PixNum,0,ReadNum)-ImB(PixNum,0,0)
        EndFor
      EndIf else if Horizontal eq 0 then begin
        For PixNum = 0, NumPix-1 do begin
          ImMB(PixNum,0,ReadNum) = Im(0,PixNum,ReadNum)-ImB(0, PixNum, 0)
        EndFor
      Endif Else Begin
        For PixNum = 0, NumPix-1 do begin
          ImMB(PixNum, 0, ReadNum) = Im(PixNum/3,PixNum mod 3,ReadNum)-ImB(PixNum/3, PixNum mod 3, 0)
        EndFor
      EndElse
    EndFor

    ;Subtract the reference pixels if necessary    
    If UseRef eq 1 then begin
      RefRamp = Return_RefPix_xRG(KeyStr.RawObjectPath, 4, Col = XPPPix, Row = YPPPix)
      RefRamp = RefRamp-RefRamp(0)
      For PixNum = 0, NumPix - 1 do begin
        ImMB(PixNum, 0, *) = ImMB(PixNum, 0, *) - RefRamp
      EndFor
    EndIf

    MinImMB    = Min(ImMB(*,0,0:LastRead-1))
    MaxImMB    = Max(ImMB(*,0,0:LastRead-1))
    Items      = StrArr(NumPix)
    PSyms      = LonArr(NumPix)
    TextColors = LonArr(NumPix)
    PColors    = LonArr(NumPix) 
    LThicks    = LonArr(NumPix)
    LStyles    = LonArr(NumPix) 
    Plot, [0,0], /nodata, background = fsc_color('white'), $
	yrange = [MinImMB, MaxImMB], xrange = [0, LastRead], $
        color  = fsc_color('black'), xtitle ='Read Number', $
	ytitle = 'Bias Subtracted ADU', $
        position = [0.14, 0.12, 0.77, 0.90], /normal, xstyle = 8 
    Axis, XAxis = 1, color=fsc_color('black'), xrange=[0, INTime], $
          XStyle = 1, xtitle = 'Seconds'
    For PixNum = 0, NumPix-1 do begin
      oplot, ImMB(PixNum, 0, *), color = ColorNum.ColorNums(PixNum+1)
      ;Items(PixNum)      = 'Rad ' + Strtrim(PixNum, 2)
      Items(PixNum)      = Strtrim(XPixVals(PixNum),2)+' , '+ $
                           Strtrim(YPixVals(PixNum),2)
      PColors(PixNum)    = ColorNum.ColorNums(PixNum+1)
      TextColors(PixNum) = fsc_color('black')
      PSyms(PixNum)      = 0  
      LThicks(PixNum)	 = 6
      LStyles(PixNum)    = 0
    EndFor
    if LegendLoc eq 0 then begin
      legend, Items, Color = PColors, TextColor = TextColors, PSym = PSyms, $
       position = [0.78, 0.9], /normal, Thick = LThicks, LineStyle = LStyles, $
       number = 0, box=0, pspacing=1.5
    endif else begin
      legend, Items, Color = PColors, TextColor = TextColors, PSym = PSyms, $
       position = [0.78, 0.9], /normal, Thick = LThicks, LineStyle = LStyles, $
       number = 0, box=0, pspacing=1.5
    endelse
    ;Put the temperature and VSUB on the plot  
    xyouts, 0.81,0.35, 'Temp = '+strtrim(long(KeyStr.DetTemp),2)+ ' K', $
           color=fsc_color('black'), /normal
    xyouts, 0.81,0.27, 'VSUB = '+strtrim(long(round(KeyStr.VSUB)),2)+ ' V', $
           color=fsc_color('black'), /normal
    ;Plot a .png and a .tif if TvFLAG==3
    If KeyStr.TvFlag eq 1 or KeyStr.TvFlag eq 3 and SaveFig eq 1 then begin
      TiffName = KeyStr.PlotDir+KeyStr.RawObjectKey+$
         'RadialNegPersistPlot'+strtrim(XPPPix,2)+'_'+$
          strtrim(YPPPix,2)
      Img = tvread(/tiff, FileName = TiffName, /nodialog)
      print, 'File written to : ' + TiffName 

      PNGName = KeyStr.PlotDir+KeyStr.RawObjectKey+$
         'RadialNegPersistPlot'+strtrim(XPPPix,2)+'_'+$
          strtrim(YPPPix,2)
      Img = tvread(/png, FileName = PNGName, /nodialog)
      Print, 'File written to : ' + PNGName
    EndIf else if KeyStr.TvFlag eq 2 then begin
      device, /close
    EndIf 
    stop

  end
  2: begin
    ;Plot just the persistent ramp
    ;Get info for single pixel of window mode or negative persistence image
    Fits_read_datacube, KeyStr.RawObjectPath, ImN, NH, $
        XStart = XPix, XStop = XPix, $
        YStart = YPix, YStop = YPix 
    Plot, ImN, Yrange = [Min(ImN), Max(ImN)], $
          XTitle = 'Read Number', $
          YTitle = 'ADU in Second Ramp' , background = fsc_color('white'), $
          color=fsc_color('black'), position = [0.125, 0.10, 0.90, 0.90], $
          /normal, xstyle = 8, ystyle = 8
    !p.noerase=1
    XYOuts, 0.3, 0.75, 'Signal for Pixel '+Strtrim(Xpix,2)+' , '+Strtrim(YPix,2), $
          /normal, color=fsc_color('black')
    Axis, XAxis = 1, color=fsc_color('black'), xrange=[0, INTime], XStyle = 1, $
          xtitle = 'Seconds'
    stop
  end
endcase

stop

end
