function c = regfals(Func, a, b, tol, max)
%  
% REGFALS  Find a zero of a nonlinear equation of one variable 
%          using the regula falsi algorithm. Func is the name of 
%          an M-file that contains a real-valued function of a   
%	   single real variable, and a and b are the initial  
%          guesses.  Note that a bad formulation of the problem 
%	   may cause divergence.
%
%	   An optional fourth argument sets the tolerance for 
%	   the convergence. The presence of an optional fifth 
%	   argument specifies the maximum iteration number.
%  
%  
% pre-processing, set default tolerance and maximum iteration 
% number 

if nargin<4, tol=1e-10; max=1000; end
if nargin==4, max=1000; end

%  
% start the regula falsi algorithm
%  

i = 1;
TOL_FLAG = 1;
while ( (i<max) & TOL_FLAG ),
  fb = feval(Func,b);
  fa = feval(Func,a);
  c = (a*fb-b*fa)/(fb-fa);
  fc = feval(Func,c);
  if (sign(fc)==sign(fa)),
    a = c;
  else
    b = c;
  end
  if (abs(feval(Func,c))<tol),
    TOL_FLAG = 0;
  end
  t(i) = i;
  x(i) = c;
  i = i + 1;
end

% 
% plot to see the convergence/divergence of the process
% 

plot(t, x, 'x');
title('Convergence/Divergence of the Regula Falsi Algorithm')
xlabel('iteration number')

% 
% examples of calling this function:
% 
%	>> regfals('cp1', 400, 600)
%	>> regfals('cp1', 400, 600, 0.000001)
%	>> regfals('cp1', 400, 600, 0.000001, 1000)
% 

return

end
