SUBROUTINE Int2Cart(Nat,IndZmat,IntCoord,XyzCoord)

  Use Path_module, ONLY : Pi

  IMPLICIT NONE
  
  INTEGER, PARAMETER :: Kint=Kind(1)
  INTEGER, PARAMETER :: KREAL=Kind(1.0D0)

  INTEGER(KINT), INTENT(IN) :: Nat
  INTEGER(KINT), INTENT(IN) :: IndZmat(Nat,5)
  REAL(KREAL), INTENT(IN) :: IntCoord(3*Nat-6)
  REAL(KREAL), INTENT(OUT) :: XyzCoord(Nat,3)

  INTEGER(KINT) :: I,J,K,L,Idx
  REAl(KREAL), ALLOCATABLE :: ValZmat(:,:),XyzTmp(:,:)
  REAL(KREAL) :: d, a_val
  LOGICAL :: debug

  INTERFACE
     function valid(string) result (isValid)
       CHARACTER(*), intent(in) :: string
       logical                  :: isValid
     END function VALID

  END INTERFACE

  debug=valid('int2cart')

   if (debug) WRITE(*,*) '================ Entering Int2Cart ==================='

  ALLOCATE(ValZmat(Nat,3),XyzTmp(Nat,3))

  ValZmat=0.d0
  ValZmat(2,1)=IntCoord(1)
  ValZmat(3,1)=IntCoord(2)
  ValZmat(3,2)=IntCoord(3)*180./Pi
  DO I=4,Nat
     ValZmat(I,1)=IntCoord(3*I-8)
     ValZmat(I,2)=IntCoord(3*I-7)*180./Pi
     ValZmat(I,3)=IntCoord(3*I-6)*180./Pi
  END DO

  IF (debug) THEN
     WRITE(*,*) 'DBG Int2Cart'
     DO I=1,Nat
        WRITe(*,'(1X,I3,3(1X,I3,1X,F10.4))') IndZmat(I,1), IndZmat(I,2), ValZmat(I,1), IndZmat(I,3),&
             ValZmat(I,2), IndZmat(I,4), Valzmat(I,3)
     END DO
  END IF

  Xyztmp=0.d0
  Xyztmp(2,1)=valzmat(2,1)
  d=valzmat(3,1)
  a_val=valzmat(3,2)/180.*Pi
!              write(*,*) "aval,pi",a_val,valzmat(3,2),pi
  if (Nat.GE.3) THEN
     if (IndZmat(3,2).EQ.1)  THEN
        Xyztmp(3,1)=Xyztmp(1,1)+d*cos(a_val)
     ELSE
        Xyztmp(3,1)=Xyztmp(2,1)-d*cos(a_val)
     ENDIF
     Xyztmp(3,2)=d*sin(a_val)
  ENDIF
  !              i=1
  !                WRITE(*,*) 'TOTOCart:',i, (Xyztmp(I,J),J=1,3)
  !                WRITE(*,*) 'TOTOZma:',i, (valzmat(I,J),J=1,3)
  !              i=2
  !                WRITE(*,*) 'TOTOCart:',i, (Xyztmp(I,J),J=1,3)
  !                WRITE(*,*) 'TOTOZma:',i, (valzmat(I,J),J=1,3)
  !              i=3
  !                WRITE(*,*) 'TOTOCart:',i, (Xyztmp(I,J),J=1,3)
  !                WRITE(*,*) 'TOTOZma:',i, (valzmat(I,J),J=1,3)

  DO i=4,Nat
     call ConvertZmat_cart(i,IndZmat,valzmat,                &
          Xyztmp(1,1), Xyztmp(1,2),Xyztmp(1,3))
     !                  WRITE(*,*) 'TOTOZma:',i,IndZmat(I,1),            &
     !                        (IndZmat(I,J+1),valzmat(I,J),J=1,3)
     !                   WRITE(*,*) 'TOTOCart:',i, (Xyztmp(I,J),J=1,3)
  END DO

  IF (debug) THEN
     WRITE(*,*) 'DBG Int2Cart XyzTmp'
     DO I=1,Nat
        WRITe(*,'(1X,I3,3(1X,F10.4))') I, XyzTmp(I,1:3)
     END DO
  END IF


!  XyzCoord=Reshape(XyzTmp,(/3,Nat/),ORDER=(/2,1/))
  XyzCoord=XyzTmp

  DEALLOCATE(valzmat,xyztmp)
  if (debug) WRITE(*,*) '================ Exiting Int2cart ==================='

END SUBROUTINE Int2Cart
