%--------------------------------------------------------------------------
% FTE_fit_LG.m
%
% Test example for fitting a mode shape to an CCD image. This is a 
% specific example, tuned for the measured image. You will need to
% adapt the script to fit different images.
%
% This script requires the files 'testLGdata.wct' or 'LG010210_0019small.png'.
%
% Part of the SimTools package
% Keiko Kokeyama, Andreas Freise, 14.02.2011 afreise@googlemail.com
%---------------------------------------------------------------------  
%

% Description: Example for fitting an LG mode shape to an CCD image
% Keywords: example, LG, mode, fit, Gauss
 
clear all;
verbose=1;
%datafile='pos2.wct';

% example for reading a text file
%%{
datafile='testLGdata.wct'; 
disp(sprintf('loading %s ...',datafile));
open_command = [' data=load (''',datafile,''');'];
eval(open_command);
%%}

%{
% example for reading an image
ldata=imread('LG010210_0019small.png');
% convert RGB image to grayscale values
data=mean(ldata,3);
%}

pixel=13.4e-6;
lambda=1064e-9;
  
box_threshold=[0.3, 0.3, 0.2, 0.2, 0.2, 0.1, 0.1];
guess_threshold=[0.75, 0.4, 0.75, 0.4, 0.85, 0.75, 0.4];
fit_tol=0.01;

% smothing data
[data_p]=FT_blur_data(data, 10, 3);

% normalise data to be between 0 and 1
data_p=FT_normalise_data(data_p,0,1);

fail=1;
idx=1;
while((fail==1) && (idx<length(box_threshold)));
  if(idx>1)
    disp(sprintf('  Trying again with thresholds %g %g',box_threshold(idx),guess_threshold(idx)));
  end
  
  % reduce data set to take into account only values >box_threshold
  [data_fit,fit_offset]=FT_box_data(data_p,box_threshold(idx));
  [index]=find(data_fit<box_threshold(idx));
  data_fit(index)=0.0;
 
  [gr,gc]=FT_guess_center_LG(data_fit,guess_threshold(idx),1, verbose);    
  [radius,gr,gc]= FT_guess_size_LG(data_fit,pixel,lambda,3,3,gr,gc,1, verbose);
  drawnow;
  [offset,radius,residual,fail] = FT_fit_LG_cos(data_fit, 3, 3, pixel, lambda, radius, gr, gc, fit_tol,verbose);
  idx=idx+1;
end

offset(1)=offset(1)+fit_offset(2)*pixel;
offset(2)=offset(2)+fit_offset(1)*pixel;
[rows,cols]=size(data);
x=(linspace(1,cols,cols))*pixel;
y=(linspace(1,rows,rows))*pixel;
gp=FT_init_gauss_param(lambda,1,'w0',radius,'z',0);
[field]=FT_LG_cos_field(gp,3,3,x,y,offset);
field=field.^2;
field=field/max(max(field));
data=data/max(max(data));

figure(224)
clf;
subplot(1,2,1)
hold on;
surf(data, 'Edgecolor','none');
view(0,-90);
contour(field,3,'Edgecolor','w');
axis square;
axis tight
hold off;
title('data and fit');
subplot(1,2,2)
surf(residual,'EdgeColor','None');
axis square;
axis tight;
view(0,-90);
title('residuals');
[rows,cols]=size(residual);
text(cols*0.5,rows*1.2,datestr(now));