function Ok = writePerFolderData( future, destination, useUniqueFolder )
% parallel.pool.writePerFolderData - write data to client destination
%    Ok = parallel.pool.writePerFolderData(POOL, FUTURE, DESTINATION, USEUNIQUEFOLDER)
%    writes the data held in FUTURE to the corresponding location in the client 
%    side DESTINATION folder. 
%    If USEUNIQUEFOLDER is true the worker IDs held in FUTURE are appended to
%    DESTINATION to generate unique folder names for each worker. By
%    default USEUNIQUEFOLDER is set to true.
%
%    Ok is a logical which can be used to ensure that the copy executed 
%    successfully - on successful completion, the value TRUE is returned. 
%
%    Examples:
%    Consider a worker-side folder structure
%      <per-worker-root>/testing/my_model.slx
%      <per-worker-root>/testing/someData/data1.mat
%      <per-worker-root>/testing/someData/subdir/data1.mat
%    Copy files from the per-worker folder:
%      p = gcp();
%      subdir = 'testing';
%      f = parallel.pool.getDataFromPerWorkerFolder(p, subdir);
%    f is a parallel.FevalOnAllFuture containing the worker ID and data. To
%    write this data to disk:
%      destination = '/shared/project/someData';
%      ok = parallel.pool.writePerFolderData(f, destination, true);
%    This will create the following files on the client:
%      <destination>/<worker_id>/testing/my_model.slx
%      <destination>/<worker_id>/testing/someData/data1.mat
%      <destination>/<worker_id>/testing/someData/subdir/data1.mat
%
%   See also parallel.pool.getDataFromPerWorkerFolder, 
%   parallel.pool.getDataFromPerHostFolder.

% Copyright 2016-2023 The MathWorks, Inc.

if nargin < 3
    useUniqueFolder = true;
end

% Convert any string inputs to character vectors
destination = convertStringsToChars(destination);

validateattributes(destination, {'char', 'string'}, {'row', 'nonempty'});
validateattributes(useUniqueFolder, {'logical'}, {'scalar'});
validateattributes(future, {'parallel.FevalOnAllFuture'}, {'row', 'nonempty'});


[tid, data] = fetchOutputs(future, 'UniformOutput', false);
if useUniqueFolder
    destinations = cellfun(@(id) fullfile(destination, num2str(id)), tid, 'UniformOutput', false);
else
    destinations = cellfun(@(id) fullfile(destination), tid, 'UniformOutput', false);
end
Ok = cellfun(@parallel.internal.pool.FolderManagement.writeZipData, data, destinations);
Ok = all(Ok);

end


