function retval = backtrack(fngrad,fn,x,p)
% usage:  alpha = backtrack(fngrad,fn,xold,p)
% description: returns step length along descent direction
% p, starting at x, with initial step length alpha0, shrink 
% factor rho, Wolfe 1 constant c1, to find first acceptable
% step length alpha. Input parameters:
% fngrad: gradient function name
% fn: function name
% x: starting point
% p: search direction

% global variables:
global parms;

% local variables:
% rho: shrink factor
% c1: Wolfe condition 1 parameter
% alpha1: initial step length
% f: fn(x)
% reduct: convenient constant
% doneflag: done flag

% initialize the problem, no bulletproofing done here
rho = parms.backtrackrho;
c1 = parms.c1;
alpha1 = parms.alpha1;
retval = alpha1/rho; % differs from text since return is allowed to be alpha0
f = feval(fn,x);
reduct = c1*feval(fngrad,x)'*p;
doneflag = 0; % not done at the outset
% let's avoid infinite loops
while (~doneflag)
  retval = rho*retval;
  if (feval(fn,x+retval*p) <= f + retval*reduct) % Wolfe1 ok?
    doneflag = 1;
  end
end
