% Kentucky Derby

clear all; hold off;
y=[0 22.4 45.8 95.8 121.2]; % Time elapsed
t=[0 0.25 0.5    1  1.25];  % Distance traveled
nPlotPts=10;

N=length(t)-1;    % N=20 here
for k=1:N
    h(k)=t(k+1)-t(k);
    b(k)=6*(y(k+1)-y(k))/h(k);
end
u(2)=2*(h(1)+h(2));
v(2)=b(2)-b(1);
for k=3:N
    u(k)=2*(h(k)+h(k-1))-h(k-1)^2/u(k-1);
    v(k)=b(k)-b(k-1)-h(k-1)*v(k-1)/u(k-1);
end
z(N+1)=0;
for k=N:-1:2
    z(k)=(v(k)-h(k)*z(k+1))/u(k);
end
z(1)=0;
for k=1:N
    B(k)=-h(k)*z(k+1)/6-h(k)*z(k)/3+(y(k+1)-y(k))/h(k);
    C(k)=0.5*z(k);
    D(k)=(z(k+1)-z(k))/(6*h(k));
end;

A=y(1:N)';
xPlot=[]; pPlot=[];
for k=1:N
    x=linspace(t(k),t(k+1),nPlotPts);
    p=HornerShift([A(k) B(k) C(k) D(k)],x,t(k));
    xPlot=[xPlot x]; pPlot=[pPlot p];
end
% plot(t,y,'r*',xPlot,pPlot,'b-'); axis equal;
% title('Natural Cubic Spline Interpolation: Dorsal Part of a Duck');

% Find the time when horse is at the 0.75 mile mark:
k=3;    % 0.75 mile lies in the 3rd segment.
pPt=HornerShift([A(k) B(k) C(k) D(k)],0.75,t(k));


%[xPlot, pPlot] = cubicSplineNaturalF(x,t,nPlotPts)
plot(xPlot,pPlot,'b-'); hold on;
plot(t,y,'r.','markerSize',8); 
plot(0.75,pPt,'k.','markerSize',8);
ylabel('Time in seconds');
xlabel('Distance Traveled in Miles');
title('Race Time of Thunder Gulch in 1995 Kentucky Derby');
