function [X, indices] = internal_maxpool(X, poolSize, padding, stride, poolOverTime, layout)
% This function is undocumented and will change in a future release.

%   Copyright 2019-2022 The MathWorks, Inc.

if ~isreal(X)
    error(message('deep:dlarray:ComplexNotSupported'))
end

if (nargin < 6) || isempty(layout)
    % If storage format *is* empty, then we aren't using lazy permutation.
    % In this case, the dedicated temporal built-ins aren't used because
    % the caller has permuted and treated the T dimension as a spatial
    % dimension.
    poolOverTime = false;
else
    % If storage format is non-empty, then we are to use lazy permutation.
    X = { X, layout.StorageFormat };
end

% Reshape as [top1 top2 ... topn bot1 bot2 ... botn] to match the CPU builtin
padding = reshape(reshape(padding, 2, [])', 1, []);

if poolOverTime
    nSpatialDims = nnz(X{2} == 'S');
end

% Call the builtin
if nargout > 1
    if poolOverTime
        [X, indices] = matlab.internal.math.cnn.maxPoolingTemporal(X, nSpatialDims, poolSize, padding, stride);
    else
        [X, indices] = builtin('_maxpool', X, poolSize, padding, stride);
    end
    if numel(indices) ~= numel(X)
        % indices is empty when the feature map contains NaN in
        % the entire pooling region.
        error(message('deep:dlarray:PoolingNotEnoughIndices'));
    end
else
    if poolOverTime
        X = matlab.internal.math.cnn.maxPoolingTemporal(X, nSpatialDims, poolSize, padding, stride);
    else
        X = builtin('_maxpool', X, poolSize, padding, stride);
    end
end

end