function removeIncludePaths(buildInfo, pathsToRemove, groupsToRemove)
%removeIncludePaths Remove specified include paths from buildInfo.
% removeIncludePaths(BUILDINFO, PATHSTOREMOVE) removes the specified
% include paths from the build information.
%
% removeIncludePaths(BUILDINFO, PATHSTOREMOVE, GROUPSTOREMOVE) also
% removes include paths in the specified groups from the build
% information.

% Copyright 2023 The MathWorks, Inc.
arguments
buildInfo (1,1) RTW.BuildInfo
pathsToRemove (1,:) {mustBeText}
groupsToRemove (1,:) {mustBeText} = {}
end
pathsToRemove = i_toCellstr(pathsToRemove);
groupsToRemove = i_toCellstr(groupsToRemove);

if isempty(buildInfo.Inc)
return;
end

nExistingPaths = numel(buildInfo.Inc.Paths);
removeFlag = false(1, nExistingPaths);

if ~isempty(pathsToRemove)
% pathsToRemove may be complete paths, or tokenized, e.g., in terms
% of $(MATLAB_ROOT) or $(START_DIR), so we need to check both.
pathsUnexpanded = {buildInfo.Inc.Paths.Value};
pathsExpanded = buildInfo.Settings.expandPaths(pathsUnexpanded);
pathsToRemoveMatch = ismember(pathsUnexpanded, pathsToRemove) | ...
ismember(pathsExpanded, pathsToRemove);
removeFlag = removeFlag | pathsToRemoveMatch;
end

if ~isempty(groupsToRemove)
groupsToRemoveMatch = ismember({buildInfo.Inc.Paths.Group}, groupsToRemove);
removeFlag = removeFlag | groupsToRemoveMatch;
end

buildInfo.Inc.Paths(removeFlag) = [];
end

function ret = i_toCellstr(in)
% Convert input to a cellstr, treating '' as empty.
if isempty(in)
ret = {};
else
ret = cellstr(in);
end
end