;xy_offsets
;
;PURPOSE:
;	This script will return the difference in coordinates between a 
;	ShackHartman image centroid and the corresponding point on the 
;	reference grid
;
;	
pro new_xy_offsets,Date=Date,stats_directory=stats_directory,$
	x_center_file=x_center_file,y_center_file=y_center_file


If (not keyword_set(Date)) then Date='10'
If (not keyword_set(stats_directory)) then stats_directory='stats_temp'
If (not keyword_set(x_center_file)) then x_center_file='x_centers.txt'
If (not keyword_set(y_center_file)) then y_center_file='y_centers.txt'
If (not keyword_set(letter)) then letter=['a','b','c','d','e','f','g','h','i']


stats_directory='/a/pippin01/Volumes/u08/lsst/CPanalysis/2005-05-'+Date+$
	  '/ShackHartman/'+stats_directory+'/'

;GET ALL OF THE STATS FILES
stats_files=file_search(stats_Directory+'*5132*_stats.txt',count=num_of_stats_files)

;OBTAIN THE FITTED CENTERS FOR ALL IMAGES
readcol,stats_Directory+x_center_file,x_fit_center,format='X,X,f'
readcol,stats_Directory+y_center_file,y_fit_center,format='X,X,f'

;CONSTANTS
num_of_files=N_elements(x_fit_center)
num=25

print,num_of_stats_files
print,num_of_files

;ARRAY REFERENCE 25x25=625 FOR GRID
subx=2*indgen(num)-25           ;The x-reference numbers
suby=indgen(num)-12             ;The y-reference numbers

for file_number=0,num_of_files-1 do begin

	stats_path_parts=strsplit(stats_files(file_number),'/',/extract)
	stats_file_ref=strsplit(stats_path_parts(N_elements(stats_path_parts)-1)$
	,'stats.txt',/extract,/regex)
	stats_file_ref=stats_file_ref(0)
	
	;Take the centroid values from the stats.txt files
	stats_file_name=stats_files(file_number)
	offsets_file_name=stats_directory+stats_file_ref+'offsets.txt'

	readcol,stats_file_name,grid_index,x_coord,y_coord,format='f,f,f'
	grid_spots=N_elements(x_coord)

	;Figure out the new reference grid, applied around x_center and y_center
        x_ref_col=12.5*subx+x_fit_center(file_number)
        y_ref_col=25.0*suby+y_fit_center(file_number)
	index=findgen(num*num)
	gridx=fltarr(num*num)
	gridy=fltarr(num*num)
	gridx(index)=x_ref_col(index mod num)
	gridy(index)=y_ref_col(index/num)

	not_fitted=where(x_coord eq -1,complement=fitted)

	;Obtain the difference between centroid and grid point
	x_offset=x_coord-gridx
	y_offset=y_coord-gridy

	;If point was not fitted, set to -1
 	x_offset(not_fitted)=-1
	y_offset(not_fitted)=-1	


	get_lun,offsets
	openw,offsets,offsets_file_name
	
	for stat_index=0, num*num-1 do begin

		printf,offsets,FORMAT='(%"%i\t%f\t%f\t%f\t%f")',stat_index,$
		x_coord(stat_index),x_offset(stat_index),$
		y_coord(stat_index),y_offset(stat_index)
	
	endfor
	
	close,offsets
	free_lun,offsets
		 
	
	
endfor

stop

end

