%--------------------------------------------------------------------------
% function [f_roots] = FT_find_zeros(x,f,num_roots)
%
% A Matlab function which finds the zeros of a given function.  This 
% function was designed to find the zeros for combinations of bessel 
% functions and is suitable for functions which oscillate around zero.  For
% a function, f, where |f| has local minima which are not 0 care should be
% taken as this function identifies the zeros by locating the minima of
% |f|.
%
% x:        Initial x values.  +/-(x(2)-x(1))/2 is the accuracy of the
%           zeros found.  The function extends the range of x (in the
%           positive direction) until the required number of zeros are
%           found.
% f:        Reference to annonymous function f.
% num_roots:Number of zeros to find.
%
% Typical use of FT_find_zeros() (i.e. for function sin(x)):
%
% x = 0:0.01:2*pi;
% f = @(x) sin(x);
% f_roots = FT_find_zeros(x,f,2);
%
% f_roots:  Returned roots of the equation.
%
% Part of the Simtools package, http://www.gwoptics.org/simtools
% Charlotte Bond    07.02.2012
%--------------------------------------------------------------------------
%

function [f_roots] = FT_find_zeros(x,f,num_roots)

    % Number of roots currently found
    N=0;
    
    % Extend x until given number of roots is found
    while(N < num_roots)
        
        % Reference to function
        y = f(x);
    
        % Transform data so zeros are maximum points, i.e. peaks
        loc_data = max(y) - abs(y);
    
        % Find peaks (i.e. zeros)
        [pks,idx] = findpeaks(loc_data);
        
        % Number of peaks/ zeros found
        N = length(idx);
        
        % If the number of roots found doesnt meet the given number keep
        % looking
        if(N < num_roots) 
            % Extend x-axis
            x=min(x):(x(2)-x(1)):2*max(x);
        end
        
    end
    
    % Use fzero() to find num_roots more accurate zeros
    for i=1:num_roots
        f_roots(i) = fzero(f,x(idx(i)));
    end
    
end

