function [LP, codistr] = hCountcatsImpl(codistr, LP, dim)
; %#ok<NOSEM> % Undocumented
%   Implementation of COUNTCATS for codistributor1d.  

%   Copyright 2016-2022 The MathWorks, Inc.
    
% COUNTCATS behaves a little differently to other reductions in that the
% reduced dimension is not 1, but 1 for each category. We first use
% COUNTCATS itself to get the local results, then reduce across workers by
% adding up the counts.

% Due to various stalls (g1560250) we ensure throwing the error on all
% workers by using syncOnError.
LP = distributedutil.syncOnError(@countcats, LP, dim);

% Work out the final size
gsize = codistr.Cached.GlobalSize;
gsize(end + 1: dim - 1) = 1; % Pad with ones if necessary
gsize(dim) = size(LP,dim);

part = codistr.Partition;

if dim == codistr.Dimension
    % Reduce across worker, putting result on worker 1
    LP = spmdPlus( LP, 1 );
    
    % Set the partition to show where the result lies
    part(:) = 0;
    part(1) = gsize(dim);
else
    % Reduction dimension not the distributed dimension, so we're done.
end

% Create a new distribution of the right size
codistr = codistributor1d(codistr.Dimension, part, gsize);
end