% 01032024 do copy file instead change file name because its faster
% and you can have a backup

% Flexible settings

% Copy file from/to directory
oldPath = 'G:\maxproj\B070_3\hyb01\hyb01_maxProj';
newPath = 'G:\maxproj\B070_3\hyb01\hyb01_maxProj_3';

%% Option 1: mannually get the old & newStr -------------------------------
cd(oldPath);
oldStr = dir('*.tif');
oldStr = {oldStr.name}';
oldStr = erase(oldStr,'.tif');
newStr = labellist;

[oldStr,newStr];
openvar ans
return

%% Option 2: change tile number -------------------------------------------

% Digit of number in the old & new name
% i.e. 1: 3-digit, 001; 4-digit, 0001
oldNumDigit = 1; % to be changed
newNumDigit = 3; % name you want

% Old and new number
oldNum = 001:006;
newNum = 085:090;

%% Fixed settings

% Convert to verctor for easier mannual checking if needed
oldNum = reshape(oldNum,[],1);
newNum = reshape(newNum,[],1);

% Checking digit accuracy -------------------------------------------------
maxNum = max(oldNum);
digitAllow = (10^(oldNumDigit))-1;
if maxNum > digitAllow
    error(['Old number digit only allows max: ', num2str(digitAllow)]);
end

maxNum = max(newNum);
digitAllow = (10^(newNumDigit))-1;
if maxNum > digitAllow
    error(['new number digit only allows max: ', num2str(digitAllow)]);
end

% Checking numel ----------------------------------------------------------
if numel(oldNum) ~= numel(newNum)
    error('Numbers of elements are different between oldNum and newNum.');
end

% Assemble string ---------------------------------------------------------
oldStr = arrayfun(@(X) num2str(X,['%0',num2str(oldNumDigit),'d']),...
    oldNum,'UniformOutput',false);
newStr = arrayfun(@(X) num2str(X,['%0',num2str(newNumDigit),'d']),...
    newNum,'UniformOutput',false);

% Complete file name by adding xy as prepend, z as append
% (if the name contains xy and z, include z at the end
% i.e. if the position is xy1, do xy1z, because xy1 also can be found in
% xy1000, so xy1z is different from xy1000z)
fh = @(X) ['xy',X,'z'];
oldStr = cellfun(@(X) fh(X),oldStr,'UniformOutput',false);
newStr = cellfun(@(X) fh(X),newStr,'UniformOutput',false);

[oldStr,newStr];
openvar ans

return

%% Mannually run this part if the old/new file name (old/newStr) is ok

clc

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

cd(oldPath);

% Get file name
fileName = dir();
fileName = {fileName.name};

tic;
for i = 1:numel(oldStr)

    iOldStr = oldStr{i};
    iNewStr = newStr{i};

    % Get file name with old string
    TF = contains(fileName,iOldStr);
    iFileName = fileName(TF);

    if isempty(iFileName)
        warning(['Not found: ',iOldStr]); continue
    end
    
    for j = 1:numel(iFileName) % parfor
        jFileName = iFileName{j};
        % Replace the string
        jFileName2 = strrep(jFileName,iOldStr,iNewStr);

        copyfile(jFileName,fullfile(newPath,jFileName2));
    end

    disp(['Done: ',iOldStr]); toc;
end


