function [T]=segmask(folders,num_cond,crop_seed,z,resize,cell_par,cropcheck)
if nargin ==6, cropcheck = 1; end
set(0,'DefaultFigureWindowStyle','docked') 
cd(folders{2})
%find the last time frame
T = 0;
E = 2;
while E >0
    T = T+1;
    list = dir([folders{2},'/*',sprintf('t%03d',T),'*c1*.tif']);
    E = length(list);
end

%load first mask
list = dir([folders{2},'/*',sprintf('t%03d',1),'*c1*.tif']);
I0 = imresize(imread(list(z).name),resize);
% bw pic
bw = false(size(I0));
[row, col]=find(I0>0);
for i = 1:length(row)
    bw(row(i),col(i))=1;
end
%seperate each cell
for thr = 1:max(I0(:))
    c = false(size(I0));
    [row, col]=find(I0==thr);
    for i = 1:length(row)
        c(row(i),col(i))=1;
    end
    cc1 = bwconncomp(c,8);
    ccone = regionprops(cc1,'Centroid','MajorAxisLength','PixelIdxList','Area','Eccentricity');
    if thr ==1
        cellone = ccone;
        cc = cc1;
    else
        cellone = [cellone; ccone];
        cc.PixelIdxList = {cc.PixelIdxList{:},cc1.PixelIdxList{:}};
    end
end
j = false(1,length(cellone));
for i = 1:length(cellone)
    if cellone(i).Area<cell_par(1) || cellone(i).Eccentricity > cell_par(2)
        j(i)=1;
    end
end
cellone(j)=[];
cc.PixelIdxList={cc.PixelIdxList{~j}}';
cc.NumObjects = length(cc.PixelIdxList);
XY=zeros(length(cellone),2);
for i = 1:length(cellone)
    XY(i,:)=cellone(i).Centroid;
end
[~,index] =sortrows(XY,2);
cc.PixelIdxList={cc.PixelIdxList{index}};
RGB = label2rgb(labelmatrix(cc), @spring, 'c', 'shuffle');
cc0=cc;
%cell map
str = 'Y';
while str == 'Y'
    figure(9)
    x = linspace(1,size(RGB,2));
    y = linspace(1,-size(RGB,1));
    plot(x,y,'w')
    hold on
    stat= regionprops(cc,'Centroid','MajorAxisLength');
    for lab = 1:cc.NumObjects
        centers= floor(stat(lab).Centroid);
        text(centers(1),-1*centers(2),num2str(lab));
    end
    axis([0 size(RGB,2)+10 -size(RGB,1)-10 0]);
    axis off
    hold off
    drawnow
    frame = getframe(9);

    im = im2uint16(imcrop(rgb2gray(frame2im(frame)),crop_seed)); %use imcrop in command to copy the position 
    
    rgb(:,:,1)= im2uint16(bw)/2+(2^16-1-imresize((im),[size(I0,1) size(I0,2)]));
    rgb(:,:,2)= imresize(im2uint16(imbinarize(imread(list(z).name)))/2,[size(I0,1) size(I0,2)]) ...
        +(2^16-1-imresize((im),[size(I0,1) size(I0,2)])); %first image
    rgb(:,:,3)= 2^16-1-imresize((im),[size(I0,1) size(I0,2)]);
    imshow(rgb);
    if cropcheck ==1
        prompt = 'Crop again? Y/N [N]: ';
        str = input(prompt,'s');
        if isempty(str)
            str = 'N';
        end
    else 
        str = 'N';
    end
end
rgb=imresize(rgb,0.5);
[A,map]=rgb2ind(rgb,256);
filename = ['cell_trace_Condition_Nr_',num2str(num_cond),'.gif'];
imwrite(A,map,fullfile(folders{1},filename),'gif',...
    'Loopcount',inf,'DelayTime',0.05);

% trace cell
cell_trace = zeros(cc.NumObjects,T);
frame_trace = zeros(cc.NumObjects,T);
% save first cell trace done above
cd(folders{1})
frame_name = ['cc_c' num2str(num_cond) '_t' num2str(1) '.mat'];
save(frame_name,'cc')
stat_trace= regionprops(cc,'Centroid',...
    'MajorAxisLength','PixelIdxList');
% first cell id 
for cell_id = 1:cc.NumObjects
    cell_trace(cell_id,1)= cell_id; 
    frame_trace(cell_id,1)=1;
end
all_cell = cc.NumObjects;


for j = 2:T-1
        j
    tic
    %load masks from the second to the last 
    cd(folders{2})
    list = dir([folders{2},'/*',sprintf('t%03d',j),'*c1*.tif']);
    I0 = imresize(imread(list(z).name),resize);
    % bw pic
    bw = false(size(I0));
    [row, col]=find(I0>0);
    for i = 1:length(row)
        bw(row(i),col(i))=1;
    end
    %seperate each cell
    for thr = 1:max(I0(:))
        c = false(size(I0));
        [row, col]=find(I0==thr);
        for i = 1:length(row)
            c(row(i),col(i))=1;
        end
        cc1 = bwconncomp(c,8);
        ccone = regionprops(cc1,'Centroid','MajorAxisLength','PixelIdxList');
        if thr ==1
            cellone = ccone;
            cc = cc1;
        else
            cellone = [cellone; ccone];
            cc.PixelIdxList = {cc.PixelIdxList{:},cc1.PixelIdxList{:}};
        end
    end
    p = false(1,length(cellone));
    for i = 1:length(cellone)
        if length(cellone(i).PixelIdxList)<50
            p(i)=1;
        end
    end
    cellone(p)=[];
    cc.PixelIdxList={cc.PixelIdxList{~p}}';
    cc.NumObjects = length(cc.PixelIdxList);
    RGB = label2rgb(labelmatrix(cc), @spring, 'c', 'shuffle');

    clear centers
              
    
    stat_trace= regionprops( labelmatrix(cc),...
        'Centroid','MajorAxisLength','PixelIdxList');
    Cxy_cur = reshape([stat_trace(:).Centroid],[2,length([stat_trace(:).Centroid])/2])';

    % compare to cells from the last frame
    cd(folders{1})
    [last_frame_row, last_frame_col]=find(frame_trace');
    last_frame=last_frame_row([find(last_frame_col(1:end-1)-...
        last_frame_col(2:end));length(last_frame_col)]);
    Cxy_pre=zeros(all_cell,2);
    L1=zeros(1,all_cell);
    PL=cell(1,all_cell);
    str=cell(1,all_cell);
    parfor cell_id = 1:all_cell
       previous_frame_name = ['cc_c' num2str(num_cond) '_t' num2str(last_frame(cell_id)) '.mat'];
       cc_previous = load(previous_frame_name);
       stat_previous= regionprops( labelmatrix(cc_previous.cc),...
              'Centroid','MajorAxisLength','PixelIdxList');
       Cxy_pre(cell_id,:)=stat_previous(cell_trace(cell_id,j-1)).Centroid;
       L1(1,cell_id)=length(stat_previous(cell_trace(cell_id,j-1)).PixelIdxList);
       PL{1,cell_id}=stat_previous(cell_trace(cell_id,j-1)).PixelIdxList;
       str{cell_id}=num2str(cell_id);
    end
    N=(ones(1,all_cell)'*Cxy_cur(:,1)'-...
      (ones(1,length(Cxy_cur(:,1)))'*Cxy_pre(:,1)')').^2+...
      (ones(1,all_cell)'*Cxy_cur(:,2)'-...
      (ones(1,length(Cxy_cur(:,2)))'*Cxy_pre(:,2)')').^2;
    N5=sort(N')';N5=N5(:,5);    
    N = ((N-(ones(1,length(Cxy_cur(:,2)))'*N5')')<=0).*(N+eps);
    [cur_cell_id,~]=find(N');
    cur_cell_id = reshape(cur_cell_id,[5,all_cell]);
    M={stat_trace(cur_cell_id).PixelIdxList};
    D=zeros(5,all_cell);
    L2=zeros(5,all_cell);
    for n = 1:length(D(:))
        D(n)=length(intersect(PL{ceil(n/5)},M{n}));
        L2(n)=length(M{n});
    end
    threshold = 0.8;
    cur_cell_id=sum(cur_cell_id.*(((D./(ones(1,5)'*L1) > ...
        threshold)/2+(D./L2 > threshold)/2)==1)); 
    frame_trace(find(cur_cell_id)',j)=1;
    centers=Cxy_pre;
    centers(find(cur_cell_id),:)=Cxy_cur(cur_cell_id(find(cur_cell_id)),:);

    cur_cell_id(find(~cur_cell_id))=cell_trace(find(~cur_cell_id)',j-1);
    cell_trace(:,j)=cur_cell_id';
    %cell map
    figure(9)
    x = linspace(1,size(RGB,2));
    y = linspace(1,-size(RGB,1));
    plot(x,y,'w')
    hold on
    text(centers(:,1),-1*centers(:,2),str);


    axis([0 size(RGB,2)+10 -size(RGB,1)-10 0]);
    axis off
    hold off
    drawnow
    frame = getframe(9);
    clear rgb
    im = im2uint16(imcrop(rgb2gray(frame2im(frame)),crop_seed)); 
    
    rgb(:,:,1)= im2uint16(bw)/2+(2^16-1-imresize((im),[size(I0,1) size(I0,2)]));
    rgb(:,:,2)= imresize(im2uint16(imbinarize(imread(list(z).name)))/2,[size(I0,1) size(I0,2)]) ...
        +(2^16-1-imresize((im),[size(I0,1) size(I0,2)])); %first image
    rgb(:,:,3)= 2^16-1-imresize((im),[size(I0,1) size(I0,2)]);
    %imshow(rgb);
    rgb=imresize(rgb,0.5);
    [A,map]=rgb2ind(rgb,256);


    filename = ['cell_trace_Condition_Nr_',num2str(num_cond),'.gif'];

    imwrite(A,map,fullfile(folders{1},filename),'gif',...
        'WriteMode','append','DelayTime',0.05);
    
    %save frame
    cd(folders{1})
    frame_name = ['cc_c' num2str(num_cond) '_t' num2str(j) '.mat'];
    save(frame_name,'cc')
    toc    
end




%save data
cc=cc0;
cd(folders{1})
save('tracefile.mat','cell_trace','frame_trace','cc','T')
cd(folders{3})
end