function [fun, x, t, flg] = NonlinearShooting(Fun,dyFun,dypFun,BV)
% On input: 
%   Fun, dyFun and dypFun are the function and its partial derivatives. 
%   BV is a data structure containing
%   BV.a, BV.b: end points of interval
%   BV.alpha, BV.beta: boundary values at end points.
%   BV.t0: initial guess for t.
%   BV.N: max # of Newton Iterations.
%   BV.tol: tolerance
%
% On output
%   t:  values of t used in Newton Method
%   x:  points in the interval.
% fun: function values at points x.
%  flg: Method converged if flg = 0, and diverged otherwise.
%   
% Written by Ming Gu for Math 128B, Spring 2010
% 
[FunFcn,msg] = fcnchk(Fun,0);
if ~isempty(msg)
    error('InvalidFUN',msg);
end
[dyFunFcn,msg] = fcnchk(dyFun,0);
if ~isempty(msg)
    error('InvalidFUN',msg);
end
[dypFunFcn,msg] = fcnchk(dypFun,0);
if ~isempty(msg)
    error('InvalidFUN',msg);
end
N = BV.N;
tol = BV.tol;
t(1) = BV.t0;
flg = 1;
for k = 1:N
    BV.t = t(k);
    [fun,dfun,x] = SolveODEwithShooting(FunFcn, dyFunFcn, dypFunFcn, BV);
    funb         = fun(end) - BV.beta;
    if (norm(funb) < tol)
%
% converged
%
       flg = 0;
       return;
    end
    newt   = t(k) - dfun(end)\funb;
    if (~isfinite(newt))
       return;
    end
    t(k+1) = newt;
end


       

