;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
;pro tv_n_windows_hxrg
;
;PURPOSE:
;	To display multiple windows on an idl tv screen from data taken 
;       with an HxRG detector in multiple window mode.
;
;INPUTS:
;	FitsFileName - The path to the file that contains the naxis1 x naxis2 x
;                      number of reads x number of windows data cube
;       FitsDir: The directory that contains the fit file.  This should actually
;                be indicated in the path
;       BiasSub: 
;         0 - Don't subtract Read (2n+1) - Read (2n)
;         1 - Do the subtraction
;       Scale: int
;         0 - scale with the mean and std
;         1 - scale with the min and max
;       TvFlag: int
;         0 - Don't display the image and plot
;         1 - Display the image and plot
;       IMax: float
;         The maximium intensity to include on the flux plot
;       MakeMPG: int
;         0 - Don't Create an MPEG file 
;         1 - Create an MPEG file 
;
;NOTES:
;  If you are making an MPEG, it is highly recommended that you set TVFLAG=0 
;  so that the drawings are made to the z buffer instead of the x window.  
;  This will make the code execute a lot faster.
;
;EXAMPLES:
;tv_n_windows_hxrg, '/nfs/slac/g/ki/ki03/lances/H2RG-32-147/ASIC/07Dec17/Focus/SAO55420_H2RG_SIPIN_OneWindow100_Reads_Dec17_2007_20_22_16.fits'
;
;tv_n_windows_hxrg, '/nfs/slac/g/ki/ki03/lances/H2RG-32-147/ASIC/07Dec14/M67/M67M67_H2RG_SIPIN_MultipleWindows1000_Reads_Dec15_2007_06_10_52.fits', /tvflag, /biassub
;tv_n_windows_hxrg, '/nfs/slac/g/ki/ki03/lances/H2RG-32-147/ASIC/07Dec14/Focus/HD37756_H2RG_SIPIN_OneWindow300_Reads_Dec14_2007_22_42_39.fits', /makempg, /biassub,/tvflag

pro tv_n_windows_hxrg, FitsFileName, FitsDir = FitsDir, Offset=Offset, $
    BiasSub = BiasSub, Scale=Scale, TvFlag=TvFlag, IMax=IMax, MakeMPG=MakeMPG

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

Common FitsCube, FCB, unit
If N_Elements(OFfset)  eq 0 then Offset  = 0
If N_Elements(BiasSub) eq 0 then BiasSub = 0
If N_Elements(Scale)   eq 0 then Scale   = 0
If N_Elements(DoPhot)  eq 0 then DoPhot  = 0
If N_Elements(TvFlag)  eq 0 then TvFlag  = 0
If N_Elements(IMax)    eq 0 then IMax    = 500
If N_Elements(MakeMPG) eq 0 then MakeMPG = 0
@KeywordStruct_xRG.pro
@PlotSettings_xRG.pro

;Open the FitsFile to the first valid data byte after the header.
;The common file control block FCB holds the structure to the fits file
Position = fits_open_datacube(FitsFileName, FCB, Header, 'Read')

naxis1 = fcb.axis(0)
naxis2 = fcb.axis(1)
naxis3 = fcb.axis(2)
naxis4 = fcb.axis(3)
bitpix = fcb.bitpix(0)
bzero = fcb.bzero(0)
bytes_per_word = (abs(bitpix)/8)

;Determine Viewing Border
Border     = 2
WinSize    = 160
WinSizeWB  = WinSize+Border
NRows      = NAxis4/2
If NAxis4 eq 0 then NRows = 1
If NAxis4 eq 0 then NCols = 1 else NCols=2

;Set up XWindow
if TvFlag gt 0 and MakeMPG eq 0 then begin
  If NAxis4 eq 0 and TvFlag eq 1 then begin
     NAxis4 = 1
     window, 0, xsize=512,ysize=512
     if DoPhot eq 1 then window, 1, xsize=512, ysize=300
     If BiasSub eq 0 then NAxis3 = NAxis3/2
  endif else if TvFlag eq 1 then begin
    !p.noerase = 1
    window, xsize = NCols*WinSizeWB, ysize = NRows*WinSizeWB
  endif
;Make the mpeg on the z window in the buffer
endif else if MakeMPG gt 0 then begin
  set_plot, 'z'
  if NAxis4 gt 0 then begin
    device, set_resolution=[NCols*WinSizeWB, NRows*WinSizeWB]
  endif else  begin
    NAxis4 = 1
    device, set_resolution=[512, 512]
  endelse
endif 

;Configure MPEG if /MakeMPG
if MakeMPG eq 1 then begin
  MPEGName = KeyStr.RedObjectDir+KeyStr.RawObjectKey+'.mpg'
  If NAxis4 gt 1 then $
  Movie    = mpeg_open([NCOls*WinSizeWB, NRows*WinSizeWB], quality=100) $
  else $
  Movie    = mpeg_open([512,512], quality=100) 

  MovieFrame = 0
  FrameGap = 3 ;The number of frames to be inserted between 
endif  

If NAxis4 gt 0 then begin
  FluxArray = Fltarr(Naxis3,Naxis4)  
EndIf else begin
  FluxArray = Fltarr(Naxis3,1)
Endelse

if TvFlag gt 1 then begin
  window, 1, xsize=512, ysize=512
  plot, [0],[0], /nodata, xrange=[0, Naxis3], yrange=[0,IMax]
endif

if BiasSub eq 0 then LastFrame = NAxis3-1 else LastFrame = NAxis3/2-1

for FrameNum = 0 , LastFrame - 1 do begin
  for WindowNum = 0, Naxis4 - 1 do begin
    print, 'Frame: ' + string(FrameNum)
    If BiasSub eq 0 then begin
      Fits_Read_Datacube,FitsFileName, Data, Header, $
             ZStart = Naxis4*FrameNum+WindowNum, $
             ZStop  = Naxis4*FrameNum+WindowNum, Offset=Offset
    EndIf Else Begin
      Fits_Read_Datacube,FitsFileName, Data1, Header, $
             ZStart = 2*Naxis4*FrameNum+2*WindowNum, $
             ZStop  = 2*Naxis4*FrameNum+2*WindowNum, Offset=Offset
      Fits_Read_Datacube,FitsFileName, Data2, Header, $
             ZStart = 2*Naxis4*FrameNum+1+2*WindowNum, $
             ZStop  = 2*Naxis4*FrameNum+1+2*WindowNum, Offset=Offset
      Data = long(Data2)-long(Data1)
    EndElse
    ThisWindow = Data
    MeanWin = Mean(thisWindow)
    StdDevWin = StdDev(thisWindow)

    If Scale eq 0 then begin
      MinWin = MeanWin-2*StdDevWin
      MaxWin = MeanWin+2*StdDevWin
    EndIf else begin
      MinWin = Min(ThisWindow)+StdDevWin
      MaxWin = Max(thisWindow)-StdDevWin
    Endelse
 
    if TvFlag eq 1 then begin
      if Naxis4 gt 1 then begin
        if TvFlag gt 0 and MakeMPG eq 0 then wset,0
        tv, bytscl(congrid(thisWindow,WinSize,WinSize), $
	       min = MinWin, $
	       max = MaxWin), $
			(WindowNum mod 2)*(WinSizeWB), $
			(WindowNum/2)*(WinSizeWB)
      endif else begin
        if TvFlag gt 0 and MakeMPG eq 0 then wset,0
        tv, bytscl(congrid(thisWindow,512,512), $
               min = MinWin, $
               max = MaxWin)
      endelse
      Flux     = total(ThisWindow)
      ThisRead = FrameNum
      if TvFlag gt 1 and MakeMPG eq 0 then begin
        wset,1
        oplot, [ThisRead], [Flux], psym=2
      endif  
    endif
    position = position + long(naxis1)*long(naxis2)*bytes_per_word
    Star       = ThisWindow
    MeanStar   = Mean(Star)
    StdDevStar = StdDev(Star)
    StarCen = Return_Centroid(Star-min(Star))
  endfor

  ;Update Movie if /MakeMPG
  if MakeMPG eq 1 then begin
      MovieIm = tvread()
      for i = 0, FrameGap do begin
        MovieFrame=MovieFrame+1
        Mpeg_Put, Movie, IMAGE = MovieIm, Frame = MovieFrame
      endfor
  endif
  if TvFlag gt 0 and MakeMPG eq 0 then wait, .5
endfor

if MakeMPG eq 1 then mpeg_save, Movie, FILENAME= MpegName

end
