function t = ubvec_next_gray ( n, t )

%*****************************************************************************80
%
%% UBVEC_NEXT_GRAY computes the next UBVEC in the Gray code.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    19 November 2015
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Donald Kreher, Douglas Simpson,
%    Combinatorial Algorithms,
%    CRC Press, 1998,
%    ISBN: 0-8493-3988-X,
%    LC: QA164.K73.
%
%  Parameters:
%
%    Input, integer N, the number of digits in each element.
%    N must be positive.
%
%    Input/output, integer T(N).
%    On input, T contains an element of the Gray code, that is,
%    each entry T(I) is either 0 or 1.
%    On output, T contains the successor to the input value; this
%    is an element of the Gray code, which differs from the input
%    value in a single position.
%
  weight = sum ( t(1:n) );

  if ( mod ( weight, 2 ) == 0 )

    if ( t(n) == 0 )
      t(n) = 1;
    else
      t(n) = 0;
    end

    return

  else

    for i = n : -1 : 2
      if ( t(i) == 1 )
        if ( t(i-1) == 0 )
          t(i-1) = 1;
        else
          t(i-1) = 0;
        end
        return
      end
    end
%
%  The final element was input.
%  Return the first element.
%
    t(1:n) = 0;

  end

  return
end
