;^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Lance Simms, Stanford University 2009
;pro Tri_Color_Image_xRG
;
;PURPOSE:
;	To form a tri-color image from a set of either two or three images 
;	(either 'I' and 'G' and ('I'+'G')/2 or 'I', 'G', and 'Y'
;
;	The program accepts a FileList as input.  The Filelist has the format of
;
;	[Lines 1-3] FileNames w/full path    (\t)   XOffset  (\t)  YOffset. 
;		   
;	[Lines 4-6] Bright Star Coordinates in First File
;
;		    Col 0	Col1	Col2	Col3	Col4	Col5
;	[Lines 7]   "YMin"	YMin	"YMax"	YMax	"YGam"	YGam
;	[Lines 8]   "IMin"	IMin	"IMax"	IMax	"IGam"	IGam
;	[Lines 9]   "GMin"	GMin	"GMax"	GMax	"GGam"	GGam
;
;       where IMin,IMax, etc. are the color scale ranges for that particular 
;	color.  Y - Red, I-Green, G-Blue. The files should be ordered Y, I, G.
;
;INPUTS:
;  FITSDIR: (string)
;	The directory that contains the FILELIST and the files to be used in
;	forming the tri-color image.
;  FILELIST: (string)
;	The relative name of the file containing the information described above.
;
;OUTPUTS:
;  1)  [Tri-color].tif 
;  2)  [Tri-color].png
;         These files will have the following name
;         [KeyStr.RedObjectDir+KeyStr.ObjectName]
;
;KEYWORDS:
;  TVFLAG: (int)
;	0 - Don't plot the star centroiding process
;	1 - Plot the star centroids
;  SKIPSTAR: (int)
;       The number of stars to skip over before the plotting begins in the 
;       case that TVFLAGLOCAL != 0
;  SKIPY: (int)
;	0 - An image from the Y filter is not being used
;	1 - An image from the Y filter is being used
;  STRETCHT: (int)
;	0 - Use linear scaling
;	1 - Use Gamma scaling (note that the Gam and GammaVals must be set in 
;	    FileList in order for this to work)
;  STARREGIONSIZE: (int)
;       The box that will be used to contain the star and the sky surrounding 
;       it measured in pixels.  The box will be STARREGIONSIZE x STARREGIONSIZE
;  REDFACTOR: (int)
;	A scaling factor to compensate for the lack of quantum efficiency in 
;	the redder filters.
;  AUTOOFFSETS: int
;       0 - Use the exact offsets listed in FileList to shift the images
;       1 - Use the offsets to as initial guesses and refine them by computing centroids
;  CROPXRIGHT: int
;       The amount of pixels to crop on the right
;  CROPXLEFT: int
;       The amount of pixels to crop on the left
;  CROPYTOP: int
;       The amount of pixels to crop from the top
;  CROPYBOT: int
;       The amount of pixels to crop from the bottom
;CALLING SEQUENCE:
;  Tri_Color_Image_xRG, FitsDir, FileList
;
;EXAMPLES:
;  Tri_Color_Image_xRG, '/nfs/slac/g/ki/ki03/lances/H2RG-32-147/ASIC/Reduced/07Dec12/NGC2683', 'NGC2683_GI_Slopes.lst'
;  Tri_Color_Image_xRG, '/nfs/slac/g/ki/ki04/lances/H1RG-022/LEACH/Reduced/2007Nov18/Orion/','OrionTrapeziumGIY_Slopes.lst'
;  Tri_Color_Image_xRG, '/nfs/slac/g/ki/ki04/lances/H1RG-022/LEACH/Reduced/2007Nov18/Orion/','OrionTrapeziumGIY_Slopes.lst', stretcht=1
;
;NO AUTOMATIC ALIGNMENT
;  Tri_Color_Image_xRG, '/nfs/slac/g/ki/ki04/lances/H1RG-022/LEACH/Reduced/2007Nov18/Orion/','OrionTrapeziumGIY_Slopes.lst', stretcht=1, starregionsize=10, autooffsets=0
;///////////////////////////////////////////////////////////////////////////
pro Tri_Color_Image_xRG, FitsDir, FileList, $
        TvFlag = TvFlag, SkipStar=SkipStar, $
	SkipY = SkipY,   StretchT = StretchT,  $
	RedFactor = RedFactor, StarRegionSize= StarRegionSize, $
        AutoOffsets = AutoOffsets, CropXLeft=CropXLeft, CropXRight=CropXRight, $
        CropYTop=CropYTop, CropYBot=CropYBot

  ;Make some common blocks
  Common KeyParams, KeyStr
  Common ColorStr, ColNameStr, ColNumStr, ColorTri, ColorNumTri

  ;Move to the dir
  cd, FitsDir

  ;Set the Keyword Parameters
  If N_Elements(StretchT)       eq 0 then StretchT 	 = 0
  If N_Elements(SkipY) 	        eq 0 then SkipY 	 = 0
  If N_Elements(SkipStar)       eq 0 then SkipStar       = 0
  If N_Elements(RedFactor)      eq 0 then RedFactor      = 0
  If N_Elements(StarRegionSize) eq 0 then StarRegionSize = 10
  If N_Elements(AutoOffsets)    eq 0 then AutoOffsets    = 1
  If N_Elements(CropXLeft)      eq 0 then CropXLeft      = 35
  If N_Elements(CropXRight)     eq 0 then CropXRight     = 35
  If N_Elements(CropYBot)       eq 0 then CropYBot       = 20
  If N_Elements(CropYTop)       eq 0 then CropYTop       = 20

  ;Get defaults for keywords
  @KeywordStruct_xRG.pro
  @PlotSettings_xRG

  ;Get the files from a list in a file
  ReadCol, FileList, RawFiles, XOff, YOff, Format = 'A,I,I'
  ;Put the info in the structure
  KeyStr.DitherFiles(0:N_Elements(RawFiles)-1) = RawFiles
  KeyStr.NumDithers = N_Elements(RawFiles)

  ;Get some parameters
  FileParam= Return_File_Params_xRG(RawFiles(0))

  ;Get the bright star coordinates from the same file
  ReadCol, FileList, XStart, YStart, Format = 'I,I', $
    SkipLine = N_Elements(RawFiles)
  For i = 0, N_Elements(XStart)-1 do begin
    KeyStr.RAs(0:N_Elements(RawFiles)-1,i)  = XOff
    KeyStr.DECs(0:N_Elements(RawFiles)-1,i) = YOff
  EndFor

  ;Get the color minima and maxima from the file
  ReadCol, FileList, Mins, MinVals, Maxs, MaxVals, Gams, GammaVals, $
      Format='A,D,A,D,A,D,A,D'

  ;Get the offsets of the images
  if AutoOffsets eq 1 then begin
    Return_Dither_Offsets_xRG, XStart, YStart, TvFlagLocal=TvFlag, $
      StarRegionSize= StarRegionSize, SkipStar = SkipStar
  endif else begin
    KeyStr.XOffs(0:2) = XOff
    KeyStr.YOffs(0:2) = YOff
  endelse
  NumRawFiles = N_elements(RawFiles)

  ;Figure out the biggest dimensions of the colored images
  XSizeMax = 0L & YSizeMax = 0L
  For FileNum = 0, NumRawFiles -1 do begin
     Fits_Read, RawFiles(FileNum), NoData, FitsHeader, /header_only
     XSizeMax = XSizeMax > long(SxPar(FitsHeader, 'NAXIS1'))
     YSizeMax = YSizeMax > long(SxPar(FitsHeader, 'NAXIS2'))
  EndFor

  ;Find the Maximums for the dimensions of the array
  ValidRAs  = KeyStr.XOffs(0:NumRawFiles-1)
  ValidDECs = KeyStr.YOffs(0:NumRawFiles-1)
  MinRAOff  = Min(ValidRAs)  & MaxRAOff  = Max(ValidRAs)
  MinDECOff = Min(ValidDECs) & MaxDECOff = Max(ValidDECs)
  NewArrXSize = XSizeMax + (MaxRAOff-MinRAOff)
  NewArrYSize = YSizeMax + (MaxDECOff - MinDECOff)

  ;Form an array big enough for all the dithers
  FullIms  = DblArr(NewArrXSize, NewArrYSize, 3)
  FoundY = 0
  FiltersUsed = ''
  If SkipY eq 1 then YCube = 1

  For FileNum= 0, NumRawFiles - 1 do begin
      print, 'Dithering with File : ' + RawFiles(FileNum)

      ;Read in the frame
      Fits_Read,  RawFiles(FileNum), Frame, FitsHeader
      ThisNaxis1 = long(SxPar(FitsHeader,'NAXIS1'))
      ThisNaxis2 = long(SxPar(FitsHeader,'NAXIS2'))
      ThisFilter = Strtrim(SxPar(FitsHeader, 'FILTER'),2)
      print,min(frame), max(frame)
	print, ThisFilter
      ;Put Proper Color in proper spot
      ;I - 742 nm ; G - 476 nm ; I+G/2 - 620 or so
      If strtrim(ThisFilter,2) eq 'I' then begin
	print, 'Found I'
         If SkipY eq 0 then begin
            Cube  = 1
            ICube = 1
	 EndIf else begin
	    Cube  = 0
	    ICube = 0
	    print, 'Found I'
	 EndElse
	 FiltersUsed = FiltersUsed+'I'
      EndIf Else if strtrim(ThisFilter,2) eq 'Y' then begin
         Cube   = 0
         YCube  = 0
	 FoundY = 1
	 If not skipY then FiltersUsed = FiltersUsed+'Y'
      EndIf Else if strtrim(ThisFilter,2) eq 'G' then begin
	 Cube  = 2
	 GCube = 2
	 FiltersUsed = FiltersUsed+'G'
      EndIf

      print, 'Putting Filter : ' + ThisFilter + ' In ' +Strtrim(Cube,2)
      ;Shift the images in the opposite direction to stack
      XOff = -(KeyStr.XOffs(FileNum)-MaxRAOff)
      YOff = -(KeyStr.YOffs(FileNum)-MaxDECOff)

      ;Put it in the right spot in the dithered large cube
      If not (SkipY and ThisFilter eq 'Y') then $
         FullIms(XOff : XOff +ThisNaxis1-1, $
                 YOff : YOff +ThisNaxis2-1, $
                 Cube) = Frame

  EndFor

  ;If no image in Y, make it the average of the I and G
  If FoundY eq 0 or SkipY eq 1 then begin
      FullIms(*,*,YCube) = (FullIms(*,*,ICube)+FullIms(*,*,GCube))/2
      ;MinVals = [MinVals, MinVals(1)] & MaxVals = [MaxVals, MaxVals(1)]
  EndIf

  If StretchT eq 0 then begin
    ;Linear Scaling
    FullImScaled = BytArr(NewArrXSize, NewArrYSize, 3)
    FullImScaled(*,*,YCube)=BytScl(FullIms(*,*,YCube)+$
    	RedFactor*FullIms(*,*,ICube),$
        min=MinVals(YCube),max=MaxVals(YCube))
    FullImScaled(*,*,ICube)=BytScl(FullIms(*,*,ICube),$
        min=MinVals(ICube),max=MaxVals(ICube))
    FullImScaled(*,*,GCube)=BytScl(FullIms(*,*,GCube),$
        min=MinVals(GCube),max=MaxVals(GCube))

  EndIf else if StretchT eq 1 then begin
    FullImScaled = BytArr(NewArrXSize, NewArrYSize, 3)
    FullImScaled(*,*,YCube)=GMaScl(FullIms(*,*,YCube),Gamma=GammaVals(YCube), $
	min=MinVals(YCube),max=MaxVals(YCube))
    FullImScaled(*,*,ICube)=GMaScl(FullIms(*,*,ICube),Gamma=GammaVals(ICube), $
	min=MinVals(ICube),max=MaxVals(ICube))
    FullImScaled(*,*,GCube)=GMaScl(FullIms(*,*,GCube),Gamma=GammaVals(GCube), $
  	min=MinVals(GCube),max=MaxVals(GCube))
  EndIf

  ;Write a fits file
  Fits_Write, KeyStr.RedObjectDir+KeyStr.ObjectName+$
	Strtrim(FiltersUsed,2)+'Color.fits', FullIms
  ;Attempt to put image in right orientation
  FullImScaled = Reverse(FullImScaled,1)

  ;Window,xsize=700,ysize=700
  ;Set_Plot,'z'
  Write_Tiff, KeyStr.RedObjectDir+KeyStr.ObjectName+$
	'_'+Strtrim(FiltersUsed,2)+'_Color.tif', $
	red=FullImScaled(*,*,0),$
	green=FullImScaled(*,*,1),$
	blue=FullImScaled(*,*,2),$
	planarconfig=2

  If stregex(!version.os, 'Win', /boolean) then begin
      set_plot,'WIN'
  EndIf else begin
	  set_plot,'X'
  EndElse

  ;FULL SIZED IMAGE
  Window,xsize=700,ysize=700
  Tv,congrid(FullImScaled(*,*,*),700,700,3),true=3

  PngImg = tvrd(true=1)
  PngImg = reverse(PngImg,2)
  tvlct,reds,greens,blues,/get
  write_png,KeyStr.RedObjectDir+KeyStr.ObjectName+$
	'_'+Strtrim(FiltersUsed,2)+'_Color.png', $
    PngImg,reds,greens,blues

  ;CROPPED IMAGE
  Window,1, xpos=100, ypos=100, xsize=1000, ysize=1000
  Tv,congrid(FullImScaled(CropXLeft:NewArrXSize-CropXRight, $
                          CropYBot :NewArrYSize-CropYTop,*),1000,1000,3),true=3
  PngImg = tvrd(true=1)
  PngImg = reverse(PngImg,2)
  tvlct,reds,greens,blues,/get
  write_png,KeyStr.RedObjectDir+KeyStr.ObjectName+$
        '_'+Strtrim(FiltersUsed,2)+'_CroppedColor.png', $
    PngImg,reds,greens,blues

  If stregex(!version.os, 'Win', /boolean) then begin
      set_plot,'WIN'
  EndIf else begin
	  set_plot,'X'
  EndElse
  stop

end
