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-2013 The MathWorks, Inc.


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

tmpDflag = strfind(tokenizedPaths,'$');

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

if ~isempty(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)
            try
                repstring = evalin('base', toks(idy).dirtoken);
                if ~ischar(repstring)
                    DAStudio.error('RTW:buildProcess:tokenEvalError', ...
                                   toks(idy).dirtoken);
                end
                expandedPaths{idx} = strrep(expandedPaths{idx}, ...
                                            ['$' toks(idy).dirtoken '$'],...
                                            repstring);
            catch exc
                DAStudio.error('RTW:buildProcess:tokenEvalError', ...
                               toks(idy).dirtoken);
            end
            if ~ischar(expandedPaths{idx})
                DAStudio.error('RTW:buildProcess:tokenEvalError', ...
                               toks(idy).dirtoken);
            end
        end
    end
    expandedPaths = regexprep(expandedPaths, '[\\/]', filesep);
    
    if strInputFlag
        expandedPaths = expandedPaths{end};
    end
end
%endfunction expandToken
