function mdlRefIncDirsUpdated = copyModelReferenceHeaders...
    (lLocalAnchorDir, lRelativePathToAnchor, mdlRefIncDirs, headerExts)
%COPYMODELREFERENCEHEADERS

%   Copyright 2018-2019 The MathWorks, Inc.

% Resolve tokenized paths
mdlRefIncDirs = strrep(mdlRefIncDirs, '$(START_DIR)', lLocalAnchorDir);...
mdlRefIncDirs = strrep(mdlRefIncDirs, '$(MATLAB_ROOT)', matlabroot);

mdlRefIncDirsUpdated = {};
if ~isempty(mdlRefIncDirs)
    childHeaderDir = 'referenced_model_includes';
    fullChildHeaderDir = fullfile(pwd,childHeaderDir);
    % remove the referenced model headers if they exist
    if (exist(fullChildHeaderDir,'dir') == 7)
        builtin('delete',fullfile(childHeaderDir,'*.h'));
        builtin('delete',fullfile(childHeaderDir,'*.hpp'));
    else
        mkdir(fullChildHeaderDir);
    end
    
    % normalize the filesep
    formattedIncDirs = regexprep(mdlRefIncDirs, '[\\/]',...
                                 regexptranslate('escape',filesep));
    
    formattedIncDirs = unique(formattedIncDirs, 'stable');
    
    % Prepend wild card to header extensions
    typesToCopy = regexprep(headerExts, '.*', '*$0');

    for i=1:length(formattedIncDirs)
        for j=1:length(typesToCopy)
            src = fullfile( formattedIncDirs{i}, typesToCopy{j} );
            % we don't actually care about the return value from this call to
            % copyfile.  By capturing it, we are avoiding an error from being
            % thrown if there are no '.h' files in the inc dir (which is quite
            % common).  If the first return arg is going to a variable, it returns
            % cleanly.  however, if there is no return var, it throws an error.
            succ = builtin('copyfile',src, childHeaderDir); %#ok
        end
    end
    
    % For consistency with other include paths convert relative path like 
    % referenced_model_includes to path like 
    % $(START_DIR)/<buildFolder>/referenced_model_includes
    childHeaderDirWithPath = i_addTokenizedPath(childHeaderDir, lRelativePathToAnchor);
    
    mdlRefIncDirsUpdated = {childHeaderDirWithPath};   
end


function childHeaderDirWithPath = i_addTokenizedPath(childHeaderDir, lRelativePathToAnchor)

% At this point, the build folder must be pwd
buildFolderNotTokenized = pwd;

% Get relative path from $(START_DIR) to build folder
pathToBuildFolder = coder.make.internal.flipRelativePathToAnchor...
    (lRelativePathToAnchor, buildFolderNotTokenized);

% Tokenized include path
childHeaderDirWithPath = fullfile('$(START_DIR)', pathToBuildFolder, childHeaderDir);

    



