function x=ssec2(xs,fx,c,erc,nmax)
% function x=ssec2(xs,fx,c,erc,nmax)  finds linear approximation of f(x)=0
% xs gives an interval to seek a solution to f(x) = 0 in.
% fx is a character vector that tells how to find f(x).
% c is a vector of parameters in f(x)
% erc gives the difference between successive values of x allowed
%   when convergence is deemed to be achieved.
% nmax is the maximum number of trials, before quitting.
% If erc and nmax are not given, then the program uses:
%    erc=.0001 and nmax=10
% If only two arguments are given, c is set to null.
% The program uses the function ssec1 for each iteration.
% Example 1: >> cs=[1 -2 -4.25 7.5]; 
%            >> disp(ssec2([2 3],'polyval(c,x)',cs,.0001,10))
% Example 2: >> disp(ssec2([3 4],'sin(x)'))
if nargin<=3
   erc=.0001;
   nmax=10;
end
if nargin==2
   c=[];
end
xl=min(xs);
xr=max(xs);
xs0=[xl,xr];
xs=xs0;
for j=1:nmax
   for k=1:nmax
     x=ssec1(xs,fx,c);
     if x<xl|x>xr
        break
     end
     xs=[xs(2) x];
     fnew=eval(fx);
     if abs(fnew)<=erc
        return
     end
     if abs(xs(2)-xs(1))<=eps
        break
     end
   end
   xm=(xl+xr)/2;
   x=xm;
   fm=eval(fx);
   x=xl;
   fl=eval(fx);
   if fl*fm>0
      xl=xm;
   else
      xr=xm;
   end
   xs=[xl,xr];
end
disp('*******************************************************')
fprintf('* ssec2 did not converge, xl:%10.5g xr:%10.5g *\n',xs(1),xs(2))
disp('*******************************************************')
if abs(xs0(2)-xs0(1))<abs(xs(1)-xs(2)) 
  x=sum(xs0)/2;
end
 
