function [Cell frames S S0]=modelfit2(Cell,i,um)
%Function modelfit2 fits the 2nd run of cell trajectory. Takes in an input
%of Cell which is of the form struct. i is the frame at which a change of
%parameter is introduced, while um is the pixel to micrometer conversion.

%Initialise Parameters
fps=27.9;                   %Frames per second
S0=Cell.model(i,:);         %Starting position
S=Cell.coord(i:length(Cell.coord),:);   %Takes in coordinates to be fitted
frames=length(S)-1;         %Number of frames 
t=0:(1/fps):(frames/fps);   %Time points

A0 = [0.1 0.1];

%Curve fitting using least squares method
[X,resnorm] = lsqcurvefit(@traj2,A0,t,S);

%Stores parameters A, B and alpha. resnorm indicates quality of data fit
Cell.A{1,2}=X(1,:);
% Cell.B{1,2}=X(2,:);
% Cell.alpha{1,2}=X(3,1);
Cell.resnorm{1,2}=resnorm;

%Generates the model for cell trajectory
[Cell.model(i:length(Cell.coord),1) Cell.model(i:length(Cell.coord),2)]= ...
    traj(Cell.A{1,2},Cell.model_v(i,:),Cell.alpha{1,1},fps,frames,S0);

subplot(2,1,1);
plot(Cell.model(:,1),Cell.model(:,2))
hold on;
plot(Cell.coord(:,1),Cell.coord(:,2),'r+');
hold off;
xlabel('x-displacement'); ylabel('y-displacement'); title('Cell Trajectory')

%Generates the velocity profile based on trajectory model
for n=1:length(S)
    for m=1:2
        Cell.model_v(n+i,m)=(Cell.B{1,1}(1,m)-Cell.A{1,2}(1,m))*exp(-Cell.alpha{1,1}*(t(n)))+Cell.A{1,2}(1,m);
    end;
    Cell.norm_model_v(n+i,1)=um*norm(Cell.model_v(n,:));
end;

subplot(2,1,2);
plot(Cell.norm_model_v);
hold on;
plot(Cell.v_frame,'r*');
xlabel('Frame Number'); ylabel('Velocity'); title('Cell Velocity')