function mmmaxprojfast(fname,chseq,medorder)
%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.

if ~exist('medorder','var')
    medorder=0;
end

folders=dir(['*',fname,'*']);
folders=sort_nat({folders.name});
mkdir maxproj
parfor n=1:length(folders)
    cd(folders{n});
    files=dir('*.tif');
    files={files.name};
    info=imfinfo(files{1});
    %parse file names
    tcz=cell(length(files),3);
    for m=1:length(files)
        tcz(m,:)=textscan(files{m},'%*s %u %s %u','Delimiter',{'_','.'});
        %find sequencing channels
        
    end
    tcz(:,2)=cellfun(@cell2mat,tcz(:,2),'UniformOutput',false);
    
    ch=unique(tcz(:,2));
    %sort channels using the sequence given.
    ch=ch(chseq);
    
    
    %make max projectios
    for m=1:length(ch)
        idx=find(strcmp(tcz(:,2),ch(m)));
        im=zeros(info.Height,info.Width,length(idx));
        for q=1:length(idx)
            im(:,:,q)=imread(files{idx(q)});
        end
        if medorder==0||size(im,3)==1
            if m==1
                imwrite(uint16(max(im,[],3)),['../maxproj/MAX_',folders{n},'.tif']);
            else
                imwrite(uint16(max(im,[],3)),['../maxproj/MAX_',folders{n},'.tif'],'WriteMode','Append');
            end
        else
            if m==1
                imwrite(uint16(max(medfilt1(im,medorder,[],3),[],3)),['../maxproj/MAX_',folders{n},'.tif']);
            else
                imwrite(uint16(max(medfilt1(im,medorder,[],3),[],3)),['../maxproj/MAX_',folders{n},'.tif'],'WriteMode','Append');
            end
        end
        
    end
    cd ..
end

