%should be named by sample name followed by 'seq' followed by an index
%(usually automaticaly generated by mm.
folders=dir('*seq*');
folders=sort_nat({folders.name});
for i=1:length(folders)
    rootdir=cd(folders{i});
    poslist=dir('*Pos*');
    poslist=sort_nat({poslist.name});
    
    for n=1:length(poslist)
        cd(poslist{n});
        files=dir('*.tif');
        files={files.name};
        info=imfinfo(files{1});
        %parse file names
        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));
        
        %assuming ch is ACGT, sort them.
        ch=ch([3 4 1 2]);
        
        %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 m==1
                imwrite(uint16(max(im,[],3)),['../../MAX_',folders{i},'_',poslist{n},'_seq',num2str(i),'.tif']);
            else
                imwrite(uint16(max(im,[],3)),['../../MAX_',folders{i},'_',poslist{n},'_seq',num2str(i),'.tif'],'WriteMode','Append');
            end
        end
        cd ..
    end
    cd ..
end
%% separate by Pos
for i=1:length(poslist)
    mkdir(poslist{i});
    files=dir(['*',poslist{i},'*.tif']);
    files={files.name};
    for n=1:length(files)
        movefile(files{n},[poslist{i},'/',files{n}]);
    end
end
    

%% fix channel bleedthrough and make rgb
%run this in a folder with images to fix.
xlightfiximages('MAX');
rgbout1('fixed',3);
mkdir('RGB');
movefile('RGB*.tif','RGB/');
