function ubvec = ubvec_next_grlex ( n, ubvec )

%*****************************************************************************80
%
%% ubvec_next_grlex() generates the next UBVEC in GRLEX order.
%
%  Discussion:
%
%    N = 3
%
%    Input      Output
%    -----      ------
%    0 0 0  =>  0 0 1
%    0 0 1  =>  0 1 0
%    0 1 0  =>  1 0 0
%    1 0 0  =>  0 1 1
%    0 1 1  =>  1 0 1
%    1 0 1  =>  1 1 0
%    1 1 0  =>  1 1 1
%    1 1 1  =>  0 0 0
%
%    A UBVEC is a vector of N binary digits.
%
%    A UBVEC can be interpreted as a binary representation of an
%    unsigned integer, with the first entry being the coefficient of
%    2^(N-1) and the last entry the coefficient of 1.
%
%    UBVEC   #
%    -----  --
%    00000   0
%    00001   1
%    00010   2
%    10000  16
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    19 November 2015
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer N, the dimension.
%
%    integer UBVEC(N), the binary vector whose 
%    successor is desired.
%
%  Output:
%
%    integer UBVEC(N), the successor to the input vector.
%

%
%  Initialize locations of 0 and 1.
%
  if ( ubvec(1) == 0 )
    z = 1;
    o = 0;
  else
    z = 0;
    o = 1;
  end
%
%  Moving from right to left, search for a "1", preceded by a "0".
%
  for i = n : -1 : 2
    if ( ubvec(i) == 1 )
      o = i;
      if ( ubvec(i-1) == 0 )
        z = i - 1;
        break;
      end
    end
  end
%
%  UBVEC = 0
%
  if ( o == 0 )
    ubvec(n) = 1;
%
%  01 never occurs.  So for sure, B(1) = 1.
%
  elseif ( z == 0 )
    s = sum ( ubvec(1:n) );
    if ( s == n )
      ubvec(1:n) = 0;
    else
      ubvec(1:n-s-1) = 0;
      ubvec(n-s:n) = 1;
    end
%
%  Found the rightmost "01" string.
%  Replace it by "10".
%  Shift following 1's to the right.
%
  else
    ubvec(z) = 1;
    ubvec(o) = 0;
    s = sum ( ubvec(o+1:n) );
    ubvec(o+1:n-s) = 0;
    ubvec(n+1-s:n) = 1;
  end

  return
end

