function [ x, x1, ierror, k ] = rhein1 ( x, x1, abserr, kmax, f )

%*****************************************************************************80
%
%% rhein1() implements the Rheinboldt bisection - secant method.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    15 May 2024
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Werner Rheinboldt,
%    Algorithms for finding zeros of a function,
%    UMAP Journal,
%    Volume 2, Number 1, 1981, pages 43 - 72.
%
%  Input:
%
%    real X, X1: two distinct points that start the method.
%
%    real ABSERR, an error tolerance.
%
%    integer KMAX, the maximum number of iterations allowed.
%
%    real external F, the name of the routine that
%    evaluates the function or its derivatives, of the form
%      function f ( x, ider )
%
%  Output:
%
%    real X, X1: X is an approximate root satisfying
%    abs ( F(X) ) < ABSERR, and X1 is the previous estimate.
%
%    integer IERROR, error indicator.
%    0, no error occurred.
%    nonzero, an error occurred, and the iteration was halted.
%
%    integer K, the number of steps taken.
%

%
%  Initialization.
%
  i = 0;
  ierror = 0;
  k = 0;
  fx = f ( x, 0 );
  fx1 = f ( x1, 0 );

  if ( abs ( fx1 ) < abs ( fx ) )
    t = x;
    x = x1;
    x1 = t;
    t = fx;
    fx = fx1;
    fx1 = t;
  end

  x2 = x1;
  fx2 = fx1;
  t = 0.5 * abs ( x - x1 );
%
%  Iteration loop:
%
  while ( true )
%
%  If the error tolerance is satisfied, then exit.
%
    if ( abs ( fx ) <= abserr )
      break
    end

    k = k + 1;

    if ( kmax < k )
      ierror = 2;
      return
    end
%
%  Force ABS ( FX ) <= ABS ( FX1 ).
%
    if ( abs ( fx1 ) < abs ( fx ) )

      x2 = x;
      x = x1;
      x1 = x2;

      fx2 = fx;
      fx = fx1;
      fx1 = fx2;

    end

    em = 0.5 * ( x1 - x );
%
%  Compute the numerator and denominator for secant step.
%
    p = ( x - x2 ) * fx;
    q = fx2 - fx;

    if ( p < 0.0 )
      p = - p;
      q = - q;
    end
%
%  Save the old minimum residual point.
%
    x2 = x;
    fx2 = fx;
%
%  Test for forced bisection.
%
    i = i + 1;
    forced = false;

    if ( 3 < i )
      if ( t < 8.0 * abs ( em ) )
        forced = true;
      else
        i = 0;
        t = em;
      end
    end
%
%  Set the increment.
%
    if ( forced )
      dx = em;
    elseif ( p <= abs ( q ) * abserr )
      dx = sign ( em ) * abserr;
    elseif ( p < q * em )
      dx = p / q;
    else
      dx = em;
    end
%
%  Update the iterate and function values.
%
    x = x + dx;
    fx = f ( x, 0 );
%
%  Preserve the change of sign interval.
%
    if ( sign ( fx ) == sign ( fx1 ) )
      x1 = x2;
      fx1 = fx2;
    end

  end

  return
end
