          program Xyz2irc
! 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 ROOT file of PAW
! it also needs a file call list which has the following structure:
! the first line gives the time when you want to start your analysis
! 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:
! 3.
! 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
!!
! v 3.2
! Added the p command that gives the oriented angle between two planes
! Syntax: p At1 At2 At3 At4 At5 At6
! At1, At2, At3 define the first plane
! At4, At5, At6 define the second plane
! How it works: gives the angles between the normal of the two planes, defined by
! the cross produc At2-At1 x At2-At3 etc.
!!!!


          IMPLICIT NONE
          INTEGER(4), PARAMETER :: maxnat=10000,MaxList=100

          CHARACTER(120) :: f1
          REAL(8) ::   geos(3,maxnat)
          CHARACTER(33) :: fmt
          CHARACTER(3) :: atoms(maxnat)
          character(5) :: Type
          CHARACTER(120) :: line
          INTEGER(4) :: NbPrint
          REAL(8) ::   AU2PS,Pi
! Mass is not used for now.
!          REAL(8) ::  Mass(MaxNat)
          REAL(8) :: Ener, Conv
          INTEGER(4) :: At1,At2,At3,At4,At5,At6,IOOUT
          INTEGER(4) ::  IArg, I, NNN, Ng, J

          INTEGER(4) :: Nat,NbDist, NbAngle, NbDie,NbP,NbCOM
          INTEGER(4) :: At1B(MaxList),At2B(MaxList)
          INTEGER(4) :: At1A(MaxList),At2A(MaxList),At3A(MaxList)
          INTEGER(4) :: At1D(MaxList),At2D(MaxList),At3D(MaxList),At4D(MaxList)
          INTEGER(4) :: At1p(MaxList),At2p(MaxList),At3p(MaxList), &
                   At4p(MaxList),At5p(MaxList),At6p(MaxList) 
          INTEGER(4) :: AtCom(0:MaxList,MaxList)
          REAL(8) ::    VB(MaxList),VA(MaxList),VD(MaxList),VCOM(MaxList)
          REAL(8) ::    Vp(MaxList)
          LOGICAL FExist

          COMMON /Indices/Nat,NbDist,NbAngle,NbDie,NbP,NbCom, At1B,At2B, &
              At1A,At2A,At3A,At1D,At2D,At3D,At4D,AtCom,  &
              At1p,At2p,At3p,At4p,At5p,At6p
          COMMON /Values/VB,VA,VD,Vp,VCom
          COMMON /Const/AU2ps,Pi

          AU2PS=1./41341.37
          NbPrint=100
          Pi=dacos(-1.d0)
          IOOUT=13
          Conv=1.
          iarg=iargc()
          if (iarg.lt.1) then
             WRITE(*,*) "=============================================="
             WRITE(*,*) "==                                          =="
             WRITE(*,*) "==   Xyz2Scan: Xyz file to scan file        =="
             WRITE(*,*) "==                                          =="
             WRITE(*,*) "=============================================="
             WRITE(*,*) "Usage: xyz2scan XYZ_file "
             WRITE(*,*) "The XYZ file should follow the 'usual' format:"
             WRITE(*,*) "Number of atoms on the first line "
             WRITE(*,*) "Comment on the second line"
             WRITE(*,*) "The geometry is given in cartesian coordinates"
             WRITE(*,*) "with atom symbol and three coordinates:"
             WRITE(*,*) " C   0. 1. 0."
             WRITE(*,*) ""
             WRITE(*,*) " xyz2scan also needs a file called 'list' "
             WRITE(*,*) "which has the following structure:"
             WRITE(*,*) "Each line contains the type of the value you"
             WRITE(*,*) "want to follow, it can be:"
             WRITE(*,*) " - b  for a Bond distance"
             WRITE(*,*) " - a for an angle"
             WRITE(*,*) " - d for a dihedral"
             WRITE(*,*) " - p for the oriented angle between two planes"
             WRITE(*,*) "This descriptor is followed by the number of"
             WRITE(*,*) "the atoms involved"
             WRITE(*,*) "One can also create 'barycenter' atoms that"
             WRITE(*,*) "can then be used as normal atoms."
             WRITE(*,*) "the descriptor is 'c' followed by the number"
             WRITE(*,*) "of atoms and the list of atoms:"
             WRITE(*,*) " c 2  1 5"
             WRITE(*,*) "A typical file can be:"
             WRITE(*,*) " b  1  2"
             WRITE(*,*) " b 2  3"
             WRITE(*,*) " a 1 2 3"
             WRITE(*,*) "     "
             WRITE(*,*) "=============================================="
             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(*,*) "File *list* is missing"
             STOP
          END IF

          open(11,file=f1)
          READ(11,*) nnn
          close(11)

      
          if (nnn.GT.MaxNat) THEN
             WRITE(*,*) "Sorry but your system has too many atoms"
             WRITE(*,*) "Change the value of MaxNat in the source file"
             WRITE(*,*) "and then recompile."
             WRITE(*,*) "For information, now MaxNat=",MaxNat
             WRITE(*,*) "and you have ",nnn," atoms."
             STOP
          END IF

          Nat=nnn

         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
          END IF
          if (Type.eq."a") THEN
             NbAngle=NbAngle+1
             READ(Line,*) At1,At2,At3
             At1A(NbAngle)=At1
             At2A(NbAngle)=At2
             At3A(NbAngle)=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."p") THEN
             NbP=NbP+1
             READ(Line,*) At1,At2,At3,At4,At5,At6
             At1p(NbP)=At1
             At2p(NbP)=At2
             At3p(NbP)=At3
             At4p(NbP)=At4
             At5p(NbP)=At5
             At6p(NbP)=At6
          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"
          END IF

         END DO

         CLOSE(14)

! We read one geoetry to get the atoms name
         open(11,file=f1)
          call rtraitem(11,nnn,ener,geos,atoms)
         close(11)


! We write things
! First NbCom
         if (NbCom.GE.1) THEN
            WRITE(*,*) "# Added center of mass"
            WRITE(IOOUT,*) "# Added center of mass"
            DO J=1,NbCom
            WRITE(IOOUT,'("# c ",I4,20(A3,I3))') AtCom(0,J),           &
               (Atoms(AtCom(i,J)),AtCom(i,J),i=1,At1)
            WRITE(*,'("# c ",I4,20(A3,I3))') AtCom(0,J),              &
               (Atoms(AtCom(i,J)),AtCom(i,J),i=1,At1)
            END DO
         END IF

! Distances
         if (NbDist.GE.1) THEN
            WRITE(*,*) "# Bonds"
            WRITE(IOOUT,*) "# Bonds"
            DO J=1,NbDist
               At1= At1B(J)
               At2=At2B(J)
             WRITE(IOOUT,'("# b ",2(A3,I3))') Atoms(At1),At1, &
                   Atoms(At2),At2
             WRITE(*,'("# b ",2(A3,I3))') Atoms(At1),At1,Atoms(At2),At2
            END DO
         END IF

! Angles
         if (NbAngle.GE.1) THEN
            WRITE(*,*) "# Angles"
            WRITE(IOOUT,*) "# Angles"
            DO J=1,NbAngle
            At1= At1A(J)
            At2= At2A(J)
            At3= At3A(J)
            WRITE(IOOUT,'("# 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 DO
         END IF


! Dihedrals 
         if (NbDie.GE.1) THEN
            WRITE(*,*) "# Dihedrals"
            WRITE(IOOUT,*) "# Dihedrals"
            DO J=1,NbDie
            At1= At1D(J)
            At2= At2D(J)
            At3= At3D(J)
            At4= At4D(J)
            WRITE(IOOUT,'("# 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 DO
         END IF

! Planar angles
         if (NbP.GE.1) THEN
            WRITE(*,*) "# Planes angles"
            WRITE(IOOUT,*) "# Planes angles"
            DO J=1,NbP
            At1= At1p(J)
            At2= At2p(J)
            At3= At3p(J)
            At4= At4p(J)
            At5= At5p(J)
            At6= At6p(J)
            WRITE(IOOUT,'("# p ",8(A3,I3))') Atoms(At1),At1,Atoms(At2) &
               ,At2,Atoms(At3),At3,Atoms(At4),At4 &
               ,Atoms(At5),At5,Atoms(At6),At6
            WRITE(*,'("# p ",8(A3,I3))') Atoms(At1),At1,Atoms(At2),At2,    &
               Atoms(At3),At3,Atoms(At4),At4             &
               ,Atoms(At5),At5,Atoms(At6),At6
            END DO
         END IF


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

          ng=1

          open(11,file=f1)

10           call rtraitem(11,nnn,ener,geos,atoms)
!           WRITE(*,*) nnn

           if (nnn.gt.0) then
! We convert coordinates in a0 into Angstroem
!              write(*,*) "Analyse !"
            Call Analyse(geos)

             write(IOOUT,fmt) (VB(j)/Conv,j=1,NbDist),  &
                 (VA(j),j=1,NbAngle),    &
                 (VD(j),j=1,NbDie),(Vp(j),j=1,NbP),ener
             write(*,fmt) (VB(j)/Conv,j=1,NbDist),   &
                 (VA(j),j=1,NbAngle),                &
                 (VD(j),j=1,NbDie),(Vp(j),j=1,NbP),ener

           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 subroutine rtraitem

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

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! 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(5) :: Type
      CHARACTER(120) :: LINE
      INTEGER(4) ::  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 READLINE



      SUBROUTINE Analyse(geos)

      IMPLICIT NONE
      INTEGER(4),PARAMETER  :: MaxNat=10000,MaxList=100

      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,NbP,NbCOM
          INTEGER(4) :: At1B(MaxList),At2B(MaxList)
          INTEGER(4) :: At1A(MaxList),At2A(MaxList),At3A(MaxList)
          INTEGER(4) :: At1D(MaxList),At2D(MaxList),At3D(MaxList), &
                   At4D(MaxList)
          INTEGER(4) :: At1p(MaxList),At2p(MaxList),At3p(MaxList), &
                   At4p(MaxList),At5p(MaxList),At6p(MaxList)
          INTEGER(4) :: AtCom(0:MaxList,MaxList)
          REAL(8) ::    VB(MaxList),VA(MaxList),VD(MaxList),VCOM(MaxList)
          REAL(8) ::    Vp(MaxList)

          LOGICAL :: Debug=.FALSE.

          COMMON /Indices/Nat,NbDist,NbAngle,NbDie,NbP,NbCom, At1B,At2B, &
              At1A,At2A,At3A,At1D,At2D,At3D,At4D,AtCom, &
              At1p,At2p,At3p,At4p,At5p,At6p
          COMMON /Values/VB,VA,VD,Vp,VCom
          COMMON /Const/AU2ps,Pi

          if (Debug) THEN
             DO I=1,Nat
                WRITE(*,'(1X,I3,3(1X,F15.6))') i,(geos(j,i),j=1,3)
             END DO
          END IF
! 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
                 DO k=1,3
                   COG(k)=COG(k)/AtCOM(0,i) 
                   geos(k,Nat+i)=COG(k)
                END DO
             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)
               if (d1<=1e-12) THEN
                  WRITE(*,*) "WARNING: Dihedral, d1=0"
                  ca=-1.
                  sa=0.
               END IF
               if (d2<=1e-12) THEN
                  WRITE(*,*) "WARNING: Dihedral, d2=0"
                  ca=-1.
                  sa=0.
               END IF
               ca=(v4x*v5x+v4y*v5y+v4z*v5z)/(d1*d2)
               sa=v1x*v5x+v1y*v5y+v1z*v5z
               if (abs(ca)>1.) ca=sign(1.d0,ca)
               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
!                WRITE(*,*) "Dihe ca,sa,d1,d2",ca,sa,d1,d2,acos(ca)

               
!!!!!!!!! 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

            DO i=1,NbP
! v1= At2-At1
               v1x=geos(1,At1p(i))-geos(1,At2p(i))
               v1y=geos(2,At1p(i))-geos(2,At2p(i))
               v1z=geos(3,At1p(i))-geos(3,At2p(i))
! v2=At2-At3
               v2x=geos(1,At3p(i))-geos(1,At2p(i))
               v2y=geos(2,At3p(i))-geos(2,At2p(i))
               v2z=geos(3,At3p(i))-geos(3,At2p(i))
! v4 = v1 x v2
               v4x=v1y*v2z-v1z*v2y
               v4y=v1z*v2x-v1x*v2z
               v4z=v1x*v2y-v1y*v2x
               d1=sqrt(v4x**2+v4y**2+v4z**2)

! v3= At5-At4
               v3x=geos(1,At4p(i))-geos(1,At5p(i))
               v3y=geos(2,At4p(i))-geos(2,At5p(i))
               v3z=geos(3,At4p(i))-geos(3,At5p(i))
! v2=At5-At6
               v2x=geos(1,At6p(i))-geos(1,At5p(i))
               v2y=geos(2,At6p(i))-geos(2,At5p(i))
               v2z=geos(3,At6p(i))-geos(3,At5p(i))

! v5 = v3 x v2
               v5x=v3y*v2z-v3z*v2y
               v5y=v3z*v2x-v3x*v2z
               v5z=v3x*v2y-v3y*v2x
               d2=sqrt(v5x**2+v5y**2+v5z**2)

               ca=(v4x*v5x+v4y*v5y+v4z*v5z)/(d1*d2)
               sa=v1x*v5x+v1y*v5y+v1z*v5z
               Vp(i)=acos(ca)*180./Pi
               if (sa<0.) Vp(i)=-Vp(i)
!               WRITE(*,*) "Dihe",v5x,v5y,v5z,v4x,v4y,v4z,d1,d2,
!     &(v4x*v5x+v4y*v5y+v4z*v5z)/(d1*d2),pi
!!!!!!!!! Another solution, more elegant ?
! See Dihedral routine
            END DO


          END SUBROUTINE Analyse
