;analysesoariamge
;
;Purpose: 
;	This script takes in an image from the SOAR telescope.
;
;	ViewingMode=1 
;	The frames with an exposure time of 30 seconds
;	will be examined for cosmic rays.  These frames are extremely out of 
;	focus, so only cosmic rays come above the background count
;
;	ViewingMode=2
;	The frames in focus will be examined.  Stars, cosmic rays, and galaxies
;	should all be flagged as Contiguous sets of pixels

Pro analysesoarimage,date=date,SingleImage=SingleImage,$
	       SearchRegion=Searchregion,VR=VR,$
	       ViewingMode=ViewingMode,Sigma=Sigma,$
	       ThresholdSlope=ThresholdSlope,$
	       MinThreshold=MinThreshold
If (not keyword_set(SingleImage)) then SingleImage = 1
If (not keyword_set(date)) then date = '11'
If (not keyword_set(Sigma)) then Sigma = 1.1
If (not keyword_set(SubBack)) then SubBack = 0
If (not keyword_set(Pitch)) then Pitch = 15
If (not keyword_set(Thickness)) then Thickness = 40
If (not keyword_set(ViewingMode)) then ViewingMode=2
If (not keyword_set(ThresholdSlope)) then ThresholdSlope = 0
If (not keyword_set(MinThreshold)) then MinThreshold = 1100

;///////////////////////////////////////////////////////////////////
;PRIMITIVE SUBTRACTION AND FLAT FIELD
CalibrationDir='/nfs/slac/g/ki/ki08/lsst/CPcampaign/SOAR/2005-05-09/'+$
	      'Calibration/Images/'
BiasFrameFile=CalibrationDir+'Zero09May2005.fits'
fits_read,BiasFrameFile,Bias,BiasHeader
FlatFrameFile=CalibrationDir+'SFlat_09May2005R.fits'
fits_read,FlatFrameFile,Flat,FlatHeader
FlatNormal=float(Flat)/max(Flat)
ZeroFrameFile='/nfs/slac/g/ki/ki08/lsst/CPcampaign/SOAR/2005-05-09/'+$
              'Raw/zero.1024.fits'
fits_read,ZeroFrameFile,ZeroFrame,ZeroHeader
;SOAR IMAGES IN RESPECTIVE 2005-05-{9,10,11,12} DIRECTORIES
SOARDir='/nfs/slac/g/ki/ki08/lsst/CPanalysis/SOAR/2005-05-'+Date+$
	'/Raw/'
SOARFiles=file_search(SOARDir+'*.fits',count=NumSOARFiles)
Naxis1=SXPAR(ZeroHeader,'NAXIS1')
Naxis2=SXPAR(ZeroHeader,'NAXIS2')
Im=fltarr(Naxis1,Naxis2)

ExpTime=0
;/////////////////////////////////////////////////////////////////////
If ViewingMode eq 1 then begin
  for i=0, 143 do begin; NumSOARFiles-2 do begin
    fits_read,SOARFiles(i),Im1,header1,/header_only
    ExpTime=SXPAR(header1,'EXPTIME')
    WindDir=SXPAR(header1,'WINDDIR')
    TimeObs=SXPAR(header1,'TIME-OBS')
    TelFocus=SXPAR(header1,'TELFOCUS')

    ;Get rid of nasty pixels
    If ExpTime eq 30.0 then begin
      fits_read,SOARFiles(i),Im1,header1
      fits_read,SOARFiles(i+1),Im2,header2
      Diff=float(Im2)-float(Im1)
      DiffHist=histogram(Diff,Nbins=40,locations=locDiffHist)
      ImHist=histogram(Im1,Nbins=40,locations=locImHist)

      SatPix=where(Im1 gt 50000)
      Im1(SatPix)=0                  ;BAD PIXELS
      Im1(0:1536)=0                  ;TWO BAD ROWS

      Hits=where(Im1 gt threshold)
      Im(Hits) = Im1(Hits)
   endif
  endfor
endif else if ViewingMode eq 2 then begin
  i=20 
  ExpTime=0
  while ExpTime ne 5.0 do begin
      fits_read,SOARFiles(i),Im1,header1
      ExpTime=SXPAR(header1,'EXPTIME')
      i=i+1
  endwhile
  SatPix=where(Im1 gt 50000)
  Im1(SatPix)=0                  ;BAD PIXELS
  Im1(0:1536)=0                  ;TWO BAD ROWS
endif

TvFlag=1
if TvFlag eq 1 then begin
   set_plot,'x'
endif else if TVFlag eq 2 then begin
   FileStringParts=strsplit(SoarFiles(i-1),'/',/extract)
   FileName=FileStringParts(N_elements(FileStringParts)-1)
   FileNameParts=strsplit(FileName,'.',/extract)
   PSName=FileNameParts(0)+'.'+FileNameParts(1)+'.ps'
   set_plot,'ps'
   device,filename=SOARDir+PSName
   loadct,0                       ;load color table 39
   device,/color                   ;allow color on the postscript
   device,ysize=7.5,/inches        ;Height of plot in y
   device,xsize=7.0,/inches        ;Width of plot in x
   device,yoffset=0.50,/inches      ;Y position of lower left corner
   device,xoffset=0.00,/inches
   white='FFFFFF'x
   black='000000'x
   !P.CHARSIZE=1.0
   !P.CHARTHICK=2
   !P.THICK=4
endif

ReturnArr=ReturnEvents(Im1,Naxis1,Naxis2,MinThreshold,ThresholdSlope,$
		       Sigma,Pitch,Thickness,TvFlag)
;////////////////////////////////////////////////////////////////////////
;HISTOGRAMS AND SUCH
Lambda1Arr=ReturnArr(0,*)
Lambda2Arr=ReturnArr(1,*)
EArr=ReturnArr(2,*)
FluxArr=ReturnArr(3,*)
TrackLength2DArr=ReturnArr(4,*)
TrackLength3DArr=ReturnArr(5,*)
PerpCountsArr=ReturnArr(6,*)
HitSizeArr=ReturnArr(7,*)
HitWidthArr=ReturnArr(8,*)
XExtentArr=ReturnArr(9,*)
YExtentArr=ReturnArr(10,*)
NoHits=N_elements(XExtentArr)

NoSpots=ReturnArr(11,0)
NoDeltas=ReturnArr(11,1)
NoWorms=ReturnArr(11,2)
NoFakeStars=ReturnArr(11,3)
NoMuons=ReturnArr(11,4)
NoUnidentified=ReturnArr(11,5)
NoHits=N_elements(XExtentArr)

print,"Number of Spots     = ",NoSpots
print,"Number of Deltas    = ",NoDeltas
print,"Number of Muons     = ",NoMuons
print,"Number of Worms     = ",NoWorms
print,"Number of FakeStars = ",NoFakeStars
print,"Number of UCR	   = ",NoUnidentified
print,"Total		   = ",NoHits


;////////////////////////////////////////////////////////////////////////
;HISTOGRAMS AND SUCH
!p.multi=[0,1,1]
bar_plot,returnArr(11,0:5),$
         barnames=['Spots','Deltas','Worms','"Stars"','Muons','UnIdentified']
if TvFlag eq 1 then stop
!p.multi=[0,2,2]
HitSizeHist=histogram(HitSizeArr,Nbins=25,max=25,locations=locHitSize)
plot,locHitSize,HitSizeHist,psym=10,title='Real Data Num pixels hit'
TrackLength3DHist=histogram(TrackLength3DArr,Nbins=10,$
                          locations=locTrack3DLength)
plot,locTrack3DLength,TrackLength3DHist,psym=10,title='TrackLength'
TrackLength2DHist=histogram(TrackLength2DArr,Nbins=15,$
                          locations=locTrack2DLength)
plot,locTrack2DLength,TrackLength2DHist,psym=10,title='TrackLength 2D'
HitWidthHist=histogram(HitWidthArr,Nbins=15,$
                          locations=locHitWidth)
if TvFlag eq 1 then stop
plot,locHitWidth,HitWidthHist,psym=10,title='Track Width'
lambda1Hist=histogram(Lambda1Arr,Nbins=10,$
                      locations=locLambda1)
plot,locLambda1,Lambda1Hist,psym=10,title='Real Data Lambda 1'
lambda2Hist=histogram(Lambda2Arr,Nbins=10,$
                      locations=locLambda2)
plot,locLambda2,Lambda2Hist,psym=10,title='Lambda 2'
lambda2Hist=histogram(Lambda2Arr,Nbins=10,$
                      locations=locLambda2)
plot,Lambda1Arr,Lambda2Arr,psym=2,xtitle='Lambda 1',ytitle='Lambda 2'
plot,lambda2arr,perpcountsarr*10^(-4.),psym=2,$
                      xtitle='Lambda 2',ytitle='Perp Counts'

if TvFlag eq 2 then device,/close
stop

end
