function setBuildInfoRootFolders(tokens, paths)
%SETBUILDINFOROOTFOLDERS adds or modifies BuildInfo root folders.
% 
%   SETBUILDINFOROOTFOLDERS(TOKEN, PATH) associates a token with a root 
%   folder path. The function creates the BuildInfo root folder if it does 
%   not exist.
%
%   SETBUILDINFOROOTFOLDERS({TOKEN1,..., TOKENn}, {PATH1,..., PATHn}) 
%   associates each token with the corresponding root folder path.
%
%   SETBUILDINFOROOTFOLDERS(ROOTFOLDERS) overwrites current BuildInfo root
%   folders by using ROOTFOLDERS, an array of objects returned by 
%   getBuildInfoRootFolders.
% 
%   Example:
%      setBuildInfoRootFolders('$(MY_TOKEN)','/path')
%      getBuildInfoRootFolders
% 
%   See also GETBUILDINFOROOTFOLDERS, REMOVEBUILDINFOROOTFOLDERS

% Copyright 2021-2023 The MathWorks, Inc.

arguments
    tokens = {};
    paths  = {};
end

if nargin == 1 && isa(tokens, 'coder.make.RootFolder')
    rootFolders = tokens;
else
    tokens = convertStringsToChars(tokens);
    paths = convertStringsToChars(paths);
    if ischar(tokens)
        tokens = {tokens};
    end
    if ischar(paths)
        paths = {paths};
    end
    if length(tokens)~=length(paths)
        msg = message('coder_compile:CoderCompile:badBuildInfoRootFoldersArgs',...
            'setBuildInfoRootFolders');
        error(msg.Identifier, '%s', string(msg));
    end
    % Create the RootFolder entries
    inputRootFolders = cellfun(@(t,p) coder.make.RootFolder(t, p), tokens, paths, 'UniformOutput',true);

    if ispref('BuildInfo', 'BuildInfoRootFolders')
        rootFolders = getpref('BuildInfo', 'BuildInfoRootFolders'); 
        assert(isa(rootFolders, 'coder.make.RootFolder'));
        idxToDiscard = ismember({rootFolders.Token}, tokens);       
        rootFolders = [rootFolders(~idxToDiscard), inputRootFolders];
    else
        rootFolders = inputRootFolders;
    end
end
setpref('BuildInfo', 'BuildInfoRootFolders', rootFolders);
end
