
% Last updated: 10122023 LY

% Flexible settings
% Note: 
% 1. the current default file name structure is: xy, z, c; otherwise
% please change the sitting in IMG.getSysSetting
% 2. the setting for maxProj & temporary stitching image folder name is in
% IMG.getSysSetting

% Directory for the raw data
directory = 'D:\barseq\B070_3\hyb01001';

% Folder for maxProj & temporary stitched image
outDirectory = 'G:\maxproj\B070_3\hyb01001';

% Ratio to scale down for maxProj & temporary stitching to boost speed
scaleRatio = 1;

% Number of z-stacks
nZ = 31;
% Number of channels
nCh = 3;
% Overlap fraction between tiles
overlapFraction = 15;

% Fixed settings ----------------------------------------------------------

% Add path for the functions (IMG.m)
addpath('C:\Users\Nikon\Desktop\LY');

sysSetting = IMG.getSysSetting;
imageSetting = IMG.getImageSetting;

% Full path for maxProj & temporary stiched image
[~,folderName,~] = fileparts(directory);
outDirectory = fullfile(outDirectory,folderName);
maxDirectory = [outDirectory,sysSetting.maxProjFolderName];
fuseDirectory = [outDirectory,sysSetting.temStitchFolderName];

if ~exist(fuseDirectory)
    mkdir(fuseDirectory);
end

%% Max projection on the fly
IMG.maxProj(directory,maxDirectory,scaleRatio,imageSetting,sysSetting);

return
%% Fuse image
% Note, this step requires MIJ
excelInTbl = cell2table(excelIn(2:end,2:end),...
    'RowNames',excelIn(2:end,1),'VariableNames',excelIn(1,2:end));

for i = 7%:size(excelInTbl,1)

    % Number of row and col for current stitching grid
    iRow = excelInTbl.nRow(i);
    iCol = excelInTbl.nCol(i);

    % First index of xy for this stitched image
    if i == 1
        firstInd = 1;
    else
        firstInd = excelInTbl{1:i-1,:};
        firstInd = prod(firstInd,2);
        firstInd = sum(firstInd)+1;
    end

    % FIJI, Grid/Collection stitching
    MIJ.run("Grid/Collection stitching", ...
        strcat("type=[Grid: row-by-row] order=[Left & Down]",...
        " grid_size_x=", num2str(iCol),...
        " grid_size_y=", num2str(iRow),...
        " tile_overlap=", num2str(overlapFraction),...
        " first_file_index_i=", num2str(firstInd),...
        " directory=", maxDirectory, ...
        " file_names=xy{iii}.tif output_textfile_name=TileConfiguration.txt fusion_method=[Linear Blending] regression_threshold=0.30 max/avg_displacement_threshold=2.50 absolute_displacement_threshold=3.50 computation_parameters=[Save computation time (but use more RAM)] image_output=[Fuse and display]"));
    
    iFileName = excelInTbl.Properties.RowNames{i};
    iFileName = [iFileName,sysSetting.imFormat];    
    MIJ.run("Save",strcat("path=",fullfile(fuseDirectory,iFileName)));

    disp(['Fused image: ',iFileName]);
%     MIJ.run("Close");
end