%
%--------------------------------------------------------------------------
% FTE_finesse_ccd.m
%
% Test example that uses FT_mode_content and related functions with a
% Finesse output file in which the beam amplitude has been generated
% with the `beam' detector.
%
% This file requires to run `kat test_beam.out' manually first
%
% Part of the SimTools package
% Andreas Freise  12.02.2011
%--------------------------------------------------------------------------
%

% Description: Example for using SimTools with Finesse: get mode coefficients of output beam
% Keywords: finesse, example, simulation, kat, beam, ccd, mode, coefficient, Gauss

clear all;

% create a data structure to store Finess related data
Run=FT_create_new_kat_run;

% read in output data (you need to run `kat test_beam' manually before this)
Run=FT_read_kat_output_data(Run,'test_beam.out');

% creat complex number from data stored as real, imaginary parts
field=Run.z(:,:,1)+i*Run.z(:,:,2);

% beam width in the x and y direction
w0 = 0.0182164474749;

% computing total power
power=FT_power_in_field(field,Run.x*w0,Run.y*w0);

% ---- define laser mode
lambda = 1064e-9;
% distance to beam waist
z = 0;
% create Gaussian beam parameter
[gp] = FT_init_gauss_param(lambda,1,'w0',w0,'z',z);

% ---- define numerical Grid
% size of grid, defined as -range/2 ... range/2
xrange=4*w0;
yrange=4*w0;

% number of points in the grid
xpoints=length(Run.x);
ypoints=length(Run.y);

% create grid
Grid=FT_init_grid(xpoints, ypoints, xrange, yrange, 0,0);

% ---- do mode decomposition
max_mode_order = 4;
[gc,n_coeff]=FT_init_gauss_coefficients('HG', max_mode_order);
fprintf('Computing mode coefficients ...\n');
[gc] = FT_mode_content(gc, gp, field,Grid.xaxis,Grid.yaxis,[0,0,0]);
FT_print_gauss_coefficients(gc,1e-3,0);
fprintf('Total power in modes %.3g (should be 1)!\n',sum(abs(gc.value(:)).^2));
fprintf('Plotting result ...\n');

% recreate field with mode coefficients, scale to same power as real field
[newfield] = sqrt(power)*FT_gauss_coefficients_to_field(gp, gc, Grid.xaxis, Grid.yaxis,[0,0,0]);

% plot original and recreated field to check if they are the same
figure
subplot(1,2,1)
surf(abs(field),'FaceColor','interp','EdgeColor','none','FaceLighting','phong');
view(2)
axis square
axis tight
colorbar;
mymap=neg_colormap();
colormap(mymap)

subplot(1,2,2)
surf(abs(newfield),'FaceColor','interp','EdgeColor','none','FaceLighting','phong');
view(2)
axis square
axis tight
colorbar;
mymap=FT_neg_colormap();
colormap(mymap)

