;new_center_drift
;
;PURPOSE:
;	This file will take the fitted grid centers from the file centers.txt 
;	(returned by coo_mag_to_stats.pro) and perform a linear fit of the 
;	center vs. image number (i.e. time).
;
;CALLING SEQUENCE:
;       new_center_drift,[Date=Date,[Directory=Directory,[stats_directory=$
;	stats_directory,[xcenter=xcenter,[ycenter=ycenter,$
;	center_file=center_file]]]]]]
;
;INPUTS
;       DATE: the string '10','11',or '12' corresponding to
;             2005-05-10,2005-05-11, and 2005-05-12
;	STATS_DIRECTORY: the directory in which the statistics are located
;	CENTER_FILE: The name of the file containing the fitted centers and
;		     their corresponding erros
;	X_CENTERS:   The name of the file to which the linear fit for the 
;		     x coordinate will be written
;	Y_CENTERS:   The The name of the file to which the linear fit for the
;                    y coordinate will be written
;
;OUTPUTS:
;
;	FILES:
;	x_centers.txt-this file contains the following fields
;		File-The number of the file in the directory.
;		X center-The individually fitted center for each image
;		X fit Center-The center returned by the linear fit
;		m-The slope of the linear fit
;		b-The y-intercept of the linear fit
;		diff-The difference between the individually fitted center
;		     and the linear fitted center across images
;
;	y_centers.txt-this file contains the following fields
;               File-The number of the file in the directory.
;               Y center-The individually fitted center for each image
;               Y fit Center-The center returned by the linear fit
;               m-The slope of the linear fit
;               b-The y-intercept of the linear fit
;               diff-The difference between the individually fitted center
;                    and the linear fitted center across images
;
;	[shifted_dir]/h5132

pro new_center_drift, Date=Date,shift_directory=shift_directory,$
		stats_directory=stats_directory, center_file=center_file,$
		x_centers=x_centers,y_centers=y_centers

If (not keyword_set(Date)) then Date='11'
If (not keyword_set(stats_directory)) then stats_directory='stats_temp/'
If (not keyword_set(shift_directory)) then shift_directory='shifted/'
Shack_directory='/a/pippin01/Volumes/u08/lsst/CPanalysis/2005-05-'+Date+'/ShackHartman/'
If (not keyword_set(center_file)) then center_file=shack_directory+$
	stats_directory+'centers.txt'
If (not keyword_set(x_centers_file)) then x_centers_file=shack_Directory+$
	stats_directory+'x_centers.txt'
If (not keyword_set(y_centers_file)) then y_centers_file=shack_Directory+$
	stats_directory+'y_centers.txt'


;FILES AND HOLDING

readcol,center_file,x_centers,y_centers,xerrs,yerrs,format='f,f,f,f'
num_files=N_elements(x_centers)
raw_files=FILE_SEARCH(shack_Directory+'raw/h*.fits',count=num_raw_files)
get_lun,xfile
get_lun,yfile

x_slopes=fltarr(num_files)
y_slopes=fltarr(num_files)
x_stop_index=0
start_index=0
x_fit_guess=fltarr(2)
y_fit_guess=fltarr(2)
file_index_arr=findgen(num_files)

openw,xfile,x_centers_file
openw,yfile,y_centers_file

printf,xfile,FORMAT='(%"%s\t%s\t%s\t%s\t\t%s\t\t%s")',$
      'File ','X center','X Fit Center','m','b','diff'
printf,yfile,FORMAT='(%"%s\t%s\t%s\t%s\t\t%s\t\t%s")',$
      'File ','Y center','Y Fit Center','m','b','diff'

set_plot,'ps'

device,filename=Shack_Directory+'postscripts/new_centers.ps'
                                                                                
loadct,39                       ;load color table 39
device,/color                   ;allow color on the postscript
device,ysize=8.5,/inches        ;Height of plot in y
device,xsize=10.0,/inches        ;Width of plot in x
device,yoffset=1.0,/inches      ;Y position of lower left corner
                                                                                
white='FFFFFF'x
black='000000'x                                                                                 
!P.CHARSIZE=1.2
!P.THICK=4.
!P.multi=[0,1,2]

for file_index=0,num_files-2 do begin
	
	;Build array of x and y coordinates and corresponding slopes to feed 
	;to the linear fitting functions
	
	x_slopes(file_index)=x_centers(file_index+1)-x_centers(file_index)
	y_slopes(file_index)=y_centers(file_index+1)-y_centers(file_index)

	raw_path_parts=strsplit(raw_files(file_index),'/',/extract)
        raw_file_ref=strsplit(raw_path_parts(N_elements(raw_path_parts)-1),$
	'raw.fits',/extract,/regex)
	pre_letter=strsplit(raw_file_ref,'_',/extract)
	pre_letter=pre_letter(0)
	print,raw_file_ref
	print,pre_letter


	If ((y_slopes(file_index) gt 3) and (file_index-start_index gt 1))$
	   or (file_index eq num_files-2) or (((file_index+1) mod 100) eq 0)$
	   or (file_index eq 70) then begin
		
		begin_num=start_index mod 100
		end_num=file_index mod 100
		
		
		;Open file for IRAF IMCOMBINE SHIFTS
		get_lun,imshift
		shift_dir_full=Shack_Directory+shift_directory+pre_letter+$
                strtrim(string((start_index mod 100)+1),2)+'-'+$
                strtrim(string((file_index mod 100)+1),2)

		file_mkdir,shift_dir_full
	
		openw,imshift,shift_dir_full+'/shifts.txt'

		;Open file for List of Image names
		get_lun,images
		openw,images,shift_dir_full+'/images.txt'

		;Open file for List of Shited Image names
		get_lun,shifted
		openw,shifted,shift_dir_full+'/shifted.txt'

                y_fit_guess(0)=float(y_centers(start_index))
                y_fit_guess(1)=float(mean(y_slopes[start_index:file_index]))
                x_fit_guess(0)=float(x_centers(start_index))
                x_fit_guess(1)=float(mean(x_slopes[start_index:file_index]))
 
		y_fit=curvefit(findgen(file_index-start_index+1),$
                y_centers[start_index:file_index],weights,y_fit_guess,$
                /noderivative,function_name='linear_function_2_y',$
                yerror=yerror)

		x_fit=curvefit(findgen(file_index-start_index+1),$
                x_centers[start_index:file_index],xerrs,x_fit_guess,$
                /noderivative,function_name='linear_function_2_x',$
                yerror=xerror)

					
		for sub_index=0,n_elements(y_fit)-1 do begin   
			y_t_center=y_centers(start_index+sub_index)
			y_f_center=y_fit(sub_index)
			y_diff=y_f_center-y_t_center                                                             
                	x_t_center=x_centers(start_index+sub_index)
                        x_f_center=x_fit(sub_index)
                        x_diff=x_f_center-x_t_center 
	
			printf,yfile,FORMAT='(%"%d\t%f\t%f\t%f\t%f\t%f")',$
			start_index+sub_index,y_t_center,$
			y_f_center,y_fit_guess(0),$
			y_fit_guess(1),y_diff

			printf,xfile,FORMAT='(%"%i\t%f\t%f\t%f\t%f\t%f")',$
                        start_index+sub_index,x_t_center,x_f_center,$
			x_fit_guess(0),$
                 	x_fit_guess(1),x_diff

		
			;OFFSETS WRITTEN TO [SHIFTED]/Shifts.txt
			printf,imshift,FORMAT='(%"%f\t%f")',$
			x_fit(0)-x_fit(sub_index),$
			y_fit(0)-y_fit(sub_index)

			;IMAGE NAMES WRITTEN TO [SHIFTED]/Images.txt
			printf,images,FORMAT='(%"%s")',$
			raw_files(start_index+sub_index)
			
			;SHIFTED NAMES WRITTEN TO [SHIFTED]/Shifted.txt
			printf,shifted,FORMAT='(%"%s")',$
			shift_dir_full+'/'+pre_letter+'_'+$
                        strtrim(string((start_index+sub_index) mod 100)+1,2)+'_shifted.fits'
		endfor

			plot,x_centers[start_index:file_index],$
                	psym=1,title="Fitted X coordinates for "+$
			pre_letter+' '+$
			strtrim(string(start_index mod 100),2)+'-'+$
                	strtrim(string(file_index mod 100),2),$
			xtitle="File Sub Number",ytitle="X Coordinate",$
                	background=white,color=black,yrange=[540,550],$
			POSITION=[0.10,0.10,0.9,0.45]                                                                                     
                	oplot,x_fit

			plot,y_centers[start_index:file_index],$
                 	psym=1,title="Fitted Y coordinates for "+$
			pre_letter+' '+$
			strtrim(string(start_index mod 100),2)+'-'+$
                 	strtrim(string(file_index mod 100),2),xtitle="File Sub Number",$
			ytitle="Y Coordinate",$
                 	background=white,color=black,yrange=[460,472],$
			POSITION=[0.10,0.55,0.9,0.95]                                                                                 
                	oplot,y_fit

			
			start_index=file_index+1

			;CLOSE FILES AND FREE HANDLES
			close,shifted
			free_lun,shifted
			close,imshift
			free_lun,imshift                	
		        close,images
			free_lun,images
		 
        endif


	print,file_index                                                                                


endfor	

close,xfile
close,yfile


free_lun,xfile
free_lun,yfile

device,/close

stop
end

