function includeList = pruneAndCopySupportPackageFiles( requiredFileList, supportPackages, targetDir )
%PRUNEANDCOPYSUPPORTPACKAGEFILES Copies a subset of the listed support
%packages to the target directory

    includeList = {};
    
    requiredFileList = cell(requiredFileList);
    supportPackages = cell(supportPackages);

    if(~isdir(targetDir))
        % throw an exception if the target directory does not exist
        error(message(...
                    'Compiler:supportpackage:TargetDirNotFound', targetDir));
    end

    % initialize the list of deployable support packages
    deployableSupportPkgs = matlab.depfun.internal.DeployableSupportPackages;
    
    % for storing the results of a call to requirements if needed
    dependentFileList = {};
    
    % iterate through the packages and process them accordingly
    pkgCnt = length(supportPackages);
    for pkgItr = 1:pkgCnt
        
        % get the support package info
        pkg = deployableSupportPkgs.getSupportPackage(char(supportPackages(pkgItr)));
        
        if(isempty(pkg))
            % the support pack isn't registered
             error(message(...
                    'Compiler:supportpackage:SupportPackageNotRegistered', char(supportPackages(pkgItr))));
        end
        % any other validations we should do on the support pack?
        
        
        % if the support package has conditional includes
        % we need to call requirements 
        if(pkg.hasConditionalIncludes)
            % Only call requirements once (if needed at all)
            if(isempty(dependentFileList))
                dependentFileList = dependentFiles(requiredFileList);
            end
        end

        fileList = pkg.getIncludeList(dependentFileList);

        % If it's OK to copy the files
        % create a subdirectory based off of the support package name
        % newTargetDir = fullfile(targetDir, pkg.Folder);
        if(pkg.okToCopyFiles)
            newTargetDir = fullfile(targetDir, pkg.name);
            mkdir (newTargetDir);
            
            for i = 1:length(fileList)
                copyfile(fileList{i}, newTargetDir);
            end
            % add the single directory to the includeList
            includeList = [includeList newTargetDir];
        else
            % otherwise add the file list to the includeList
            includeList = [includeList fileList];
        end    
    end
    

end


function dependentFileList = dependentFiles(requiredFileList)

    warnstatus = warning('OFF', 'MATLAB:dispatcher:pathWarning');
    
    dependentFiles = matlab.depfun.internal.requirements(requiredFileList, 'MCR');
    
    if(~isempty(dependentFiles))
                dependentFileList = {dependentFiles(:).path}; 
            else
                dependentFileList = cellfun(@(x) which(x), vararequiredFileListrgin, 'UniformOutput', false);
    end
    warning(warnstatus);
end
