;pro examine_pixel_list
;
;PURPOSE:
;	To take in set of pixels and plot their individual ramps for a 
;	dark and an object file.
;
;INPUTS:
;	PIXELS - A one dimensional list of pixel indices into the 2-d array 
;		 (1-d coordinates). The pixel values of those coordinates will
;		 be plotted  
;		 If pixels is not supplied, the xstart, xstop, ystart, and ystop 
;		 keywords will be used to define a region 
;KEYWORDS:
;
;	PIXELSKIP - A number of pixels that will be skipped to reach farther back into
;		    the list
pro WindowStartUp

    Common ExState, State, Masks
    Common Images, DarkIm, ObjectIm, FlatIm

    State.WindowBase = widget_base(title='Window', column = 1, uvalue = 'WindowBase')
    State.MainDrawId = widget_draw(State.WindowBase, xsize=512, ysize = 512, frame = 2, $
                             uvalue = 'MainWindowGetPix', /motion_events, /button_events,$
			     keyboard_events=1)
    Widget_Control, State.WindowBase, Set_Uvalue = info, /No_Copy
    Widget_Control, /Realize, State.WindowBase
    Widget_Control, State.MainDrawId, get_value = Tmp_Value
    State.MainWindowID = Tmp_Value
    Widget_Control, State.MainDrawID, Event_Pro = 'Examine_Pixel_List_Event'
    XManager, 'Examine_Pixel_List', State.WindowBase,/no_block

End

pro Examine_Pixel_List_Event, Event
 
    Common ExState
    case Event.type of 
         0: begin  
            print, event.x,event.y
	    State.PixelXSub = floor(event.x * float(State.Width/512.))
            State.PixelYSub = floor(event.y * float(State.Height/512.))
            State.PixelX = State.PixelXSub + State.XStart
            State.PixelY = State.PixelYSub + State.YStart 
	    print, State.PixelX, State.PixelY
	    PlotPixels, State.PixelXSub, State.PixelYSub, State.PixelX, State.PixelY 
         end
         else: begin 
         end
    endcase 
end

pro PlotPixels, PixelXSub, PixelYSub, PixelX, PixelY
    Common ExState
    Common Images
    Common KeyParams, SlopeStr, KeyStr, SlopeFitStr
 
    !p.multi=[0,2,2]
    PixTInd = PixelX + PixelY*State.Naxis2
    ;Check to see if it falls in one of the pixel mask categories
    If (where(Masks.DeadInd eq PixTInd))[0] ne -1 then begin
       PixelType = 'Dead'
    EndIf else if (where(Masks.LeakyInd eq PixTInd))[0] ne -1 then begin 
       PixelType = 'Leaky'
    Endif else if (where(Masks.LeakyNNInd eq PixTInd))[0] ne -1 then begin
       PixelType = 'Next to Leaky'
    Endif else if (where(Masks.HotInd eq PixTInd))[0] ne -1 then begin
       PixelType = 'Hot'
    Endif else begin
       PixelType = 'Good'
    EndElse

    If KeyStr.TvFlag eq 3 then begin 
      Set_plot,'z'
      device,set_resolution=[1400,1200]
      !p.charsize=2
      !p.charthick=2.5
      !x.thick=1.75
      !y.thick=1.75
      !p.thick=2.25
      !p.noerase=0
      loadct, 0
      !p.font = 1
      device, font = 'Helvetica Bold'
    EndIf
    
    If PixelY gt State.Ref/2 then begin
      ;Subtract Biases
      ObjectRamp = long(ObjectIm(PixelXSub, PixelYSub, *)) - $
                   long(ObjectIm(PixelXSub, PixelYSub,0))
      DarkRamp   = long(DarkIm(PixelXSub,PixelYSub,*) - $
		   long(DarkIm(PixelXSub,PixelYSub,0)))

       ;Plot the Dark Image Ramp========================1
       Plot, DarkIm(PixelXSub, PixelYSub, *), $
	  title = 'Dark Image for '+strtrim(PixelX,2)+','+strtrim(PixelY,2), $
	  min = min(DarkIm(PixelXSub,PixelYSub,*)), $
	  max = max(DarkIm(PixelXSub,PixelYSub,*)), $	
	  color = fsc_color('black'), background = fsc_color('white')

      ;Plot the Object Image Ramp=======================2
      Plot, ObjectRamp, $
	    title = 'Object Image for '+strtrim(PixelX,2)+','+strtrim(PixelY,2), $
	    min = min(ObjectRamp), max = max(ObjectRamp), $
	    color=fsc_color('black')
      xyouts, 0.75,0.6, 'Bias Read : ' + Strtrim(ObjectIm(PixelXSub,PixelYSub,0)), $
	    /normal, $
	    color = fsc_color('black')
      xyouts, 0.75,0.65, 'Last Read : ' + $
	    Strtrim(ObjectIm(PixelXSub,PixelYSub,State.NReads - 1)), /normal, $
	    color=fsc_color('black')
      xyouts, 0.75, 0.70, 'Pixel Type : ', /normal, color = fsc_color('black')
      xyouts, 0.85, 0.70, PixelType, /normal, color = fsc_color('red')

      ;Plot the Object - Dark===========================3
      Plot, FlatIm(PixelXSub, PixelYSub, *), $
	    title = 'Flat', $
	    color = fsc_color('black')

      ;Plot the Object - Dark - Bias ===================4
      Plot, ObjectRamp - DarkRamp, $
	    title = 'Object - Dark : No Bias', $
	    color = fsc_color('black')

      If State.SlopeFit then begin 
        NumPoints = $
	N_Elements(where(SlopeFitStr.SN(PixelXSub,PixelYSub,*) ne 0))
        xyouts, 0.75, .25, 'Num Points :'+ Strtrim(NumPoints,2), $
	    /normal, color=fsc_color('black')
        xyouts, 0.75, .20, 'Slope : ' + $
	    Strtrim(SlopeFitStr.Slopes(PixelXSub,PixelYSub)),$
	    /normal, color=fsc_color('black')
        xyouts, 0.75, .15, 'Slope/Flat :'+ $
	    Strtrim(SlopeFitStr.SLopes(PixelXSub, PixelYSub)/$
	    FlatIm(PixelXSub,PixelYSub,1)*Max(FlatIm),2), $
	    /normal, color=fsc_color('black')

      EndIf
      If KeyStr.TvFlag eq 3 then begin 
	   PlotName = 'PixelSlopesFor_'+Strtrim(PixelX,2)+'_'+Strtrim(PixelY,2)+'.png'
           PngImg = tvrd()
            tvlct,reds,greens,blues,/get
            write_png,KeyStr.PlotDir+PlotName, $
                 PngImg,reds,greens,blues
	   KeyStr.TvFlag = 1
           Set_plot,'x'
           resetplt 
      EndIf 

      Print, ObjectRamp - DarkRamp 
    EndIf

End

pro Examine_Pixel_List, Pixels, TvFlag = TvFlag, XStart = XStart, $
	XStop = XStop, YStart=YStart, YStop = YStop , $
	PixelSkip = PixelSkip, DarkFile = DarkFile, $
	ObjectFile = ObjectFile, Date = Date, NReads = NReads, $
	GUI = GUI, PlotIm = PlotIm, SlopeFit = SlopeFit

If not keyword_set(PixelSkip) then PixelSkip = 0
If not keyword_set(GUI) then GUI = 0
If not keyword_set(PlotIm) then PlotIm = 0
If not keyword_set(SlopeFit) then SlopeFit = 0

;Coords of bright stars in the default image
If Not keyword_set(XStart) then XStart = 1565
If Not keyword_set(XStop)  then XStop  = 1615
If Not keyword_set(YStart) then YStart = 2470
If Not keyword_set(YStop)  then YStop  = 2530

;Set up some state variables
Common ExState
Common Images
Common KeyParams, SlopeStr, KeyStr, SlopeFitStr

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

State = { WindowBase: 0L, $
	  MainDrawID: 0L, $
	  MainWindowID: 0L, $
	  Naxis1      : Naxis1, $
	  Naxis2      : Naxis2, $
	  NumPixels   : 0L, $
	  PixelX      : 0L, $
	  PixelY      : 0L, $
	  PixelXSub   : 0L, $
	  PixelYSub   : 0L, $
	  XStart      : XStart, $
	  YStart      : YStart, $
	  XStop       : XStop, $
	  YStop       : YStop, $
	  Height      : 0L, $
	  Width	      : 0L, $
	  Ref         : Ref ,$
          NReads      : NReads , $
	  SlopeFit    : SlopeFit }

Userwindow = !d.window
wset, Userwindow

;Initialize the widget
WindowStartUp

;A region was supplied to the script or a list of pixels
If (Size(Pixels))[0] eq 0 then begin 
  State.Width = long(XStop-XStart+1) & State.Height = long(YStop-YStart+1)
  State.NumPixels = long(State.Width)*long(State.Height)

  ;Get the relative coordinates of the pixels in the window
  PixelsSub =  (Indgen(State.NumPixels) mod State.Width) + $
	       (Indgen(State.NumPixels)/ State.Width)*State.Width
  PixelsXSub = PixelsSub mod State.Width &  PixelsYSub=PixelsSub/State.Width
  ;Get the absolute value of the pixels on the full frame
  Pixels =    (Indgen(State.NumPixels) mod State.Width)+XStart+$
	      ((Indgen(State.NumPixels)/State.Width)+YStart)*(Naxis2)
  PixelsX=    Pixels mod Naxis1  &      PixelsY = Pixels/Naxis2

EndIf Else begin 
  State.NumPixels = N_Elements(Pixels)
  XStart = 0  & XStop = Naxis1-1
  YStart = 0  & YStop = Naxis2-1
  PixelsXSub = Pixels mod Naxis1 &  PixelsYSub = Pixels/Naxis2
  PixelsX    = PixelsXSub        &  PixelsY    = PixelsYSub

EndElse

If Not keyword_set(ObjectFile) then $
   ObjectFile = '/nfs/slac/g/ki/ki09/lances/07Apr28/'+$
'M13_Dither3_0ArcSecondsEast_20ArcSecondsNorth_H4RG_SIPIN_20_Reads_Apr29_2007_02_47_59.fits'

;Read in the Object File
Position = Fits_Open_DataCube(ObjectFile, ObjectFCB, ObjectHeader, 'Read')
FileParams = Return_File_Params(ObjectHeader)
State.NReads=KeyStr.TotalReads
ObjectIm = Fits_Read_DataCube_Region(ObjectFile, ObjectFCB, ObjectHeader, $
                XStart, XStop, YStart, YStop, 0, KeyStr.TotalReads-1)
ObjectClose = Fits_Close_DataCube(ObjectFCB)
Position = Fits_Open_DataCube(ObjectFile, ObjectFCB, ObjectHeader, 'Read')
print, 'Opened Object'

;Get some files for the plotting
If Not keyword_set(DarkFile) then DarkFile   = KeyStr.DarkName 
If Not keyword_set(FlatFile) then FlatFile   = KeyStr.FlatName

;Read in the files that will be used for the examination
Position = Fits_Open_DataCube(DarkFile, DarkFCB, DarkHeader, 'Read')
DarkIm = Fits_Read_DataCube_Region(DarkFile, DarkFCB, DarkHeader, $
		XStart, XStop, YStart, YStop, 0,KeyStr.TotalReads-1)
DarkClose = Fits_Close_DataCube(DarkFCB)
print, 'Opened Dark'
;Read in the Flat File
Position = Fits_Open_DataCube(FlatFile, FlatFCB, FlatHeader, 'Read')
FlatIm = Fits_Read_DataCube_Region(FlatFile, FlatFCB, FlatHeader, $
                XStart, XStop, YStart, YStop, 0, 1)
FlatClose = Fits_Close_DataCube(FlatFCB)
print, 'Opened Flat'

;Try to fit the slope
If Slopefit then begin
  SlopeStr = Return_SlopeFit_Region(ObjectIm, DarkCube = DarkIm, $
			RawHeader = ObjectHeader, /subtractdark)
EndIf
 
wset, state.mainwindowid
tvscl, congrid(ObjectIm(*,*,State.NReads-1), 512,512)
;tvscl, congrid(ObjectIm(*,*,6)/double(FlatIm(*,*,1)),512,512)
window,1

;Allow for plotting of the image being viewed to a .png
If PlotIm eq 1 then begin
   Set_plot,'z' 
   device,set_resolution=[512,512]
   DisplayIm = Fltarr(State.width, State.Height,3)
   DisplayIm = [[[ObjectIm(*,*,State.NReads-1)]], $
	        [[ObjectIm(*,*,State.NReads-1)]], $
		[[ObjectIm(*,*,State.NReads-1)]]]
   tvimage, Congrid(bytscl(DisplayIm),512,512,3) ,/tv, true = 3
   PlotName = 'M13Region.png'
   PngImg = tvrd()
   tvlct,reds,greens,blues,/get
   write_png,KeyStr.PlotDir+PlotName, $
                 PngImg,reds,greens,blues
   KeyStr.TvFlag = 1
   Set_plot,'x'
   resetplt
EndIf

tvscl,congrid(ObjectIm(*,*,State.NReads-1),512,512)

;tvscl, congrid(ObjectIm(*,*,10)/double(FlatIm(*,*,1)),512,512)

;Get the bad pixel maps to check what type of pixel we're plotting
Masks = Return_Pixel_Masks()

;If a list was supplied then plot the pixels in that list
If GUI eq 0 then begin
   For PixInd = 0L, State.NumPixels-1 do begin
    ;Allow for skipping of some pixels
    PixTInd = PixInd + PixelSkip
    PixelX    = PixelsX(PixTInd)      & PixelY    = PixelsY(PixTInd)
    PixelXSub = PixelsXSub(PixTInd)   & PixelYSub = PixelsYSub(PixTInd)
    PlotPixels, PixelXSub, PixelYSub, PixelX, PixelY
    stop
   EndFor
EndIf

End

