;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
;plot_conservation_persistence_xRG
;
;PURPOSE: 
;  To add up all of the signal in the box surrounding an area afflicted by 
;  negative persistence to see if Halo + Core = Background
;KEYWORDS:
;  Vertical:
;	0 - Plot the slideshow horizontally
;	1 - Plot the slideshow vertically
;  XPIX, YPIX:
;	  - the coordinates to center the box around
;  BOXSIZE:
;	  - the size of the box (BoxSize x BoxSize) to use as the region
;  XBOXOFF, YBOXOFF:
;	  - the offsets of the seconds
;  SHOWFRAMES: int
;       0 - Don't show the slideshow
;       1 - Show the slideshow
;M36 =================================
;  plot_conservation_persistence_xRG, '/nfs/slac/g/ki/ki03/lances/H1RG-022/LEACH/2007Nov13_2/M36/M36_Yfilter_200_1_0_-20_20.fits', xpix = 532, ypix = 685, /leach
; plot_conservation_persistence_xRG, '/nfs/slac/g/ki/ki03/lances/H1RG-022/LEACH/2007Nov13_2/M36/M36_Yfilter_200_1_0_-20_20.fits', xpix = 532, ypix = 685,yboxoff=100,xboxoff=0,tvflag=1,/leach
;
;SUPER LONG RAMP =====================
; plot_conservation_persistence_xRG, '/nfs/slac/g/ki/ki03/lances/H1RG-022/ASIC/07Nov19/SAO5417_I_NegPerDark_H1RG_SIPIN_2500_Reads_Nov19_2007_22_45_50.fits', date='07Nov19', xpix = 339, ypix = 264, xboxoff=0, yboxoff = 80, boxsize=80, tvflag = 1
;  plot_conservation_persistence_xRG, '/nfs/slac/g/ki/ki03/lances/H1RG-022/ASIC/07Nov17/Dark_15V_VSUB_H1RG_SIPIN_700_Reads_Nov18_2007_15_42_19.fits', date='07Nov19', xpix = 315, ypix = 400, xboxoff=0, yboxoff = 80, boxsize=1, tvflag = 1

;VSUB RAMPS ==========================
;
pro plot_conservation_persistence_xRG, FitsFileName, $
	Mode=Mode, XPix=XPix, YPix = YPix, TvFlag = TvFlag, $
 	BoxSize=BoxSize, XBoxOff=XBoxOff, YBoxOff = YBoxOff, $
 	BothScales = BothScales, Date = Date, Leach=Leach, $
	Vertical = Vertical, ShowFrames=ShowFrames

If N_Elements(XPix)       eq 0 then XPix       = 462
If N_Elements(YPix)       eq 0 then YPix       = 293
If N_Elements(Mode)       eq 0 then Mode       = 0
If N_Elements(TvFlag)     eq 0 then TvFlag     = 0
If N_Elements(BothScales) eq 0 then BothScales = 0
If N_Elements(BoxSize)    eq 0 then BoxSize    = 100
If N_Elements(XBoxOff)    eq 0 then XBoxOff    = 100
If N_Elements(YBoxOff)    eq 0 then YBoxOff    = 100
If N_Elements(Leach)	  eq 0 then Leach      = 0
If N_Elements(Vertical)   eq 0 then Vertical   = 0
If N_Elements(ShowFrames) eq 0 then ShowFrames = 0

;Make the Common Block
Common KeyParams, KeyStr
;Include all the keywords from the KeywordStruct.pro file
@KeywordStruct_xRG.pro
@PlotSettings_xRG.pro
loadct,3

;Set up the plotting for a slideshow of the reads
If KeyStr.TvFlag eq 1 then begin
    If ShowFrames eq 1 then begin
      If Vertical eq 0 then begin
        window, 0, xpos=0, ypos=100, xsize=1000, ysize=200
      Endif else begin
        window, 0, xpos=1200, ypos=100, xsize=200, ysize=1000
      EndElse
      !p.charthick=1.9
      !p.charsize=1.9
      !p.thick=2.0
      plot, [0,0], /nodata, background=fsc_color('white')
    EndIF
EndIf Else If KeyStr.TvFlag eq 3 then begin
    Set_Plot,'z', /copy
    device, z_buffer=0
    If Vertical eq 0 then begin
      device, set_resolution = [ 1000, 200]
    EndIf else begin
      device, set_resolution = [ 200, 1000]
    EndElse
    loadct, 3
    plot, [0,0], /nodata, background=fsc_color('white')
EndIf

;The Default File is the one with the negative persistence
KeyStr.RawObjectPath    = FitsFileName
KeyStr.ObjectName       = FitsFileName

Fits_Read, KeyStr.RawObjectPath, NoData, NH, /header_only
FileParams = Return_File_Params_xRG(KeyStr.RawObjectPath)
If KeyStr.WindowMode then begin
   XNPix = XPix - KeyStr.XWindowStart(0)
   YNPix = YPix - KeyStr.YWindowStart(0)
EndIf
If KeyStr.ITime eq 0 then begin
    If Leach eq 0 then begin
      FrameNTime = (KeyStr.Naxis1*10.e-6+40.e-6)*KeyStr.Naxis2
      INTime     = KeyStr.Naxis3*FrameNTime
    EndIf else begin
      FrameNTime = 0.33
      INTime     = KeyStr.Naxis3*FrameNTime
    Endelse
EndIf Else Begin
    FrameNTime = KeyStr.ITime/KeyStr.Naxis3
    INTime     = KeyStr.ITime
EndElse

;Output JPG showing development of persistence
NumImages = 10
ImageMult = KeyStr.Naxis3/NumImages

Case Mode of 
  0: begin
     ;Get the bias frames
     FrameNum = 0
     Fits_Read_DataCube, FitsFileName, Im, FitsHeader, $
        XStart = XPix-BoxSize/2, XStop = XPix+BoxSize/2,$
        YStart = YPix-BoxSize/2, YStop = YPix+BoxSize/2
     Im=Return_RefPix_xRG(Im, 3, FitsFileName=FitsFileName, $
        XStart = XPix-BoxSize/2, XStop = XPix+BoxSize/2,$
        YStart = YPix-BoxSize/2, YStop = YPix+BoxSize/2)
     Fits_Read_DataCube, FitsFileName, ImB, FitsHeader, $
        XStart = XPix-BoxSize/2+XBoxOff, XStop = XPix+BoxSize/2+XBoxOff,$
        YStart = YPix-BoxSize/2+YBoxOff, YStop = YPix+BoxSize/2+YBoxOff
     ImB=Return_RefPix_xRG(ImB, 3, FitsFileName=FitsFileName, $
        XStart = XPix-BoxSize/2+XBoxOff, XStop = XPix+BoxSize/2+XBoxOff,$
        YStart = YPix-BoxSize/2+YBoxOff, YStop = YPix+BoxSize/2+YBoxOff)
     ImBias = Long(Im(*,*,0)) & ImBBias = Long(ImB(*,*,0))
     ImMB   = LonArr(BoxSize+1,BoxSize+1,KeyStr.Naxis3)
     ImBMB  = LonArr(BoxSize+1,BoxSize+1,KeyStr.Naxis3)

     For FrameNum = 0, KeyStr.Naxis3-1 do begin
       ImMB(*,*,FrameNum) = Im(*,*,FrameNum)-ImBias(*,*)  
       ImBMB(*,*,FrameNum) = ImB(*,*,FrameNum)-ImBBias(*,*)
     Endfor
     If BothScales then begin
       MinIm  = Min([min(ImMB), min(ImBMB)])
       MaxIm  = Max([max(ImMB), max(ImBMB)])
     EndIf else begin
       MinIm  = min(ImMB)
       MaxIm  = max(ImMB)
     EndElse
     ITIME  = Float(SxPar(FitsHeader, 'ITIME'))
     Naxis1 = Long(SxPar(FitsHeader, 'NAXIS1'))
     Naxis2 = Long(SxPar(FitsHeader, 'NAXIS2'))
     Depth  = Long(SxPar(FitsHeader, 'NAXIS3'))
     KeyStr.Naxis3= Depth
     Cols       = (Rows = BoxSize)
     MeanBoxArr = Fltarr(KeyStr.Naxis3)  
     MeanSkyArr = Fltarr(KeyStr.Naxis3)
     For FrameNum = 0, KeyStr.Naxis3-1 do begin

       FrameTime = ITIME/Depth
       MeanBoxArr[FrameNum] = mean(ImMB(*,*,FrameNum))
       MeanSkyArr[FrameNum] = mean(ImBMB(*,*,FrameNum))
       print, MeanBoxArr[FrameNum], MeanSkyArr[FrameNum]
       If FrameNum mod ImageMult eq 0 and FrameNum gt 0 and ShowFrames eq 1 $
       then begin
	 XOffSet = FrameNum/ImageMult
         YOffSet = FrameNum/ImageMult

         If Vertical eq 0 then begin
           tvimage, bytscl(congrid(ImMB(*,*,FrameNum),  512,512), $
		         min = MinIm, max = MaxIm), $
	     position = [XOffset*0.1, 0.0, 0.1+XOffset*0.1, 0.5], $
             /normal, background=fsc_color('white')
           tvimage, bytscl(congrid(ImBMB(*,*,FrameNum), 512,512), $
			 min = MinIm, max = MaxIm), $
             position = [XOffset*0.1, 0.5, 0.1+XOffset*0.1, 1.0], $ 
	     /normal, background=fsc_color('white')
           xyouts, XOffset*0.1+0.01, 0.9, 'Read ' + Strtrim(FrameNum,2), $
	     color=fsc_color('white'), /normal
	  EndIf Else begin
           tvimage, bytscl(congrid(ImMB(*,*,FrameNum),  512,512), $
                         min = MinIm, max = MaxIm), $
             position = [0.0, YOffset*0.1, 0.5, 0.1+YOffset*0.1], $
             /normal, background=fsc_color('white')
           tvimage, bytscl(congrid(ImBMB(*,*,FrameNum), 512,512), $
                         min = MinIm, max = MaxIm), $
             position = [0.5,YOffset*0.1, 1.0, 0.1+YOffset*0.1], $
             /normal, background=fsc_color('white')
           xyouts, 0.5, 0.1*YOffset+0.08, 'Read ' + Strtrim(FrameNum,2), $
             color=fsc_color('white'), /normal

	  EndElse
       EndIf
     EndFor
     If ShowFrames eq 1 then begin
       If Vertical eq 0 then begin
         ColorBar, position = [0.06, 0.1, 0.08, 0.9], /vertical, $
          minrange = MinIm, maxrange = MaxIm, $
	  charsize=1.5, charthick=1.5, $
	  color = fsc_color('black')
       Endif Else begin
         ColorBar, position = [0.1, 0.06, 0.9, 0.08],  $
          minrange = MinIm, maxrange = MaxIm, $
          charsize=1.0, charthick=1.0, $
          color = fsc_color('black')
       EndElse
       If KeyStr.TvFlag eq 1 or KeyStr.TvFlag eq 3 then begin
         Img  = tvread(/tiff, FileName = KeyStr.PlotDir+KeyStr.RawObjectKey+$
 		     '_'+Strtrim(XPix,2)+'_'+Strtrim(YPix,2)+'ReadSequence', $
      		     /nodialog)
       EndIf
     EndIf
  end
endcase

;Now fit the lines to see if they agree and if charge is conserved
window, 1,xpos=0, ypos=100, xsize=512,ysize=512
;SlopeStr = Return_Slope_Params(FitsHeader)
NumReads  = Long(SxPar(FitsHeader, 'NAXIS3'))
ReadTimes = Findgen(NumReads)*0.33
linefit_1rg, ReadTimes(1:NumReads-1), MeanSkyArr(1:NumReads-1), mSky, bSky, sigmSky, sigbSky, eSky, cSky
linefit_1rg, ReadTimes(1:NumReads-1), MeanBoxArr(1:NumReads-1), mBox, bBox, sigmBox, sigbBox, eBox, cBox

MinArr = Min([Min(MeanBoxArr), Min(MeanSkyArr)])
MaxArr = Max([Max(MeanBoxArr), Max(MeanSkyArr)])
Plot, MeanBoxArr(1:NumReads-1), $
   Yrange = [MinArr, MaxArr], $
   XTitle = 'Read Number', $
   YTitle = 'Bias Subracted ADU' , background = fsc_color('white'), $
   color=fsc_color('black'), position = [0.125, 0.10, 0.90, 0.90], $
   /normal, xstyle = 8
OPlot, MeanSkyArr(1:NumReads-1), color=fsc_color('red')
Axis, XAxis = 1, color=fsc_color('black'), xrange=[0, ReadTimes(NumReads-1)], $
            XStyle = 1, xtitle = 'Seconds'
ItemsB      = [Strtrim(BoxSize,2)+' x '+Strtrim(BoxSize,2)+' Persistence Area', $
	       Strtrim(BoxSize,2)+' x '+Strtrim(BoxSize,2)+' Dark Area']
ColorsB     = [fsc_color('black'), fsc_color('red')]
TextColorsB = [fsc_color('black'), fsc_color('black')]
PsymB	    = [0,0]
Legend, ItemsB, Colors = ColorsB, TextColors = TextColorsB, PSym= PSymB

XYOuts, 0.5, 0.25, 'Slope = '+ $
  Strtrim(mBox,2), $
  /normal, color=fsc_color('black')
XYOUTS, 0.5, 0.20, 'Slope = ' + $
   Strtrim(mSky,2), $
  /normal, color=fsc_color('red')

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+'_'+Strtrim(XPix,2)+'_'+$
     Strtrim(YPix,2)+'PerConservationSlopes.tif', $
     red=Img24(*,*,0), green=Img24(*,*,1), blue=Img24(*,*,2), $
     planarconfig=2, orientation=1, compression=0
EndIf

stop

end
