function expandedPaths = expandToken(tokenizedPaths)
% Function: expandToken =============================================
% Abstract:
%    Replace '$mydir$' with eval('mydir') in the paths. Input can be a string
%    or cell of strings.

%    Copyright 2007-2020 The MathWorks, Inc.


expandedPaths = tokenizedPaths;
if isempty(expandedPaths)
    return;
end

tmpDflag = contains(tokenizedPaths,'$');

% if there is no $ symbol in the Paths string, no need to do the replace

if any(tmpDflag)
    strInputFlag = ischar(tokenizedPaths);
    if strInputFlag
        expandedPaths = {expandedPaths};
    end

    if strcmp('\', filesep)
        ml_root_string = regexprep(matlabroot, '\\', '\\\\');
    else
        ml_root_string = matlabroot;
    end
    
    pat = '\$(?<dirtoken>[^\$]*)\$';
    
    for idx = 1:length(expandedPaths)
        % replace $matlab_root for backward compatibility
        expandedPaths{idx} = regexprep(expandedPaths{idx},...
                                       '\$\(matlab_root\)',...
                                       ml_root_string,...
                                       'ignorecase');

        toks = regexp(expandedPaths{idx},pat,'names');
        for idy = 1:length(toks)
            tokDirToken = toks(idy).dirtoken;
            try
                repstring = evalin('base', tokDirToken);
                if ~ischar(repstring)
                    error(message('RTW:buildProcess:tokenEvalError', ...
                                   tokDirToken));
                end
                expandedPaths{idx} = strrep(expandedPaths{idx}, ...
                                            ['$' tokDirToken '$'],...
                                            repstring);
            catch exc
                error(message('RTW:buildProcess:tokenEvalError', ...
                               tokDirToken));
            end
            if ~ischar(expandedPaths{idx})
                error(message('RTW:buildProcess:tokenEvalError', ...
                               tokDirToken));
            end
        end
    end
    expandedPaths = regexprep(expandedPaths, '[\\/]', filesep);
    
    if strInputFlag
        expandedPaths = expandedPaths{end};
    end
end
%endfunction expandToken
