function data = deserialize( bbhArray, doFree, profEnabled )
%parallel.internal.pool.deserialize - Deserialize data

%   Copyright 2012-2019 The MathWorks, Inc.

if nargin < 3 || profEnabled
    [id, profEnabled] = parallel.internal.pool.serializationProfiling(...
        'deserialize', true, [], -1);
end

if nargin < 2 || isempty(doFree)
    % Default case - we are in charge of freeing the data.
    doFree = true;
end

numBufs = numel(bbhArray);
if doFree
    % If we're going to free the arrays, nothing to do here - the
    % free(bbhArray(...)) calls takes care of that. Here we assume that if we
    % are responsible for freeing the buffers, then no-one else is going to
    % free them.
else
    % In this case, we are not to free the original buffers - therefore, we assume
    % that someone else might, so we make a duplicate
    for idx = 1:numBufs
        bbhArray(idx) = duplicate( bbhArray( idx ) );
    end
end

try
    data = distcompByteBufferHandles2MxArray( bbhArray );
    numBytes = numel( data );
    data = distcompdeserialize( data );
    if profEnabled
        parallel.internal.pool.serializationProfiling('deserialize', false, id, numBytes);
    end
    E = [];
catch E
end

for idx = 1:numBufs
    free(bbhArray(idx));
end
if ~isempty(E)
    throw(E);
end
end
