
function [x,y,ymodel,paramsout]=fit_trace();

% load data
load('pdh_data.mat')

% Fit parameters:
% factor = 2112.11, offset = 8.0404e-05
% loss = 3159.05ppm, midx = 0.0270865
% modulation frequency = 14.706MHz

% decimate data
x=data(:,1);
y=data(:,2);
x=decimate(x,100);
y=decimate(y,100);

%plot(x,y)

% name of kat file which contains 'blocks'
inname='auto.kat';
% name of file that we will create now from this script
katname='fit.kat';

% read in block from testblock.kat
block=FT_read_blocks_from_file(inname);


outbl(1)=FT_copy_block(block,'input'); 
outbl(2)=FT_copy_block(block,'cavity');
outbl(3)=FT_copy_block(block,'commands');

cbl=FT_copy_block(block,'const');

% initialise Finesse
FT=FT_init_Finesse('name','kat','path','/Users/adf/bin/');
FT=FT_check_for_kat_binary(FT);

tolerance=5e-5;
verbose=1;
  
  if (verbose>=1)
    fit_display='iter';
  else
    fit_display='off';
  end

  % initialise fit   
  options=optimset('Display',fit_display, 'TolX', tolerance, 'TolFun',tolerance, 'MaxIter', 10000);
  paramsin=zeros(1,4);
  paramsin(1)=0.0;
  paramsin(2)=2112.58;
  paramsin(3)=3200;
  paramsin(4)=0.01;

  paramsout=fminsearch(@mytestf,paramsin,options,cbl,outbl,FT,katname,y);

  ymodel=run_finesse(paramsout, cbl, outbl, FT, katname);

  params=paramsout;
  fprintf(' Fit parameters:\n');
  fprintf(' factor = %g, offset = %g\n',params(2), params(1));
  fprintf(' loss = %gppm, midx = %g\n',abs(params(3)), params(4));
  
  figure
  plot(1e3*x,y,'b',1e3*x,ymodel,'k--')
  axis tight;
  legend('measurement', 'simulation');
  xlabel('time [ms]');
  ylabel('Error signal [V]');

  

function [diff]=mytestf(params, cbl, outbl, FT, katname, y)

  ymodel=run_finesse(params, cbl, outbl, FT, katname);

  diff=(y-ymodel).^2;
  diff=sqrt(sum(diff)/length(diff));



function ymodel=run_finesse(params, cbl, outbl, FT, katname)
  
  loss=params(3);
  midx=params(4);
  
  sloss=sprintf('%gu',abs(loss));
  
  [const_lines]=FT_find_element_in_active_block(cbl,2,'mL');
  for i=const_lines
    cbl.txt_lines(i)={FT_replace_value_in_line(cbl.txt_lines(i),3,sloss)};
  end

  [const_lines]=FT_find_element_in_active_block(cbl,2,'midx');
  for i=const_lines
    cbl.txt_lines(i)={FT_replace_value_in_line(cbl.txt_lines(i),3,midx)};
  end
  
  outbl(4)=FT_copy_block(cbl,'const');

  FT_write_blocks_into_file(outbl,katname);
  Run=FT_create_new_kat_run();
  Run.filename=katname;
  Run=FT_run_kat_simulation(FT,Run,0);
  
  ymodel=Run.y*params(2)+params(1);