function addBuildConfigCommon(h,byUser,cfgName,cfgDesc)

%   Copyright 2014-2020 The MathWorks, Inc.

narginchk( 2, 4 );
if nargin > 2
    cfgName = convertStringsToChars(cfgName);
end
if nargin > 3
    cfgDesc = convertStringsToChars(cfgDesc);
end
% Set up the build configuration object
cfgObj = [  ];
if isa( cfgName, 'coder.make.BuildConfiguration' )
    cfgObj = cfgName;
    cfgName = cfgObj.Name;  % registration of this depends on the name
    if nargin<4
        cfgDesc = cfgObj.Description;
    end
    cfgObj.File = cfgDesc;
elseif ismember( cfgName, {'all','Specify'} )
    warning( message( 'coder_compile:toolchain:ReservedBuildConfigKey', cfgName ) );
    return
end
% Check the build configuration name
if isempty( cfgName )
    % The 'Name' property of the Build Configuration object
    % must not be empty.
    error( message( 'coder_compile:toolchain:EmptyBuildConfigName' ) );
else
    h.errorIfReservedName( cfgName );
end
% Make sure we have a valid build config object
if isempty( cfgObj )
    % Create a build configuration object based on inputs
    cfgObj = coder.make.BuildConfiguration( cfgName );
    if nargin==4
        cfgObj.Description = cfgDesc;
    end
    % Populate it
    if byUser
        [options,macros,~] = h.getBuildConfigOptionsInfo();
        for i = 1:numel( options )
            % h.addBuildConfigurationOption(options{i}, macros{i});
            cfgObj.addOption( options{ i }, h.createBuildItem( macros{ i }, '' ) );
        end
    end
else
    % Check if the build configuration object contains the
    % same set of options as in the other configs
    if byUser
        options = h.getBuildConfigOptionsInfo();
        str = '';
        hasMissingOption = false;
        for i = 1:numel( options )
            if ~cfgObj.isOption( options{ i } )
                hasMissingOption = true;
                if isempty( str )
                    str = [ '''', options{ i }, '''' ];
                else
                    str = [ str, ', ''', options{ i }, '''' ];  %#ok<AGROW>
                end
            end
        end
        if hasMissingOption
            error( message( 'coder_compile:toolchain:CannotAddBuildConfig', cfgName, str ) );
        end
    end
end
% Add the build configuration object to the list
h.BuildConfigurations.add( cfgName, cfgObj );
end
