function updatedHooks = updateHooksFromTopOfXil(topMostModelHooks, ...
    lBuildHooksOnlyForERT, topOfXilModel)
%UPDATEHOOKSFROMTOPOFXIL updates build hooks for top-of-XIL model

%   Copyright 2018-2019 The MathWorks, Inc.

% If the top model is configured for GRT, any ERT-only hooks will have been
% filtered out and we must add them back in
topMostModelHooks = [topMostModelHooks lBuildHooksOnlyForERT];

% If there are build hooks originating from the top-most (not the
% top-of-XIL) model we only keep them if they return
% useTopOfXilModelAsHost==false
if ~isempty(topMostModelHooks)
    classNames = {topMostModelHooks.className};
    useTopOfXilModelAsHostFcns = classNames + ".useTopOfXilModelAsHost";

    % Remove build hooks originating from the top-most model that must be
    % overridden by settings from the top-of-XIL model
    useTopOfXilIdx = cellfun(@feval, useTopOfXilModelAsHostFcns);
    hooks = topMostModelHooks(~useTopOfXilIdx);
else
    hooks = [];
end


% Query the top-of-XIL model to obtain all potential build hooks; we will
% only add these hooks if they return useTopOfXilModelAsHost==true
mdlRefHooks = coder.coverage.getBuildHooks(topOfXilModel);

if ~isempty(mdlRefHooks)
    classNames = {mdlRefHooks.className};
    useTopOfXilModelAsHostFcns = classNames + ".useTopOfXilModelAsHost";

    % Add hooks that return useTopOfXilModelAsHost==true
    useTopOfXilIdx = cellfun(@feval, useTopOfXilModelAsHostFcns);
    newHooks = mdlRefHooks(useTopOfXilIdx);
else
    newHooks = [];
end

updatedHooks = [hooks newHooks];
