function relativePath = getRelativePath(absolutePath, basePath)
% Given an absolutePath and basePath, return the relative path.
%

% Copyright 2022 The MathWorks, Inc.

relativePath = '';
tok = filesep;
% escape the '\' on windows
if tok == '\'
    tok = '\\';
end
p1 = textscan(absolutePath, '%s', 'Delimiter', '[\\/]');
p1 = p1{1};
p2 = textscan(basePath, '%s', 'Delimiter', '[\\/]');
p2 = p2{1};
len1 = length(p1);
len2 = length(p2);
minLength = min(len1, len2);
% In PC, filename is case-insensitive.
if tok(1) == '/' 
    f = @strcmp;
else
    f = @strcmpi;
end
% find the common path
common = minLength;
for i=1:minLength   
    if ~f(p1{i}, p2{i})
        common = i-1;
        break;       
    end
end
% No relative path, return the absolute path.
if common == 0
    relativePath = absolutePath;
    return;
end
for j=common+1:len2
    relativePath = [relativePath '..' filesep]; %#ok
end
if tok(1) == '/'
    relativePath = [relativePath sprintf('%s/', p1{common+1:end})];
else
    relativePath = [relativePath sprintf('%s\\', p1{common+1:end})];
end
relativePath = strrep(relativePath, '\','/');
if length(relativePath) > 1
    relativePath = relativePath(1:end-1);
end
