function hooks = updateBuildHooks(lCodeCoverageSettings, oldBuildHooks)
%UPDATEBUILDHOOKS

%   Copyright 2010-2017 The MathWorks, Inc.

if ~isempty(lCodeCoverageSettings)
    validateattributes(lCodeCoverageSettings, ...
        {'coder.coverage.CodeCoverageSettings'}, {'scalar'});
end

[toolNames, toolClasses] = coder.coverage.CodeCoverageHelper.getTools();

hooks = oldBuildHooks;

% Start by disabling all code coverage tool hooks
for i=1:length(toolClasses)
    if ~isempty(coder.coverage.BuildHook.getBuildHookFromHooksForClass...
                (hooks, toolClasses{i}))
        hooks = coder.coverage.BuildHook.setEnabledFromHooks...
                (hooks, toolClasses{i}, 'off');
    end
end

if isempty(lCodeCoverageSettings)
    % Code coverage is not enabled therefore no coverage hook to configure
    return
end

covTool=lCodeCoverageSettings.CoverageTool;

if any(strcmp(toolNames, covTool)) && ~strcmp(covTool, 'None')
    covToolClassIdx = strcmp(toolNames, covTool);
    covToolClass = toolClasses{covToolClassIdx};
else
    covToolClass = '';
end

if ~isempty(covToolClass)

    if strcmp(lCodeCoverageSettings.TopModelCoverage,'on')
        argsTopModelOnly = {'CoverageForTopModel','on'};
    else
        argsTopModelOnly = {'CoverageForTopModel','off'};
    end
    if strcmp(lCodeCoverageSettings.ReferencedModelCoverage,'on')
        includeReferencedModels='on';
    else
        includeReferencedModels='off';
    end
    if strcmp(lCodeCoverageSettings.TopModelCoverage,'on') || ...
            strcmp(includeReferencedModels, 'on')
        includeTopModel='on';
    else
        includeTopModel='off';
    end
    hooks = coder.coverage.BuildHook.addHookFromHooks...
            (hooks, covToolClass, ...
             'ArgsTopModelOnly',argsTopModelOnly,...
             'IncludeReferencedModels', includeReferencedModels,...
             'IncludeTopModel', includeTopModel, ...
             'Enabled','on');
end
