%--------------------------------------------------------------------------
% function [A_out,data_out] =
% FT_fit_and_remove_1D_zernike_polynomial(data_in,n,m,A_in)
%
% A function for Matlab which fits a particular Zernike polynomial defined 
% over a 1D surface and removes it from 1D surface data.
%
% data_in:      1D surface data
% n,m:          indices of the zernike polynomial to fit
% A_in:         input amplitude of the zernike polynomial to fit to the
%               surface
% 
% A_out:        final amplitude fitted and removed from the data
% data_out:     the original data with the fitted polynomial removed.
%
% Charlotte Bond    20.12.2011
%--------------------------------------------------------------------------
%

function [A_out,data_out] = FT_fit_and_remove_1D_zernike_polynomial(data_in,n,m,A_in)

    [idx]=find(~isnan(data_in));
    
    data=data_in(idx);

    % Parameters are amplitudes of odd polynomial (A_odd) and even polynomial
    % (A_even).
    params = [A_in];
    
    % Set options for fminsearch ('help optimset' gives the list of options)
    options=optimset('Display','iter', 'TolX', 1e-06, 'TolFun',1e-12, 'MaxIter', 1000000);
    
    % Create link to test function below
    f=@testfunc;
  
    % Run the fitting algorithm
    params=fminsearch(f,params,options,data,n,m);
    
    A_out = params(1);
    
    points = length(data);
    R = ceil((points-1)/2);

    Zdata = A_out * FT_1D_zernike_polynomial(n,m,'horizontal',points,R);
    
    data_out = data - Zdata;

end


function [y] = testfunc(params,data,n,m)

    A = params(1);

    points = length(data);
    R = ceil(points/2);

    Zdata = A * FT_1D_zernike_polynomial(n,m,'horizontal',points,R);

    y=sqrt(sum((data-Zdata).^2))/points;




end
