function haveAttachedFiles = attachDependentFilesToPool(aPool, filesToAnalyse)
%

%   Copyright 2012-2020 The MathWorks, Inc.
    
haveAttachedFiles = false;

% See if a pool exists
if isempty(aPool)
    error(message('parallel:lang:pool:PoolNotRunning'));
end
% See if we should even attempt to attach files to the pool
client = aPool.hGetClient();
if ~isa(client, 'parallel.internal.pool.AbstractInteractiveClient')
    % Not an interactive parallel pool client, so do nothing.
    return
end
if ~client.ParallelJob.AutoAttachFiles
    return
end

if isempty(filesToAnalyse)
    return;
end

if ~iscell(filesToAnalyse)
    filesToAnalyse = {filesToAnalyse};
end

% Use the pool's analysis cache to short-circuit analysis for already-analysed
% files.
filteredFilesToAnalyse = needToAnalyse(aPool.hGetAnalysedSet(), filesToAnalyse);
if isempty(filteredFilesToAnalyse)
    dctSchedulerMessage(6, 'attachDependentFilesToPool - nothing left to analyse.');
    return;
end

msg = getString(message('parallel:lang:pool:PerformingDependencyAnalysis'));
fprintf('%s', msg);
printNewLineCleanup = onCleanup(@() fprintf('\n'));

% Suppress the parallel:cluster:DepfunError warning before analyzing the files
warnState = warning('off', 'parallel:cluster:DepfunError');
warnCleanupObj = onCleanup(@() warning(warnState));

fcn = @parallel.internal.apishared.AttachedFiles.calculateAttachedFiles;
filesToAttach = cellfun(fcn, filteredFilesToAnalyse, 'UniformOutput', false);
filesToAttach = [filesToAttach{:}];
% Let the analysis set know we've done the analysis so it does not need to be
% repeated (unless the set determines it should be invalidated).
analysed(aPool.hGetAnalysedSet(), filteredFilesToAnalyse);

try
    if ~isempty(filesToAttach)
        dctSchedulerMessage(6, 'attachDependentFilesToPool - will attach:\n%s', sprintf('\t%s\n', filesToAttach{:}));
        aPool.hGetFileManager.addOrUpdateAutoAttachedFiles(filesToAttach);
        haveAttachedFiles = true;
    end
catch E
    dctSchedulerMessage(1, 'Failed to addOrUpdateAutoAttachedFiles.', E);
    rethrow(E);
end

doneMsg = getString(message('parallel:lang:pool:DoneDependencyAnalysis'));
fprintf('%s', doneMsg);
