function y = nbincdf_scalar(x, r, p, doUpper, outProto)
% Process one element of the NBINCDF output

%   Copyright 2021 The MathWorks, Inc.

% 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.
if ~(0 < r && isfinite(r) && 0 < p && p <= 1) || isnan(x)
    y = NaN("like",outProto);
    return;
end

xx = floor(x);
y = zeros("like",outProto);

% Compute Y when 0 <= X.  Data outside this range return 0.
if 0 <= xx
    if isinf(xx)
        % Positive infinite values of X return 1.
        if doUpper
            y = zeros("like",outProto);
        else
            y = ones("like",outProto);
        end
    elseif x < 0
        % Uppertail when X<=0, return 1.
        if doUpper
            y = ones("like",outProto);
        else
            y = zeros("like",outProto);
        end
    else
        % Use the relationship between binomial and beta distributions to
        % quickly calculate the CDF.
        if doUpper
            y = betainc(p,r,xx+1,"upper");
        else
            y = betainc(p,r,xx+1);
        end
        % Make sure that round-off errors never make Y greater than 1.
        y = min(y,1);
    end
end

end
