function [ x, y ] = be_fit ( f, x_range, y_initial, nstep )
%
%  function [ x, y ] = be_fit ( f, x_range, y_initial, nstep )
%
%  BE_FIT uses NSTEP steps of the backward Euler FIT method to 
%  estimate Y, the solution of an ODE, at the equally spaced points X in the 
%  range X_RANGE(1) to X_RANGE(2).  
%
%  One step of the predictor, Euler's forward method,
%  is followed by up to 10 function iterations (FIT) on Euler's backward method.
%
%  The name of the derivative function is F. 
%
TOL = 0.00001;

x(1) = x_range(1);
dx = ( x_range(2) - x_range(1) ) / nstep;
y(:,1) = y_initial;

for i = 1 : nstep

  x(i+1) = x(i) + dx;
  yp = y(:,i) + dx * feval ( f, x(i), y(:,i) );

  it = 0;
  resmax = TOL + 1.0;

  while ( resmax > TOL && it < 10 ) 
    yp = y(:,i) + dx * feval ( f, x(i+1), yp );
    res = abs ( yp - ( y(:,i) + dx * feval ( f, x(i+1), yp ) ) );
    resmax = max ( res );
    it = it + 1;
  end

  y(:,i+1) = yp;

end
