clear, clc
%Input path to the functions folder containing the int2strz.m function
addpath %path
curdir = pwd;

%Input the plate rows and columns of the empty wells to be used for
%background subtraction

emptyrows = 1;
emptycolumns = 2:4;

%Input the plate rows and columns of wells to be analyzed and the number of
%imaging sites per well

rows = 2:7;
columns = 2:11;
sites = 2;

w=waitbar(0,'Deleting Thumbs');

%%

direct=dir;
OriginalFolderCount=numel(direct)-3;

% Removing image thumbnails

for f=1:OriginalFolderCount
    cd(direct(f+3).name);
    delete('*thumb*');
    cd(curdir)
end

cd(direct(4).name)
subdirect=dir;
for i=1:numel(subdirect(4).name)
    if subdirect(3).name(i)=='_'
        m=i-1;
        break
    end
end
ExperimentName=subdirect(4).name(1:m);
cd(curdir)

if subdirect(4).name(m+5)~='_'
    %type 1 = one site one wavelength
    nametype=1;
    
elseif subdirect(4).name(m+6)=='s'
    if subdirect(4).name(m+9)~='w'&&subdirect(4).name(m+10)~='w'
    %type 2 = multiple sites one wavelength
        nametype=2;
    else
    %type 4 = multiple sites multiple wavelengths
    nametype=4;
    end
elseif subdirect(4).name(m+6)=='w'
    %type 3 = one site multiple wavelengths
    nametype=3;
end

if numel(dir('TimePoint_0'))>0
    firstpoint=0;
else
    firstpoint=1;
end

timepoints=OriginalFolderCount-1+firstpoint;

if nametype==1
    for t=firstpoint:timepoints
        if t==firstpoint, tic, w=waitbar(0,w,'Calculating Time Remaining');end
        M = 1;
        xmax = double(max(abs(t(:))));
        if xmax>=1
            M = M + floor(log10(xmax));               
            if M<2, M = 2; end
        else
            M = M+1;
        end
        S = sprintf(['%0' int2str(M) '.0f'],round(t(:)));
        S = reshape(S,M,numel(t)).';
        Timepoint=S;
        
        timefolder=['TimePoint_',int2str(t)];
        
        cd(timefolder)
        for y=1:16 %A to P
            Row=char(y+64);
            rowname=[ExperimentName,'_',Row,'*'];
            if numel(dir(rowname))>0
                for x=1:24
                    M = 1;
                    xmax = double(max(abs(x(:))));
                    if xmax>=1
                        M = M + floor(log10(xmax));               
                        if M<2, M = 2; end
                    else
                        M = M+1;
                    end
                    S = sprintf(['%0' int2str(M) '.0f'],round(x(:)));
                    S = reshape(S,M,numel(x)).';
                    Column=S;
                
                        file=[ExperimentName,'_',Row,Column,'*'];
                        if numel(dir(file))>0
                            if t>firstpoint
                                w=waitbar(t/(2*timepoints),w,'Reorganizing images'); 
                            end
                            imageD=dir(file);
                            image=imread(imageD(1).name);
                            if t<firstpoint+1
                                cd(curdir)
                                foldername=['well ',Row, Column];
                                mkdir(foldername);
                            end
                            imagename=['t',Timepoint];
                            foldername=['well ', Row ,Column];
                            cd(curdir);
                            NewDirect=dir;
                            cd (foldername)
                            imwrite(image,[imagename,'.tif'])
                            cd(curdir)
                            cd(timefolder)
                        end
                      
                end
            end
        end
        if t==firstpoint,t1=toc;end
        cd(curdir)
    end

elseif nametype==2
    for t=firstpoint:timepoints
        if t==firstpoint, tic, w=waitbar(0,w,'Calculating Time Remaining');end
        M = 1;
        xmax = double(max(abs(t(:))));
        if xmax>=1
            M = M + floor(log10(xmax));               
            if M<2, M = 2; end
        else
            M = M+1;
        end
        S = sprintf(['%0' int2str(M) '.0f'],round(t(:)));
        S = reshape(S,M,numel(t)).';
        Timepoint=S;
        
        timefolder=['TimePoint_',int2str(t)];
        
        cd(timefolder)
        for y=1:16 %A to P
            Row=char(y+64);
            rowname=[ExperimentName,'_',Row,'*'];
            if numel(dir(rowname))>0
                for x=1:24
                    M = 1;
                    xmax = double(max(abs(x(:))));
                    if xmax>=1
                        M = M + floor(log10(xmax));               
                        if M<2, M = 2; end
                    else
                        M = M+1;
                    end
                    S = sprintf(['%0' int2str(M) '.0f'],round(x(:)));
                    S = reshape(S,M,numel(x)).';
                    Column=S;
                
                        file=[ExperimentName,'_',Row,Column,'_s*'];
                        if numel(dir(file))>0
                            if t>firstpoint
                                w=waitbar(t/(2*timepoints),w,'Reorganizing images');
                            end
                            NumberofSites=numel(dir(file));
                            for s=1:NumberofSites
                                cd(curdir),cd(timefolder)
                                file=[ExperimentName,'_',Row,Column,'_s',int2str(s),'*'];
                                imageD=dir(file);
                                image=imread(imageD(1).name);
                                if t<firstpoint+1
                                    if s<2
                                        cd(curdir)
                                        foldername=['well ',Row, Column];
                                        mkdir(foldername);
                                    end
                                end
                                imagename=['site ', int2str(s),' t',Timepoint];
                                foldername=['well ', Row ,Column];
                                cd(curdir);
                                NewDirect=dir;
                                cd (foldername)
                                imwrite(image,[imagename,'.tif'])
                                cd(curdir)
                                cd(timefolder)
                            end
                        end
                end
            end
        end
        if t==firstpoint,t1=toc;end
        cd(curdir)
    end
elseif nametype==3
    for t=firstpoint:timepoints
        if t==firstpoint, tic, w=waitbar(0,w,'Calculating Time Remaining');end
        M = 1;
        xmax = double(max(abs(t(:))));
        if xmax>=1
            M = M + floor(log10(xmax));               
            if M<2, M = 2; end
        else
            M = M+1;
        end
        S = sprintf(['%0' int2str(M) '.0f'],round(t(:)));
        S = reshape(S,M,numel(t)).';
        Timepoint=S;
        
        timefolder=['TimePoint_',int2str(t)];
        
        cd(timefolder)
        for y=1:16 %A to P
            Row=char(y+64);
            rowname=[ExperimentName,'_',Row,'*'];
            if numel(dir(rowname))>0
                for x=1:24
                    M = 1;
                    xmax = double(max(abs(x(:))));
                    if xmax>=1
                        M = M + floor(log10(xmax));               
                        if M<2, M = 2; end
                    else
                        M = M+1;
                    end
                    S = sprintf(['%0' int2str(M) '.0f'],round(x(:)));
                    S = reshape(S,M,numel(x)).';
                    Column=S;
                
                        file=[ExperimentName,'_',Row,Column,'*'];
                        if numel(dir(file))>0
                            if t>firstpoint
                               w=waitbar(t/(2*timepoints),w,'Reorganizing images');
                            end
                        
                            file=[ExperimentName,'_',Row,Column,'_w*'];
                            imageD=dir(file);
                            NumberofWavelengths=numel(imageD);                    
                            images=zeros((length(imread(imageD(1).name))),length((imread(imageD(1).name))),NumberofWavelengths);
                            for i=1:NumberofWavelengths
                                images=uint16(images);
                                images(:,:,i)=imread(imageD(i).name);
                            end
                            if t<firstpoint+1
                                cd(curdir)
                                foldername=['well ',Row, Column];
                                mkdir(foldername);
                            end
                            for i=1:NumberofWavelengths
                                imagename=['wavelength ',int2str(i),' t',Timepoint];
                                foldername=['well ', Row ,Column];
                                image=images(:,:,i);
                                cd(curdir);
                                NewDirect=dir;
                                cd (foldername)
                                imwrite(image,[imagename,'.tif'])
                            end
                            cd(curdir)
                            cd(timefolder)
                        end
                end
            end
        end
        if t==firstpoint,t1=toc;end
        cd(curdir)
    end
elseif nametype==4
	for t=firstpoint:timepoints
        if t==firstpoint, tic, w=waitbar(0,w,'Calculating Time Remaining');end
        M = 1;
        xmax = double(max(abs(t(:))));
        if xmax>=1
            M = M + floor(log10(xmax));               
            if M<2, M = 2; end
        else
            M = M+1;
        end
        S = sprintf(['%0' int2str(M) '.0f'],round(t(:)));
        S = reshape(S,M,numel(t)).';
        Timepoint=S;
        
        timefolder=['TimePoint_',int2str(t)];
        
        cd(timefolder)
        for y=1:16 %A to P
            Row=char(y+64);
            rowname=[ExperimentName,'_',Row,'*'];
            if numel(dir(rowname))>0
                for x=1:24
                    M = 1;
                    xmax = double(max(abs(x(:))));
                    if xmax>=1
                        M = M + floor(log10(xmax));               
                        if M<2, M = 2; end
                    else
                        M = M+1;
                    end
                    S = sprintf(['%0' int2str(M) '.0f'],round(x(:)));
                    S = reshape(S,M,numel(x)).';
                    Column=S;
                    file=[ExperimentName,'_',Row,Column,'_s*_w1*'];
                    if numel(dir(file))>0
                        if t>firstpoint
                        	w=waitbar(t/(2*timepoints),w,'Reorganizing images');
                        end
                        NumberofSites=numel(dir(file));
                        for s=1:NumberofSites
                        	file=[ExperimentName,'_',Row,Column,'_s',int2str(s),'_w*'];
                            imageD=dir(file);
                            NumberofWavelengths=numel(imageD);                    
                            images=zeros((length(imread(imageD(1).name))),length((imread(imageD(1).name))),NumberofWavelengths);
                            for i=1:NumberofWavelengths
                            	images=uint16(images);
                            	images(:,:,i)=imread(imageD(i).name);
                            end
                            if t<firstpoint+1
                            	if s<2
                                	cd(curdir)
                                	foldername=['well ',Row, Column];
                                	mkdir(foldername);
                            	end
                            end
                            for i=1:NumberofWavelengths
                            	imagename=['site ', int2str(s), ' wavelength ',int2str(i),' t',Timepoint];
                                foldername=['well ', Row ,Column];
                                image=images(:,:,i);
                                cd(curdir);
                                NewDirect=dir;
                                cd (foldername)
                                imwrite(image,[imagename,'.tif'])
                            end
                            cd(curdir)
                            cd(timefolder)
                         end
                      
                     end
                end
            end
        end
        cd(curdir)
        if t==firstpoint,t1=toc;end
	end
end

try
    rmdir('*TimePoint*','s')
catch
    try
        rmdir('*TimePoint*','s')
    catch
        warning('Thumb.db could not be deleted at this time')
    end
end

%%
% Generating TIF stacks from reorganized images

for t=firstpoint:timepoints
    tic

        if t == firstpoint, tic
        else
            w = waitbar((timepoints + t)/(2*timepoints),w,'Generating stacks');
        end
    
    AveD = 1;i = 1;

    for y = emptyrows
        for x = emptycolumns
            
            %Row identifies what letter the well should be
            Row = char(y+64);        
            %Column identifies what number the well should be
            Column = int2strz(x, 2);
            foldername = ['well ', Row, Column];
            cd(foldername)
            
            for s = 1:sites
                
                imname = ['site ',int2str(s),' t',int2strz(t,2),'.tif'];
                imdir = dir(imname);
                DAP = imread(imdir.name);
                
                DAP2 = imgaussfilt(DAP,15);
                
                AveD = AveD*(i-1)/i+double(DAP2)/i;

                i = i+1;
            end

            cd(curdir)
        end
    end
    
    DAPback = uint16(AveD);
    
for y = rows
    for x = columns
        
        Column = int2strz(x,2);
        Row = char(y+64);
        
        foldername = ['well ',Row,Column];
        if numel(dir(foldername)) == 0, continue, end
        for s = 1:sites

        imname = [foldername,'/site ', int2str(s), ' t', int2strz(t,2), '.tif'];
        imdir = dir(imname);
        DAP = imread([foldername, '/', imdir.name]);
        
        ims = uint16(double(DAP)./double(DAPback)*mean(mean(DAPback)));
        
        
        cd('..')
        try
            cd('stacks')
        catch
            mkdir('stacks')
            cd('stacks')
        end
        
        if t == firstpoint
            imwrite(uint16(ims), [Row,Column, '_', int2str(s),'.tif'])
        else
            try
            imwrite(uint16(ims), [Row, Column, '_', int2str(s), '.tif'], 'WriteMode', 'append')
            catch
              try
                imwrite(uint16(ims), [Row, Column, '_', int2str(s), '.tif'], 'WriteMode', 'append')  
              catch
                try
                    imwrite(uint16(ims), [Row, Column, '_', int2str(s), '.tif'], 'WriteMode', 'append')  
                catch
                    try
                        imwrite(uint16(ims), [Row, Column, '_', int2str(s), '.tif'], 'WriteMode', 'append')  
                    catch
                        try
                            imwrite(uint16(ims), [Row, Column, '_', int2str(s), '.tif'], 'WriteMode', 'append')  
                        catch
                            imwrite(uint16(ims),[Row, Column, '_', int2str(s), '.tif'], 'WriteMode', 'append')  
                        end                          
                    end
                end
              end
            end
        end

         
        cd(curdir) 
       end
    end
end
    t1 = toc;
end

close(w)
