%Creates video of Bacteria Motility

function [bac]=bacvideo(vid_time,frame_rate,dframe,ImSize,BkCol,SigBkCol,p)

%Initialise Parameters
t=-pi:0.1:pi;
frames=zeros(p,1);

for i=1:p
    %Generates Motility Data
    [bac(i).coord,bac(i).frames]=motility(vid_time,frame_rate,300,0,1,80,2,10);
    bac(i).center_x=ImSize/(2.5*normrnd(1,0.25));
    bac(i).center_y=ImSize/(2.5*normrnd(1,0.25));
    %[coord,nframes]=motility(vid_time,frame_rate,data_pts,von_a,von_k,norm
    %_u,norm_sig,exp_l)
    frames(i,1)=bac(i).frames;
end;
    
nframes=min(frames);

for i=1:p
    %Generates Bacteria Shape and Intensity
    [bac(i).bactshape,bac(i).bactinten]=shape(nframes,dframe,30, 10, 2, 20, 2);
    %[bactshape,bactinten]=shape(nframes,dframe,L, W, SigSize, I, SigInt);
end;

%Generates Background Image

%Create Image Size
backgnd=cell(1+dframe,1); %Square Matrix of Size ImSize
bkggen=zeros(ImSize);    %Declare Blank Background

%Initialise Background Iterative Points and Index
backgnd{1,1}=abs(normrnd(BkCol,SigBkCol,ImSize));
backgnd{1+dframe,1}=abs(normrnd(BkCol,SigBkCol,ImSize));
low=1;
high=1+dframe;

figure('Position',[1 1 ImSize ImSize]);
colormap gray;
    
for n=1:nframes
    %Generates Series of Images
    if mod(n,dframe)==1
        if n==low
            bkggen=backgnd{1,1};
        elseif n==high
            bkggen=backgnd{1+dframe,1};
            
            %Switches low to high and generates new data for high
            backgnd{1,1}=backgnd{1+dframe,1};
            backgnd{1+dframe,1}=abs(normrnd(BkCol,SigBkCol,ImSize));
            low=high;
            high=low+dframe;
        end;
    else
        bkggen=backgnd{1,1}+((backgnd{1+dframe,1}-backgnd{1,1})/dframe)*(n-low);
    end;
    
    image(bkggen);
    hold on
    
    for i=1:p
        %Draws Shape of Bacteria & Membrane
        bac(i).x=bac(i).bactshape(n,1)*cos(t)+bac(i).coord(n,1)+bac(i).center_x;
        bac(i).y=bac(i).bactshape(n,2)*sin(t+bac(i).bactshape(n,3))+bac(i).coord(n,2)+bac(i).center_y; 
        bac(i).membr_x=1.2*bac(i).bactshape(n,1)*cos(t)+bac(i).coord(n,1)+bac(i).center_x;
        bac(i).membr_y=1.2*bac(i).bactshape(n,2)*sin(t+bac(i).bactshape(n,3))+bac(i).coord(n,2)+bac(i).center_y;  

        hold on
        fill(bac(i).membr_x,bac(i).membr_y,[bac(i).bactinten(n,2) bac(i).bactinten(n,2) bac(i).bactinten(n,2)],'EdgeColor','none');
        fill(bac(i).x,bac(i).y,[bac(i).bactinten(n,1) bac(i).bactinten(n,1) bac(i).bactinten(n,1)],'EdgeColor','none');  

        axis off
        M(n)=getframe;
    end;
    %Stores Frame Data
    
    hold off;
end;

%Saves as Video
%movie2avi(M,'test.avi','compression','none','fps',frame_rate);
