function [x_next,counter] = Newton(f,d,imax, tol, x_guess )

% Set iteration counter
counter=1;


% Set next guess to infinity to fool while condition
abs_diff_between_guess=inf;

% Start iterating - note stop conditions
while (abs_diff_between_guess>tol) && (counter<=imax)
    
    % Calculate values of the function at the guess
    f_at_guess_first=feval(f,x_guess);
    


    % Calculate derivative of the function at the guesse
    df_dx_at_guess_first=feval(d,x_guess);
    
    % Calculate next point using secant formula
    x_next = x_guess - f_at_guess_first/df_dx_at_guess_first;
    
    % Output to screen
    fprintf('ITERATION %i \r',counter)
    fprintf('First Guess = %10.6f \r',x_guess)
    fprintf('Next guess = %10.6f \r \r',x_next)

 % To test tolerance
    abs_diff_between_guess=abs(x_guess-x_next);

    % Update the guesses
    x_guess=x_next;

    % Increment counter
    counter=counter+1;

end
counter = counter-1; 