function [lBuildInfo, lBuildOpts] = loadBuildInfo(buildInfo_in, validate)
% loadBuildInfo loads the content of a buildInfo.mat file
% and updates the root folder to be consistent with the 
% location where the file is loaded from

% Copyright 2012-2020 The MathWorks, Inc.
    
if nargin < 2
    validate=false;
end

% Convert any string input to char
buildInfo = convertStringsToChars(buildInfo_in);

if ischar(buildInfo) && isfolder(buildInfo)
    buildInfoPath = fullfile(buildInfo_in, 'buildInfo.mat');
else
    buildInfoPath = buildInfo_in;
end

if ischar(buildInfoPath) && isfile(buildInfoPath)
    loadFolder = fileparts(buildInfoPath);
    bi = load(buildInfoPath);
else
    % TODO(g2194323): argument validation
    assert(false, 'Incorrect arguments supplied to loadBuildInfo')
end

if validate
    i_validateMatFileContent(bi, buildInfoPath);
end

lBuildInfo = bi.buildInfo;
lBuildOpts = bi.buildOpts;

% Update buildInfo
postLoadUpdate(lBuildInfo, loadFolder);



function i_validateMatFileContent(bi, buildInfoPath)
    
    if ~isfield(bi, 'buildInfo')
        valid = false;
    elseif ~isa(bi.buildInfo, 'RTW.BuildInfo')
        valid = false;
    elseif ~isfield(bi, 'buildOpts')
        valid = false;
    elseif ~isa(bi.buildOpts, 'coder.make.BuildOpts')
        valid = false;
    else
        valid = true;
    end
    
    if ~valid
        msg = message('coder_compile:CoderCompile:InvalidBuildInfoMat', ...
                      buildInfoPath);
        error(msg.Identifier, '%s', string(msg));
    end
