function chi_squared=chi2value(profiles,meanprofile,x,y,x_on,x_off,y_on,y_off,FIG)

% x_on=10;
% x_off=500;
% y_on=ymin;
% y_off=ymax;

ind_x_chi2=find(x>=x_on & x<=x_off);
Lx=x_off-x_on;

ind_y_chi2=find(y>=y_on & y<=y_off);
Ly=y_off-y_on;

sz=size(profiles);

if sz(1)==length(x)
    profiles=profiles';
end

sz=size(meanprofile);

if sz(1)*sz(2)==length(x) % then mean profile is a vector
    meanprofile=repmat(meanprofile,length(y),1);
end

% integrate first x then y
for iy=ind_y_chi2
    rel_diff_depth_sq=((profiles(iy,:)-meanprofile(iy,:))./meanprofile(iy,:)).^2;
 if FIG
    figure(34)
   subplot(411)
    plot(x(ind_x_chi2),profiles(iy,ind_x_chi2))
    hold on
    grid on
    plot(x(ind_x_chi2),meanprofile(iy,ind_x_chi2),'m:'); hold off
   subplot(412)
    diff_depth=profiles(iy,ind_x_chi2)-meanprofile(iy,ind_x_chi2);
    plot(x(ind_x_chi2),diff_depth)
    grid on
   subplot(413)
    plot(x(ind_x_chi2),(profiles(iy,ind_x_chi2)-meanprofile(iy,ind_x_chi2))./meanprofile(iy,ind_x_chi2))
    grid on
       
   subplot(414)
    plot(x(ind_x_chi2),rel_diff_depth_sq(ind_x_chi2))
 end
    
    Ax = trapz(x(ind_x_chi2),rel_diff_depth_sq(ind_x_chi2));
    chi2_profile(iy)=1/Lx*Ax;
    Lx;
if FIG
    subplot(414); hold on; text(x(ind_x_chi2(round(length(ind_x_chi2)/2))),0,['\chi ^2 =' num2str(chi2_profile(iy))],'VerticalAlignment','bottom'); hold off
   % pause(0.1)    
end
end
% figure
% plot(y(ind_y_chi2),chi2_profile(ind_y_chi2))
Axy= trapz(y(ind_y_chi2),chi2_profile(ind_y_chi2));
Ly;
chi_squared=1/Ly*Axy;



% 
% 
% 
% % integrate first x then y
% for iy=ind_y_Xi
%     diff_depth=((profiles(iy,:)-meanprofile)./meanprofile).^2;
%  if 0
%     figure(34)
%    subplot(411)
%     plot(x(ind_x_Xi),profiles(iy,ind_x_Xi))
%     hold on
%     plot(x(ind_x_Xi),meanprofile(ind_x_Xi),'m:'); hold off
%    subplot(412)
%     diff_depth=profiles(iy,ind_x_Xi)-meanprofile(ind_x_Xi);
%     plot(x(ind_x_Xi),diff_depth)
%     grid on
%    subplot(413)
%     plot(x(ind_x_Xi),(profiles(iy,ind_x_Xi)-meanprofile(ind_x_Xi))./meanprofile(ind_x_Xi))
%     grid on
%         diff_depth=((profiles(iy,:)-meanprofile)./meanprofile).^2;
%    subplot(414)
%     plot(x(ind_x_Xi),diff_depth(ind_x_Xi))
%  end
%     
%     Ax = trapz(x(ind_x_Xi),diff_depth(ind_x_Xi))
%     Xi2_profile(iy)=1/Lx*Ax
%     Lx
% if 0
%     subplot(411); hold on; text(400,0,['\Xi ^2 =' num2str(Xi2_profile(iy))]); hold off
%    % pause(0.1)    
% end
% end
% % figure
% % plot(y(ind_y_Xi),Xi2_profile(ind_y_Xi))
% Axy= trapz(y(ind_y_Xi),Xi2_profile(ind_y_Xi));
% Ly
% Xi_squared=1/Ly*Axy;
