function [fun, dfun, x, flg] = NewtonMethod(Fun, dFun,x0, N, tol,rho)
% On input: 
%   Fun and dFun are the names of function and its derivative. 
%   x0 is initial guess, and tol tolerance.
%
% On output
%   fun and dfun contain all function values and derivatives 
%   computed by Newton
%   flg = 0 means success; otherwise method failed.
%   x(end) is the root 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(1)= x0;
for k = 1:N
    fun(k)  = FunFcn(x(k),rho);
    dfun(k) = dFunFcn(x(k),rho);
    if (abs(fun(k)) < tol)
       flg = 0;
       return;
    end
    if (dfun(k) == 0)
       return;
    end
    x(k+1) = x(k) - fun(k)/dfun(k);
end

       

