function b = ubvec_unrank_grlex ( rank, n )

%*****************************************************************************80
%
%% ubvec_unrank_grlex() unranks a UBVEC using the GRLEX ordering.
%
%  Discussion:
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    11 January 2021
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer RANK, the rank.
%    0 <= RANK < 2^N.
%
%    integer N, the size of the BVEC.
%
%  Output:
%
%    integer B(N), the UBVEC of the given rank.
%
  mk = 0;

  for k = 0 : n

    mk_old = mk;
    mk_plus = nchoosek ( n, k );
    mk = mk_old + mk_plus;

    if ( rank < mk )
      rank_k = rank - mk_old;
      t = ksubset_colex_unrank ( rank_k, k, n );
      b(1:n) = 0;
      b(t(1:k)) = 1;
      b = b(n:-1:1);
      return
    end

  end
%
%  If we got here, the rank is too large.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'UBVEC_UNRANK_GRLEX - Fatal error!\n' );
  fprintf ( 1, '  Input value of rank is too high.\n' );
  error ( 'UBVEC_UNRANK_GRLEX - Fatal error!' );
end

