;xy_offsets
;
;PURPOSE:
;	This script will calculate the covariances of the ShackHartman images 
;	using the distorted grid obtained by averaging all of the positions.

pro newest_cn_depth_w_offsets,Date=Date,stats_directory=stats_directory,$
	x_center_file=x_center_file,y_center_file=y_center_file,$
	depth=depth,x_off=x_off,y_off=y_off


If (not keyword_set(Date)) then Date='10'
If (not keyword_set(stats_directory)) then stats_directory='stats_1_31'
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(depth)) then depth=0
If (not keyword_set(postscript_dir)) then postscript_dir='distorted_postscripts'
If (not keyword_set(x_off)) then x_off=[0,.2,.4]
If (not keyword_set(y_off)) then y_off=[0,0,0]

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

;ARRAYS OF FILES
offset_files=file_search(stats_directory+'*5132*newest_offsets.txt',count=num_stats_files)
readcol,stats_directory+'newest_x_centers.txt',x_center,x_fit_center,$
        format='X,f,f'
readcol,stats_directory+'newest_y_centers.txt',y_center,y_fit_center,$
        format='X,f,f'
x_off_cen=x_center-x_fit_center
y_off_cen=y_center-y_fit_center
stop

;CONSTANTS
num=25
grid_spots=625
index=findgen(625)

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

;HUGE DATA CUBE
x_offset_hor=fltarr(num_stats_files,grid_spots)
y_offset_hor=fltarr(num_stats_files,grid_spots)
x_offset_ver=fltarr(num_stats_files,grid_spots)
y_offset_ver=fltarr(num_stats_files,grid_spots)

;Correlations
Cxt_full=fltarr(num_stats_files,num,depth)
Cxl_full=fltarr(num_stats_files,num,depth)
Cyt_full=fltarr(num_stats_files,num,depth)
Cyl_full=fltarr(num_stats_files,num,depth)


;FILL THE DATA CUBES
for file_number=0,num_stats_files-1 do begin

	;Take the results from the offset.txt files and fill the cube
	readcol,offset_files(file_number),x_offset,y_offset,format='X,X,f,X,f'
 
        if center_sub eq 1 then begin
        ;Obtain the difference ordered in COLUMN, ROW between centroid and grid         point
           x_offset=x_offset-x_off_cen(file_number)
           y_offset=y_offset-y_off_cen(file_number)
        endif 
      
	;Obtain the difference ordered in COLUMN, ROW between centroid and grid 	point
	x_offset_hor(file_number,*)=x_offset
	y_offset_hor(file_number,*)=y_offset

	;Obtain the difference ordered in ROW, COLUMN
	x_offset_ver(file_number,*)=x_offset((index mod 25)*25+index/25)
	y_offset_ver(file_number,*)=y_offset((index mod 25)*25+index/25)
	
endfor
	
;DATA CUBEs are now in place. Begin the covariance

;Loop through all of the files in the 


offsets=n_elements(x_off)

Cxt_means=fltarr(offsets,num,depth)
Cxl_means=fltarr(offsets,num,depth)
Cyt_means=fltarr(offsets,num,depth)
Cyl_means=fltarr(offsets,num,depth)

for off=0, offsets-1 do begin

for file_number=0,num_stats_files-depth do begin

  ;CORRELATIONS
  Cxl=fltarr(num,depth)
  Cxt=fltarr(num,depth)
  Cyl=fltarr(num,depth)
  Cyt=fltarr(num,depth)

     for time=0, depth-1 do begin

	for spacing=0, num-1 do begin
	
	  Cxl_arr=fltarr(num*num)
       	  Cxt_arr=fltarr(num*num)
	  Cyl_arr=fltarr(num*num)
	  Cyt_arr=fltarr(num*num)

	  ;SCAN FIRST ALONG THE ROWS
	
	  for column_index=0, num-1 do begin
	     for row_index=0, num -1 do begin
		 spot_index=column_index*num+row_index
			
		 ;If we have reached the edge, start on the next row
		 If (row_index+spacing) ge num then break
		 ;Check to see if both have valid values
		 If (x_offset_hor(file_number,spot_index) ne -10) and $
		    (x_offset_hor(file_number+time,spot_index+spacing) ne -10) $
		    then begin
		    ;add offset in to tweek the plots
		    Cxl_arr(spot_index)=(x_offset_hor(file_number,spot_index)+$
		       x_off(off))*$
		       (x_offset_hor(file_number+time,spot_index+spacing)+$
		       x_off(off))
		    Cxt_arr(spot_index)=(y_offset_hor(file_number,spot_index)+$
		       y_off(off))*$
                    (y_offset_hor(file_number+time,spot_index+spacing)+$
		       y_off(off))
		    ;print,FORMAT='(%"%i\t%i\t")',spot_index,spot_index+spacing
	
		 endif

	      endfor
	   endfor
		
	   correlated=where(Cxl_arr ne 0)
	   If correlated(0) ne -1 then begin
		Cxl(spacing,time)=mean(Cxl_arr(correlated))
		Cxt(spacing,time)=mean(Cxt_arr(correlated))
	   endif else begin
		Cxl(spacing,time)=-10
		Cxt(spacing,time)=-10
	   endelse
		
	   ;printf,xcor,FORMAT='(%"%f\t%f\t%i")',Cxl(spacing-1),Cxt(spacing-1),N_elements(correlated)
		
	
           ;SCAN SECOND ALONG Y

           for column_index=0, num-1 do begin
               for row_index=0, num -1 do begin
                   spot_index=column_index*num+row_index
	
        	   ;If we have reached the edge, start on the next row
                   If (row_index+spacing) ge num then break
                   ;Check to see if both have valid values
                   If (y_offset_ver(file_number,spot_index) ne -10) and $
                   (y_offset_ver(file_number+time,spot_index+spacing) ne -10) $
		   then begin

                   Cyl_arr(spot_index)=(y_offset_ver(file_number,spot_index)+$
		     y_off(off))*$
                   (y_offset_ver(file_number+time,spot_index+spacing)+$
		     y_off(off))
                   Cyt_arr(spot_index)=(x_offset_ver(file_number,spot_index)+$
		     x_off(off))*$
                   (x_offset_ver(file_number+time,spot_index+spacing)+$
		     x_off(off))
                   ;print,FORMAT='(%"%i\t%i\t")',spot_index,spot_index+spacing

          	   endif

                   endfor
            endfor

            correlated=where(Cyl_arr ne 0)
            If correlated(0) ne -1 then begin
                 Cyl(spacing,time)=mean(Cyl_arr(correlated))
                 Cyt(spacing,time)=mean(Cyt_arr(correlated))
            endif else begin
                 Cyl(spacing,time)=-10
                 Cyt(spacing,time)=-10
            endelse

            ;printf,ycor,FORMAT='(%"%f\t%f\t%i")',Cyl(spacing-1),Cyt(spacing-1),N_elements(correlated)

     	  endfor
	
	endfor	
	;partvelvec,x_offset(fitted),y_offset(fitted),gridx(fitted),$
	;	gridy(fitted),yrange=[150,800],xrange=[200,850]

	;close,xcor
	;free_lun,xcor		
	;close,ycor
	;free_lun,ycor
	
	Cxt_full(file_number,*,*)=Cxt
	Cxl_full(file_number,*,*)=Cxl
	Cyt_full(file_number,*,*)=Cyt
	Cyl_full(file_number,*,*)=Cyl


endfor	
		

for n=0, num-1 do begin
	for m=0, depth-1 do begin

	Cxt_means(off,n,m)=mean(Cxt_full(*,n,m))
	Cxl_means(off,n,m)=mean(Cxl_full(*,n,m))
	Cyl_means(off,n,m)=mean(Cyl_full(*,n,m))
	Cyt_means(off,n,m)=mean(Cyt_full(*,n,m))

	endfor
endfor

endfor

set_plot,'ps'
device,filename=Postscript_dir+'Cns_mean_offsets.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=.7
!P.THICK=4.

items_time=['t=0']
sym_time=[1]
items_k_tran=['Data Points','n!e-7/32!n','n!e-13/64!n','n!e-27/128!n']
sym_k_tran=[1,0,0,0]
line_k_tran=[0,1,2,3]
items_k_lon=['Data Points','n!e-1/3!n']
sym_k_long=[0,1]
colors_time=[0]



;*************FIRST PLOT
!P.multi=[0,1,1]

plot,Cxt_means(0,*,0),psym=1,title="Transverse correlation along X direction",$
               xtitle="n",ytitle="Covariance",$
               background=white,color=black,$
               yrange=[min(Cxt_means(0,*,0))-3,max(Cxt_means(0,*,0))+.5],$
               POSITION=[0.10,0.10,0.9,0.9]

;Over Plot the various separations in time and also generate legends

for k=1,offsets-1 do begin

        oplot,Cxt_means(k,*,0)-Cxt_means(0,*,0),psym=(((k+1) mod 5)+1),color=20*((k+1)/5)
        sym_time=[sym_time,((k+1) mod 5)+1]
        items_time=[items_time,string(strtrim(x_off(k)))+' pixel offset']
        colors_time=[colors_time,(20*((k+1)/5))]
endfor

legend,items_time,psym=sym_time,position=[.7,.8],colors=colors_time,/normal

!p.multi=[0,1,1]
;***************FIFTH PLOT
plot,Cxl_means(0,*,0),psym=1,title="Longitudinal correlation along X direction",$
               xtitle="n",ytitle="Covariance (Pixels Squared)",$
               background=white,color=black,$
               yrange=[min(Cxl_means(0,*,0))-3,max(Cxl_means(0,*,0))+.5],$
               POSITION=[0.10,0.10,0.9,0.9]

for k=1,offsets-1 do begin

        oplot,Cxl_means(0,*,0)-Cxl_means(k,*,0),psym=(((k+1) mod 5)+1),color=20*((k+1)/5)

endfor

legend,items_time,psym=sym_time,position=[.2,.4],/normal,colors=colors_time

!P.multi=[0,1,1]

;**************NINTH PLOT
plot,Cyt_means(0,*,0),psym=1,title="Transverse correlation along Y direction",$
               xtitle="n",ytitle="Covariance (Pixels Squared)",$
               background=white,color=black,$
               yrange=[min(Cyt_means(0,*,0))-3,max(Cyt_means(0,*,0))+.5],$
               POSITION=[0.10,0.10,0.9,0.9]

for k=1,offsets-1 do begin

        oplot,Cyt_means(0,*,0)-Cyt_means(k,*,0),psym=(((k+1) mod 5)+1),$
	color=20*((k+1)/5)

endfor

legend,items_time,psym=sym_time,position=[.6,.8],/normal,colors=colors_time


;***************THIRTEENTH PLOT
!p.multi=[0,1,1]

plot,Cyl_means(0,*,0),psym=1,title="Longitudinal correlation along Y direction",$
               xtitle="n",ytitle="Covariance (Pixels Squared)",$
               background=white,color=black,$
               yrange=[min(Cyl_means(0,*,0))-3,max(Cyl_means(0,*,0))+.5],$
               POSITION=[0.10,0.10,0.9,0.9]

for k=1,offsets-1 do begin

        oplot,Cyl_means(0,*,0)-Cyl_means(k,*,0),psym=(((k+1) mod 5)+1),$
	color=20*((k+1)/5)

endfor

legend,items_time,psym=sym_time,position=[.6,.8],/normal,colors=colors_time

device,/close
set_plot,'X'


end


