function syncRelativePathToAnchor(lBuildInfo)
%syncRelativePathToAnchor synchronizes build arg relative path to anchor
%    If RELATIVE_PATH_TO_ANCHOR is already present as a buildInfo buildArg
%    check that it is consistent with START_DIR and build folder; if not 
%    present, add it.

% Copyright 2019-2020 The MathWorks, Inc.

lComponentBuildFolder = lBuildInfo.ComponentBuildFolder;

if isempty(lComponentBuildFolder)
    % Special case where build folder is the same as the anchor folder
    lRelativePathToAnchor = '.';
else
    % Cleanup any path components like "myfolder/.."
    lComponentBuildFolder = RTW.reduceRelativePath(lComponentBuildFolder);
    
    % Transform path like folder1/folder2 to reverse path ../..
    expr = ['[^' regexptranslate('escape', filesep) ']+'];
    lRelativePathToAnchor = regexprep(lComponentBuildFolder, expr, '..');
end

% Now check consistency with buildInfo
[key, biRelativePathToAnchor] = ...
    findBuildArg(lBuildInfo, 'RELATIVE_PATH_TO_ANCHOR');

if isempty(key) || ~strcmp(biRelativePathToAnchor, lRelativePathToAnchor)
    
    % Remove any existing RELATIVE_PATH_TO_ANCHOR
    if isempty(lBuildInfo.BuildArgs)
        keys = {};
    else
        keys = {lBuildInfo.BuildArgs.Key};
    end
    keepIdx = ~strcmp(keys, 'RELATIVE_PATH_TO_ANCHOR');
    lBuildInfo.BuildArgs = lBuildInfo.BuildArgs(keepIdx);
   
    % Create the build arg             
    newBuildArg = RTW.BuildInfoKeyValuePair...
        ('RELATIVE_PATH_TO_ANCHOR', lRelativePathToAnchor, ...
        coder.make.internal.BuildInfoGroup.BuildArgMakeVar,...
        'RELATIVE_PATH_TO_ANCHOR', lBuildInfo.Settings);
    
    % Checksum calculations require that the position of the build arg be
    % consistent from one build to the next. Achieve this by pre-pending.
    lBuildInfo.BuildArgs = [newBuildArg; lBuildInfo.BuildArgs];
end

