;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
;make last_minus_first_xrg
;
;PURPOSE:
;  To create a .fits file consisting of only the last minus first read.
;  This deals with the large files that ds9 cannot handle
;
;INPUTS:
;  FitsFileName (string)
;      The Full Path to the Fits File to be used
;
;OUTPUTS:
;  [FitsFileName]_LMF.fits 
;      This fits file has only LastRead - FirstRead.  It will be written
;      to the same directory as the one containing FitsFileName. 
;
;KEYWORDS:
;       DETSTR: string
;         The name of the detector used ('H1RG-022', 'H2RG-32-147', 'H4RG-007')
;       ELECSTR: string
;         The name of the electronics used ('ASIC', 'LEACH')
;       DATE: string
;         The Date during which they were taken.  Also the subdirectory that
;         the files are in ('07Dec18', '07Apr25', etc.)
; 	MKJPG: int
;	  If set, a .tif image will be generated that has the 
;         coordinates, XStartJPG, XStopJPG, YStartJPG, YStopJPG
;       MKSLDSHW: int
;	  If set, a 10 image slide sequence of reads will be output
;	  in .tif format
;  	VERTICAL: int
;	  If set, the slideshow will be vertical rather than horizontal
;	XSTARTJPG: int
;	  The x startcoordinate of the rectangular region used for the .jpg
;       XSTOPJPG: int
;         The x stop coordinate of the rectangular region used for the .jpg
;       YSTARTJPG: int
;         The y coordinate of the rectangular region used for the .jpg
;       YSTOPJPG: int
;         The y coordinate of the rectangular region used for the .jpg
;	FULLFRAME: int
;	  0 - The coordinates XSTARTJPG, ... will be used
;	  1 - All of the pixels will be included
;	USEREF: int
;         0 - Don't subtract reference pix
;         1 - Subtract reference pixels
;	FIRSTREAD: int
;	  The first read to use in the output image [LastRead] - [Zeroth Read]
;	LASTREAD: int
;	  The last read to use in the output image [LastRead] - [Zeroth Read]
;	NUMSEQ: int   
;	  The number of slides to put in the image.  They will be distributed
;	  uniformly in time throughout the ramp
;       PLOTSUBDIR: string
;	  The subdirectory for the plot to be written to.  The full directory
;	  will be 
;	  KeyStr.DataDir+KeyStr.DetStr+PlotSubDir
;	BIASSUB: int
;	  0 - Don't subtract the 0th read
;	  1 - Subtract the 0th read
;	MINSCALE: int
;	  The minimum of the color scale for the slideshow or jpg to be shown
;	MAXSCALE: int
;	  The maximum of the color scale for the slideshow or jpg to be shown
;
;EXAMPLES:
;make_last_minus_first_xrg,'/nfs/slac/g/ki/ki03/lances/H1RG-022/ASIC/07Nov19/NGC7419_I_Dither1_20ArcSecondsEast_0ArcSecondsNorth_H1RG_SIPIN_100_Reads_Nov19_2007_21_01_10.fits',/MkJPG, date='07Nov19'
;
;SUPER LONG RAMP===============
;make_last_minus_first_1rg,'/nfs/slac/g/ki/ki03/lances/H1RG/KPNO_11_07/ASIC/07Nov19/SAO5417_I_NegPerDark_H1RG_SIPIN_2500_Reads_Nov19_2007_22_45_50.fits', date='07Nov19'
;make_last_minus_first_1rg,'/nfs/slac/g/ki/ki03/lances/H1RG/KPNO_11_07/ASIC/07Nov19/SAO5417_I_NegPerDark_H1RG_SIPIN_2500_Reads_Nov19_2007_22_45_50.fits', date='07Nov19', xstartjpg=318, xstopjpg = 358, ystartjpg = 245, ystopjpg = 285, /mkjpg

pro make_last_minus_first_xrg, FitsFileName, $
	DetStr = DetStr, ElecStr = ElecStr, $
	TvFlag = TvFlag, Date = Date, $
	MkJPG = MkJPG, MkSldShw = MkSldShw, Vertical = Vertical,$
	XStartJPG = XStartJPG, XStopJPG = XStopJPG,$
	YStartJPG = YStartJPG, YStopJPG = YStopJPG, $
	FullFrame=FullFrame, FirstRead=FirstRead, $
	LastRead = LastRead, NumSeq = NumSeq, PlotSubDir = PlotSubDir, $
	BiasSub = BiasSub, MinScale = MinScale, MaxScale=MaxScale, $
        UseRef=UseRef

;Include all the keywords from the KeywordStruct.pro file
Common KeyParams, KeyStr
@KeywordStruct_xRG.pro
@PlotSettings_xRG.pro
;Load the color table that looks like the ds9 BB
loadct,3

;*****KEYWORDS**************************************************************************
If N_Elements(MkJPG)      eq 0 then MkJPG      = 0
If N_Elements(MkSldShw)   eq 0 then MkSldShw   = 0
If N_Elements(XStartJPG)  eq 0 then XStartJPG  = 378
If N_Elements(XStopJPG)   eq 0 then XStopJPG   = 420
If N_Elements(YStartJPG)  eq 0 then YStartJPG  = 450
IF N_Elements(YStopJPG)   eq 0 then YStopJPG   = 490
If N_Elements(FullFrame)  eq 0 then FullFrame  = 0
If N_Elements(Vertical)   eq 0 then Vertical   = 0
If N_Elements(NumSeq)     eq 0 then NumSeq     = 10
If N_Elements(PlotSubDir) eq 0 then PlotSubDir = ''
If N_Elements(BiasSub)    eq 0 then BiasSub    = 1 
If FullFrame then begin
   XStartJPG = 0 & XStopJPG = KeyStr.Naxis1-1
   YStartJPG = 0 & YStopJPG = KeyStr.Naxis2-1
EndIf

;/////////////////////////////////////////////////////////////////////
;PLOT SETTINGS

If KeyStr.TvFlag 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=0, ypos=100, xsize=280, ysize=700
    EndElse
    !p.charthick=1.9
    !p.charsize=1.9
    !p.thick=2.0
    plot, [0,0], /nodata, background=fsc_color('white')
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, 400]
    EndIf else begin
      device, set_resolution = [ 400, 1000]
    EndElse
    loadct, 3
    plot, [0,0], /nodata, background=fsc_color('white')
EndIf Else begin
    loadct, 3
    plot, [0,0], /nodata, background=fsc_color('white') 
EndElse

;/////////////////////////////////////////////////////////////////////
;WRITE THE FITS FILE
;
;The Default File is the one with the negative persistence
KeyStr.PlotDir = KeyStr.DataDir+KeyStr.DetStr+KeyStr.PathDelim+$
		 'Plots'+KeyStr.PathDelim+PlotSubDir+KeyStr.PathDelim
KeyStr.RawObjectPath = FitsFileName
FileParams = Return_File_Params_xRG(KeyStr.RawObjectPath)

;Allow for the last read to be one other than NAXIS3
If N_Elements(LastRead) eq 0 then LastRead = KeyStr.Naxis3-1

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


;***************************************************************************
;Ramp of pixel exhibiting positive persistence
Fits_read_datacube, KeyStr.RawObjectPath, ImL, NH, $
    ZStart = LastRead, ZStop = LastRead, Offset = Offset
Fits_read_datacube, KeyStr.RawObjectPath, ImF, NH, $
    ZStart = 0, ZStop = 0, Offset = Offset

If KeyStr.UseRef then begin
   MeanOff = mean([ImF(1:3,4:KeyStr.Naxis2-1)])
   ImF=Return_RefPix_xRG(ImF, 1, MeanOff=MeanOff)
   ImL=Return_RefPix_xRG(ImL,1, MeanOff=MeanOff)
Endif
LMF = Long(ImL)-Long(ImF)
If FirstRead eq 0 and LastRead eq KeyStr.NReads-1 then begin
  Fits_Write, KeyStr.RedObjectDir+KeyStr.RawObjectKey+'_LMF.fits', LMF
EndIf else begin
  Fits_Write, KeyStr.RedObjectDir+KeyStr.RawObjectKey+'_'+strtrim(LastRead,2)+$
            '_Minus_'+strtrim(FirstRead,2)+'.fits', LMF
EndElse

;///////////////////////////////////////////////////////////////////////////
;WRITE A JPG IF MKJPG==1
If MkJPG then begin
   SubIm = LMF(XStartJPG:XStopJPG, YStartJPG:YStopJPG)
   MeanSubIm   = Mean(SubIm)
   StdDevSubIm = StdDev(SubIm)
   MinSubIm    = MeanSubIm-0.5*StdDevSubIm
   MaxSubIm    = MeanSubIm+1.5*StdDevSubIm
   window, xsize = 512, ysize=512
   plot, [0,0], /nodata, background=fsc_color('white')
   TvImage, bytscl(congrid(SubIm,768,768), $
	    min = MinSubIm, $
	    max = MaxSubIm), $ 
	background=fsc_color('white'), $
	position = [0.00, 0.1, 1.0, 1.0], /normal
   ColorBar, position = [0.05, 0.05, 0.95, 0.08], $
          minrange = MinSubIm, maxrange = MaxSubIm, $
          charsize=1.5, charthick=1.5, $
          color = fsc_color('black')
   Img  = tvrd(true=3)
   Img24=reverse(Img,2)
   TVLCT, R, G, B, /Get
   Write_Tiff, KeyStr.PlotDir+KeyStr.RawObjectKey+'_'+$
	 Strtrim(XStartJPG,2)+'-'+Strtrim(XStopJPG,2)+'_'+$
	 Strtrim(YStartJPG,2)+'-'+Strtrim(YStopJPG,2)+'.tif', $
         red=Img24(*,*,0), green=Img24(*,*,1), blue=Img24(*,*,2), $
         planarconfig=2, orientation=1, compression=0
EndIf
;*************************************************************************
;/////////////////////////////////////////////////////////////////////////
;SlideShow of 10 reads in sequence
If MkSldShw then begin

  ;Read in the relevant rectangle of the file
  Fits_read_datacube, KeyStr.RawObjectPath, Im, FitsHeader, $
        XStart = XStartJPG, XStop = XStopJPG,$
        YStart = YStartJPG, YStop = YStopJPG
  XBoxSize = XStopJPG - XStartJPG
  YBoxSize = YStopJPG - YStartJPG

  ;Decide on whether or not to subtract the 0th read
  If BiasSub eq 1 then begin
    ImBias  = Long(Im(*,*,0)) 
  EndIf Else Begin
    ImBias  = LonArr(XBoxSize+1, YBoxSize+1)
  EndElse
  ImMB    = LonArr(XBoxSize+1, YBoxSize+1,KeyStr.Naxis3)
  For FrameNum = 0, KeyStr.Naxis3-1 do begin
    ImMB(*,*,FrameNum) = Im(*,*,FrameNum)-ImBias(*,*)
  Endfor

  ;Determine the min and max for the color scale
  MeanIm   = Mean(ImMB)
  StdDevIm = StdDev(ImMB)
  MinIm    = MeanIm-2.5*StdDevIm
  MaxIm    = MeanIm+5.5*StdDevIm
  If N_Elements(MinScale) eq 0 then MinIm  = MinIm else MinIm = MinScale
  If N_Elements(MaxScale) eq 0 then MaxIm  = MaxIm else MaxIm = MaxScale

  ITIME  = Float(SxPar(FitsHeader, 'ITIME'))
  Naxis1 = Long(SxPar(FitsHeader, 'NAXIS1'))
  Naxis2 = Long(SxPar(FitsHeader, 'NAXIS2'))
  Depth  = Long(SxPar(FitsHeader, 'NAXIS3'))
  KeyStr.Naxis3 = Depth
  MeanBoxArr = Fltarr(KeyStr.Naxis3)

  ;Start by resetting the plot
  For FrameNum = 0, KeyStr.Naxis3-1 do begin

    FrameTime = ITIME/Depth
    MeanBoxArr[FrameNum] = mean(ImMB(*,*,FrameNum))
    print, MeanBoxArr[FrameNum] 
    If FrameNum mod ImageMult eq 9 and FrameNum gt 0 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 mod 5)*0.18+0.10,0.5-0.5*(XOffset/5), $
		               (XOffset mod 5)*0.18+0.28,1.0-0.5*(XOffset/5)],$
             	    /normal, background=fsc_color('white')
           xyouts, (XOffset mod 5)*0.18+0.11, 0.9-0.5*(XOffset/5), $
		   'Read ' + Strtrim(FrameNum,2), $
                    color=fsc_color('white'), /normal
        EndIf Else begin
           tvimage, bytscl(congrid(ImMB(*,*,FrameNum),  512,512), $
                         min = MinIm, max = MaxIm), $
             position = [(YOffset/5)*0.5,     (YOffset mod 5)*0.18+.1,$
			 (YOffset/5)*0.5+0.5, (YOffset mod 5)*0.18+0.18+.1], $
             /normal, background=fsc_color('white')
           xyouts, (Yoffset/5)*0.5, (YOffset mod 5)*0.18+0.12, $
	     'Read ' + Strtrim(FrameNum,2), $
             color=fsc_color('white'), /normal
        EndElse
     EndIf
   EndFor
   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(XStartJPG,2)+'_'+Strtrim(XStopJPG,2)+$
		     '_'+Strtrim(YStartJPG,2)+'_'+Strtrim(YStopJPG,2)+$
		     'ReadSequence', $
                     /nodialog)
      stop
      Img24=reverse(Img,2)
      TVLCT, R, G, B, /Get
      Write_Tiff, KeyStr.PlotDir+KeyStr.RawObjectKey+'_'+Strtrim(XPix,2)+'_'+$
        Strtrim(YPix,2)+'_ReadSequence.tif', $
        red=Img24(*,*,0), green=Img24(*,*,1), blue=Img24(*,*,2), $
        planarconfig=2, orientation=1, compression=0
       stop
     EndIf
EndIf

stop

end
