function x = vector_sumlex_next ( x )

%*****************************************************************************80
%
%% vector_sumlex_next() returns the next integer vector in sumlex order.
%
%  Discussion:
%
%    Consider integer vectors of length N, ordered by their sum.
%    Vectors of equal sum are ordered lexically.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    17 September 2022
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer X(N), the current vector.
%
%  Output:
%
%    integer X(N), the next vector.
%
  s = sum ( x );
  n = length ( x );
%
%  Case:  (0,0,0,...0,S) -> (S+1,0,0,...,0)
%
  if ( x(1) == s )
    x(1) = 0;
    x(n) = s + 1;
%
%  Case: 
%    Rightmost nonzero sends one unit left, and the rest to last position.
%
  else

    t = 0;
    for j = n : -1 : 2
      if ( x(j) ~= 0 )
        t = x(j);
        x(j) = 0;
        x(j-1) = x(j-1) + 1;
        x(n) = t - 1;
        break;
      end
    end

    if ( t == 0 )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'vector_sumlex_next(): Fatal error!\n' );
      fprintf ( 1, '  Could not find an entry to borrow from.\n' );
      error ( 'vector_sumlex_next(): Fatal error!' )
    end

  end

  return
end

