          program Xyz2Path
! This programs reads a XYZ file and converts it into distances,
! valence angle and dihedral angles.
! It prints them as a function of the irc distance...
!-----------------------------------------------
! Input: name of the XYZ File
! it also needs a file call list which has the following structure:
! one line contains the type of the value you want to follow, it can be
! b  for a Bond distance
! a for an angle
! d for a dihedral
! this descriptor is followed by the number of the atoms involved !
! a typical file can be:
! b  1  2
! b 2  3
! a 1 2 3
!----------------------------------------------
! Ouput: A files call Scan.dat
! wich contains in the first lines the input file (as a reminder)
! and then for each step the wanted values
!------------------------------------------------
! Second version also reads the energy (as to be written after E= on
! the comment line)
!------------------------------------------------
! Third version contains a new command: c for Center of Mass
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! v 3.1 the c command now creates the center of mass... and allows
! people to do whatever they want with it...
! Syntax: c NbAt ListAt


          IMPLICIT NONE

          INCLUDE "Xyz2Path.param"

          character*40 f1
          REAL*8   geos(3,maxnat), geos1(3,maxnat)
          character*33 fmt
          character*3 atoms(maxnat)
          character*5 Type
          Character*120 line
          INTEGER*4 NbPrint
          REAL*8   AU2PS,Pi
          REAL*8  Mass(MaxNat), Ener, Conv, Ds, s
          REAL*8  MassAt(0:86)
          INTEGER*4 At1,At2,At3,At4,IOOUT,Iat
          INTEGER*4  IArg, I, NNN, Ng, J

          INTEGER*4 Nat,NbDist, NbAngle, NbDie,NbCOM
          INTEGER*4 At1B(MaxNat),At2B(MaxNat)
          INTEGER*4 At1A(MaxNat),At2A(MaxNat),At3A(MaxNat)
          INTEGER*4 At1D(MaxNat),At2D(MaxNat),At3D(MaxNat),At4D(MaxNat)
          INTEGER*4 AtCom(0:MaxNat,MaxNat)
          REAL*8    VB(MaxNat),VA(MaxNat),VD(MaxNat),VCOM(MaxNat)

          REAL*8 MRot(3,3), Rmsd
          LOGICAL FExist,FRot,FAlign,Debug

          INTEGER*4 ConvertNumAt
          external ConvertNumAt

          COMMON /Indices/Nat,NbDist,NbAngle,NbDie,NbCom, At1B,At2B,
     &         At1A,At2A,At3A,At1D,At2D,At3D,At4D,AtCom
          COMMON /Values/VB,VA,VD,VCom
          COMMON /Const/AU2ps,Pi
 
          DATA MassAt/0.0D0,                                             
     $           1.0078D0,                      4.0026D0,                
     $            7.0160D0, 9.0122D0,11.0093D0,                          
     $           12.0000D0,14.0031D0,15.9949D0,18.9984D0,19.9924D0,      
     $           22.9898D0,23.9850D0,26.9815D0,                          
     $           27.9769D0,30.9738D0,31.9721D0,34.9688D0,39.9624D0,      
     $           39.0983D0,40.08D0,                                      
     $             44.9559D0, 47.88D0, 50.9415D0, 51.996D0, 54.9380D0,   
     $             55.847D0, 58.9332D0, 58.69D0, 63.546D0, 65.39D0,      
     $           69.72D0,72.59D0,74.9216D0,78.96D0,79.904D0,83.80D0,     
     $           85.4678D0,87.62D0,88.9059D0,91.224D0,92.9064D0,         
     $   95.94D0,98D0,101.07D0,102.906D0,106.42D0,107.868D0,112.41D0,    
     $   114.82D0,118.71D0,121.75D0,127.60D0,126.905D0,131.29D0,          
!     6           'CS','BA',
     $           132.905,137.34,                                          
!     6       'LA',
!               'CE','PR','ND','PM','SM','EU','GD',
!               'TB','DY','HO', 'ER','TM','YB','LU',
     $      138.91,                                                       
     $       140.12, 130.91, 144.24,147.,150.35, 151.96,157.25,           
     $       158.924, 162.50, 164.93, 167.26,168.93,173.04,174.97,        
!     6                'HF','TA',' W','RE','OS','IR','PT',
!                      'AU','HG',
!     6                                 'TL','PB','BI','PO','AT','RN'/
     $       178.49, 180.95, 183.85, 186.2, 190.2, 192.2, 195.09,         
     $       196.97, 200.59,                                              
     $       204.37, 207.19,208.98,210.,210.,222. /


          AU2PS=1./41341.37
          NbPrint=100
          Pi=dacos(-1.d0)
          IOOUT=13
          Conv=1.
          FRot=.TRUE.
          FAlign=.TRUE.
          Debug=.FALSE.
          NbDist=0
          NbAngle=0
          NbDie=0

          iarg=command_argument_count()
          if (iarg.lt.1) then
                 write(*,*) 'XYZ filename:'
              read(*,'(a)') f1
            else
              call getarg(1,f1)
          endif

          open(13,file='Scan.dat')

          INQUIRE(File='list',Exist=FExist)
          if (.NOT.FExist) THEN
             WRITE(*,*) "No file 'list', just printing Energy"
          END IF

          open(11,file=f1)
          call rtraitem(11,nnn,ener,geos1,atoms)
          close(11)

         DO I=1,nnn
            Iat=ConvertNumAt(atoms(I))
            Mass(I)=MassAt(Iat)
!           write(*,*) I,Atoms(I),Mass(I),geos1(:,I)
         END DO

         Nat=nnn

         if (FExist) THEN
         open(14,file='list')
         Type="d"
         DO WHILE (Type.ne."E")
          CALL READLINE(14,Type,Line)
!          WRITE(*,*) Line,Type
          if (Type.eq."b") THEN
             NbDist=NbDist+1
             READ(Line,*) At1,At2
             At1B(NbDist)=At1
             At2B(NbDist)=At2
             WRITE(13,'("# b ",2(A3,I3))') Atoms(At1),At1,Atoms(At2),At2
             WRITE(*,'("# b ",2(A3,I3))') Atoms(At1),At1,Atoms(At2),At2
          END IF
          if (Type.eq."a") THEN
             NbAngle=NbAngle+1
             READ(Line,*) At1,At2,At3
             At1A(NbAngle)=At1
             At2A(NbAngle)=At2
             At3A(NbAngle)=At3
            WRITE(13,'("# a ",3(A3,I3))') Atoms(At1),At1,Atoms(At2),
     &            At2, Atoms(At3),At3
            WRITE(*,'("# a ",3(A3,I3))') Atoms(At1),At1,Atoms(At2),
     &           At2, Atoms(At3),At3
          END IF
          if (Type.eq."d") THEN
             NbDie=NbDie+1
             READ(Line,*) At1,At2,At3,At4
             At1D(NbDie)=At1
             At2D(NbDie)=At2
             At3D(NbDie)=At3
             At4D(NbDie)=At4
            WRITE(13,'("# d ",4(A3,I3))') Atoms(At1),At1,Atoms(At2),At2,  
     &          Atoms(At3),At3,Atoms(At4),At4
            WRITE(*,'("# d ",4(A3,I3))') Atoms(At1),At1,Atoms(At2),At2,   
     &          Atoms(At3),At3,Atoms(At4),At4

          END IF
          if (Type.eq."c") THEN
            NbCOM=NbCOM+1
            READ(Line,*) At1,(AtCom(j,NbCOM),j=1,At1)
            AtCom(0,NbCOM)=At1
            Atoms(nat+NbCom)="G"
            WRITE(13,'("# c ",I4,20(A3,I3))') At1,                  
     &          (Atoms(AtCom(i,NbCoM)),AtCom(i,NbCOM),i=1,At1)
            WRITE(*,'("# c ",I4,20(A3,I3))') At1,                   
     &          (Atoms(AtCom(i,NbCoM)),AtCom(i,NbCOM),i=1,At1)
          END IF

         END DO
         END IF



          fmt='(   (1X,F12.5),1X,F15.6)'
          write(fmt(2:4),'(i3)') NbDist+NbAngle+NbDie+1
!           write(*,*) nat3
!          write(*,*) 'fmt:',fmt

          ng=1

         s=0.

          open(11,file=f1)

10           call rtraitem(11,nnn,ener,geos,atoms)
!           WRITE(*,*) nnn
           if (nnn.gt.0) then

          call CalcRmsd(nnn, geos1, geos,MRot,rmsd,FRot,FAlign,debug)
         ds=0.
           DO I=1,nnn
             DO J=1,3
             ds=ds+mass(I)*(geos(J,I)-geos1(J,I))**2
!            write(*,*) I,J,geos(J,I),Geos1(J,I),ds
             geos1(J,I)=Geos(J,I)
              END DO
            END DO
           s=s+sqrt(ds)

! We convert coordinates in a0 into Angstroem
!              write(*,*) "Analyse !"
            if (FExist) THEN
            Call Analyse(geos)

             write(IOOUT,fmt) s,(VB(j)/Conv,j=1,NbDist),
     &            (VA(j),j=1,NbAngle),
     &            (VD(j),j=1,NbDie),ener
             write(*,fmt) s,(VB(j)/Conv,j=1,NbDist),
     &            (VA(j),j=1,NbAngle),
     &            (VD(j),j=1,NbDie),ener
             ELSE
                        write(IOOUT,fmt) s,ener
             write(*,fmt) s,ener
            END IF 
           ng=ng+1
            goto 10
           endif
           WRITE(*,*) 'Found ',ng-1,' geometries'
           close(11)
         end

!--------------------------------------------------------------
          subroutine rtraitem(ifil,nnn,E,tab,atoms)
!           implicit real*8 (a-h,o-z)
            IMPLICIT NONE
           character*120 line
           character*3 Atoms(*)
           integer*4 nnn, IFil, Idx, I, J
           REAL*8  Tab(3,*), E


           read(ifil,*,err=99,end=99) nnn
           read(ifil,'(A)') line
           idx=index(line,'E')
!           WRITE(*,*) 'idx,line',idx,line
           if (idx/=0) THEN
             line=line(idx+2:)
              idx=index(line,"=")
              if (idx/=0) line=line(idx+1:)
              idx=index(line,":")
              if (idx/=0) line=line(idx+1:)
              read(line,*) E
           ELSE
             E=0.
           END IF
           
!           write(*,*) 'coucou',line
           do i=1,nnn
              read(ifil,'(A)',err=99,end=99) Line
              do while (line(1:1)==' ')
                 line=line(2:)
              end do
              atoms(i)=line(1:3)
!            write(*,*) 'coucou atoms',atoms(i)
              do while (line(1:1).ne.' ')
                 line=line(2:)
              end do
!              WRITE(*,*) 'coucou2:',i,line
              read(line,*) (tab(j,i),j=1,3)
           end do
!           WRITE(*,*) 'coucou:',nnn,tab(1,1)
           return
99           nnn=0
!             WRITE(*,*) 'Erreur lecture',ifil,nnn
             return
          end

!--------------------------------------------------------------

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! READLINE
! This subroutine reads a line for a file, and converts
! the first field into a character variable, and the rest into 4 integers
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

      SUBROUTINE READLINE(IOIN,Type,Line)
        
       IMPLICIT NONE
      CHARACTER Type*5,LINE*120
      INTEGER i,IOIN
      READ(IOIN,'(A120)',ERR=999,END=999) LINE
!      WRITE(*,*) Line
      DO WHILE (LINE(1:1).eq.' ')
         LINE=LINE(2:)
      END DO

      i=1
      DO WHILE (LINE(i:i).ne.' ')
         i=i+1
      END DO
      
      if (i.ge.6) THEN
         WRITE(*,*) 'Pb with READLINE:',LINE
         GOTO 999
      END IF
      Type=LINE(1:i-1)
      LINE=LINE(i:120) // " 0 0 0 0"

      RETURN
 999  Type="E"
      END



      SUBROUTINE Analyse(geos)

      IMPLICIT NONE
          INCLUDE "Xyz2Path.param"

      REAL*8 geos(3,maxnat)
      REAL*8 AU2PS,Pi
      INTEGER*4 i,j,k
      REAL*8 V1x,V1y,V1z,V2x,V2y,V2z,V3x,V3y,V3z
      REAL*8 d1,d2,ca,sa
      REAL*8 V4x,v4y,v4z,v5x,v5y,v5z
      REAL*8 COG(3)

      INTEGER*4 Nat,NbDist, NbAngle, NbDie,NbCOM
      INTEGER*4 At1B(MaxNat),At2B(MaxNat)
      INTEGER*4 At1A(MaxNat),At2A(MaxNat),At3A(MaxNat)
      INTEGER*4 At1D(MaxNat),At2D(MaxNat),At3D(MaxNat),At4D(MaxNat)
      INTEGER*4 AtCom(0:MaxNat,MaxNat)
      REAL*8    VB(MaxNat),VA(MaxNat),VD(MaxNat),VCOM(MaxNat)

      COMMON /Indices/Nat,NbDist,NbAngle,NbDie,NbCom,   
     &      At1B,At2B,At1A,At2A,At3A,At1D,At2D,At3D,At4D,AtCom
      COMMON /Values/VB,VA,VD,VCom
      COMMON /Const/AU2ps,Pi

          DO I=1,Nat
             WRITE(*,'(1X,I3,3(1X,F15.6))') i,(geos(j,i),j=1,3)
          END DO

! First, we create the Centre of Mass atoms
            DO i=1,NbCOM
              COG(1)=0.
              COG(2)=0.
              COG(3)=0.
              DO j=1,AtCOm(0,i)
                 DO k=1,3
                    COG(k)=COG(k)+geos(k,AtCom(j,i))
                 END DO
              END DO
              DO k=1,3
                 COG(k)=COG(k)/AtCOM(0,i)
                 geos(k,Nat+i)=COG(k)
              END DO
            END DO


            DO i=1,NbDist
               VB(i)=sqrt((geos(1,At1B(i))-geos(1,At2B(i)))**2+  
     &      (geos(2,At1B(i))-geos(2,At2B(i)))**2+                     
     &      (geos(3,At1B(i))-geos(3,At2B(i)))**2)
            END DO
            DO i=1,NbAngle
               v1x=geos(1,At1A(i))-geos(1,At2A(i))
               v1y=geos(2,At1A(i))-geos(2,At2A(i))
               v1z=geos(3,At1A(i))-geos(3,At2A(i))
               d1=sqrt(v1x**2+v1y**2+v1z**2)
               v2x=geos(1,At3A(i))-geos(1,At2A(i))
               v2y=geos(2,At3A(i))-geos(2,At2A(i))
               v2z=geos(3,At3A(i))-geos(3,At2A(i))
               d2=sqrt(v2x**2+v2y**2+v2z**2)
               VA(i)=acos((v1x*v2x+v1y*v2y+v1z*v2z)/(d1*d2))*180./Pi
            END DO
            DO i=1,NbDie
!               WRITE(*,*) At1D(i),At2D(i),At3D(i),At4D(i)
!              WRITE(*,*) geos(1,At1D(i)),geos(2,At1D(i)),geos(3,At1D(i))
!              WRITE(*,*) geos(1,At2D(i)),geos(2,At2D(i)),geos(3,At2D(i))
               v1x=geos(1,At1D(i))-geos(1,At2D(i))
               v1y=geos(2,At1D(i))-geos(2,At2D(i))
               v1z=geos(3,At1D(i))-geos(3,At2D(i))
               v2x=geos(1,At3D(i))-geos(1,At2D(i))
               v2y=geos(2,At3D(i))-geos(2,At2D(i))
               v2z=geos(3,At3D(i))-geos(3,At2D(i))
               v3x=geos(1,At4D(i))-geos(1,At3D(i))
               v3y=geos(2,At4D(i))-geos(2,At3D(i))
               v3z=geos(3,At4D(i))-geos(3,At3D(i))
          
               v4x=v1y*v2z-v1z*v2y
               v4y=v1z*v2x-v1x*v2z
               v4z=v1x*v2y-v1y*v2x
               d1=sqrt(v4x**2+v4y**2+v4z**2)
               v5x=-v2y*v3z+v2z*v3y
               v5y=-v2z*v3x+v2x*v3z
               v5z=-v2x*v3y+v2y*v3x
               d2=sqrt(v5x**2+v5y**2+v5z**2)
               ca=(v4x*v5x+v4y*v5y+v4z*v5z)/(d1*d2)
               sa=v1x*v5x+v1y*v5y+v1z*v5z
               VD(i)=acos(ca)*180./Pi
               if (sa<0.) VD(i)=-VD(i)
!               WRITE(*,*) "Dihe",v5x,v5y,v5z,v4x,v4y,v4z,d1,d2,
!     &(v4x*v5x+v4y*v5y+v4z*v5z)/(d1*d2),pi
!!!!!!!!! Another solution, more elegant ?
!               norm2=sqrt(v2x**2+v2y**2+v2z**2)
!               sa=(v4x*(v5y*v2z-v5z*v2y) 
!     *            -v4y*(v5x*v2z-v5z*v2x) 
!     *            +v4z*(v5x*v2y-v5y*v2x))
!     *       /(d1*norm2*d2)
!               angle_d=datan2(sa,ca)*180./Pi
!               WRITE(*,*) sa,ca,angle_d,d1,d2,norm2
!               WRITE(*,*) VD(i),angle_d
            END DO

        END

C================================================================
C    Convertit un nom d'atome (2 lettres) en nombre de masse (entier)
C cette fonction a ete modifiee pour pouvoir convertir un nom
C d'atome avec un numero a la fin...
C================================================================

        FUNCTION ConvertNumAt(ATOM)


        IMPLICIT NONE 

        INTEGER*4 I,Long,ConvertNumAt,IC
        character*2 ATOM*2,ATOME*3,L_Atom*2
        INTEGER*4  Max_Z
        PARAMETER (Max_Z=86)
        CHARACTER*2  Nom(0:Max_Z)

       DATA NOM/ ' X',' H',                                    'HE',
     $          'LI','BE',            ' B',' C',' N',' O',' F','NE',
     $          'NA','MG',            'AL','SI',' P',' S','CL','AR',
     $          ' K','CA',
     $      'SC','TI',' V','CR','MN','FE','CO','NI','CU','ZN',
     $                                'GA','GE','AS','SE','BR','KR',
     $          'RB','SR',
     $      ' Y','ZR','NB','MO','TC','RU','RH','PD','AG','CD',
     $                                'IN','SN','SB','TE',' I','XE',
     $          'CS','BA',
     $      'LA',
     $        'CE','PR','ND','PM','SM','EU','GD','TB','DY','HO',
     $        'ER','TM','YB','LU',
     $               'HF','TA',' W','RE','OS','IR','PT','AU','HG',
     $                                'TL','PB','BI','PO','AT','RN'/


C Verifie qu'il n'y a que des lettres et des espaces dans ATOM
!        WRITE(*,*) 'DBG CNVNUMAT, ATOM:',ATOM

        L_atom=Atom
        IF (ATOM(1:1).LT.'A') L_ATOM(1:1)=' '
        IC=Ichar(ATOM(1:1))
        IF ((ic.le.123).AND.(ic.ge.97)) L_ATOM(1:1)=CHAr(IC-32)
        IF (ATOM(2:2).LT.'A') L_ATOM(2:2)=' '
        IC=Ichar(ATOM(2:2))
        IF ((ic.le.123).AND.(ic.ge.97)) L_ATOM(2:2)=CHAr(IC-32)
C Justifie le nom sur la droite (et non sur la gauche comme souvent...)
         Long=INDEX(L_ATOM,' ')-1
         ATOME=' ' // L_ATOM
        IF (Long.EQ.1) L_ATOM=ATOME(1:2)
!        WRITE(*,*) 'DBG CNVNUMAT, L_ATOM:',L_ATOM
        I=max_Z
        DO WHILE ((nom(I).NE.L_ATOM) .AND. (I.GT.0))
         I=I-1
        END DO
        ConvertNumAT=I
        END
! This subroutine calculates RMSD using quaternions.
! It is based on the F90 routine bu E. Coutsias
! http://www.math.unm.edu/~vageli/homepage.html
! I (PFL) have just translated it, and I have changed the diagonalization
! subroutine.
! I also made some changes to make it suitable for Cart package.
!----------------------------------------------------------------------
!----------------------------------------------------------------------
! Copyright (C) 2004, 2005 Chaok Seok, Evangelos Coutsias and Ken Dill
!      UCSF, Univeristy of New Mexico, Seoul National University
! Witten by Chaok Seok and Evangelos Coutsias 2004.
                                                                                
! This library is free software; you can redistribute it and/or
! modify it under the terms of the GNU Lesser General Public
! License as published by the Free Software Foundation; either
! version 2.1 of the License, or (at your option) any later version.
!
                                                                                
! This library is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
! Lesser General Public License for more details.
!
                                                                                
! You should have received a copy of the GNU Lesser General Public
! License along with this library; if not, write to the Free Software
! Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
!----------------------------------------------------------------------------

      subroutine CalcRmsd(na, geom,geom2,U,rmsd,FRot,FAlign,debug)
!-----------------------------------------------------------------------
!  This subroutine calculates the least square rmsd of two coordinate
!  sets coord1(3,n) and coord2(3,n) using a method based on quaternion.
!  It then calculate the  rotation matrix U and the centers of coord, and uses
! them to align the two molecules.
!-----------------------------------------------------------------------


      IMPLICIT NONE

      INCLUDE "Xyz2Path.param"

      INTEGER*4 IOIN, IOOUT, IOSCRN, IOPRNT, IOTAMP
      COMMON/IODEFS/IOIN,IOOUT,IOSCRN,IOPRNT,IOTAMP

      integer*4 na
      real*8  geom(3,MaxNAt), Geom2(3,MaxNAt)
      real*8  U(3,3), rmsd
      LOGICAL  FRot,FAlign,Debug

      REAL*8 Coord1(3,MaxNAt), Coord2(3,MaxNAt)
      real*8  xc1,yc1,zc1, xc2,yc2,zc2
      

      integer*4 i, j,  ia
      real*8 x_norm, y_norm, lambda
      real*8 Rmatrix(3,3)
      real*8 S(4,4)
      real*8 EigVec(4,4), EigVal(4)



  ! calculate the barycenters, centroidal coordinates, and the norms
      x_norm = 0.0d0
      y_norm = 0.0d0
      xc1=0.
      yc1=0.
      zc1=0.
      xc2=0.
      yc2=0.
      zc2=0.
      do ia=1,na
         xc1=xc1+geom(1,ia)
         xc2=xc2+geom2(1,ia)
         yc1=yc1+geom(2,ia)
         yc2=yc2+geom2(2,ia)
         zc1=zc1+geom(3,ia)
         zc2=zc2+geom2(3,ia)
!         if (debug) WRITE(*,'(A,I5,4(1X,F10.4))') 'ia...',ia,x(ia),
!     &                        x2(ia),xc1,xc2
      END DO
      xc1=xc1/dble(na)
      yc1=yc1/dble(na)
      zc1=zc1/dble(na)
      xc2=xc2/dble(na)
      yc2=yc2/dble(na)
      zc2=zc2/dble(na)

      IF (debug) WRITE(*,'(1X,A,3(1X,F10.4))') 'Center1',xc1,yc1,zc1
      IF (debug) WRITE(*,'(1X,A,3(1X,F10.4))') 'Center2',xc2,yc2,zc2
      do i=1,na
         Coord1(1,i)=geom(1,i)-xc1
         Coord1(2,i)=geom(2,i)-yc1
         Coord1(3,i)=geom(3,i)-zc1
         Coord2(1,i)=geom2(1,i)-xc2
         Coord2(2,i)=geom2(2,i)-yc2
         Coord2(3,i)=geom2(3,i)-zc2
         x_norm=x_norm+Coord1(1,i)**2+Coord1(2,i)**2+Coord1(3,i)**2
         y_norm=y_norm+Coord2(1,i)**2+Coord2(2,i)**2+Coord2(3,i)**2
      end do

      IF (debug) THEN
         WRITE(*,*) "R matrix"
         DO I=1,3
            WRITE(*,*) (RMatrix(I,j),j=1,3)
         END DO
      END IF

  ! calculate the R matrix
      do i = 1, 3
         do j = 1, 3
            Rmatrix(i,j)=0.
            do ia=1,na
               Rmatrix(i,j) = Rmatrix(i,j)+Coord1(i,ia)*Coord2(j,ia)
            END DO
         end do
      end do

      IF (debug) THEN
         WRITE(*,*) "R matrix"
         DO I=1,3
            WRITE(*,*) (RMatrix(I,j),j=1,3)
         END DO
      END IF


  ! S matrix
      S(1, 1) = Rmatrix(1, 1) + Rmatrix(2, 2) + Rmatrix(3, 3)
      S(2, 1) = Rmatrix(2, 3) - Rmatrix(3, 2)
      S(3, 1) = Rmatrix(3, 1) - Rmatrix(1, 3)
      S(4, 1) = Rmatrix(1, 2) - Rmatrix(2, 1)

      S(1, 2) = S(2, 1)
      S(2, 2) = Rmatrix(1, 1) - Rmatrix(2, 2) - Rmatrix(3, 3)
      S(3, 2) = Rmatrix(1, 2) + Rmatrix(2, 1)
      S(4, 2) = Rmatrix(1, 3) + Rmatrix(3, 1)

      S(1, 3) = S(3, 1)
      S(2, 3) = S(3, 2)
      S(3, 3) =-Rmatrix(1, 1) + Rmatrix(2, 2) - Rmatrix(3, 3)
      S(4, 3) = Rmatrix(2, 3) + Rmatrix(3, 2)

      S(1, 4) = S(4, 1)
      S(2, 4) = S(4, 2)
      S(3, 4) = S(4, 3)
      S(4, 4) =-Rmatrix(1, 1) - Rmatrix(2, 2) + Rmatrix(3, 3) 


! PFL : I use my usual Jacobi diagonalisation
  ! Calculate eigenvalues and eigenvectors, and 
  ! take the maximum eigenvalue lambda and the corresponding eigenvector q.

      IF (debug) THEN
         WRITE(*,*) "S matrix"
         DO I=1,4
            WRITE(*,*) (S(I,j),j=1,4)
         END DO
      END IF

      Call Jacobi(S,4,EigVal,EigVec,4)

      Call Trie(4,EigVal,EigVec,4)

      Lambda=EigVal(4)

! RMS Deviation
       rmsd=sqrt(max(0.0d0,((x_norm+y_norm)-2.0d0*lambda))/dble(na))

      if (FRot.OR.FAlign) Call rotation_matrix(EigVec(1,4),U)
      IF (FAlign) THEN
         DO I=1,na
            geom2(1,i)=Coord2(1,i)*U(1,1)+Coord2(2,i)*U(2,1)
     &           +Coord2(3,i)*U(3,1) +xc1
            geom2(2,i)=Coord2(1,i)*U(1,2)+Coord2(2,i)*U(2,2)
     &           +Coord2(3,i)*U(3,2) +yc1
            geom2(3,i)=Coord2(1,i)*U(1,3)+Coord2(2,i)*U(2,3)
     &           +Coord2(3,i)*U(3,3) +zc1
         END DO
      END IF

      END


!-----------------------------------------------------------------------
      subroutine rotation_matrix(q, U)
!-----------------------------------------------------------------------
! This subroutine constructs rotation matrix U from quaternion q.
!-----------------------------------------------------------------------
! This subroutine calculates RMSD using quaternions.
! It is based on the F90 routine bu E. Coutsias
! http://www.math.unm.edu/~vageli/homepage.html
! I (PFL) have just translated it, and I have changed the diagonalization
! subroutine.
! I also made some changes to make it suitable for Cart package.
!----------------------------------------------------------------------
!----------------------------------------------------------------------
! Copyright (C) 2004, 2005 Chaok Seok, Evangelos Coutsias and Ken Dill
!      UCSF, Univeristy of New Mexico, Seoul National University
! Witten by Chaok Seok and Evangelos Coutsias 2004.
                                                                                
! This library is free software; you can redistribute it and/or
! modify it under the terms of the GNU Lesser General Public
! License as published by the Free Software Foundation; either
! version 2.1 of the License, or (at your option) any later version.
!
                                                                                
! This library is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
! Lesser General Public License for more details.
!
                                                                                
! You should have received a copy of the GNU Lesser General Public
! License along with this library; if not, write to the Free Software
! Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
!----------------------------------------------------------------------------

      real*8 q(4)
      real*8 U(3,3)
      real*8 q0,q1,q2,q3,b0,b1,b2,b3,q00,q01,q02,q03
      REAL*8 q11,q12,q13,q22,q23,q33

      q0 = q(1)
      q1 = q(2)
      q2 = q(3)
      q3 = q(4)

      b0 = 2.0d0*q0
      b1 = 2.0d0*q1
      b2 = 2.0d0*q2
      b3 = 2.0d0*q3

      q00 = b0*q0-1.0d0
      q01 = b0*q1
      q02 = b0*q2
      q03 = b0*q3

      q11 = b1*q1
      q12 = b1*q2
      q13 = b1*q3  
      
      q22 = b2*q2
      q23 = b2*q3
      
      q33 = b3*q3 
      
      U(1,1) = q00+q11
      U(1,2) = q12-q03
      U(1,3) = q13+q02
      
      U(2,1) = q12+q03
      U(2,2) = q00+q22
      U(2,3) = q23-q01
      
      U(3,1) = q13-q02
      U(3,2) = q23+q01
      U(3,3) = q00+q33
      
      end 
      
c============================================================
c
c ++  diagonalisation par jacobi
c     vecteur propre i : V(i,i)
c     valeur propre i : D(i)
c
c============================================================
c 
      SUBROUTINE JACOBI(A,N,D,V,max_N)
      IMPLICIT REAL*8 (A-H,O-Z)
      parameter (max_it=500)
      DIMENSION A(max_N,max_N),B(max_N),Z(max_N)
      DIMENSION V(max_N,max_N),D(max_N)


      DO 12 IP=1,N
        DO 11 IQ=1,N
          V(IP,IQ)=0.
11      CONTINUE
        V(IP,IP)=1.
12    CONTINUE
      DO 13 IP=1,N
        B(IP)=A(IP,IP)
        D(IP)=B(IP)
        Z(IP)=0.
13    CONTINUE
      NROT=0
      DO 24 I=1,max_it
        SM=0.
        DO 15 IP=1,N-1
          DO 14 IQ=IP+1,N
            SM=SM+ABS(A(IP,IQ))
14        CONTINUE
15      CONTINUE
        IF(SM.EQ.0.)RETURN
        IF(I.LT.4)THEN
          TRESH=0.2*SM/N**2
        ELSE
          TRESH=0.
        ENDIF
        DO 22 IP=1,N-1
          DO 21 IQ=IP+1,N
            G=100.*ABS(A(IP,IQ))
            IF((I.GT.4).AND.(ABS(D(IP))+G.EQ.ABS(D(IP)))
     *         .AND.(ABS(D(IQ))+G.EQ.ABS(D(IQ))))THEN
              A(IP,IQ)=0.
            ELSE IF(ABS(A(IP,IQ)).GT.TRESH)THEN
              H=D(IQ)-D(IP)
              IF(ABS(H)+G.EQ.ABS(H))THEN
                T=A(IP,IQ)/H
              ELSE
                THETA=0.5*H/A(IP,IQ)
                T=1./(ABS(THETA)+SQRT(1.+THETA**2))
                IF(THETA.LT.0.)T=-T
              ENDIF
              C=1./SQRT(1+T**2)
              S=T*C
              TAU=S/(1.+C)
              H=T*A(IP,IQ)
              Z(IP)=Z(IP)-H
              Z(IQ)=Z(IQ)+H
              D(IP)=D(IP)-H
              D(IQ)=D(IQ)+H
              A(IP,IQ)=0.
              DO 16 J=1,IP-1
                G=A(J,IP)
                H=A(J,IQ)
                A(J,IP)=G-S*(H+G*TAU)
                A(J,IQ)=H+S*(G-H*TAU)
16            CONTINUE
              DO 17 J=IP+1,IQ-1
                G=A(IP,J)
                H=A(J,IQ)
                A(IP,J)=G-S*(H+G*TAU)
                A(J,IQ)=H+S*(G-H*TAU)
17            CONTINUE
              DO 18 J=IQ+1,N
                G=A(IP,J)
                H=A(IQ,J)
                A(IP,J)=G-S*(H+G*TAU)
                A(IQ,J)=H+S*(G-H*TAU)
18            CONTINUE
              DO 19 J=1,N
                G=V(J,IP)
                H=V(J,IQ)
                V(J,IP)=G-S*(H+G*TAU)
                V(J,IQ)=H+S*(G-H*TAU)
19            CONTINUE
              NROT=NROT+1
            ENDIF
21        CONTINUE
22      CONTINUE
        DO 23 IP=1,N
          B(IP)=B(IP)+Z(IP)
          D(IP)=B(IP)
          Z(IP)=0.
23      CONTINUE
24    CONTINUE
      write(6,*) max_it,' iterations should never happen'
      STOP
      RETURN
      END
c
c============================================================
c
c ++  trie des vecteur dans l'ordre croissant
c
c============================================================
c
        SUBROUTINE trie(nb_niv,ene,psi,max_niv)
        integer i,j,k,nb_niv,max_niv
        real*8 ene(max_niv),psi(max_niv,max_niv)
        real*8 a

        DO i=1,nb_niv
          DO j=i+1,nb_niv
            IF (ene(i) .GT. ene(j)) THEN
c              permutation
              a=ene(i)
              ene(i)=ene(j)
              ene(j)=a
              DO k=1,nb_niv
                 a=psi(k,i)
                 psi(k,i)=psi(k,j)
                 psi(k,j)=a
              END DO
            END IF
          END DO
        END DO

        END

