function x = hypergeometric_sample ( n, m, l )

%*****************************************************************************80
%
%% hypergeometric_sample() samples the Hypergeometric PDF.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    01 August 2016
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Jerry Banks, editor,
%    Handbook of Simulation,
%    Engineering and Management Press Books, 1998, page 165.
%
%  Input:
%
%    integer N, the number of balls selected.
%    0 <= N <= L.
%
%    integer M, the number of white balls in the population.
%    0 <= M <= L.
%
%    integer L, the number of balls to select from.
%    0 <= L.
%
%  Output:
%
%    integer X, a sample of the PDF.
%
  c1_log = i4_choose_log ( l - m, n );
  c2_log = i4_choose_log ( l,     n );

  a = exp ( c1_log - c2_log );
  b = a;

  u = rand ( 1, 1 );

  x = 0;

  while ( a < u )

    b = b * ( m - x ) * ( n - x ) / ( ( x + 1 ) * ( l - m - n + x + 1 ) );

    a = a + b;

    x = x + 1;

  end

  return
end
