;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
;pro Examine_Column_Bleeding_xRG
;
;PURPOSE:
;
;   To examine the elevated signal in the columns after a bright star 
;   has been read out.
;
;NOTES:
;
;INPUTS (Necessary Keywords):
;       FitsFileName - string
;         The name of the file to be slopefitted.  The program will 
;	  attempt to write the output to the proper directory.
;       Mode: int
;         0 - Plot the signal vs. row number (column plot)
;         1 - Make a slideshow that shows the onset of the column bleeding
; 
;KEYWORDS:
;       COLMIN: int (MODE==1 only)
;         The first column to consider in the plot
;       COLMAX: int (MODE==1 only)
;         The last column to consider in the plot 
; 	ROWMIN: int
;         The first row to consider in the plot
;       ROWMAX: int
;         The last row to consider in the plot 
; 	COLSPEC: int 
;         The column that will be plotted if MODE == 0
;       DARKSUB: int
;         0 - Don't subtract a dark
;         1 - subtract a dark
;       READNUM: int
;         The number of the read to use if the mode is 0 and 
;         we are plotting the column dependence
;       USESKY: str
;         If this is set to the full path of a file, that image will 
;         be subtracted from FITSFILENAME
;       VERTICAL: int
;         0 - if MODE == 1, plot the slides horizontally
;         1 - if MODE == 1, plot the slides vertically
;   	TVFLAG: 
;	  0 - Default, Don't plot anything
;	  1 - Plot to the X window	
;	  2 - Plot to postscript
;	  3 - Plot to a .png
;
;CALLING SEQUENCE:
;         Examine_Column_Bleeding_xRG, [FitsFileName=]
;
;EXAMPLES:
;  MODE == 0  ===================================================================================
;  DECENT EXAMPLE:
;  Examine_Column_Bleeding_xRG, FitsFileName='/nfs/slac/g/ki/ki04/lances/H1RG-022/ASIC/07Nov19/M44_I_H1RG_SIPIN_10_Reads_Nov20_2007_05_05_24.fits', ColSpec=597, RowMin=540, RowMax=750, /darksub, mode=0
;  Examine_Column_Bleeding_xRG, FitsFileName='/nfs/slac/g/ki/ki04/lances/H2RG-32-147/ASIC/07Dec15/NGC1893/NGC1893_G_Dither4_20ArcSecondsWest_20ArcSecondsNorth_H2RG_SIPIN_15_Reads_Dec15_2007_23_52_22.fits',ColSpec=1520, RowMin=1280, RowMax=1400, Mode=0
;  
;  MODE == 1  ====================================================================================
;  THESIS PLOT 1:
;  Examine_Column_Bleeding_xRG, UseSky='/nfs/slac/g/ki/ki04/lances/H2RG-32-147/ASIC/07Dec14/M77/M77_I_Dither2_20ArcSecondsEast_20ArcSecondsNorth_H2RG_SIPIN_30_Reads_Dec14_2007_20_27_04.fits', FitsFileName='/nfs/slac/g/ki/ki04/lances/H2RG-32-147/ASIC/07Dec14/M77/M77_I_Dither4_20ArcSecondsWest_20ArcSecondsNorth_H2RG_SIPIN_30_Reads_Dec14_2007_20_19_58.fits', ColMin=1486, ColMax=1550, RowMin=1280, RowMax=1400, Mode=1
;  THESIS PLOT 2:
;  Examine_Column_Bleeding_xRG, UseSky='/nfs/slac/g/ki/ki04/lances/H2RG-32-147/ASIC/07Dec15/NGC1893/NGC1893_G_Dither2_20ArcSecondsEast_20ArcSecondsNorth_H2RG_SIPIN_15_Reads_Dec15_2007_23_51_03.fits', FitsFileName='/nfs/slac/g/ki/ki04/lances/H2RG-32-147/ASIC/07Dec15/NGC1893/NGC1893_G_Dither4_20ArcSecondsWest_20ArcSecondsNorth_H2RG_SIPIN_15_Reads_Dec15_2007_23_52_22.fits', ColMin=1250, ColMax=1310, RowMin=1545, RowMax=1630, Mode=1
;
;****************************************************************************
pro Examine_Column_Bleeding_xRG, FitsFileName=FitsFileName, MODE=MODE, $
      ColSpec=ColSpec, ColMin=ColMin, ColMax=ColMax, RowMin=RowMin, RowMax=RowMax, $
      DarkSub = DarkSub, ReadNum = ReadNum, Vertical=Vertical, $
      TvFlag = TvFlag, UseSKY = UseSKY, NumFrames=NumFrames

if N_Elements(Mode)         eq 0 then Mode         = 0
If N_Elements(ColSpec)      eq 0 then ColSpec      = 100
If N_Elements(ColMin)       eq 0 then ColMin       = 100
If N_Elements(ColMax)       eq 0 then ColMax       = 200
If N_Elements(RowMin)       eq 0 then RowMin       = 100
If N_Elements(RowMax)       eq 0 then RowMax       = 200
If N_Elements(DarkSub)      eq 0 then DarkSub      = 0
If N_Elements(ReadNum)      eq 0 then ReadNum      = 9
If N_Elements(UseSKY)       eq 0 then UseSKY       = ''
If N_Elements(NumFrames)    eq 0 then NumFrames    = 8
If N_Elements(Vertical)     eq 0 then Vertical     = 0

Common KeyParams, KeyStr
;Include all of the keywords from the KeywordStruct file

@KeywordStruct_xRG.pro
@PlotSettings_xRG.pro

;Give the user info
print, 'About to examine: '
print,  FitsFileName

;Get the current file that's being operated on and some keys
KeyStr.RawObjectPath = FitsFileName
KeyStr.PlotDir       = '/nfs/slac/g/ki/ki04/lances/LSST/KPNO/Latex/Thesis/ElectronicCrossTalk/Figures/'
;Get the Parameters necessary to fit this file
FileParam= Return_File_Params_xRG(FitsFileName)

;Print out a few things
print, 'With median dark file: '
print,  KeyStr.DarkName
print, 'With flat file: '
print,  KeyStr.FlatName

SlopeStr = Return_Slope_Params_xRG(RawHeader)
NReads   = KeyStr.TotalReads
      
Case Mode of
  0 : begin  ;Read in Half of the raw/median image
    Fits_Read_DataCube, KeyStr.RawObjectPath , Raw , RawHeader, $
      XStart= ColSpec, XStop = ColSpec, $
      YStart= RowMin, YStop = RowMax 
  
    ;Read in Half of the dark image if dark subtraction is requested
    If KeyStr.DarkSub then begin $
      Fits_Read_DataCube, KeyStr.DarkName, Dark, DarkHeader, $
        XStart= ColSpec, XStop = ColSpec, $
        YStart= RowMin, YStop = RowMax 
      Raw_DS = lonarr(ColSpec-ColSpec+1, RowMax-RowMin+1, KeyStr.NAxis3)
      for i=0, KeyStr.NAxis3-1 do begin
        Raw_DS(*,*,i) = Raw(*,*,i)-long(Raw(*,*,0))
      endfor
    EndIf else begin
      Raw_DS = Raw
    EndElse
  
    ;Subtract the Dark
    plot, Raw_DS(*,*,ReadNum), yrange=[min(Raw_DS(*,*,ReadNum)), max(Raw_DS(*,*,ReadNum))], $
       color=fsc_color('black'), background=fsc_color('white')
  end
  1: begin
    If Vertical eq 0 then begin
      window, 0, xpos=0, ypos=100, xsize=1000, ysize=300
    Endif else begin
      window, 0, xpos=1200, ypos=100, xsize=300, ysize=1000
    EndElse
    !p.charthick=2.6
    !p.charsize=1.9
    !p.thick=2.0
    !p.font=1
    DEVICE, GET_FONTNAMES=fnames, SET_FONT='*'
    device, set_font = 'courier bold', /tt_font
    set_character_size=[200,120]
    !p.charsize=1.4  ;Set to True-Type fonts (described on
    plot, [0,0], /nodata, background=fsc_color('white')

    Fits_Read_DataCube, KeyStr.RawObjectPath , Raw , RawHeader, $
      XStart= ColMin, XStop = ColMax, $
      YStart= RowMin, YStop = RowMax
    if UseSKY ne '' then begin
      print, 'Using sky: '+strtrim(UseSKY)
      Fits_Read_DataCube, UseSKY , Sky , SkyHeader, $
        XStart= ColMin, XStop = ColMax, $
        YStart= RowMin, YStop = RowMax
      RawMinusSky = Raw-long(Sky)
    endif else begin
      print, 'Not using sky'
      RawMinusSky = Raw
    endelse

    ;Slopefit the brightest pixel
    LowerLinLim   = KeyStr.LowerLinLim
    UpperLinLim   = KeyStr.UpperLinLim
    TimePoints    = findgen(KeyStr.NAxis3)*KeyStr.FrameTime
    LastRead      = Raw(*,*,2)
    HighPix       = (where(LastRead eq max(LastRead)))[0]
    HighCol       = HighPix mod (size(LastRead))[1]
    HighRow       = HighPix/((size(LastRead))[1])
    RawRamp       = Raw(HighCol,HighRow,*)
    GoodMask = where(RawRamp gt LowerLinLim and $
                     RawRamp lt UpperLinLim, NumGood)
    TimePoints    = findgen(KeyStr.NAxis3)*KeyStr.FrameTime
    LineFit_xRG, TimePoints, RawRamp, m, b, $
       sigm, sigb, Error, CosmicEDep, CosmicRead, $
       CosmicType,  Mask=GoodMask, $
       Col=HighCol, Row=HighRow, tvflag=2, tvppt=3,$
       ThresholdFactor = KeyStr.SlopeSigThresh
    ;HERE ARE THE VALUES FROM SIDECAR CALIBRATION
    VoltsPerADU  = 61.525e-6     ; microvolts/ADU
    OffADU       = -(-1./5154.4) ; 1/ADU
    ;Make the SLIDESHOW
    For FrameNum = 0, NumFrames-1 do begin

      ;This Max voltage
      MinIm      = -10
      MaxIm      = 100
      FrameInd   = (KeyStr.NAxis3/(NumFrames-1))*FrameNum
      ThisMaxADU = m*FrameInd+b
      ThisMaxVol = VoltsPerADU*ThisMaxADU+OffADU
      ThisSlide  = RawMinusSky(FrameInd)
      XOffsetL   = float(FrameNum-1)/NumFrames
      XOffsetR   = float(FrameNum)/NumFrames
      YOffsetB   = float(FrameNum-1)/NumFrames
      YOffsetT   = float(FrameNum)/NumFrames
      Space      = (XOffsetR-XOffsetL)/NumFrames

      If Vertical eq 0 then begin
        tvimage, bytscl(congrid(RawMinusSky(*,*,FrameInd),  512,512), $
                     min = MinIm, max = MaxIm), $
          position = [XOffsetL+FrameNum*Space, 0.2, XOffsetR+FrameNum*Space, 1.0], $
          /normal, background=fsc_color('white')
        xyouts, XOffsetL+Space*FrameNum, 0.12, 'Read ' + Strtrim(FrameInd,2), $
          color=fsc_color('black'), /normal
        xyouts, XOffsetL+Space*FrameNum, 0.06, 'Max V: ' + $
          Strtrim(String(ThisMaxVol,format='(F10.2)'),2), $
          color=fsc_color('black'), /normal
       EndIf Else begin
         print, 'UNSUPPORTED'
       EndElse
    EndFor
    Img  = tvread(/tiff, FileName = KeyStr.PlotDir+KeyStr.RawObjectKey+$
                  '_ColumnBleedingSlideShow', /nodialog)
    Img  = tvread(/png, FileName = KeyStr.PlotDir+KeyStr.RawObjectKey+$
                  '_ColumnBleedingSlideShow', /nodialog)
  stop
  end
Endcase
end  
  stop
  
End
