close

flag1=0;

x0 = input('Enter the initial x-coordinate (x_0): ');
disp('           ')
y0 = input('Enter the initial y-coordinate (y_0): ');
disp('           ')
disp('One moment please...')
disp('       ')

val = -0.5*x0*abs(x0);

if((x0<=0)&(y0==val))
    T = -x0;
    t = linspace(0,T,250);
    x = t + x0;
    y = 0.5.*t.^2 + x0*t + y0;;
    u = zeros(1,250) + 1;
elseif((x0>0)&(y0==val))
    T = x0;
    t = linspace(0,T,250);
    x = x0 - t;
    y = -0.5.*t.^2 + x0*t + y0;
    u = zeros(1,250) - 1;
else
    if(y0<-0.5*x0*abs(x0))
        val1 = sqrt(0.5*x0^2 - y0);
        T1 = val1 - x0;
        t1 = linspace(0,T1,250);
        x1 = t1 + x0;
        y1 = 0.5.*t1.^2 + x0.*t1 + y0;
        T = T1 + val1;
        t2 = linspace(T1,T,250);
        x2 = -t2 + T;
        y2 = -0.5.*t2.^2 + T.*t2 - 0.5*T^2;
        t = [t1 t2];
        y = [y1 y2];
        x = [x1 x2];
        u1 = zeros(1,250) + 1;
        u2 = zeros(1,250) - 1;
        u = [u1 u2];
    else
        val2 = -sqrt(0.5*x0^2 + y0);
        T1 = x0 - val2;
        t1 = linspace(0,T1,250);
        x1 = -t1 + x0;
        y1 = -0.5.*t1.^2 + x0.*t1 + y0;
        T = T1 - val2;
        t2 = linspace(T1,T,250);
        x2 = t2 + (val2 - T1);
        y2 = 0.5.*t2.^2 - T.*t2 + 0.5*T^2;
        t = [t1 t2];
        y = [y1 y2];
        x = [x1 x2];
        u1 = zeros(1,250) - 1;
        u2 = zeros(1,250) + 1;
        u = [u1 u2];    
    end
end
 
while(flag1==0)
    disp('Would you like to plot')
    disp('   1. x')
    disp('   2. y')
    disp('   3. u')
    disp('   4. trajectory of point (x vs. y)')
    disp('   5. all four')
    var1=input('Type 1, 2, 3, 4, or 5: ');

    if(var1==1)
        flag1=1;
        plot(t,x)
        xlabel('time')
        ylabel('x')
    elseif(var1==2)
        flag1=1;
        plot(t,y)
        xlabel('time')
        ylabel('y')
     elseif(var1==3)
        flag1=1;
        plot(t,u)
        xlabel('time')
        ylabel('u')
        axis([0 T -2 2])
     elseif(var1==4)
         flag1=1;
         plot(x,y)
         xlabel('x')
         ylabel('y')
     elseif(var1==5)
         flag1=1;
         subplot(4,1,1);plot(t,x)
         subplot(4,1,1);xlabel('time')
         subplot(4,1,1);ylabel('x')
         subplot(4,1,2);plot(t,y)
         subplot(4,1,2);xlabel('time')
         subplot(4,1,2);ylabel('y')
         subplot(4,1,3);plot(t,u)
         subplot(4,1,3);xlabel('time')
         subplot(4,1,3);ylabel('u')
         subplot(4,1,3);axis([0 T -2 2])
         subplot(4,1,4);plot(x,y)
         subplot(4,1,4);xlabel('x')
         subplot(4,1,4);ylabel('y')
     else
         disp('         ')
         disp('Pardon?')
         disp('           ')
     end
end

disp('          ')
fprintf('Final time is %g.\n',T)
