function [xnew,gradnew,delta,acceptflag] = trustregion(localmtd,fnhess,fngrad,fn,gradold,xold)
% description: does a single step of trust-region method with input parameters:
% localmtd: local trust-region method
% fnhess: function hessian name
% fngrad: function grad name
% fn: function name
% gradold: gradient at starting point
% xold: starting point

% global variables:
global parms;

rhomin = parms.rhomin; 
deltashrink = parms.deltashrink;
rhomax = parms.rhomax; 
deltagrow = parms.deltagrow;
deltacurr = parms.deltacurr;
deltamax = parms.deltamax;
eta = parms.eta;
% solve local trust region problem
[p,pBp] = feval(localmtd,fnhess,fngrad,fn,gradold,xold); 
normp = norm(p);
acceptflag = 1; % be an optimist
ntmp = gradold'*p + 0.5*pBp; % check for rare divide by zero
if (ntmp == 0)
  rho = 1; % insure we accept this step
else
  rho = (feval(fn,xold+p)-feval(fn,xold))/(gradold'*p + 0.5*pBp); % reduction ratio
end
if (rho < rhomin) % should we shrink trust region?
  delta = deltashrink*normp;
else % no
  if ((rho > rhomax) & (normp >= deltacurr*(1-eps)))
    delta = min(deltagrow*deltacurr,deltamax);
  else
    delta = deltacurr;
  end
end
if (rho > eta) % accept the new step at all?
  xnew = xold + p;
  gradnew = feval(fngrad,xnew);
else % no
  xnew = xold;
  gradnew = gradold;
  acceptflag = 0;
end

ag = 0;
end

