function niestitch_mist(fname,refch, overlap)
%% initialize
% default numbers for Alder/Dogwood/Elm sequencing cycles
% %ch=5; %number of channels
% overlap=0.23; %fraction of image overlap
% refch=4; %channel used for stitching

if ~exist('fname','var')
    fname='n2vgeneseq01';
end
if ~exist('refch','var')
    refch=4;
end

if ~exist('fname','var')
    overlap=0.23';
end
%% Parse file names.
fprintf('Parsing filenames ...\n')
files=get_folders();
sipxy=cell(length(files),3);
for i=1:numel(files)
    sipxy(i,:)=textscan(files{i},'%*s %s %u %u',1,'Delimiter','_');    
end

xy=cell2mat(sipxy(:,2:3));
pos=cellfun(@cell2mat,sipxy(:,1),'UniformOutput',false);
uniqpos=sort_nat(unique(pos));

% make folders
stitch_folder='stitch';
foldername_tiles=fullfile(stitch_folder,fname,'ref_tiles');
foldername_output=fullfile(stitch_folder,fname,'stitched');
mkdir(foldername_tiles);
mkdir(foldername_output);

%% write ref channel to the stitch folder
fprintf('Copying ref channel images to the stitch folder ...\n');
for n=refch
    for i=1:numel(files)
        if isfolder(fullfile(files{i},'original'))
            copyfile(fullfile(files{i},'original',[fname,'.tif']),fullfile(foldername_tiles,[files{i},'.tif']));
        else
            copyfile(fullfile(files{i},[fname,'.tif']),fullfile(foldername_tiles,[files{i},'.tif']));
        end
    end
end


%%	Stitch reference channel using ImageJ
%paths should be addedd outside the function
fprintf('Runing MIST to stitch reference channels ...\n');
Miji(false);

% shared inputs to MIST
% find fiji path
fiji_path=fileparts(fileparts(which('miji')));
planpath=fullfile(fiji_path,'lib','fftw','fftPlans');
fftwlibraypath=fullfile(fiji_path,'lib','fftw');
if contains(planpath,' ')
    planpath=['[',planpath,']'];
end
if contains(fftwlibraypath,' ')
    fftwlibraypath=['[',fftwlibraypath,']'];
end

headless='true';
numcores = feature('numcores');
grid_direction='UR'; %000_000 starts from upper right corner.

%%
for i=1:length(uniqpos)
    % position specific inputs to MIST
    disp(uniqpos{i})
    in_pos=ismember(pos,uniqpos{i});
    grid_x=max(xy(in_pos,1))+1;
    grid_y=max(xy(in_pos,2))+1;

   
    file_name=['MAX_',uniqpos{i},'_{ccc}_{rrr}.tif'];
    output_prefix=['MAX_',uniqpos{i},'_'];
    output_path=fullfile(pwd,foldername_output);
    img_path=fullfile(pwd,foldername_tiles);

    %fix paths
    if contains(file_name,' ')
        file_name=['[',file_name,']'];
    end
    if contains(output_prefix,' ')
        output_prefix=['[',output_prefix,']'];
    end
    if contains(output_path,' ')
        output_path=['[',output_path,']'];
    end
    if contains(img_path,' ')
        img_path=['[',img_path,']'];
    end


    %assemble MIST inputs
    MIJ.run('MIST', ...
    ['gridwidth=',num2str(grid_x), ...
    ' gridheight=',num2str(grid_y) ...
    ' starttilerow=0', ...
    ' starttilecol=0', ...
    ' imagedir=',img_path, ...%may need double \\
    ' filenamepattern=',file_name, ...
    ' filenamepatterntype=ROWCOL', ...
    ' gridorigin=',grid_direction, ...
    ' assemblefrommetadata=false', ...
    ' assemblenooverlap=false', ...
    ' globalpositionsfile=[]', ...
    ' numberingpattern=HORIZONTALCOMBING', ...
    ' startrow=0', ...
    ' startcol=0', ...
    ' extentwidth=',num2str(grid_x), ...
    ' extentheight=',num2str(grid_y), ...
    ' timeslices=0', ...
    ' istimeslicesenabled=false', ...
    ' outputpath=',output_path, ...
    ' displaystitching=false', ...
    ' outputfullimage=false', ...
    ' outputmeta=true', ...
    ' outputimgpyramid=false', ...
    ' blendingmode=AVERAGE', ...
    ' blendingalpha=0.5', ...
    ' compressionmode=UNCOMPRESSED', ...
    ' outfileprefix=',output_prefix, ...
    ' unit=MICROMETER', ...
    ' unitx=0.33', ...
    ' unity=0.33', ...
    ' programtype=AUTO', ...
    ' numcputhreads=',num2str(numcores), ...
    ' loadfftwplan=true', ...
    ' savefftwplan=true', ...
    ' fftwplantype=MEASURE', ...
    ' fftwlibraryname=libfftw3', ...
    ' fftwlibraryfilename=libfftw3.dll', ...
    ' planpath=',planpath, ...%may need to tweak this in the future
    ' fftwlibrarypath=',fftwlibraypath, ...%may need to tweak this in the future
    ' stagerepeatability=0', ...
    ' horizontaloverlap=',num2str(overlap*100,'%.1f'), ...
    ' verticaloverlap=',num2str(overlap*100,'%.1f'), ...
    ' numfftpeaks=10', ...
    ' overlapuncertainty=NaN', ...
    ' isusedoubleprecision=true', ...
    ' isusebioformats=false', ...
    ' issuppressmodelwarningdialog=false', ...
    ' isenablecudaexceptions=false', ...
    ' translationrefinementmethod=EXHAUSTIVE', ...
    ' numtranslationrefinementstartpoints=32', ...
    ' headless=',headless, ...
    ' loglevel=MANDATORY', ...
    ' debuglevel=NONE']);

end
%% cleanup
%MIJ.closeAllWindows()
MIJ.exit;


