function y = binocdf(x,n,p,uflag)
%BINOCDF Binomial cumulative distribution function optimized for GPU.
%   Y=BINOCDF(X,N,P)
%   Y=BINOCDF(X,N,P,'upper')
%
%   See also BINOCDF, GPUARRAY.

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

%   Copyright 2019 The MathWorks, Inc.

if nargin > 3
    uflag = convertStringsToChars(uflag);
end

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

[errorcode, x, n, p] = distchck(3,x,n,p);

if errorcode > 0
    error(message('stats:binocdf:InputSizeMismatch'));
end

if nargin >= 4
    if ~strcmpi(uflag,'upper')
        error(message('stats:cdf:UpperTailProblem'));
    end
    x = n - 1 - floor(x);
    p = 1 - p;
end

% Scalar kernel requires static types. Do any conversions up-front.
if ~isfloat(x)
    x = double(x);
end

% Process each element independently using arrayfun. This causes the
% function to be compiled into an optimised GPU kernel.
outType = zeros(1,"like",internal.stats.dominantType(x,n,p));
y = arrayfun(@binocdf_scalar, x, n, p, outType);

end
