%Generation of Bacteria Trajectory

function [coord,nframes]=motility(vid_time,frame_rate,data_pts,von_a,von_k,norm_u,norm_sig,exp_l)

%Initialise Parameters
frame_count=0;
coord_pt=zeros(data_pts,2);
beta=zeros(data_pts,1);
tumb_frames=1;  %Bacteria Tubmles in First Frame
coord(1,:)=coord_pt(1,:);
n=1;

%Generates Bacteria Motility Statistics
theta=randraw('vonmises',[von_a,von_k],data_pts+1);      %Generates tumbling angle
v_run=randraw('norm',[norm_u,norm_sig],data_pts+1);  %Generates run speed
t_run=randraw('exp',1,data_pts+1);           %Generates run duration
t_tumb=randraw('exp',exp_l,data_pts+1);

%Generates Coordinate Points
for k=1:data_pts
    beta(k+1)=beta(k)+theta(k);  %Generates cummulative turn angle 
    %Displacement=Velocity*Time
    coord_pt(k+1,1)=coord_pt(k,1)+v_run(k+1)*cos(beta(k+1))*t_run(k+1);    
    coord_pt(k+1,2)=coord_pt(k,2)+v_run(k+1)*sin(beta(k+1))*t_run(k+1); 
end;

if (sum(t_run+t_tumb))>vid_time
    %Generates Total Number of Frames, Points Data and Skeleton
    while frame_count <= (vid_time*frame_rate)
        %Generates Total Number of Frames
        frame_count=frame_count+round(t_run(n+1)*frame_rate)+round(t_tumb(n+1)*frame_rate);
        
        %Generates Bacteria Trajectory
        
        %Set index for running
        run_frames=tumb_frames+round(t_run(n+1)*frame_rate);
        coord(run_frames,:)=coord_pt(n+1,:);
        
        %Interpolation for running frames
        for i=(tumb_frames+1):(run_frames-1)
            coord(i,:)=coord(i-1,:)+(coord(run_frames,:)-coord(tumb_frames,:))/(run_frames-tumb_frames);
        end;
        
        tumb_frames=run_frames+round(t_tumb(n)*frame_rate);
    
        %Generates Trajectory
        for i=(run_frames+1):tumb_frames
            coord(i,:)=coord(run_frames,:);
        end;
      
    %Counter
    n=n+1;
    end;
else
    sprintf('%s','Insufficient Data Points!')
end;

nframes=length(coord);