function [ t, rank ] = pivot_sequence_successor ( n, t, rank )

%*****************************************************************************80
%
%% pivot_sequence_successor() computes the pivot sequence successor.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    24 June 2024
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer n: the number of steps in the pivot sequence.
%
%    integer t(n): the previous pivot sequence.
%    To initiate the routine, call with t=ones(1,n).
%
%  Output:
%
%    integer t(n): the lexical successor of the input.
%
%
%  Check.
%
  check = pivot_sequence_check ( n, t );

  if ( ~ check )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'pivot_sequence_successor(): Fatal error!\n' );
    fprintf ( 1, '  The input array is illegal.\n' );
    error ( 'pivot_sequence_successor(): Fatal error!' );
  end

  last = 0;
  for i = n : -1 : 1
    if ( 1 < t(i) )
      last = i;
      break;
    end
  end

  if ( last == 0 )
    t = linspace ( n, 1, n );
  else
    t(last) = t(last) - 1;
    for i = last + 1 : n
      t(i) = n + 1 - i;
    end
  end

  return
end
