subroutine egrad_gaussian(e,geomcart,gradcart)

  ! This routines calculates the energy and the gradient of 
  ! a molecule, using Gaussian 

  use Path_module, only : Nat, renum,Order,OrderInv,AtName, Coord, dzdc, indzmat,Nom,Atome, massat, unit,ProgExe
  use Io_module

  IMPLICIT NONE

  ! Energy (calculated if F300K=.F., else estimated)
  REAL(KREAL), INTENT (OUT) :: e
  ! Nb degree of freedom
  REAL(KREAL), INTENT (IN) :: geomcart(Nat,3)
  ! Gradient calculated at Geom geometry
  REAL(KREAL), INTENT (OUT) :: gradcart(3*NAt)

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

  character(LCHARS) :: LINE

  logical           :: debug, G03Ok
  LOGICAL :: fexist, FSim
  LOGICAL, SAVE :: first=.true.
  LOGICAL, ALLOCATABLE :: Done(:)

  REAL(KREAL), SAVE :: Eold=1.e6
  REAL(KREAL), ALLOCATABLE :: GradTmp(:)

  REAL(KREAL) :: d, a_val, Pi

  REAL(KREAL) :: coef,x
  INTEGER(KINT) :: ItG03
  INTEGER(KINT) :: iat, jat, kat, i, j, n3at, absidg, absidg2
  INTEGER(KINT) :: kTmp, Istart,ITmp1,ITmp2, Idx
  INTEGER(KINT), PARAMETER :: IOLOG=12, IOCOM=11

  CHARACTER(132) :: FileIn, FileOut, FileChk

  CHARACTER(3) :: SepIn=' < ', SepOut=' > '
  CHARACTER(LCHARS) :: ListName, TitleTmp, CH32SVAR1
  CHARACTER(VLCHARS), SAVE :: RstrtCopy, RunCommand
  LOGICAL, SAVE :: FCopyRstrt=.False., FOrderChecked=.False.
  LOGICAL   :: FRdyn,FStopNucl, FTmp, Tchk,Tchk1
  INTEGER(kint) :: NbLists,LastIt,Nat4,NStep, Firstit
  INTEGER(KINT) :: NStepAd,NStepTmp
  INTEGER(KINT) :: IShowTmp
  REAL(KREAL)   :: FricPsiMin,FricPsiT, FricNuclTmp

  INTEGER(KINT), PARAMETER :: NbExtName=4

  INTEGER(KINT) :: ICouc

  INTEGER(KINT) :: ILine
  INTEGER(KINT) :: NPulses, PulseLen, NStepWarm,NStepAv,NStepEq,NStepTot
  REAL(KREAL) :: TempWarm,Mean,Slope,Dev,RTmp1,RTmp2

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

  LOGICAL, EXTERNAL :: valid

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

  Pi=dacos(-1.0d0)
  n3at=3*nat

  debug=valid('EGRAD')
  if (debug) Call Header("Entering Egrad_gaussian")

  if (first) THEN
     First=.FALSE.
     call system("uname > Path.tmp")
     OPEN(IOTMP,FILE='Path.tmp')
     READ(IOTMP,'(A)') Line
     CLOSE(IOTMP)
     IF (index(Line,'CYGWIN').NE.0) THEN
        SepIn='   '
        SepOut='   '
     END IF
  END IF

  gradcart=0.
  E=0.
  FileIn=Trim(CalcName) // "." // Trim(ISuffix)
  FileOut=Trim(CalcName) // "." // Trim(OSuffix)
  FileChk=Trim(CalcName) // ".chk"
  RunCommand=Trim(ProgExe) // SepIn // Trim(FileIn) // SepOut // Trim(FileOut)

  IF (DEBUG) WRITE(*,*)'RunCommand:',TRIM(RunCommand)

  ! we create the input file

  OPEN(IOTMP,File=FileIn)

  Current => Gauss_root
  DO WHILE (ASSOCIATED(Current%next))
     WRITE(IOTMP,'(1X,A)') Trim(current%line)
     WRITE(*,'(1X,A)') Trim(current%line)
     Current => current%next
  END DO

  WRITE(IOTMP,*) 

  Current => Gauss_comment
  DO WHILE (ASSOCIATED(Current%next))
     WRITE(IOTMP,'(1X,A)') Trim(current%line)
     Current => current%next
  END DO
  !  WRITE(IOOUT,"('Geometry ',I3,'/',I3,' for iteration ',I3)"),Igeom,NgeomF,Iopt

  WRITE(IOTMP,*) 
  WRITE(IOTMP,*) Trim(Gauss_charge)

  DO I=1,Nat
     If (renum) THEN
        Iat=Order(I)
        WRITE(IOTMP,'(1X,A10,3(1X,F15.8),A)') Trim(AtName(I)),GeomCart(Iat,:), TRIM(Gauss_Paste(I))
     ELSE
        Iat=OrderInv(I)
        WRITE(IOTMP,'(1X,A10,3(1X,F15.8),A)') Trim(AtName(Iat)),GeomCart(I,:), TRIM(Gauss_Paste(Iat))
     END IF
  END DO

  WRITE(IOTMP,*) 

  Current => Gauss_End
  DO WHILE (ASSOCIATED(Current%next))
     WRITE(IOTMP,'(1X,A)') Trim(current%line)
     Current => current%next
  END DO

  WRITE(IOTMP,*) 
  CLOSE(IOTMP)

  IF (debug) THEN
     WRITE(*,*) 'DBG EGRAD ' //  Trim(FileIn),' COORD=',TRIM(COORD)
     call system('cat ' // Trim(FileIn))
  END IF

!!! PFL 15th March 2008 ->
! Sometimes for unknown reasons G03 fails.
! We thus add one test to check that Gaussian has finisehd properly.
! We also check that we do not run an infinite loop...

 G03Ok=.FALSE.
 ItG03=0

  DO WHILE ((.NOT.G03Ok).AND.(ItG03<3))
   ItG03=ItG03+1
  call system(RunCommand)
 OPEN(IOTMP,FILE=FileOut, STATUS='old', POSITION='APPEND')
 BACKSPACE(IOTMP)
 READ(IOTMP,'(A)') Line
 IF (LINE(2:19).EQ.'Normal termination')  G03Ok=.TRUE.
  END DO
  CLOSE(IOTMP)
  IF (.NOT.G03Ok) THEN
     WRITE(*,*) "Egrad_gaussian Failed..."
     WRITE(*,*) "Wrong termination of Gaussian after 3 tries. Check Input and geometry"
     STOP
  END IF

  if (debug) WRITE(*,*) 'DBG EGRAD, back from calculation'

  ! Whatever the coordinate system, we read the cartesian gradient
  ! and we convert it to Zmat or other if needed

  OPEN(IOTMP,FILE=FileOut, STATUS='old')
  ! We first search for the forces
  READ(IOTMP,'(A)') LINE
  DO WHILE (INDEX(LINE,'Forces (Hartrees/Bohr)')==0)
     ! here, we have a problem, because there are so many ways to write E for Gaussian :-)
     ! but we do not really need E except if we want to weight the different points
     ! on the path... that will be done later :-)
     ! And I should use ConvGaussXmol ...
! PFL 3rd Jan 2008 ->
! I have finally upgraded the energy reading phase so that it should be able to read 
! many formats corresponding to HF, DFT, MP2, AM1, PM3, ONIOM with or w/o PCM
     
! For MP2, energy is after the last =
     IF ((Line(2:9)=="E2 =    ")) THEN
	    Itmp1=Index(LINE,"=",BACK=.TRUE.)+1
		READ(LINE(Itmp1:),*) e
      END IF
! For other methods, it is after the first =
     IF ((LINE(2:9)=='Energy= ').OR.(Line(2:9)=="SCF Done").OR.(Line(2:9)=="ONIOM: e") &
	 .OR.(Line(2:9)==" with al") &
         .OR.(Line(2:31)=="Counterpoise: corrected energy")) THEN
	    Itmp1=Index(LINE,"=")+1
		READ(LINE(Itmp1:),*) e
	END IF
! <- PFL 3 Jan 2008
     READ(IOTMP,'(A)') LINE
  END DO
  if (debug) WRITE(*,*) "GradCart reading - renum=",Renum
  READ(IOTMP,'(A)') LINE
  READ(IOTMP,'(A)') LINE
  DO I=1,Nat
     Iat=I
     IF (renum) Iat=Order(I)
     READ(IOTMP,*)  Itmp1,ITmp2, GradCart(3*Iat-2:3*Iat)
     if (debug) WRITE(*,*) "I,Iat,GradCart:",I,Iat,GradCart(3*Iat-2:3*Iat)
  END DO

! Gaussian gives the Forces in ua/a0, so we convert it into the 
! gradient in ua/Angstrom 
  gradCart=-1.0d0*gradCart*Unit

!  if (debug.AND.(COORD.EQ.'ZMAT')) THEN
!     DO WHILE (INDEX(LINE,'Internal Coordinate Forces')==0)
!        READ(IOTMP,'(A)') LINE
!!        WRITE(*,*) 'Pas bon:' // TRIM(LINE)
!     END DO
!     WRITE(*,*) TRIM(LINE)
!     DO I=1,Nat+2
!        READ(IOTMP,'(A)') LINE
!        WRITE(*,*) TRIM(LINE)
!     END DO
!  END IF

  CLOSE(IOTMP)

  if (debug) Call header("Egrad_gaussian Over")

  RETURN

999 CONTINUE
  if (.NOT.Ftmp) WRITE(*,*) 'We should not be here !!!!'
  STOP
  ! ======================================================================
end subroutine egrad_gaussian
