;xy_offsets
;
;PURPOSE:
;	This script will return the difference in coordinates between a 
;	ShackHartman image centroid and the corresponding point on the 
;	reference grid
;
;	Since the center of the grid seems to be drifting 

pro routine_tv_offsets,Date=Date,stats_directory=stats_directory,$
	x_center_file=x_center_file,y_center_file=y_center_file,$
	exam_date=exam_date


If (not keyword_set(Date)) then Date='10'
If (not keyword_set(exam_date)) then exam_date='1_31'
If (not keyword_set(stats_directory)) then stats_directory='stats_'+exam_date
If (not keyword_set(x_center_file)) then x_center_file='newest_x_centers.txt'
If (not keyword_set(y_center_file)) then y_center_file='newest_y_centers.txt'
If (not keyword_set(letter)) then letter=['a','b','c','d','e','f','g','h','i']


stats_Directory='/nfs/slac/g/ki/ki08/lsst/CPanalysis/2005-05-'+Date+'/ShackHartman/'$
	  +stats_directory+'/'

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

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

;Correlations
C=fltarr(25)

set_plot,'X'
!p.multi=[0,1,2]
avg_sub = 1
file_names=file_search(stats_directory+'*5132*_stats.txt',count=num_stats_files)
stat_names=file_search(stats_directory+'*5132*_sub_offsets.txt')

for file_index=0,num_stats_files-1 do begin

	;Take the centroid values from the stats.txt files
	file_name=file_names(file_index)
	stat_name=stat_names(file_index)

	readcol,stat_name,grid_index,x_coord,x_offset,y_coord,$
		y_offset,format='f,f,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_index)
        y_ref_col=25.0*suby+y_fit_center(file_index)
	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 -10,complement=fitted)

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

        if avg_sub eq 1 then begin
           x_offset(fitted)=x_offset(fitted)-mean(x_offset(fitted))
           y_offset(fitted)=y_offset(fitted)-mean(y_offset(fitted))
        endif
        plot,x_offset,y_offset,color=white,psym=2 
	partvelvec,x_offset(fitted),y_offset(fitted),gridx(fitted),$
		gridy(fitted),yrange=[150,800],xrange=[200,850]

	
	vec_field=tvrd()
	tv,vec_field	

	wait,2
endfor


stop

end

