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

%   Copyright 2021 The MathWorks, Inc.

% Out of range or missing parameters or probabilities 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) || ~(0 <= y && y <= 1)
    x = NaN("like",outProto);

elseif y == 1
    % Return Inf if the probability is 1.
    x = Inf("like",outProto);

else
    % Initialize X to 0.
    x = zeros("like",outProto);
    % Accumulate probabilities to satisfy the values in Y.
    fudge = 40*eps(y);
    cumdist = nbinpdf_scalar(x,r,p,outProto);
    while cumdist + fudge < y
        x = x + 1;
        cumdist = iUpdateCDF(cumdist,x,r,p);
    end
end
end

function cumdist = iUpdateCDF(cumdist,count,r,p)
outProto = cumdist; % Use cumdist to set the type
if cumdist > 0.5
    doUpper = true;
    cumdist = 1 - nbincdf_scalar(count,r,p,doUpper,outProto);
else
    cumdist = cumdist + nbinpdf_scalar(count,r,p,outProto);
end
end
