;pro Find_Hot_Pixels 
;
;PURPOSE:
;	To try and find the hot pixels of the detector.  This is done 
;	using (1) the slopefits to the median darks and (2) the .
;
;INPUTS:
;
;OUTPUTS:
;
;KEYWORDS:
;       ROOTDIR: 
;         The Directory holding the directories of Raw files
;       DATE:
;         The Date during which they were taken.  Also the subdirectory that 
;         the files are in.
;       REDUCEDDIR:
;         The directory where the processed images and plots will be placed in.
;       BLOCKLENGTH:
;         An offset for files that were written improperly.  The readu 
;         function reads the values with this offset in place.
;       OBJECTNAME:
;         The string that indicates what files are being sought.  The filenames
;         should begin with this string ('Dark', 'Raw', etc.).
;	OVERRIDE: 
;	  Do the processing even if the output file already exists
;	BATCHMODE:
;	  Use the list of slope images (path defined in KeywordStruct.pro)
;	  as the input to the test for high dark current. 
;	TVFLAG:
;	  3 - generate a .png file showing the histogram of the median 
;	      of the dark current slopes after removing the high dark 
;	      current pixels 
;**************************************************************************

pro Find_Hot_Pixels, RootDir=RootDir, Date=Date, $
         ReducedDir = ReducedDir, BlockLength = BlockLength, $
         ObjectName=ObjectName, NReads = NReads, ThisFilter = ThisFilter,$
         OverRide = OverRide, BatchMode = BatchMode, TvFlag = TvFlag

  IF N_Elements(BatchMode) eq 0 then BatchMode = 1

  Common KeyParams, KeyStr

  ;Include KeywordStruct.pro file with all the defaults for keywords
  @KeywordStruct.pro
  @PlotSettings.pro
  PlotName = 'HotHistogram.png'
  ;Make the directories if they don't exist
  File_Mkdir, LeakyMasterDir & File_Mkdir, HotMasterDir
 
  ;Start in the RootDir/Date directory
  cd, Rootdir+Date

  ;Get the Files from a list in the Leaky Directory or from a search
  If BatchMode then begin 
    ReadCol, DarkSlopeList, RawFiles, Format = 'A'
    NumFiles   = N_Elements(RawFiles)
  EndIf 

  ;Get a Few Kewyords
  Fits_Read,  RawFiles(0), NoData, FitsHeader, /header_only
  TotalReads = long(sxpar(FitsHeader,'NAXIS3'))
  ArrSize = long(KeyStr.Naxis1*KeyStr.Naxis2)

  ;Make an array for all of the slopes
  SlopeArr = Fltarr(KeyStr.Naxis1, KeyStr.Naxis2, NumFiles)

  ;Get the masks already in place
  Masks = Return_Pixel_Masks()
  

  ;************************************************* 1 High DarkCurrent Pix
  ;Go through the dark current slopes and find the ones where a line could 
  ;not be fit as well as the ones that were greater than 500 counts/sec
  For FileNum = 0, NumFiles -1 do begin 
      Fits_Read_DataCube,RawFiles(FileNum), RawIm, RawHeader
      Slopes = RawIm(*,*,0)

      ;Kill the pixels that have already been found in other masks
      Slopes(0:KeyStr.Ch0W-1,*) = 0  
      Slopes(Masks.LeakyInd) = 0
      Slopes(Masks.DeadInd)  = 0

      ;Form the final array
      SlopeArr(*,*,FileNum) = Slopes

      ;A little verbosity
      print,'Looking at File : '+Strtrim(FileNum,2)
      print,'Number of NaNs  : '+Strtrim(N_Elements(where(Finite(Slopes) eq 0)))

  endfor

  SlopeMedian = Median(SlopeArr, dimension = 3)

  ;Form the Hot Pixel Mask
  HotMask = bytarr(KeyStr.Naxis1, KeyStr.Naxis2)
  HotMask(where(finite(SlopeMedian) eq 0)) = 1
    SlopeMedian(where(finite(SlopeMedian) eq 0)) = 0

  ;Look for very hot pixels
  HotMask(where(SlopeMedian gt 300, NumHot)) = 1
  print, 'Number of High Dark Current Pixels : ' , NumHot
 
  ;*****************************************************2 Super Hot Pix 
  ;Also look for pixels that were very near the upper rail in the 
  ;bias read of the darks. They will not have time to show up with 
  ;a high slope since they are already bent over in the parabola
  ValidDates = ['07Apr26']
  For DateNum = 0, N_Elements(ValidDates)-1 do begin
    MedianDarks = File_Search(Keystr.RootDir + 'Reduced'+$ 
			KeyStr.PathDelim+ValidDates(DateNum)+$
			KeyStr.PathDelim+'Darks'+KeyStr.PathDelim+$
			'Median*ForEachOf*Reads.fits')
    For DarkNum = 0, N_Elements(MedianDarks)-1 do begin
        Fits_Read_DataCube, MedianDarks(DarkNum), MedDarkBias, MedHeader, $
		ZStart=0, ZStop=0
        FullADRange = Max(MedDarkBias)-Min(MedDarkBias)
	CutThresh = Min(MedDarkBias) + 0.70*FullADRange
	MedDarkBias(Masks.BadPixels) = 0
        SuperHotInds = where(MedDarkBias gt CutThresh, NumSuperHot)
	print, 'Number of Super Hot Pixels: ' , NumSuperHot
	HotMask(SuperHotInds) = 1                         
    EndFor
  EndFor 

  ;******************************************************************
  NumHot = N_Elements(where(HotMask eq 1))
  print, 'Found '+strtrim(NumHot,2) + ' Hot Pixels'
  ;Write the Mask out
  Fits_Write, HotMasterMapPath, HotMask

  If TvFlag eq 3 then begin
     SlopeHist = Histogram(SlopeMedian, locations = LocPix)
     SlopeHist = [0, SlopeHist]
     Plot, LocPix, SlopeHist, yrange = [0,100], color=fsc_color('black'), $
	   background = fsc_color('white'), $
	   title = 'Dark Current Slopes', xtitle = 'Counts/Sec', $
	   ytitle = 'Number'
           PngImg = tvrd()
            tvlct,reds,greens,blues,/get
            write_png,PlotDir+PlotName, $
                 PngImg,reds,greens,blues
  EndIf
   
stop

end
