function [fun, x, flg] = NewtonMethod2(Fun, dFun,x0, N, tol)
% On input: 
%   Fun and dFun are the names of function and its Jacobian.
%   x0 is initial guess, and tol tolerance.
%
% On output
%   fun and dfun contain all function values and Jacobian
%   computed by Newton
%   flg = 0 means success; otherwise method failed.
%   x(:,end) is the solution if flg = 0.
%   
% Written by Ming Gu for Math 128B, Spring 2010
% 
[FunFcn,msg] = fcnchk(Fun,0);
if ~isempty(msg)
    error('InvalidFUN',msg);
end
[dFunFcn,msg] = fcnchk(dFun,0);
if ~isempty(msg)
    error('InvalidFUN',msg);
end
flg = 1;
x   = [];
x(:,1) = x0;
fun = [];
for k = 1:N
    fun(:,k)  = FunFcn(x(:,k));
    dfun    = dFunFcn(x(:,k));
    if (norm(fun(:,k)) < tol)
       flg = 0;
       return;
    end
    newx   = x(:,k) - dfun\fun(:,k);
    if (isfinite(newx))
        x(:,k+1) = newx;
    else
       return;
    end
end


       

