function X = hGatherImpl(codistr, LP, destWorker)
; %#ok<NOSEM> % Undocumented
% Implementation of hGatherImpl for codistributor2dbc.

%   Copyright 2009-2022 The MathWorks, Inc.

% Have one worker receive the local parts from all the other workers and
% combine them into a single array.
if destWorker ~= 0
    collectWorker = destWorker;
else
    collectWorker = 1;
end

% Note that the implementation below conserves memory, but it does so at the
% cost of using lots of sends/receives to a single worker.
mwTag = 31634;
if spmdIndex == collectWorker
    % Allocate space for the final array and put the first local part into it.
    sz = codistr.Cached.GlobalSize;
    % Let X be of the correct size and have the same attributes as the 
    % local part.
    X = distributedutil.Allocator.create(sz, LP);
    % Put our local part into X.
    rows = codistr.globalIndices(1, spmdIndex);
    cols = codistr.globalIndices(2, spmdIndex);
    X(rows, cols) = LP;
    % Receive the local parts from all the other workers and put them into X.
    for srcWorker = [1:collectWorker-1, collectWorker+1:spmdSize]
        LP = spmdReceive(srcWorker, mwTag);
        rows = codistr.globalIndices(1, srcWorker);
        cols = codistr.globalIndices(2, srcWorker);
        X(rows, cols) = LP; 
    end
else
    % Send our local part to the collecting worker.
    X = [];
    spmdSend(LP, collectWorker, mwTag);
end

if destWorker == 0
    % All workers want the gathered matrix.
    X = spmdBroadcast(collectWorker, X);
end

