function x_new = r83_gs_sl ( n, a, b, x, it_max )

%*****************************************************************************80
%
%% r83_gs_sl() solves a R83 system using Gauss-Seidel iteration.
%
%  Discussion:
%
%    The R83 storage format is used for a tridiagonal matrix.
%    The superdiagonal is stored in entries (1,2:min(M+1,N)).
%    The diagonal in entries (2,1:min(M,N)).
%    The subdiagonal in (3,min(M-1,N)). 
%    R8GE A(I,J) = R83 A(I-J+2,J).  
%
%    This routine simply applies a given number of steps of the
%    iteration to an input approximate solution.  On first call, you can
%    simply pass in the zero vector as an approximate solution.  If
%    the returned value is not acceptable, you may call again, using
%    it as the starting point for additional iterations.
%
%  Example:
%
%    An R83 matrix of order 3x5 would be stored:
%
%       *  A12 A23 A34  *
%      A11 A22 A33  *   *
%      A21 A32  *   *   *
%
%    An R83 matrix of order 5x5 would be stored:
%
%       *  A12 A23 A34 A45
%      A11 A22 A33 A44 A55
%      A21 A32 A43 A54  *
%
%    An R83 matrix of order 5x3 would be stored:
%
%       *  A12 A23
%      A11 A22 A33
%      A21 A32 A43
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    10 September 2015
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer N, the order of the matrix.
%    N must be at least 2.
%
%    real A(3,N), the R83 matrix.
%
%    real B(N), the right hand side of the linear system.
%
%    real X(N), an approximate solution to the system.
%
%    integer IT_MAX, the maximum number of iterations.
%
%  Output:
%
%    real X_NEW(N), an approximate solution to the system.
%

%
%  No diagonal matrix entry can be zero.
%
  for i = 1 : n
    if ( a(2,i) == 0.0 )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'R83_GS_SL - Fatal error!\n' );
      fprintf ( 1, '  Zero diagonal entry, index = %d\n', i );
      error ( 'R83_GS_SL - Fatal error!' );
    end
  end

  for it_num = 1 : it_max

    x_new(1) = ( b(1) - a(1,2) * x(2)   ) / a(2,1);
    for i = 2 : n - 1
      x_new(i) = ( b(i) - a(3,i-1) * x_new(i-1) - a(1,i+1) * x(i+1) ) ...
        / a(2,i);
    end
    x_new(n) = ( b(n) - a(3,n-1) * x_new(n-1) ) / a(2,n);

    x(1:n) = x_new(1:n);

  end

  return
end
