;pro refsub_2RG
;
;PURPOSE:
;	To subtract the noise apparent on the reference pixels of the H2RG from the science
;	pixels in the best way possible.  There appears to be a factor of 2.5 difference between
;	the peak to peak amplitude of the science and reference pixels.  This may have to do
;	with the parasitic capacitance mentioned in the manual
;
; CALLING SEQUENCE:
;       refsub_h2RG, input_data, output_data, scaName
;
; INPUTS:
;       input_data      - A 4096x4096 array containing the image data.
;       output_data     - A 4096x4096 fltarr for the result
;     scaName       - The name of the device that generated the input data
;
; KEYWORD PARAMETERS:
;       fwindow       - The size of the filter window.
;       order         - Filter order, see the SAVGOL help page
;       degree        - Filter degree, see the SAVGOL help page
;       plot          - Set this =1 to plot the fits
;       simple        - Set this =1 for Maximal Spatial Averaging
;                       (subtract a median reference pixel)
;
;       verbose       - Set this =1 for verbose mode.
;
;
; EXAMPLE
;        IDL> fits_read, 'theImage.fits', myData, myHeader
;        IDL> myNewDate = fltarr(4096, 4096)
;        IDL> refsub_h4rg, myData, myNewData
;
; Code borrowed from Don Figer, Ernie Morse, B.J. Rauscher and others at STSCI
;
;*************************************************************************
pro Examine_RefPix_2rg, FitsFileName, TvFlag = TvFlag, Date=Date, $
	 FWindow = FWindow, $
	 Order = Order, Degree = Degree, XPix1 = XPix1, YPix1 = YPix1, $
	 XPix2 = XPix2, YPix2 = YPix2

  If N_Elements(fwindow) eq 0 then fwindow = 64  ; 64 pixels on sides of pixel for smoothing
  If N_Elements(order)   eq 0 then order  = 0    ; Use zero to smooth
  If N_Elements(degree)  eq 0 then degree = 3    ; Three seems reasonable
  If N_Elements(XPix1)   eq 0 then XPix1  = 20
  If N_Elements(YPix1)   eq 0 then YPix1  = 20
  If N_Elements(XPix2)   eq 0 then XPix2  = 40
  If N_Elements(YPix2)   eq 0 then YPix2  = 40

  Common KeyParams, KeyStr

  ;Get all of the defaults for the keywords from the KeywordStruct file
  @KeywordStruct_2RG.pro
  @PlotSettings_2RG.pro

  KeyStr.RawFullPath = FitsFileName
  KeyStr.RawName     = FitsFileName
  Fits_read_datacube, KeyStr.RawFullPath, Im, FitsHeader
  FileParams = Return_File_Params_2RG(KeyStr.RawFullPath)

  MeanRefColL = fltarr(KeyStr.Naxis2, KeyStr.Naxis3)  ; Signals vector on left
  MeanRefColR = fltarr(KeyStr.Naxis2, KeyStr.Naxis3)  ; Signals vector on right
  MeanRowsL   = fltarr(KeyStr.Naxis2, KeyStr.Naxis3)
  MeanRowsR   = fltarr(KeyStr.Naxis2, KeyStr.Naxis3)

  For ReadNum = 0, KeyStr.Naxis3-1 do begin
    For row=0, KeyStr.Naxis2 - 1 do begin
      ; Do not use the first reference pixel on each side.
      ; HAWAII-2RG works best like this.
      MeanRefColL[row, ReadNum] = mean(Im(1:3, row, ReadNum))
      MeanRefColR[row, ReadNum] = mean(Im(KeyStr.Naxis1-4:KeyStr.Naxis1-2, row, ReadNum))
      MeanRowsL[row, ReadNum]   = mean(Im(4:103, row, ReadNum))
    EndFor
  EndFor

  ;Get the exposure times and frame times for axes purposes
  FrameTime = KeyStr.ITime/KeyStr.Naxis3
  ITime     = KeyStr.ITime
  ReadTimes = FindGen(KeyStr.Naxis3-1)*FrameTime

  ;Plot the difference between the reference pixels and the science pixels
  RefRamp1 = MeanRefColL(YPix1, 1:*)-MeanRefColL(YPix1,0)
  SciRamp1 = Im(XPix1,YPix1,1:*) - Float(Im(XPix1,YPix1,0))
  RefRamp2 = MeanRefColL(YPix2, 1:*)-MeanRefColL(YPix2,0)
  SciRamp2 = Im(XPix2,YPix2,1:*) - Float(Im(XPix2,YPix2,0))
  YMin = min([min(SciRamp1), min(RefRamp1)])
  YMax = max([max(SciRamp1), max(RefRamp1)])

  ;Plot just the Science Ramp and the Reference Ramp Separately
  Plot, RefRamp1, background = fsc_color('white'), color=fsc_color('black'), $
	xtitle = 'Read Number', ytitle = 'ADU', $
	YRange = [YMin, YMax], XStyle = 8, $
        position = [0.175, 0.10, 0.9250, 0.90], /normal
  OPlot, SciRamp1, color=fsc_color('red')
  Axis, XAxis = 1, color=fsc_color('black'), xrange=[0, ITime], $
            XStyle = 1, xtitle = 'Seconds'
  ItemsP  = ['Science Pixel '+Strtrim(XPix1,2)+','+Strtrim(YPix1,2), $
            'Avg. Ref Pixels in Row '+Strtrim(XPix1,2)]
  ColorsP = [fsc_color('black'), fsc_color('red')]
  PSymP   = [0, 0 ]
  TextColorsP = [fsc_color('black'), fsc_color('black')]
  legend, ItemsP, Psym=PSymP, Colors=ColorsP, TextColors = TextColorsP
  If KeyStr.TvFlag eq 1 then stop
  If KeyStr.TvFlag eq 3 then begin
     Img  = tvread(/tiff, FileName = KeyStr.PlotDir+KeyStr.RawKey+$
                   'RefSciPixelRamps_NoCFactor_'+Strtrim(XPix1,2)+'_'+Strtrim(YPix1,2),$
                   /nodialog)
  EndIf


  ;Show the difference Sci-Ref without capacitance factor
  YMin = min([min(SciRamp1-RefRamp1), min(SciRamp2-RefRamp2)])
  YMax = max([max(SciRamp1-RefRamp1), max(SciRamp2-RefRamp2)])
  Plot, SciRamp1-RefRamp1,background = fsc_color('white'), color=fsc_color('black'), $
        xtitle = 'Read Number', ytitle = 'ADU', XStyle = 8, $
        position = [0.175, 0.10, 0.9250, 0.90], /normal, YRange = [YMin, YMax]
  OPlot,SciRamp2-RefRamp2, color=fsc_color('red')
  Axis, XAxis = 1, color=fsc_color('black'), xrange=[0, ITime], $
            XStyle = 1, xtitle = 'Seconds'
  ItemsP  = ['Sci-Ref '+Strtrim(XPix1,2)+','+Strtrim(YPix1,2), $
	    'Sci-Ref '+Strtrim(XPix2,2)+','+Strtrim(YPix2,2)]
  ColorsP = [fsc_color('black'), fsc_color('red')]
  PSymP   = [0, 0 ]
  TextColorsP = [fsc_color('black'), fsc_color('black')]
  legend, ItemsP, Psym=PSymP, Colors=ColorsP, TextColors = TextColorsP
  If KeyStr.TvFlag eq 1 then stop
  If KeyStr.TvFlag eq 3 then begin
     Img  = tvread(/tiff, FileName = KeyStr.PlotDir+KeyStr.RawKey+$
                   'RefMinusSciPixelRamps_NoCFactor_'+Strtrim(XPix1,2)+'_'+Strtrim(YPix1,2),$
                   /nodialog)
  EndIf

  ;Show the difference Sci-Ref with capacitance factor
  Plot, SciRamp1-RefRamp1/3.75,background = fsc_color('white'), color=fsc_color('black'), $
        xtitle = 'Read Number', ytitle = 'ADU', XStyle = 8, $
        position = [0.175, 0.10, 0.9250, 0.90], /normal, YRange = [YMin, YMax]
  OPlot,SciRamp2-RefRamp2/3.75, color=fsc_color('red')
  Axis, XAxis = 1, color=fsc_color('black'), xrange=[0, ITime], $
            XStyle = 1, xtitle = 'Seconds'
  ItemsP  = ['Sci-Ref*CFactor  '+Strtrim(XPix1,2)+','+Strtrim(YPix1,2), $
            'Sci-Ref*CFactor  '+Strtrim(XPix2,2)+','+Strtrim(YPix2,2)]
  ColorsP = [fsc_color('black'), fsc_color('red')]
  PSymP   = [0, 0 ]
  TextColorsP = [fsc_color('black'), fsc_color('black')]
  legend, ItemsP, Psym=PSymP, Colors=ColorsP, TextColors = TextColorsP
  If KeyStr.TvFlag eq 1 then stop
  If KeyStr.TvFlag eq 3 then begin
     Img  = tvread(/tiff, FileName = KeyStr.PlotDir+KeyStr.RawKey+$
                   'RefMinusSciPixelRamps_CFactor_'+Strtrim(XPix1,2)+'_'+Strtrim(YPix1,2),$
                   /nodialog)
  EndIf

end
