function handles = getSourceFileHandles(this, sourceFiles)
% getSourceFileHandles returns handles for the specified source files
%
% Each element of sourceFiles must be the name of a source file including path, if any.
% Optionally, the path can be tokenized.

% Copyright 2022-2023 The MathWorks, Inc.

arguments
    this
    sourceFiles (1, :) string = ""
end

buildInfoFileSep = this.Settings.FileSep;
if  ~strcmp(buildInfoFileSep, filesep)
    sourceFiles = strrep(sourceFiles, filesep, buildInfoFileSep);
end

% Use tokenized paths for the comparison
sourceFiles = this.Settings.tokenizePaths(sourceFiles);

[sourcePaths, f, e] = coder.make.internal.fileparts(sourceFiles, buildInfoFileSep);
sourceFilesNoPath = f + e;

handles = RTW.BuildInfoFile.empty;
notFoundIdx = false(size(sourceFiles));

for i=length(sourceFiles):-1:1
    sourceFileNoPath = sourceFilesNoPath(i);
    sourcePath = sourcePaths(i);

    pathMatchIdx = strcmp({this.Src.Files.Path}, sourcePath);
    nameMatchIdx = strcmp({this.Src.Files.FileName}, sourceFileNoPath);

    matchIdx = pathMatchIdx & nameMatchIdx;

    if sum(matchIdx)==1
        handles(i) = this.Src.Files(matchIdx);
    else
        assert(sum(matchIdx)==0, 'Must be either one match or zero')
        notFoundIdx(i) = true;
    end
end


if any(notFoundIdx)
    error(message('coder_compile:CoderCompile:handleForFileNotFound', ...
        join("'" + sourceFiles(notFoundIdx) + "'", ', ')));
end


