function loadChildBuildInfos(buildInfo, loadReferencedModels)
% loadChildBuildInfos loads buildInfos for any shared libraries and 
% (optionally) and referenced model components

% Copyright 2019-2020 The MathWorks, Inc.

lRootFolder = buildInfo.Settings.LocalAnchorDir;

% Load shared library buildInfos
i_loadReferencedBuildInfos(lRootFolder, buildInfo.LinkObj);

% Load referenced model buildInfos
if loadReferencedModels
  i_loadReferencedBuildInfos(lRootFolder, buildInfo.ModelRefs);
end



function i_loadReferencedBuildInfos(lRootFolder, lLinkObj)

for i=1:length(lLinkObj)
    lnkObj  = lLinkObj(i);

    if ~isempty(lnkObj.BuildInfoHandle)
        % Already loaded
        continue
    end
    lPathTokenized = lnkObj.Path;
    lPath = strrep(lPathTokenized, '$(START_DIR)', lRootFolder);

    % Check for corresponding buildInfo.mat
    libBuildInfo = fullfile(lPath, 'buildInfo.mat');
    if ~isfile(libBuildInfo)
        continue
    end

    [libBuildInfo, libBuildOpts] = coder.make.internal.loadBuildInfo(libBuildInfo);
    libName = regexprep(lnkObj.Name, '\..*', '', 'once');
    if ~any(strcmp(libName, {libBuildInfo.ComponentName, libBuildOpts.BuildName}))
        % buildInfo does not match the library component
        continue
    end

    % Set handle for the referenced buildInfo
    lnkObj.BuildInfoHandle = libBuildInfo;
    lnkObj.BuildOptsHandle = libBuildOpts;
end
