subroutine CalcBmat_int(natoms, xyzatm, indzmat, dzdc)

  use Io_module
  use Path_module, only : MW,Pi, atome

  IMPLICIT NONE


  integer(KINT), INTENT(IN) :: natoms, indzmat(natoms,5)
  real(KREAL), INTENT(IN)   :: xyzatm(3,natoms)
  real(KREAL), INTENT(OUT)   :: dzdc(3*natoms,3*natoms)


!!!!!!!!!!!!!!!!!!!!!
!
! This routine computes the derivatives of the internal coordinates
! with respect to the cartesian coordinates.
! This is what is called the B matrix in Baker coordinates :
! B(i,j)=dz_i/dx_j
!
! it uses the same routines as Calc_baker
!
!!!!!!!!!!!!!!!!!!!!!!
!
! Input:
! natoms: number of atoms
! xyzatm(3,natoms): cartesian geometry
! indzmat(natoms,5): index of the Z-matrix definition
! atmass(natoms): mass of the atoms
! atome(natoms): ??
!
! Output:
! dzdc(3*natoms,3*natoms): B matrix
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


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

  LOGICAL :: debug
  INTEGER(KINT) :: i,j,k,iat
  INTEGER(KINT) :: iat1, iat2, iat3, iat4


  ! ======================================================================


  debug=valid('CalcBmat_int').OR.valid('CalcBMat')
  if (debug) Call Header('Entering CalcBmat_int')

  if (debug) THEN
     WRITE(*,*) 'DBG CALCBMAT_INT Xyzatm '
     DO iat=1,natoms
        write(*,'(1X,I5,3(1X,F15.6))') atome(iat), xyzatm(1:3,iat)
     END DO
     WRITE(*,*) 'DBG CALCBMAT_INT IndZmat'
     DO iat=1,natoms
        write(*,'(6(1X,I5))') iat, indzmat(iat,1:4)
     END DO
  END IF

  dzdc=0.d0
  if (natoms.ge.2) THEN
     iat1=indzmat(2,1)
     iat2=indzmat(2,2)
     Call CONSTRAINTS_BONDLENGTH_DER(Natoms,iat1,iAT2, xyzatm, dzdc(1,4))
   END IF
  if (natoms.ge.3) THEN
     iat1=indzmat(3,1)
     iat2=indzmat(3,2)
     iat3=indzmat(3,3)
     Call CONSTRAINTS_BONDLENGTH_DER(Natoms,iat1,iAT2, xyzatm, dzdc(1,7))
     CALL CONSTRAINTS_BONDANGLE_DER(Natoms,iAt1,iAT2,iAt3, xyzatm, dzdc(1,8))
  END IF
  k=10
  DO I=4, Natoms
     iat1=indzmat(i,1)
     iat2=indzmat(i,2)
     iat3=indzmat(i,3)
     iat4=indzmat(i,4)
     Call CONSTRAINTS_BONDLENGTH_DER(Natoms,iat1,iAT2, xyzatm, dzdc(1,k))
     k=k+1
     CALL CONSTRAINTS_BONDANGLE_DER(Natoms,iAt1,iAT2,iAt3, xyzatm, dzdc(1,k))
     k=k+1
     CALL CONSTRAINTS_TORSION_DER2(Natoms,iat1,iat2,iat3,iat4, xyzatm, dzdc(1,k)) 
     k=k+1
  END DO


  if (debug) THEN
     WRITE(*,*) 'DBG CALCBMAT_INT dzdc '
     k=min(3*natoms,12)
     DO iat=1,natoms
        DO j=1,3
           write(*,'(1X,I5,12(1X,F12.6))') 3*iat-3+j, dzdc(1:k,3*iat-3+j)
        END DO
     END DO
  END IF             

  if (debug) Call Header('CalcBmat_int Over')
  ! ======================================================================

end subroutine CalcBmat_int
