 SUBROUTINE AnalyzeGeom(GeomCart,Values)
! This routines read a list of geometrical variables to monitor
! This is inspired from Xyz2Path (that was inspired by Xyz2scan ...)


  use VarTypes
  use Path_module
  use Io_module

  IMPLICIT NONE


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

     SUBROUTINE die(routine, msg, file, line, unit)

       Use VarTypes
       Use io_module

       implicit none

       character(len=*), intent(in)           :: routine, msg
       character(len=*), intent(in), optional :: file
       integer(KINT), intent(in), optional      :: line, unit

     END SUBROUTINE die


     SUBROUTINE Calc_Xprim(nat,x,y,z,Coordinate,NPrim,XPrimitive,XPrimRef)

       Use VarTypes
       Use Io_module
       Use Path_module, only : pi

       IMPLICIT NONE

       Type (ListCoord), POINTER :: Coordinate
       INTEGER(KINT), INTENT(IN) :: Nat,NPrim
       REAL(KREAL), INTENT(IN) :: x(Nat), y(Nat), z(Nat)
       REAL(KREAL), INTENT(IN), OPTIONAL :: XPrimRef(NPrim) 
       REAL(KREAL), INTENT(OUT) :: XPrimitive(NPrim)

     END SUBROUTINE CALC_XPRIM

  END INTERFACE

! Input
  REAL(KREAL),INTENT(IN) :: GeomCart(Nat,3)
  REAL(KREAL), INTENT(OUT) :: Values(NbVar)

  LOGICAL :: Debug
  INTEGER(KINT) :: I,J,K,NatT
  REAL(KREAL), ALLOCATABLE :: GeoCartLoc(:,:) ! (Nat+NbCom,3)
  REAL(KREAL), ALLOCATABLE :: x(:),y(:),z(:) ! Nat+NbCom
  REAL(KREAL) :: COG(3),Weight



  Debug=Valid('AnaGeom')

  If (Debug) Call Header("Entering AnalyzeGeom")

  if (debug) THEN
     WRITE(*,*) "AnalyzeGeom  - GeomCart"
     DO K=1,Nat
        WRITE(*,'(1X,I5,3(1X,F15.8))') K,GeomCart(K,1:3)
     END DO
  END IF

  NAtt=Nat+NbCom
  ALLOCATE(GeoCartLoc(Natt,3),x(Natt),y(Natt),z(Natt))
  GeoCartLoc(1:Nat,:)=GeomCart(:,:)
  CurBary => Bary

  DO I=1, NbCom
     COG=0.
     Weight=0.
     DO j=1,CurBary%ListAtoms(0)
        DO k=1,3
           COG(k)=COG(k)+GeomCart(CurBary%ListAtoms(j),k)*CurBary%Weights(j)
        END DO
        Weight=Weight+CurBary%Weights(j)
     END DO
     COG=COG/Weight
     DO k=1,3
        GeoCartLoc(Nat+i,k)=COG(k)
     END DO
  END DO
     
  Values=0.

  if (debug) THEN
     WRITE(*,*) "AnalyzeGeom before Calc_Xprim - GeomCartLoc"
     DO K=1,Nat+NbCom
        WRITE(*,*) K,GeoCartLoc(K,1:3)
     END DO
  END IF

  x = GeoCartLoc(:,1)
  y = GeoCartLoc(:,2)
  z = GeoCartLoc(:,3)

   Call Calc_XPrim(Natt,x,y,z,GeomList,NbVar,Values)

   DeALLOCATE(GeoCartLoc,x,y,z)

   if (debug) THEN
      WRITE(*,*) 'AnalyzeGeom: NbVar,Values',NbVar,Values
   END IF

  If (Debug) Call Header("Exiting AnalizeGeom")

END SUBROUTINE AnalyzeGeom
