;pro master_pixel_mask
;
;PURPOSE:
;	To combine pixel mask from individual nights or files into a master
;	that will be used for the full frame images
;
;INPUTS:
;	MASKTYPE-
;	'Dead' - The dead pixel masks are extracted from median darks.
;		 They are located in their respective directories
;KEYWORDS:
;	MaskCombine -
;	'Or'  - All of the bad pixels are combined with a logical or, so 
;	        the map consists of any pixels that were flagged on 
;		an individual night as being hot.
;	'And' - All of the bad pixels are combined with a logical and, so 
;		the map consits of only pixels that were flagged on 
;		every night as being hot.
;
pro Master_Pixel_Mask, MaskType, MaskFiles=MaskFiles, $
	MaskCombine = MaskCombine, TvFlag=TvFlag

If N_Elements(TestMask)    eq 0 then TestMask = 1
If N_Elements(MaskCombine) eq 0 then MaskCombine = 'Or'

;Get the keyword structures
@KeywordStruct.pro
@PlotSettings.pro

Case MaskType of 
  ;*************************************************************DEAD PIXELS
  'Dead' : begin

   ;Form the name for the plot
   MaskDir  = DeadMasterDir
   PlotName = MaskType+'PixelHistograms.png'

   ;Dates of medians to include in the mask
   Dates=['07Apr26','07Apr28','07Apr30']
   Colors=['red','navy','black']
   LineStyles = [0,3,2]
   Syms=[0,0,0]
   NDates=N_Elements(Dates)
   Masks = UIntArr(Naxis1,Naxis2,NDates)

   If MaskCombine eq 'Or' then begin 
    MaskFinal = BytArr(Naxis1,Naxis2)
   EndIf Else if MaskCombine eq 'And' then begin
    MaskFinal = BytArr(Naxis1,Naxis2) & MaskFinal(*) = 1
   EndIf
 
   ;Set up for plotting
   !p.noerase = 0
   erase

   For Date = 0, NDates-1 do begin

    ;Get the individual mask files  
    MaskFile=File_Search(RootDir+'Reduced'+PathDelim+Dates(Date)+$
	    PathDelim+'DeadPix'+PathDelim+'*PixelMap*'+MaskFiles+'.fits')

    ;The mask files up to this point contain the number of times the pixel was
    ;flagged as bad, turn them into ones
    Fits_Read, MaskFile, MaskTemp, MaskHeadTemp
   
    ;Histogram the pixels for plotting purposes if tvflag is right
    If TvFlag ne 0 then begin
      DeadHist = histogram(MaskTemp)
      DeadHist = [DeadHist,0]
      plot, DeadHist, psym=10, yrange=[0,8000], $
	background = fsc_color('white'), color = fsc_color(colors(date)), $
	xtitle = '# of times I(x,y,r)-I(x,y,0) < Max Read Noise', $
	ytitle = 'Pixels', title = 'Dead Pixel Filter', $
	linestyle = linestyles(date), thick = 2
      !p.noerase = 1
    EndIf

    DeadPix = where(MaskTemp eq (max(MaskTemp)), NumDead, $
	complement = NotDeadPix)
    MaskTemp(DeadPix) = 1 & MaskTemp(NotDeadPix) = 0
    Masks(*,*,Date) = MaskTemp

    print, 'Number of Bad Pixels in Mask from ' + Dates(Date) +' : '$
	+Strtrim(NumDead,2)
    ;Form the final mask that hold only the pixels that are always flagged
    If MaskCombine eq 'And' then begin 
	MaskFinal = MaskFinal and MaskTemp
    Endif Else if MaskCombine eq 'Or' then begin
	MaskFinal = MaskFinal or MaskTemp
    EndIf

    Delvarx, MaskTemp
 
  Endfor

  ;Plot the histograms from each night on top of each other
  If TvFlag ne 0 then legend, Dates, psym=Syms, color=fsc_color(Colors), $
	textcolors = fsc_color(Colors), linestyle = LineStyles, $
	position = [0.55,0.9], /normal
  If TvFlag eq 3 then begin
     PngImg = tvrd()
     tvlct,reds,greens,blues,/get
     write_png,PlotDir+PlotName, $
        PngImg,reds,greens,blues

  ;Make a Header for the Dead Mask
  MkHdr, MaskFinalHeader, MaskFinal
  For Date =0, NDates-1 do begin
    SxAddPar, MaskFinalHeader, 'DATE'+Strtrim(Date,2), Dates(Date), $
          'Date of Masks used to form this mask'
  EndFor

  EndIf
  End
  ;***********************************************************************LEAKY
  'Leaky' : begin

  ;Directories
  MaskDir  = LeakyMasterDir
  
  ;Mask and average values for pixels from all median flats
  MaskFile = File_Search(LeakyMasterDir+$
	'LeakyPixelCenMask*MedianFlats*2Reads.fits')
  NNMaskFile  = File_Search(LeakyMasterDir+$
	'LeakyPixelNNMask*MedianFlats*2Reads.fits')

  ValsFile = File_Search(LeakyMasterDir+'LeakyPixelValues*MedianFlats*2Reads.fits')

  Fits_Read, MaskFile, LeakyCenMask, MaskFinalHeader
  Fits_Read, NNMaskFile, LeakyNNMask, LeakyNNMaskHeader
  Fits_Read, ValsFile, LeakyVals, LeakyValsHeader

  ;Demand that the pixels be flagged in every median flat
  LeakyInds            = where(LeakyCenMask eq (max(LeakyCenMask)))
  MaskFinal 	       = BytArr(Naxis1,Naxis2)
  MaskFinal(LeakyInds) = 1
  LeakyNNInds	       = where(LeakyNNMask eq max(LeakyNNMask))
  MaskNNFinal 	       = BytArr(Naxis1,Naxis2)
  MaskNNFinal(LeakyInds) = 1

  Fits_Write, MaskDir+PathDelim+MaskType+'NNMask.fits', MaskNNFinal, $
	MaskFinalHeader
  End

EndCase


;Write the mask
Print, 'Writing file : '+MaskDir+PathDelim+$
	MaskType+'Mask.fits'

Fits_Write, MaskDir+PathDelim+MaskType+'Mask.fits', MaskFinal,$
	MaskFinalHeader



If TestMask eq 1 then begin
   cd, DarkDir
   Fits_Read, 'MedianDark_Blank_ForEachOf_30Reads.fits', DarkIm
   stop
   DarkIm(0:127,*,*)=0
   RailedPix = where(MaskFinal eq 1)
   print,n_elements(RailedPix)
EndIf

!p.noerase=0
set_plot,'x'

stop

End 
