function x = beta_binomial_cdf_inv ( cdf, a, b, c )

%*****************************************************************************80
%
%% beta_binomial_cdf_inv() inverts the Beta Binomial CDF.
%
%  Discussion:
%
%    A simple discrete approach is used.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    08 October 2004
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    real CDF, the value of the CDF.
%
%    real A, B, parameters of the PDF.
%    0.0 < A,
%    0.0 < B.
%
%    integer C, a parameter of the PDF.
%    0 <= C.
%
%  Output:
%
%    integer X, the smallest X whose cumulative density function
%    is greater than or equal to CDF.
%
  if ( cdf <= 0.0 )

    x = 0;

  else

    cum = 0.0;

    for y = 0 : c

      pdf = r8_beta ( a + y, b + c - y ) / ( ( c + 1 ) ...
        * r8_beta ( y + 1, c - y + 1 ) * r8_beta ( a, b ) );

      cum = cum + pdf;

      if ( cdf <= cum )
        x = y;
        return
      end

    end

    x = c;

  end

  return
end
