function rootFolders = getBuildInfoRootFolders(tokens)
%GETBUILDINFOROOTFOLDERS gets BuildInfo root folders.
%
%   ROOTFOLDERRESULTS = GETBUILDINFOROOTFOLDERS(TOKEN) returns the BuildInfo 
%   root folder associated with TOKEN. The function produces an error if the 
%   root folder does not exist.
%
%   ROOTFOLDERRESULTS = GETBUILDINFOROOTFOLDERS({TOKEN1,...,TOKENn}) returns
%   an array of BuildInfo root folder objects that are associated with the tokens in 
%   the cell array.
%
%   ROOTFOLDERRESULTS = GETBUILDINFOROOTFOLDERS() returns an array that 
%   contains all BuildInfo root folder objects.
%
%   Example:
%      setBuildInfoRootFolders('$(MY_TOKEN)','/path')
%      getBuildInfoRootFolders('$(MY_TOKEN)')
% 
%   See also SETBUILDINFOROOTFOLDERS, REMOVEBUILDINFOROOTFOLDERS

% Copyright 2021-2022 The MathWorks, Inc.

arguments
    tokens (1,:) = {}
end

if ispref('BuildInfo', 'BuildInfoRootFolders')
    rootFolders = getpref('BuildInfo', 'BuildInfoRootFolders');
else
    rootFolders = coder.make.RootFolder.empty;
end

if ~isempty(tokens)    
    tokens = convertStringsToChars(tokens);
    if ischar(tokens)
        tokens = {tokens};
    end
    mustBeText(tokens);
    nonSavedRootFolder = ~ismember(tokens, {rootFolders.Token});
    if any(nonSavedRootFolder)
        missingTokens = strjoin(tokens(nonSavedRootFolder), ' ');
        msg = message('coder_compile:CoderCompile:missingRootFolder',...
            missingTokens);
        error(msg.Identifier, '%s', string(msg));
    else
        idx = ismember({rootFolders.Token}, tokens);
        rootFolders = rootFolders(idx);
    end
end
end
