function [ddZ2,dX2,dZ2] = internal_maxpoolDoubleBackward(flags,ddX,X,Z,poolSize,padding,stride)
% This function is undocumented and will change in a future release.

%   Copyright 2020 The MathWorks, Inc.

ddZ2Needed = flags(1);
dX2Needed = flags(2);
dZ2Needed = flags(3);

ddZ2 = [];
dX2 = [];
dZ2 = [];

if ddZ2Needed
    indices = iComputeIndices(X,poolSize,padding,stride);
    ddZ2 = internal_maxunpoolBackward(ddX,Z,[],indices);
end

if dX2Needed
    dX2 = zeros(size(X),'like',ddX);
end

if dZ2Needed
    dZ2 = zeros(size(Z),'like',ddX);
end
end

function indices = iComputeIndices(X,poolSize,padding,stride)
if isa(X,'gpuArray')
    % internal_maxpool on GPU doesn't compute indices.
    X = gather(X);
    [~, indices] = internal_maxpool(X,poolSize,padding,stride);
    indices = gpuArray(indices);
else
    [~, indices] = internal_maxpool(X,poolSize,padding,stride);
end
end