clear variables;
DirName0=pwd;

Tini=1; ttini=1; LN=1; % Real-cell
%Tini=1; ttini=50; LN=1; % Simulation

deltaT = 5;

DirOut=[DirName0,'/result'];
mkdir(DirOut);

cc=0;
vi=VideoReader([DirName0,'/video1.mp4']);
tt_num=round(vi.Duration*vi.FrameRate);

tt=1; Cval=size(read(vi,tt));

clearvars ImStack;
for tt=ttini:tt_num
    ImStack{tt-ttini+1}=double(imbinarize(rgb2gray(read(vi,tt))));
end

for tt=ttini:tt_num-deltaT
    if rem(tt,LN)==0
        
        Imp=ImStack{tt-ttini+1};
        Imn=ImStack{tt+deltaT-ttini+1};
        
        %% velosity of the centroid
        s = regionprops(Imp,'centroid');
        Cp = cat(1, s.Centroid);
        s = regionprops(Imn,'centroid');
        Cn = cat(1, s.Centroid);

        V(1:2)=(Cn(1,1:2)-Cp(1,1:2));

        Ang=angle(V(2)-i*V(1));

        Jp = imtranslate(Imp,[Cval(2)+1,Cval(1)+1]/2-Cp(1,1:2));
        Imj=imrotate(Jp,180*Ang/pi);
        [L,num]=bwlabel(Imj); clearvars Area0;
        for nn=1:num
            Area0(nn)=sum(sum(L==nn));
        end
        nnmax=find(Area0==max(Area0));
        Imj2=(L==nnmax);
    
        %% Boundary Coordinates
        Im0=function_Preprocess(Imj2);
    
        Bw=imresize(uint8(255*Im0),1/4);
    
        imwrite(Bw,[DirOut,'/image',num2str(Tini+cc),'.jpg'],'jpg');
        cc=cc+1;
    end
end

