function removeLinkObjects(h, linkObjNames, groups)
%removeLinkObjects removes specified link objects from buildInfo

% Copyright 2019 The MathWorks, Inc.

if isempty(h.LinkObj)
    return;
end
removeIdx = false(size(h.LinkObj));

if nargin == 1
    % h.removeLinkObjects() is used to remove all
    % the link objects
    removeIdx = true(size(h.LinkObj));
else
    linkObjNames = convertStringsToChars(linkObjNames);
    if ~isempty(linkObjNames)
        % If any matching names, mark for removal
        idx = ismember({h.LinkObj.Name}, linkObjNames);
        removeIdx(idx) = true;
    end
    
    if  nargin > 2 && ~isempty(groups)
        groups = convertStringsToChars(groups);
        % If any matching groups, mark for removal
        idx = ismember({h.LinkObj.Group}, groups);
        removeIdx(idx) = true;
    end
end

if any(removeIdx)
    lObjNames = {h.LinkObj(removeIdx).Name};
    % remove the designated link objects from the buildInfo
    h.LinkObj(removeIdx) = [];
    % remove the designated link object names from the maps
    refreshMaps(h, lObjNames);
end

function refreshMaps(buildInfo, objsToRemove)
% Removes the objsToRemove link object names from the BuildInfo Maps
linkObjsToRemove = isKey(buildInfo.Maps.LinkObjects, objsToRemove);
mdlRefsToRemove  = isKey(buildInfo.Maps.ModelRefs,   objsToRemove);
remove(buildInfo.Maps.LinkObjects, objsToRemove(linkObjsToRemove));
remove(buildInfo.Maps.ModelRefs  , objsToRemove(mdlRefsToRemove));
