 function [ p_new, more_new ] = perm_lex_next ( n, p, more )
%I got this code from the Internet; it wasn't written by me. Bob Tucci
% Generates permutations in lexical order, one at a time.
%
% Example:
%
%    N = 3
%
%    1   1 2 3
%    2   1 3 2
%    3   2 1 3
%    4   2 3 1
%    5   3 1 2
%    6   3 2 1
%
%  Reference:
%
%    Mok-Kong Shen,
%    Algorithm 202: Generation of Permutations in Lexicographical Order,
%    Communications of the ACM,
%    Volume 6, September 1963, page 517.
%
%  Parameters:
%
%    Input, integer N, the number of elements being permuted.
%    Input, integer P(N), the permutation, in standard index form.
%    Input, logical MORE.
%    Output, integer P(N), the next permutation.
%    Output, logical MORE.
%
%    On the first call, the user should set MORE = FALSE, 
%	which signals the routine to do initialization.
%    On return, if MORE is TRUE, then another permutation has been
%    computed and returned, while if MORE is FALSE, there are no more
%    permutations.
more_new = more;
if ( !more_new )
	%p_new = (1:n);
	p_new = linspace(1,n,n);
	more_new = 1;
else
	p_new(1:n) = p(1:n);
	if ( n <= 1 )
		p_new = [];
		more_new = 0;
		return;
	end
	w = n;
	while ( p_new(w) < p_new(w-1) )
		if ( w == 2 )
			more_new = 0;
			return;
		end
		w = w - 1;
	end
	u = p_new(w-1);
	for j=n:-1:w 
		if ( u < p_new(j) )
			p_new(w-1) = p_new(j);
			p_new(j) = u;
			ff=floor ( ( n - w - 1 ) / 2 );
			for  k= 0 : ff 
				[ p_new(n-k), p_new(w+k) ]=i_swap(
				p_new(n-k), p_new(w+k));
			end
			return;
		end
	end
end
