function [ row, col, a ] = r8st_diagonal ( m, n, nz_num, row, col, a )

%*****************************************************************************80
%
%% r8st_diagonal() reorders an r8st matrix so diagonal entries are first.
%
%  Discussion:
%
%    The r8st storage format corresponds to the SLAP Triad format.
%
%    The r8st storage format stores the row, column and value of each nonzero
%    entry of a sparse matrix.  The entries may be given in any order.  No
%    check is made for the erroneous case in which a given matrix entry is
%    specified more than once.
%
%    This routine reorders the entries of A so that the first N entries
%    are exactly the diagonal entries of the matrix, in order.
%
%  Licensing:
%
%    This code is distributed under the MIT license. 
%
%  Modified:
%
%    22 September 2015
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer M, N, the order of the matrix.
%
%    integer NZ_NUM, the number of nonzero elements in 
%    the matrix.
%
%    integer ROW(NZ_NUM), COL(NZ_NUM), the row and 
%    column indices of the nonzero elements.
%
%    real A(NZ_NUM), the nonzero elements of the matrix.
%
%  Output:
%
%    integer ROW(NZ_NUM), COL(NZ_NUM), the row and 
%    column indices of the nonzero elements.
%
%    real A(NZ_NUM), the nonzero elements of the matrix.
%
  found = 0;

  for k = 1 : nz_num

    while ( row(k) == col(k) )

      if ( row(k) == k )
        found = found + 1;
        break
      end

      i = row(k);

      j = row(i);
      row(i) = row(k);
      row(k) = j;

      j = col(i);
      col(i) = col(k);
      col(k) = j;

      t    = a(i);
      a(i) = a(k);
      a(k) = t;
 
      found = found + 1;

      if ( min ( m, n ) <= found )
        break
      end
     
    end

    if ( min ( m, n ) <= found )
      break
    end

  end

  if ( found < min ( m, n ) )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'r8st_DIAGONAL - Warning!\n' );
    fprintf ( 1, '  Number of diagonal entries expected was %d\n', min ( m, n ) );
    fprintf ( 1, '  Number found was %d\n', found );
  end

  return
end
