subroutine TranspMat(n,nterm,iat,ja,mat,m,nterm_out,iat_T,ja_T,mat_T,IW)
!-----------------------------------------------------------------------------------------
!
!  Subroutine: TranspMat
!
!  Coded by Carlo Janna
!  September 2011
!
!  Purpose: Transpose a (n x m) matrix.
!
!-----------------------------------------------------------------------------------------

use class_precision

implicit none

! Input variables
integer, intent(in)        :: n,m
integer, intent(in)        :: nterm
integer, intent(in)        :: iat(:)
integer, intent(in)        :: ja(:)
real(double), intent(in)   :: mat(:)

! Output variables
integer, intent(out)       :: nterm_out
integer, intent(out)       :: iat_T(:)
integer, intent(out)       :: ja_T(:)
real(double), intent(out)  :: mat_T(:)

! Work array (given as input, should have size at least m)
integer, intent(out)       :: IW(:)

! Local variables
integer                    :: i
integer                    :: j,ind

! Initialize pointers
do i = 1,m+1
   iat_T(i) = 0
enddo

! Count non-zeroes for each column of the input matrix
do i = 1,n
   do j = iat(i),iat(i+1)-1
      iat_T(ja(j)) = iat_T(ja(j)) + 1
   enddo
enddo

! Reset pointers
IW(1) = 1
do i = 2,m+1
   IW(i) = IW(i-1) + iat_T(i-1)
enddo
iat_T(1:m+1) = IW(1:m+1)

! Transpose coeffiecients
do i = 1,n
   do j = iat(i),iat(i+1)-1
      ind = IW(ja(j))
      ja_T(ind) = i
      mat_T(ind) = mat(j)
      IW(ja(j)) = ind+1
   enddo
enddo

nterm_out = nterm

end subroutine TranspMat
