function initBuildInfoBuildArgs(lBuildInfo, varargin)
% INITBUILDINFOBUILDARGS initializes buildInfo build arg tokens

%   Copyright 2017-2020 The MathWorks, Inc.

% As optimization, use persistent variable for inputParser
persistent p
if isempty(p)
    p = inputParser;
    addParameter(p, 'RTWBuildArgs', {});
    addParameter(p, 'TMFAndExtModeXCP', false);
    addParameter(p, 'ModelReferenceTargetType', '');
    addParameter(p, 'BuildVariantForPackNGo', '');
    addParameter(p, 'ToolchainForPackNGo', []);
    addParameter(p, 'RelativePathToAnchor', '');
    addParameter(p, 'SharedSourceFolder', '');    
end
parse(p, varargin{:});

groupBuildArg = coder.make.internal.BuildInfoGroup.BuildArgGroup;

bArgs = regexprep(p.Results.RTWBuildArgs,'^([^=]+)=.*','$1');
bArgVals = regexprep(p.Results.RTWBuildArgs,'^[^=]+=?(.*)$','$1');
bArgGroups(1:length(bArgs)) = {groupBuildArg};

% if there is no '=' then this is most likely a build target. It could be
% a -D type define, but that doesn't matter.  We just want to set
% the group label to identify which values go on the
% make line with no '=' appended.
targetIdx = cellfun(@isempty,regexp(p.Results.RTWBuildArgs,'='));
bArgGroups(targetIdx) = {'BUILD_TARGET'};

% If XCP is enabled, the EXT_MODE info in the TMF file are going to be
% ignored and replaced by the BuildInfo EXT_MODE group
if p.Results.TMFAndExtModeXCP
     [~,idx] = ismember('EXT_MODE', bArgs);
     bArgVals{idx} = '0';
end

% put the build args in the BuildInfo object as a build arg
addBuildArgs(lBuildInfo, bArgs, bArgVals, bArgGroups);

% Legacy PackNGo behaviour requires data to construct BuildTools object
if ~isempty(p.Results.ToolchainForPackNGo)
    lToolchainName = p.Results.ToolchainForPackNGo.Name;
    addBuildArgs(lBuildInfo, 'DEFAULT_TOOLCHAIN_FOR_PACKNGO', ...
                 lToolchainName, groupBuildArg);
end
if ~isempty(p.Results.BuildVariantForPackNGo)
    addBuildArgs(lBuildInfo, 'DEFAULT_BUILD_VARIANT_FOR_PACKNGO', ...
                 char(p.Results.BuildVariantForPackNGo), groupBuildArg);
end
    

% Model reference target type build arg
addBuildArgs(lBuildInfo, 'MODELREF_TARGET_TYPE', ...
             p.Results.ModelReferenceTargetType, groupBuildArg);

% Relative path to anchor
groupBuildArgPath_makevar = coder.make.internal.BuildInfoGroup.BuildArgMakeVar;
lBuildInfo.addBuildArgs('RELATIVE_PATH_TO_ANCHOR', ...
                        p.Results.RelativePathToAnchor, ...
                        groupBuildArgPath_makevar);

% Shared source folder
if ~isempty(p.Results.SharedSourceFolder)
    groupBuildArgPath = coder.make.internal.BuildInfoGroup.BuildArgPathGroup;
    lBuildInfo.addBuildArgs('SHARED_SRC_DIR', p.Results.SharedSourceFolder, ...
                            groupBuildArgPath);
end
