function stop_bug_demo
% exercise a bug: When fsolve is called with four outputs and an output
% function stops it, an error is generated because the fourth output is
% never set.

global outInit outIter outDone outStop fields_reported
outStop = 0;
options.OutputFcn = @myOutput;

solvefun = 'fsolve';

fprintf('respects output function stop flag...');
x0 = feval(@userfun,1,1); 
[x, fval, flag, output1] = feval(solvefun,@userfun, x0, options);
outStop=1;
[x, fval, flag, output2] = feval(solvefun,@userfun, x0, options);
if output1.iterations>output2.iterations, str='yes\n'; else str='NO\n'; end; fprintf(str);



function stop=myOutput(x, optimValues, state)
global outInit outIter outDone outStop fields_reported

switch lower(state)
  case 'init'; outInit = 1;
  case 'iter'; outIter = 1;
  case 'done'; outDone = 1;
end

stop = outStop;


function [y,J]=userfun(x,flag)
% userfun - function example to exercise fsolve
% with root at -1.1958, local max at 0, local min at 2
% Usage: [y,J]=userfun(x)
%        x=fsolve('userfun',[-2])
% expect: x= -1.1958
% INPUTS:
%   x = scalar
% OUTPUTS
%   y = scalar result 
%   J = Jacobian (derivative)

if nargin>1           % supply a starting point 
    if isscalar(flag) % If flag=1 supply plausible starting point.  
                      % If flag<1, move the starting point nearer the actual root.
        x0 = -2;
        root = -1.1958;
        y = flag*x0 + (1-flag)*root;
    else
        y = -2; 
    end    
    return
end

y = x^3/3 - x^2 + 2;

if nargout>1
    J = x^2 - 2*x;
end
