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

% internal_huber    Return the (weighted and masked) Huber loss between
% estimates X and true responses T averagred by normFactor.
%
% Syntax:
%   X = internal_huber(X, T, WEIGHTS, MASK, NORMFACTOR, DELTA);
%
% Inputs (image):
%   X              Predictions made by network
%   T              Targets (actual values)
%   WEIGHTS        Weights
%   MASK           Mask
%   NORMFACTOR     Normalization factor
%   DELTA          Transition point from quadratic to linear function

%   Copyright 2020-2023 The MathWorks, Inc.

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

% Huber loss
absError = abs(matlab.lang.internal.move(X) - matlab.lang.internal.move(T));
minAbsErrorDelta = min(absError, delta);

X = (minAbsErrorDelta.^2) ./ (2*delta);
X = X + matlab.lang.internal.move(absError) - matlab.lang.internal.move(minAbsErrorDelta);
X = delta .* X;

X = weights .* internal_mask(X, mask);
X = deep.internal.dlarray.reduceLoss(X, normFactor);

end
