%
% search - perform a simple linear search in given direction
%
%   xend = search( func, xstart, gdir, istep, fplot, ...
%                        [ finc, fdec, [ minstep ]] )
%
% where  func    = name of objective function
%        xstart  = starting point vector
%        gdir    = direction of search vector
%        istep   = initial step size vector
%        fplot   = plot flag
%        finc    = step acceleration factor
%                  (default = 1, that is none)
%        fdec    = step decceleration factor
%                  (default = 1, that is none)
%        minstep = minimum step size (if deccelerating)
%
% global variable "stats" contains:
%        stats(1) = number of function evaluations
%        stats(2) = number of linear steps
%        stats(3) = number of linear reversals
%
% Bob Newell, April 1996
%
%-----------------------------------------------------------
%
function xend = search( func, xstart, gdir, istep, ...
                            fplot, finc, fdec, minstep )
%
global stats
%
%  default parameters
%
if nargin < 6,
  finc = 1;
  fdec = 1;
end;
if nargin < 8,
  minstep = abs( istep ) / 1000;
end;	  
%
% evaluate the starting point
%
xold = xstart;
jold = feval( func, xold );
stats(1) = stats(1) + 1;
%
% now set off stepping
%
step = istep;
step1 = 1;
while 1,
%
% take a step in indicated direction
%
  xnew = xold + step .* gdir;
  stats(2) = stats(2) + 1;
  jnew = feval( func, xnew ); 
  stats(1) = stats(1) + 1;
%  [ xold jold xnew jnew ]
  if jnew < jold,
%
% good step, just continue and accelerate if requested
%
	step = step * finc;
	step1 = 0;
  else,
%
% bad step, reverse the direction if requested
%
    if fdec < 1,
	  if step1,
        step = - step;
	  else,
        step = - step * fdec;
	  end;
      stats(3) = stats(3) + 1;
%	  [ step minstep ]
	  if abs( step ) <= minstep,
%
% if step too small, stop returning last good point
%
	    xend = xold;
	    return;
	  end;
	else,
%
% otherwise stop returning last good point
%
	  xend = xold;
	  return;
	end;
  end;
%
% reset for another step, plotting if requested
%
  if fplot > 0,
    plot( [ xold(1) xnew(1) ], [ xold(2) xnew(2) ] );
    plot( [ xnew(1) ], [ xnew(2) ], '+' );
  end;
  jold = jnew;
  xold = xnew;
end;
%----------------------------------------------------------
%
