function [ x, em, ierror, k ] = vandevel ( x, abserr, kmax, f )

%*****************************************************************************80
%
%% vandevel() implements the Van de Vel iteration.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    12 June 2024
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Hugo vandeVel,
%    A method for computing a root of a single nonlinear equation,
%    including its multiplicity,
%    Computing,
%    Volume 14, 1975, pages 167 - 171.
%
%  Input:
%
%    real X: an estimate for the root.
%
%    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: an approximate root for which abs ( F(X) ) <= ABSERR.
%
%    real EM, an estimate of the multiplicity of the root.
%
%    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.
%
  ierror = 0;
  k = 0;
  em1 = 1.0;
  fx = f ( x, 0 );
  dfx = f ( x, 1 );
%
%  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

    if ( dfx == 0.0 )
      ierror = 3;
      return
    end

    u = fx / dfx;
    z = x - em1 * fx / dfx;
    fz = f ( z, 0 );
    dfz = f ( z, 1 );

    if ( dfz == 0.0 )
      ierror = 3;
      return
    end

    u1 = fz / dfz;

    if ( u - u1 ~= 0.0 )
      em = em1 * u / ( u - u1 );
    else
      em = em1;
    end

    em = max ( em, 1.0 );
%
%  Set the increment.
%
    dx = - em1 * fx / dfx - em * fz / dfz;
%
%  Remember current data for next step.
%
    em1 = em;
%
%  Update the iterate and function values.
%
    x = x + dx;
    fx = f ( x, 0 );
    dfx = f ( x, 1 );

  end

  return
end
