%better display values for plotting
fontsize=20;
linewidth=2;
markersize=10;

%default values for plotting
% fontsize=12;
% linewidth=0.5;
% markersize=6;

N = 10;
g = 9.8;
%vt = 100;
vt = 1;
vxo = 0.5;
vyo = 0.5;
tau = vt/g;

Ro = 2*vxo*vyo/g;
R = Ro;

jj = 0;
while jj < 1
    for ii=1:N
        f = (vyo+vt)/vxo*R(ii) + vt*tau*log(1-R(ii)/vxo/tau);
        df = (vyo+vt)/vxo + vt*tau/(1-R(ii)/vxo/tau)*(-1/vxo/tau);
        R(ii+1) = R(ii) - f/df;
        error(ii) = abs(f/df);
        if error(ii) < 1e-12*R(ii)
            break
        end
        if error(ii) > 1000*R(ii) || R(ii) < 0
            warning('range:noroot','No root could be found.')
            return
        end
        jj = 1;
        if isnan(R(ii+1))
            jj = 0;
            R = R(1)/2;
            break
        end
    end
end

time = 0:tau/1000:2*tau;
x = vxo*tau*(1-exp(-time/tau));
y = (vyo+vt)*tau*(1-exp(-time/tau)) - vt*time;

stop = length(y);
for ii=1:length(y)
    if y(ii) < 0
        stop = ii+1;
        break
    end
end

x(stop:end) = [];
y(stop:end) = [];

subplot(3,1,1)
plot(x,y,'LineWidth',linewidth)
hold all
plot([R(end) R(end)], [0 max(y)],'LineWidth',linewidth)
plot(R, linspace(0,max(y),length(R)),'o','LineWidth',linewidth,'MarkerSize',markersize)
plot([0 x(end)],[0 0],'k:','LineWidth',linewidth)
xlim([0 1.05*R(end)])
xlabel('x [m]','FontSize',fontsize)
ylabel('y [m]','FontSize',fontsize)
set(gca,'FontSize',fontsize,'LineWidth',linewidth)

subplot(3,1,2)
plot(x,y,'LineWidth',linewidth)
hold all
plot([R(end) R(end)], [0 max(y)],'LineWidth',linewidth)
plot(R, linspace(0,max(y),length(R)),'o','LineWidth',linewidth,'MarkerSize',markersize)
plot([0 x(end)],[0 0],'k:','LineWidth',linewidth)
xlim([0.95*R(end) 1.05*R(end)])
xlabel('x [m]','FontSize',fontsize)
ylabel('y [m]','FontSize',fontsize)
set(gca,'FontSize',fontsize,'LineWidth',linewidth)

subplot(3,1,3)
semilogy(error./R(2:end),'o','LineWidth',linewidth,'MarkerSize',markersize)
xlabel('iteration','FontSize',fontsize)
ylabel('fractional error','FontSize',fontsize)
set(gca,'FontSize',fontsize,'LineWidth',linewidth)