function mmimagetransfer(fname,remotelogin,remotepath)
%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 can do median filtering on the z-axis to reduce noise without
%affecting x-y resolution.
%remote path should be username@domain:path. make sure that path exists
%%

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

if remotepath(end)=='/'
    remotepath=remotepath(1:end-1);
end

%make remote folder

eval(['!ssh ',remotelogin,' mkdir -p ',remotepath])
fprintf('Created remote folder.\n');
%%
firsttime=1;
nn=0;
finishedfolders={};
while nn<5
    %%
    % wait then look for folders
    fprintf('Waiting %u sec.\n',max(pausetime-passedtime,1));
    pause(max(pausetime-passedtime,1));
    tic
    folders=dir(['*',fname,'*']);
    folders=sort_nat({folders.name});
    % find the finished folders by counting files
    newfolders=folders(~ismember(folders,finishedfolders));
    filecounts=cellfun(@(x) numel(dir([x,'/*.tif'])),newfolders);
    if firsttime %if first time, count the largest filecounts
        maxfilecounts=max(filecounts);
        firsttime=0;
    end
    %all newfolders with the max file counts are completed.
    
    if isempty(filecounts)%if no new folder, increase nn. Otherwise nn==1;
        nn=nn+1;
        newfolders={};
        fprintf('No new folder completed,counter = %u.\n',nn);
    else
        nn=1;
        newfolders=newfolders(filecounts==maxfilecounts);
    end
    %%
    if nn==5
        newfolders=folders(~ismember(folders,finishedfolders));
        %if there are still folders that doesn't have max file counts after
        %5 tries, then try to maxproj anyway before quiting the loop. Throw
        %a warning message. This should not happen under normal imaging
        %conditions.
        if ~isempty(newfolders)
            warning('Incomplete folders after 5 tries, maxproj anyway.\n');
        end
    end
    %%
    if ~isempty(newfolders)
        fullfolderpath=[];
        for n=1:length(newfolders)
            fullfolderpath=[fullfolderpath, newfolders{n},' '];
        end
        eval(['!scp -r ',fullfolderpath,remotelogin,':',remotepath,'/']);
    end
    
    
    
    
    finishedfolders=[finishedfolders,newfolders];
    
    passedtime=toc;


end


end
