clear all;

load phi_compensation.mat
load Parameter_ExEy.mat

lambda_min = 1.8e-6; 
lambda_max = 2.3e-6;  
period = 0.9e-6;     
R = 38.7e-6; 
F = 100.6e-6;  
c=3e8;
fs=1e-15;
np = round(R/period);

n_l = 56;   
n_w = 29;  
n_lambda = 300;  
x_mask = period*(-np:1:np);    
y_mask = period*(-np:1:np);   
[X_mask,Y_mask] = meshgrid(x_mask,y_mask);

x = linspace(0,n_lambda,n_lambda);
K1 = zeros(n_l,n_w); 
R1 = zeros(n_l,n_w);

 for i = 1:n_l   
    for j = 1:n_w
        y = squeeze(phi_LCP(i,j,:))';
        Lx=sum((x-mean(x)).^2);
        Ly=sum((x-mean(x)).*(y-mean(y)));
        b1=Ly/Lx;
        b0=mean(y)-b1*mean(x);
        y1=b1.*x+b0;
        R1(i,j)= 1 - sum((y-y1).^2)/sum((y-mean(y)).^2);
        if R1(i,j)<0.99   
           R1(i,j)=nan;
        end
    end
end
 
phase = reshape(phi_max,[n_l*n_w,1])./180.*pi;
delta_phase = reshape(delta_phi,[n_l*n_w,1])./180.*pi;


target_index = zeros(2*np+1,2*np+1,2);
target_compensation = zeros(2*np+1,2*np+1);

for i=1:2*np+1
    for j = 1:2*np+1
        phi_c = phi_compensation(i,j)*ones(n_l,n_w);
        delta = abs(delta_phi-phi_c);
        m = min(delta); 
        mn = min(m);   
        [row,col]= find(delta==mn);  
        target_index(i,j,1) = row(1); 
        target_index(i,j,2) = col(1);
        target_compensation(i,j) = delta_phi(row(1),col(1));
    end
end


save('Target_phase_difference','target_compensation');
save('Phi_phase_difference','phi_compensation');
