function X = internal_bincrossentropy(X, T, weights, mask, normFactor)
% This function is undocumented and will change in a future release.

% internal_bincrossentropy    Return the (weighted and masked) binary
% cross-entropy between estimates X and true responses T averaged by
% normFactor.
%
% Syntax:
%   Y = internal_bincrossentropy(X, T, weights, mask, normFactor);
%
% Inputs (image):
%   X              Predictions made by network
%   T              Targets (actual values)
%   weights        Weights
%   mask           Mask
%   normFactor     Normalization factor

%   Copyright 2019-2023 The MathWorks, Inc.

if ~isreal(X) || ~isreal(T) || ~isreal(weights) || ~isreal(mask) || ~isreal(normFactor)
    error(message('deep:dlarray:ComplexNotSupported'))
end

OneMinusX = nnet.internal.cnn.util.boundAwayFromZero(1-X);
X = nnet.internal.cnn.util.boundAwayFromZero(X);

mask = weights.*mask;
X = T .*log(X);
X = internal_mask(X, mask);

OneMinusX = (1 - T) .* log(OneMinusX);
OneMinusX = internal_mask(OneMinusX, mask);

X = -deep.internal.dlarray.reduceLoss(X, normFactor)...
    - deep.internal.dlarray.reduceLoss(OneMinusX, normFactor);

end
