%
%--------------------------------------------------------------------------
% function [F, factor, offset]=FT_fit_cavity_finesse(x,y,T_in,T_out,F_start, factor_start,offset_start, verbose)
%
% A function for Matlab which fits the Airy function of a cavity to
% a measured scan of the cavity throughput.
%
% x (real):            vector of cavity detuning (resonance must be at x=0,pi,...)
% y (real):            vector of measured throughput
% T_in (real):         power transmission of input mirror
% T_out (real):        power transmission of output mirror
% F_start (real):      initial guess for cavity finesse
% factor_start (real): initial guess for scaling factor 
% offset_start (real): initital guess for offset to resonance at x=0
% verbose (integer):   verbose=1 prints iterations of fit
%
% F (real):            cavity finesse
% factor (real):       scaling factor 
% offset (real):       offset to resonance at x=0
%
% Part of the SimTools package
% Andreas Freise 08.02.2010 afreise@googlemail.com
%--------------------------------------------------------------------------
%

% Description: Fits the Airy function of a cavity to a measured scan of
% Description: cavity throughput
% Keywords: Airy, throughput

function [F, factor, offset]=FT_fit_cavity_finesse(x,y,T_in,T_out,F_start,factor_start,offset_start, verbose)

  % fit finesse to data
  tolerance=1e-3;
  if (verbose==1)
    iter_str='iter';
  else
    iter_str='none';
  end
  options=optimset('Display',iter_str, 'TolX', tolerance, 'TolFun',tolerance, 'MaxIter', 1000);
  params=zeros(1,3);
  params(1)=F_start;
  params(2)=factor_start;
  params(3)=offset_start;
  paramsout=fminsearch(@mytestf,params,options,x,y,T_in,T_out);

  F=paramsout(1);
  factor=paramsout(2);
  offset=paramsout(3);
  
function [diff] = mytestf(params,x,y,T_in,T_out)
  y_model=params(2)*FT_cavity_throughput(T_in,T_out,params(1),x+params(3));
  diff=sum((y-y_model).^2);
  diff=sqrt(diff)/length(y);
