function niemaxprojimaging(foldername,chseq,tformch,pausetime,posinfo,tform,remotelogin,remotepath,localpath)
%make max proj of single-plane tiff files in each folder generated by micromanager. The
%folders contain "name", and chseq indicate the sequence of channels in the
%final file. This script should be run in the folder for each
%acquisition. Unlike mmmaxproj, mmmaxprojfast does not require the
%bio-format package and processes files faster, but requires manually
%determining the sequence of channels.
%This version removed the ability to do median filtering on the z-axis
%remote path should be username@domain:path. make sure that path exists
% This version works on single plane tiff outputsfrom Nikon Elements ND
% acquisition
% this version allows saving maxproj on a different path (different drive)
% and changes nikon nd acquisition filenames to ones similar to
% micromanager output.
% this version also fixes channel shift from dual-cam scopes.
%%
tic
max_worker=8;
%workernum=[2 8];
if ~exist('tformch','var')
    tformch=2:2:10;
end


if ~exist('pausetime','var')
    pausetime=1;
end
passedtime=0;

if ~exist('remotepath','var')
    remotepath=[];
else
    if remotepath(end)=='/'
        remotepath=remotepath(1:end-1);
    end
end

if ~exist('remotelogin','var')
    remotelogin=[];
end

try
    load(posinfo,'labellist');
catch
    warning('No label list, processing without correcting filenames.')
end

if ~exist('labellist','var')
    labellist={};
end

if ~exist('tform','var')
    tform=[];
end

if ~exist('localpath','var')
    localpath='maxproj/';
    fprintf('maxproj in current folder.\n')
elseif localpath(end)~='/'
    localpath=[localpath,'/',foldername,'/'];
    fprintf('Created local designated maxproj folder.\n');
end



pause(1); %pause so that this can be run before starting imaging sequence


cd(foldername);


mkdir(localpath(1:end-1));
finishedpos=[];
nn=1;
%%
% %start parpool
% poolobj = gcp('nocreate'); % If no pool, do not create new one.
% if isempty(poolobj)
%     poolsize = 0;
% else
%     poolsize = poolobj.NumWorkers
% end
% if poolsize<workernum(1)||poolsize>workernum(2)
%     p=parpool(workernum);%limit the number of workers to limit IO.
% end
%%
%make remote folder

if ~isempty(remotelogin)&&~isempty(remotepath)
    eval(['!ssh ',remotelogin,' mkdir -p ',remotepath,'/',foldername])
    fprintf('Created remote folder.\n');
end
%%

firsttime=1;
%%
while nn<5
    %%
    % wait then look for folders
    fprintf('Waiting %u sec.\n',max(pausetime-passedtime,1));
    pause(max(pausetime-passedtime,1));
    tic
    %
    files=dir('*.tif');
    files=sort_nat({files.name});
    pzc=cell(length(files),3);
    for m=1:length(files)
        pzc(m,:)=textscan(files{m},'%*u %u %u %u %*s','Delimiter',{'xy','z','c','.'});
        %find sequencing channels

    end
    pzc=cell2mat(pzc);
    uniqpos=unique(pzc(:,1));
    uniqposcounts=histcounts(pzc(:,1),min(uniqpos)-0.5:max(uniqpos)+0.5);
    %toc
    %%
    % find the finished pos by counting files

    newpos=uniqpos(~ismember(uniqpos,finishedpos));
    if firsttime %if first time, count the largest filecounts
        maxfilecounts=max(uniqposcounts);
        firsttime=0;
    end
    %all newfolders with the max file counts are completed.

    if isempty(newpos)%if no new folder, increase nn. Otherwise nn==1;
        nn=nn+1;
        fprintf('No new folder completed,counter = %u.\n',nn);
    else
        nn=1;
        newpos=newpos(uniqposcounts(newpos)==maxfilecounts);
    end
    %%
    if nn==5
        if numel(labellist)>numel(finishedpos)
            warning('More labels than positions, but all maxproj finished.')
        else
            fprintf('All folders completed.\n');
        end
    end
    %%
    % sort channel sequence
    ch=unique(pzc(:,3));
    %sort channels using the sequence given.
    ch=ch(chseq);


    newfiles={};
    %tic
    parfor (n=1:length(newpos),max_worker)
        %%
        %pause(rem(n,p.NumWorkers)/2);

        if ~isempty(labellist)
            try
                posname=labellist{newpos(n)};
            catch
                posname=['Pos',num2str(newpos(n))];
                warning('Fewer labels than positions, proceeding without changing filenames.')
            end
        else
            posname=['Pos',num2str(newpos(n))];
        end

        %%
        %make max projectios
        for m=1:length(ch)
            %%
            %tic
            idx=find(pzc(:,3)==ch(m)&pzc(:,1)==newpos(n));
            info=imfinfo(files{idx(1)});
            %toc
            im=zeros(info.Height,info.Width,length(idx));

            for q=1:length(idx)
                %tic
                im(:,:,q)=imread(files{idx(q)});
                %toc
            end
            %tic
            if ismember(chseq(m),tformch)&&~isempty(tform)
                imref=imref2d(size(im(:,:,1)));
                im=uint16(imwarp(max(im,[],3),tform,'OutputView',imref));

                if m==1
                    imwrite(im,[localpath,'MAX_',posname,'.tif']);
                else
                    imwrite(im,[localpath,'MAX_',posname,'.tif'],'WriteMode','Append');
                end
            else


                if m==1
                    imwrite(uint16(max(im,[],3)),[localpath,'MAX_',posname,'.tif']);
                else
                    imwrite(uint16(max(im,[],3)),[localpath,'MAX_',posname,'.tif'],'WriteMode','Append');
                end

            end
            %toc

        end
        %toc
        %%
        newfiles{n}=[localpath,'MAX_',posname,'.tif '];
        if ~isempty(remotelogin)&&~isempty(remotepath)
            eval(['!start /B scp ',newfiles{n},' ',remotelogin,':',remotepath,'/',foldername,'/']);
        end

    end
    %toc
    %%
    finishedpos=[finishedpos;newpos];

    fnameassemble=cell2mat(newfiles);
    %     if ~isempty(remotelogin)&&~isempty(remotepath)
    %         eval(['!start /B scp ',fnameassemble,remotelogin,':',remotepath,'/',foldername,'/']);
    %     end
    passedtime=toc;
end
cd ..

%% should add an rsync step to make sure all files are transferred
%% add the option to maxproj to a differnt folder/drive


toc
end
