;pro examine_masked_pixels
;
;PURPOSE:
;
;   To take in a list of bad pixel coordinates and for each of the coordinates,
;   display the values of that pixel for each read for a specific file
;
;   This routine should properly handle saturated pixels in a multi-read
;   exposure with the exception of pixels that got saturated on the first read.
;   Fits_Read will be used since no more large arrays will be formed, making 
;   a memory crash unlikely
;
;INPUTS:
;	FitsFileName
;
;KEYWORDS:
;	MasterMask - 0 - Use the master mask from a combination of nights.
;			 This mask has a 0 for good pixels and a 1 for bad 
;		   - 1 - Use the pixel mask from one night. 
;		         These masks have pixel values of the number of times
;			 they were flagged as being bad.
;	PAGENUM    - The number of the page (assuming 2x2 plot structure) in ;
;		     the postscript file that will be reproduced in the .png 
;		     file.  This page should be indicated in the text output.
;
;CALLING SEQUENCE:
;   Examine_Masked_Pixels, 'MedianDark_Blank_ForEachOf_30Reads.fits', $
;             rootdir='/nfs/slac/g/ki/ki09/lances/Reduced/07Apr30/Darks'
;
;REFRENCES:
;   Based on code written by Figer et. al at STSCI
;****************************************************************************
pro Examine_Masked_Pixels, RawFileName, $
	 RootDir = RootDir, Date = Date, $
	 ReducedDir = ReducedDir, ObjectName = ObjectName, $
	 SubtractDark = SubtractDark, FilterStr = FilterStr, NReads = NReads, $
	 TvFlag = TvFlag, Rem60Hz = Rem60Hz, MasterMask = MasterMask, $
	 PageNum = PageNum

  If N_Elements(MasterMask) eq 0 then MasterMask = 0
  If N_Elements(PageNum)    eq 0 then PageNum = 1

  Common SlopeParams, SlopeStr, KeyStr

  ;Include all of the keywords from the KeywordStruct file
  @KeywordStruct.pro
  @PlotSettings.pro
  If TvFlag eq 3 then begin
    xyoutcharsize=2.5 
    xyoutcharthick=3.0
    !p.charsize = xyoutcharsize
    !p.charthick = xyoutcharthick
    plotcharsize= 2
    plotcharthick=2.5
  EndIf Else begin
    xyoutcharsize=1.5
    xyoutcharthick=2.0 
    !p.charsize = xyoutcharsize
    !p.charthick = xyoutcharthick
    plotcharsize=1
    plotcharthick=1
  EndElse

  ;Get the mask threshold and a keyword for the output file
  If MasterMask then begin
    ;Read in the mask
    Fits_Read, MasterDeadMapPath, DeadMap, DeadHeader
    MaskThresh = 0
    MaskKey = 'MasterMask' 

  EndIf else begin
    ;Read in the mask
    Fits_Read, DeadPixelMaskPath, DeadMap, DeadHeader
    MaskThresh = max(DeadMap) - 1
    MaskKey = ''
  EndElse

  ;Find the dead pixel indices
  DeadPix = where(DeadMap gt MaskThresh and $
	    (Finite(DeadMap) eq 1), NumDeadIndices)
  ;Fits_Read, LeakyPixelMaskPath, LeakyMap, LeakyHeader
  ;Fits_Read, HotPixelMaskPath, HotMap, HotHeader

  If Rem60Hz then FilterStr = '_60HzRemoved'
  If stregex(RawFileName(0), 'Dark', /boolean) then begin 
     ObjectName  = 'Dark'
  EndIf

  ;We're considering 3x3 regions so HalfWidth is 1
  HWidth = 1 & HHeight = 1
 
  ;Get the current file that's being operated on
  FileNum = 0
  RawFile = RawFileName(FileNum)

  ;Get the base of the filename
  RawFileBase = (strsplit(RawFile,'.',/extract))[0]

  ;Plotting for .png
  PlotName = RawFileBase+'DeadSlopes.png'

  ;Get the unique keys in the filename for new filenames
  If stregex(RawFileBase, 'Median', /boolean) then begin 
     RawFileKey = RawFileBase 
  EndIf else begin
     RawFileKey  = strmid(RawFileBase, stregex(RawFile,'Reads_')+6)
  EndElse

  ;Open the raw FCB
  Position = Fits_Open_DataCube(RawFile, RawFCB, RawHeader, 'Read')
  Naxis1 =     RAWFcb.axis(0)
  Naxis2 =     RAWFcb.axis(1)
  TotalReads = RAWFcb.axis(2)         ;Number of Reads

  ;Get the parameters to feed the slope 
  SlopeStr = Return_Slope_Params(RawHeader)

  ;Get the dark frame if dark subtraction is required
  If SubtractDark then begin 
     DarkFileName = File_Search(DarkDir+'MedianDark*ForEachOf*'+$
        Strtrim(SlopeStr.NumGroups,2)+'Reads'+FilterStr+'.fits')
     If DarkFileName(0) eq '' then $
        DarkFileName = File_Search(DarkDir+'MedianBias*ForEachOf*'+$
        Strtrim(SlopeStr.NumGroups,2)+'Reads'+FilterStr+'.fits')
     If DarkFileName(0) eq '' then stop
     Position2 = Fits_Open_DataCube(DarkFileName, DarkFCB, DarkHeader, 'Read')
  EndIf

  ;Got through each pixel and pull it from the file
  If TvFlag eq 2 then begin
     device, filename = DeadDir+RawFileKey+'DeadPixelHistory'+MaskKey+'.ps'
  EndIf

  ;Keep Track of Number of types
  NumRH = 0	;Railed High Pixels
  NumR  = 0	;Dead Middle   Pixels
  NumRL = 0	;Railed Low  Pixels

  ;Open up a text file for output of some basic data
  get_lun, DeadPixTxtFile
  openw,   DeadPixTxtFile, DeadDir+RawFileKey+'DeadPixels'+MaskKey+'.txt'
  printf,  DeadPixTxtFile, $
       FORMAT = '(%"%s\t%s\t%s\t%s\t\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s")',$
      'Row', 'Column', 'Pixel', 'Type', 'Min', 'Max', 'Avg', 'Std', 'Page', $
      'Slope      ', 'Intercept  ', 'Error     '

  ;*****************************************************LOOP THROUGH THE BAD
  For DeadInd=0, NumDeadIndices-1 do begin
      DeadX = DeadPix(DeadInd) mod Naxis1 & DeadY = DeadPix(DeadInd)/Naxis2
      RawCube = long(Fits_Read_DataCube_Region( RawFile, RawFCB,$
                        RawHeader, $
                        DeadX-HWidth, DeadX+HWidth, $
			DeadY-HHeight,DeadY+HHeight, 0, TotalReads-1))
      If SubtractDark then $
      DarkCube = long(Fits_Read_DataCube_Region(DarkFileName, DarkFCB, $
                        DarkHeader, $
			DeadX-HWidth, DeadX+HWidth, $
			DeadY-HHeight,DeadY+HHeight, 0, TotalReads-1))

      SlopeFitStr = Return_SlopeFit_Region(RawCube, SubtractDark = 0)

      CenSlope = SlopeFitStr.Slopes(1,1)
      CenInt   = SlopeFitStr.Intercepts(1,1)
      CenErr   = SlopeFitStr.Errors(1,1)
      PixAvg   = Mean(RawCube(1,1,*))
      PixNoise = StdDev(RawCube(1,1,*)-PixAvg)
      PixMin   = Min(RawCube(1,1,*))
      PixMax   = Max(RawCube(1,1,*))
      PixType = 'Normal'
      If Mean(RawCube(1,1,*)) gt KeyStr.UpperADCThreshold then begin 
	PixType = 'Railed_High'
	NumRH += 1
      EndIf Else If $
	 Mean(RawCube(1,1,*)) lt KeyStr.LowerADCThreshold + 1000 then begin $
	PixType = 'Dead'
	NumR += 1
      EndIf Else begin
	PixType = 'Railed_Low'
	NumRL += 1
      EndElse

      ;Write to the text file
      printf, DeadPixTxtFile, $
	  FORMAT = '(%"%I\t%I\t%I\t%s\t%f\t%f\t%f\t%f\t%I\t%f\t%f\t%f")', $
	  DeadY, DeadX, DeadPix(DeadInd), PixType, PixMin, PixMax, $
	  PixAvg, PixNoise, DeadInd/4, CenSlope, CenInt, CenErr  
      print,PixType

      ;Do the plotting with 2x2 window
      If TvFlag ne 0 and DeadY ne 2617 then begin 
	 
	If (DeadInd mod 4) eq 0 then begin
	   !p.noerase = 0
	   If TvFlag eq 1 then window, xsize = 700, ysize = 700
	   erase
	Endif Else begin 
	   !p.noerase = 1
	EndElse

        Plot, RawCube(1,1,*), $
	       color = fsc_color('black'), background = fsc_color('white'), $
	       position = [ (DeadInd mod 2)*0.4 + 0.1, $
			    (DeadInd mod 4)/2*0.4+0.1, $
			    (DeadInd mod 2)*0.4 + 0.5, $
			    (DeadInd mod 4)/2*0.4+0.5], $
	       ystyle = 4*(DeadInd mod 2), xstyle = 4*(DeadInd mod 4)/2, $
	       yrange=[0,6.6e4],/normal
         oplot, CenSlope*SlopeStr.GroupTimes + CenInt, $
	        color = fsc_color('black'), linestyle = 2
	 oplot,RawCube(0,0,*), color = fsc_color('orange')
         oplot,RawCube(0,1,*), color = fsc_color('red')
         oplot,RawCube(0,2,*), color = fsc_color('blue')
         oplot,RawCube(1,0,*), color = fsc_color('brown')
         oplot,RawCube(1,2,*), color = fsc_color('purple')
	 oplot,RawCube(2,0,*), color = fsc_color('green')
	 oplot,RawCube(2,1,*), color = fsc_color('yellow')
         oplot,RawCube(2,2,*), color = fsc_color('pink')
         !p.noerase=1
	 Plot, RawCube(1,1,*), $
               color = fsc_color('black'), background = fsc_color('white'), $
                position = [ (DeadInd mod 2)*0.4 + 0.325, $
                            (DeadInd mod 4)/2*0.4+0.375, $
                            (DeadInd mod 2)*0.4 + 0.475, $
                            (DeadInd mod 4)/2*0.4+0.50], $
	       /normal

                          
	 !p.charsize = xyoutcharsize
	 !p.charthick = xyoutcharthick
	 xyouts, (DeadInd mod 2)*0.4+.125, (DeadInd mod 4)/2*0.9+0.04, $
	      Strtrim(DeadX, 2) + ' , ' + Strtrim(DeadY, 2), $ 
	      /normal, color = fsc_color('black')
         xyouts, (DeadInd mod 2)*0.4+.325, (DeadInd mod 4)/2*0.9+0.04, $
	      PixType, $
	      /normal, color = fsc_color('red')

	 !p.charsize = plotcharsize
	 !p.charthick = plotcharthick
	 ;Make a key with the makesquare.pro script
	 If (DeadInd mod 4) eq 0 then MakeSquare, TvFlag = TvFlag
         print, DeadInd/4	
 	 ;Write a png only once in the loop
	 If TvFlag eq 3  and ((DeadInd+1) mod 4) eq 0 and $
	    ((DeadInd/4) eq PageNum) then begin
            PngImg = tvrd()
            tvlct,reds,greens,blues,/get
            write_png,PlotDir+PlotName, $
                 PngImg,reds,greens,blues
	    TvFlag = 0
	EndIf
         If ((DeadInd+1) mod 4) eq 0 and (TvFlag eq 1) then stop
      EndIf

  EndFor

  xyouts, 0.1, 0.9, 'Number of SuperHot Pixels : '+Strtrim(NumRH, 2), $
	/normal, color = fsc_color('black')
  xyouts, 0.1, 0.85,'Number of Hot Pixels : '+Strtrim(NumR, 2), $
	/normal, color =fsc_color('black')
  xyouts, 0.1, 0.80,'Number of Dead Pixels : ' + Strtrim(NumRL, 2), $
	/normal, color =fsc_color('black')
  
  Close, DeadPixTxtFile
  Free_Lun, DeadPixTxtFile

If TvFlag eq 2 then device, /close

stop

End
         
