function y = nbincdf(x,r,p,uflag)
%NBINCDF Negative binomial cumulative distribution function, optimised for GPU.
%   Y = NBINCDF(X,R,P)
%
%   See also NBINCDF, GPUARRAY.

%   See toolbox/stats/stats/nbincdf for implementation details.

%   Copyright 2021 The MathWorks, Inc.

if nargin > 3 && ~strcmpi(uflag,"upper")
    error(message('stats:cdf:UpperTailProblem'));
end
doUpper = nargin > 3 && strcmpi(uflag,"upper");

if nargin < 3
    error(message('stats:nbincdf:TooFewInputs'));
end

errorcode = distchck(3,x,r,p);
if errorcode > 0
    error(message('stats:nbincdf:InputSizeMismatch'));
end

% Treat integer/logical as double
if ~isfloat(x)
    x = double(x);
end
% Work out the output type
outProto = ones("like",internal.stats.dominantType(x,r,p));

% Process each element independently using arrayfun. This causes the
% function to be compiled into an optimised GPU kernel.
y = arrayfun(@nbincdf_scalar, x, r, p, doUpper, outProto);
end
