function opath = reduceRelativePath(ipath)
%

% Copyright 2006-2021 The MathWorks, Inc.

if isempty(ipath)
opath = ipath;
return
end

% Remove any trailing \ or / in the path
trailpat = '[\\/]$';
opath = regexprep(ipath, trailpat, '');

% Do not eliminate the .. if it is preceded by a token
% For example, $(START_DIR)/../x should not be reduced
% Expression for any folder that does not start with a token or "."
folderExpr = '[^.\$][^\/\\]*';

% Expression for file separators
fileSepExpr = '[\\/]';

% Expression for '..'
dotDotExpr = '\.\.';

% Expression for middle redundant folders like A/.. in x/A/../y
exprMiddle = ['(?<=' fileSepExpr ')' folderExpr fileSepExpr dotDotExpr fileSepExpr];

% Eliminate any middle redundant folders
opath = regexprep(opath, exprMiddle, '', 'once');

% Keep replacing the middle redundant folders until there is no change
while any(~strcmp(opath, ipath))
ipath = opath;
opath = regexprep(ipath, exprMiddle, '', 'once');
end

% Eliminate any leading redundant folders like A/.. in A/../x/y/z
exprLeading = ['^' folderExpr fileSepExpr dotDotExpr fileSepExpr];
opath = regexprep(opath, exprLeading, '', 'once');

% Eliminate any trailing redundant folders like A/.. in x/y/z/A/..
exprTrailing = [fileSepExpr folderExpr fileSepExpr dotDotExpr '$'];
opath = regexprep(opath, exprTrailing, '', 'once');

% Eliminate any leading and trailing redundant folders like A/.. in A/..
exprLeadingAndTrailing = ['^' folderExpr fileSepExpr dotDotExpr '$'];
opath = regexprep(opath, exprLeadingAndTrailing, '', 'once');

% Remove any leading or trailing current folder like "./xyz" or "xyz\."
opath = regexprep(opath, '^\.(\\|/)', '', 'once');
opath = regexprep(opath, '(\\|/)\.$', '', 'once');

% Remove embedded current folder like "xyz\.\abc"
opath = regexprep(opath, '(\\|/)\.(?=(\\|/))', '', 'once');