;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
;pro Find_Hot_Pixels_xRG 
;
;PURPOSE:
;	To try and find the hot pixels of the detector.  This is done 
;	using (1) median darks and (2) the slopefits to the median darks.
;
;INPUTS:
;       FitsFileName: str
;         The full path to the dark that will be used to generate the mask
;       SlopeFileName: str
;      
;OUTPUTS:
;
;KEYWORDS:
;	OVERRIDE: 
;	  Do the processing even if the output file already exists
;	TVFLAG:
;	  3 - generate a .png file showing the histogram of the median 
;	      of the dark current slopes after removing the high dark 
;	      current pixels 
;
;EXAMPLES:
;  find_hot_pixels_xrg,'/nfs/slac/g/ki/ki03/lances/H2RG-32-147/ASIC/Reduced/07Dec19/Dark/MedianDark_Blank_80_Reads_RPS.fits', '/nfs/slac/g/ki/ki03/lances/H2RG-32-147/ASIC/Reduced/07Dec19/Dark/MedianDark_Blank_80_Reads_RPS_Slope.fits'
;  find_hot_pixels_xrg, '/nfs/slac/g/ki/ki03/lances/H1RG-022/ASIC/Reduced/07Nov17/Dark/MedianDark_Blank_200_Reads_RPS.fits', '/nfs/slac/g/ki/ki03/lances/H1RG-022/ASIC/Reduced/07Nov17/Dark/MedianDark_Blank_200_Reads_RPS_Slope.fits'
;
;**************************************************************************

pro Find_Hot_Pixels_xRG, FitsFileName, SlopeFileName, $
    OverRide = OverRide, TvFlag = TvFlag

  ;Include KeywordStruct.pro file with all the defaults for keywords
  @KeywordStruct_xRG.pro
  @PlotSettings_xRG.pro
  @NightParams_xRG.pro

  ;FileNames
  MedFileName   = FitsFileName
  SlopeFileName = SlopeFileName

  ;Get a Few Kewyords
  Fits_Read,  SlopeFileName, 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)

  ;Get the masks already in place
  Masks = Return_Pixel_Masks_xRG()
  
  ;************************************************* 1 High DarkCurrent Pix
  ;Flag pixels that could not be fit in the slopefit 
  ;as well as the ones that were greater than 500 counts/sec
  Fits_Read_DataCube, SlopeFileName, RawIm, RawHeader
  Slopes = RawIm(*,*,0)

  ;Kill the pixels that have already been found in other masks
  ;If H4RG is used, take first channel as obsolete
  If KeyStr.DetStr eq 'H4RG-10-007' then begin
    Ch0W   = KeyStr.Ch0W
  EndIf Else Begin
    Ch0W   = Ref/2
  EndElse

  Slopes(Masks.LeakyInd)                     = 0
  Slopes(Masks.DeadInd)                      = 0
  Slopes(0:Ch0W-1,*)                         = 0
  Slopes(KeyStr.Naxis1-4:KeyStr.NAxis1-1, *) = 0
  Slopes(*, 0:KeyStr.Ref/2-1)                = 0
  Slopes(*, KeyStr.NAxis2-4:KeyStr.NAxis2-1) = 0

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

  ;A little verbosity
  BadSlopeVals = where(Finite(Slopes) eq 0)
  if BadSlopeVals(0) ne -1 then begin
    print,'Number of NaNs  : '+Strtrim(N_Elements(where(Finite(Slopes) eq 0)))
    HotMask(where(finite(Slopes) eq 0)) = 1
    Slopes(where(finite(Slopes) eq 0)) = 0
  endif else begin
    print,'No NaNs Present'
  endelse
  ;Form the Hot Pixel Mask
  HotMask = bytarr(KeyStr.Naxis1, KeyStr.Naxis2)

  ;Look for very hot pixels
  DarkCurrentMax = KeyStr.CGain*2.
  HotLocs = where(Slopes gt DarkCurrentMax)
  NumHot  = 0
  if HotLocs(0) ne - 1 then HotMask(where(Slopes gt DarkCurrentMax, 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
  Fits_Read_DataCube, MedFileName, MedDarkBias, MedHeader, $
		ZStart=0, ZStop=0

  FullADRange = KeyStr.UpperLinLim-KeyStr.LowerLinLim
  MedDarkBias(Masks.LeakyInd)                     = 0
  MedDarkBias(Masks.DeadInd)                      = 0
  MedDarkBias(0:Ch0W-1,*)                         = 0
  MedDarkBias(KeyStr.Naxis1-4:KeyStr.NAxis1-1, *) = 0
  MedDarkBias(*, 0:KeyStr.Ref/2-1)                = 0
  MedDarkBias(*, KeyStr.NAxis2-4:KeyStr.NAxis2-1) = 0

  CutThresh = KeyStr.LowerLinLim + 0.70*FullADRange
  SuperHotInds = where(MedDarkBias gt CutThresh, NumSuperHot)
  if SuperHotInds(0) ne -1 then begin 
    print, 'Number of Super Hot Pixels: ' , NumSuperHot
    HotMask(SuperHotInds) = 1                         
  endif
  ;******************************************************************
  NumHot = N_Elements(where(HotMask eq 1))
  print, 'Found '+strtrim(NumHot,2) + ' Hot Pixels'

  ;Write the Mask out
  Fits_Write, HotMasterMapPath, HotMask
  stop

  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
