%
% [f2,x2,y2,M,Mtoobig,sing,newstepD] = ...
%        NextZeroC(func,x1,y1,tol,maxM,stepD,minD)
%
% Implements NextZero with step-control (see NextZero.m)
%
% inputs: func: a string with the name of a function of the
%               form [f,dfdx,dfdy] = func(x,y)
%         x1: initial x-value
%         y1: initial y-value
%         tol: tolerance - stops when it finds a point [x,y] with
%              |f(x,y)| <= tol
%         maxM: maximum number of Newton steps to allow - stops
%              even if it hasn't found a root if it exceeds maxM
%         stepD: the approximate distance away from
%              [x1,y1] to look for the next zero - this
%              is a signed distance - if > 0 we look in the
%              direction of grad(f) rotated counter-clockwise by
%              pi/2, and if < 0 we look in the direction of grad(f)
%              rotated clockwise by pi/2
%         minD : the minimum allowable distance between 
%                (x1,y1) and (x2,y2)
%
% outputs: f2: value of f at the (approximate) zero it found
%          x2: x-coordinate of the zero it found
%          y2: y-coordinate of the zero it found
%          M: number of Newton steps used
%          Mtoobig: 1 if it stopped because M exceeded
%              maxM, 0 otherwise
%          sing: 1 if it stopped because it encountered
%              a singularity: dfdx = 0 = dfdy (0 otherwise)
%          newstepD : the value of stepD that was finally used

function [f2,x2,y2,M,Mtoobig,sing,newstepD] = ...
        NextZeroC(func,x1,y1,tol,maxM,stepD,minD)

% initialize
   stopflag = 0; Mtoobig = 0; M = 0;
% main loop
   while (stopflag==0)
      [f2,x2,y2,Mthistry,Mtoobigthistry,sing] = ...
           NextZero(func,x1,y1,tol,3,stepD);
      M = M + Mthistry;
      if (sing == 1)
         stopflag = 1;
      elseif (M > maxM)
         Mtoobig = 1; stopflag = 1;
      elseif (Mtoobigthistry==1) | (Dist(x2,y2,x1,y1)>abs(minD))
         stepD = stepD/2; % try again with smaller step size
      else
         stopflag = 1; % success
      end
   end
% prepare return values
   newstepD = stepD;