;pro Read_Noise
;
;PURPOSE:
;	To examine a region of a frame from the detector and return the mean
;	and stddev as an estimate of the read noise
;INPUTS:
;	FitsFileName - The path to a fits file that will be used to extract 
;		       the noise
;
pro Read_Noise_Bad_Pix, BadPixFileName, RootDir=RootDir, Date=Date, $
  TvFlag = TvFlag, BadRows = BadRows

  ;A list of the bad rows on the detector
  If not keyword_set(BadRows) then BadRows = [2617]

  ;Include all of the keywords from the KeywordStruct file
  @KeywordStruct.pro
  @PlotSettings.pro

  ;PlotName
  PlotName1 = 'ReadNoiseOfBadPixels.png'
  PlotName2 = 'ReadNoiseOfBadRow.png'
  ;Move to the directory
  cd, DeadDir
  
  readcol, BadPixFileName, Row, Col, Pixel,PixType, PixMin, PixMax, $
	  PixAvg, PixStd, $
	  /debug, skipline = 1, $
	  format='I, I, L, A, F, F, F, F, X, X, X, X'

  ;Sort the pixels according to ones that do or do not belong to the bad rows
  BadRowInds = [0] & NonBadRowInds = [0]
  For RowNum = 0, N_Elements(BadRows)-1 do begin 
     BadRowIndsTemp = Where(Row eq BadRows(RowNum), complement=NonBadRowInds)
     BadRowInds    = [BadRowInds, BadRowIndsTemp]
     NonBadRowInds = [NonBadRowInds, NonBadRowInds]
  Endfor
  BadRowInds    = BadRowInds(1:N_Elements(BadRowInds)-1)
  NonBadRowInds = NonBadRowInds(1:N_Elements(NonBadRowInds)-1)

  If TvFlag ne 0 then begin
    If TvFlag eq 2 then device, filename = ReducedDir+'NoiseChannel0'+Date+'.ps'
    ;Plot the noise of the pixels that aren't in the bad row
    !p.multi = [0,1,1]
    NoiseHist = histogram(PixStd(NonBadRowInds), locations = LocNoise)
    NoiseHist = [0, NoiseHist]
    Plot, LocNoise, NoiseHist, psym = 10, xrange=[0,60],$
	title = 'Read noise of Dead Pixels - Gain = 12dB', $
	xtitle = 'Counts', ytitle = 'Number', color = fsc_color('black'), $
	background = fsc_color('white')
    If TvFlag eq 3 then begin 
            PngImg = tvrd()
            tvlct,reds,greens,blues,/get
            write_png,PlotDir+PlotName1, $
                 PngImg,reds,greens,blues
    EndIf

    ;Plot the noise of the pixels in the bad row
    Plot, Col(BadRowINds)/128, PixStd(BadRowInds), psym = 2, xrange=[0,32],$
        title = 'Read noise of Row 2617  - Gain = 12dB', $
        xtitle = 'Channel', ytitle = 'Noise', color = fsc_color('black'), $
        background = fsc_color('white')
    oplot,Col(BadRowInds)/128, PixStd(BadRowInds), color=fsc_color('red'), $
	psym=2
    If TvFlag eq 2 then device, /close
    If TvFlag eq 3 then begin
            PngImg = tvrd()
            tvlct,reds,greens,blues,/get
            write_png,PlotDir+PlotName2, $
                 PngImg,reds,greens,blues
    EndIf

  EndIf
  stop

end
