SUBROUTINE TestCart(SetCart)

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  !
  ! This subroutines looks at the displacements for atoms between
  ! images. If the total displacement is less than the atomic radius
  ! then it might be a good idea to treat this atom as CART.
  !
  ! Input:
  !        SetCart : if True then Cart list is set by TestCart
  !              (Normal use : call TestCart with AutoCart as the argument)  
  !
  ! Output:
  !        None
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  Use Path_module
  Use Io_module

  IMPLICIT NONE


  LOGICAL, INTENT(IN) :: SetCart

  INTEGER(KINT) :: IGeom, I,J,K,Iat
  CHARACTER(SCHARS) :: Line,Line2

  REAL(KREAL) :: d
  LOGICAL, ALLOCATABLE :: TobeCart(:) ! Nat
  LOGICAL :: Debug

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

  debug=valid('testcart')
  if (debug) WRITE(*,*) "========================= Entering TestCart ==========="

  ALLOCATE(TobeCart(Nat))

  ToBeCart=.TRUE.

  ! We put first geometry as the reference
  DO I=1,NGeomI
     DO J=I+1,NGeomI
        DO K=1,Nat
           IF (ToBeCart(K)) THEN
                Iat=Atome(K)
              d=100.*sqrt((XyzGeomI(J,1,K)-XyzGeomI(I,1,K))**2+ &
                   (XyzGeomI(J,2,K)-XyzGeomI(I,2,K))**2+ &
                   (XyzGeomI(J,3,K)-XyzGeomI(I,3,K))**2) 
              if (debug) WRITe(*,'(4(1X,I5),10(1X,F12.8))') k,i,j,iat,d,r_cov(iat),r_cov(iat)*fact,d/r_cov(iat)
              if ((d/r_cov(iat)).GE.0.5d0) ToBeCart(K)=.FALSE.
           END IF
        END DO
     END DO
  END DO

  If (Debug) THEN
     WRITE(*,*) "Atoms that might be described in CART"
     DO K=1,Nat
        IF (ToBeCart(K)) WRITE(*,'(I5)',ADVANCE="NO") K
     END DO
  END IF

  IF (SetCart) THEN
     WRITE(*,*) "AutoCART=T: Atoms that will be described in CART"
     K=1
     DO I=1,Nat
        If(ToBeCart(I)) THEN
           Cart(K)=I
           K=K+1
           WRITE(*,'(I5)',ADVANCE="NO") I
        END IF
     END DO
     Cart(K)=0
     Ncart=K-1
  END IF

  deallocate(tobecart)

if (debug) WRITE(*,*) "========================= Exiting TestCart ==========="
END SUBROUTINE TestCart


 


   
