function y = nbinpdf_scalar(x, r, p, outProto)
% Process one element of the NBINPDF output

%   Copyright 2021 The MathWorks, Inc.

if ~(0 < r && isfinite(r) && 0 < p && p <= 1) || isnan(x)
    % Out of range or missing parameters and missing data return NaN.
    % Infinite values for R correspond to a Poisson, but its mean cannot
    % be determined from the (R,P) parametrization.
    y = NaN("like",outProto);

elseif p == 1 && x == 0
    % Fix up the degenerate case.
    y = ones("like",outProto);

elseif 0 <= x && isfinite(x) && x == round(x)
    % Negative binomial distribution is defined on the non-negative
    % integers.  Data outside this support return 0.
    lognk = gammaln(r + x) - gammaln(x + 1) - gammaln(r);
    y = exp(lognk + r.*log(p) + x.*log1p(-p));

else
    % All other values are zero
    y = zeros("like",outProto);
end
end
