function [sourceFiles, folders, jsonFilesFullPath] = getExistingSharedCode(lExistingSharedCode, ...
                                                  varargin)
%

% Copyright 2016-2020 The MathWorks, Inc.


p = inputParser;

% If you specify a non-empty value of FilesToInclude, the list of files returned
% by this function is restricted to files contained within the existing shared code
% folder and in FilesToInclude.
addParameter(p, 'FilesToInclude', {}, @iscell);
parse(p, varargin{:});

% Identify all folders underneath, and including, the folder lExistingSharedCode
[sourceFiles, foldersUnique, folderIdx, jsonFilesFullPath] = ...
    i_get_all_folders(lExistingSharedCode);

% Get one to one mapping between files and folders
folders = foldersUnique(folderIdx);

% Filter out any files not of interest
lFilesToInclude = p.Results.FilesToInclude;
if ~isempty(lFilesToInclude)
    [~, ia] = intersect(sourceFiles, lFilesToInclude);
    sourceFiles = sourceFiles(ia);
    folders = folders(ia);
end    

% Identify non-unique source file names
[~, ia] = unique(sourceFiles);
dupeIdx = setxor(1:length(sourceFiles), ia);

if any(dupeIdx)
    dupeList = '';
    for i=1:length(dupeIdx)
        dupeFile = sourceFiles{dupeIdx(i)};
        thisFileDupeIdx = strcmp(dupeFile, sourceFiles);
        dupeFolders = folders(thisFileDupeIdx);
        dupeFoldersList = join(string(dupeFolders), ', ');
        dupeList = sprintf('%s%s: %s\n', dupeList, dupeFile, dupeFoldersList);
    end
    DAStudio.error('coder_xrel:crossRelease:RepositoryHasDuplicates', ...
                   lExistingSharedCode, ...
                   sprintf('\n\n%s', dupeList));
end



function [sourceFiles, foldersUnique, folderIdx, jsonFilesFullPath] = ...
    i_get_all_folders(lExistingSharedCode)

[sourceFilesFullPath, jsonFilesFullPath] = coder.internal.xrel.getSharedUtilitySources...
    (lExistingSharedCode, ...
     'Recurse', true, ...
     'ReturnFullPaths', true);

[sourceFileFolders, p, e] = cellfun...
    (@fileparts, sourceFilesFullPath, 'UniformOutput', false);
sourceFiles = strcat(p,e);

[foldersUnique, ~, ib] = unique(sourceFileFolders);
idx = 1:length(sourceFileFolders);
folderIdx = idx(ib);
