! This program reads an old hessian, old forces, new forces
! and print the updated hessian and old coordinates.
! We use the Murtagh-Sargent update

SUBROUTINE Hupdate_MS(Nfree,ds,dgrad,Hess)

  IMPLICIT NONE

  INTEGER, PARAMETER :: KINT=KIND(1)
  INTEGER, PARAMETER :: KREAL=KIND(1.D0)

  INTEGER(KINT), INTENT(IN) :: NFREE
  REAL(KREAL), INTENT(INOUT) :: Hess(Nfree,Nfree)
  REAL(KREAL), INTENT(IN) :: ds(Nfree)
  REAL(KREAL), INTENT(IN) :: dGrad(Nfree)


  REAL(KREAL), ALLOCATABLE  :: HessOld(:,:) , HupMS(:,:)
  REAL(KREAL), ALLOCATABLE  :: Hup(:,:)
  REAL(KREAL), ALLOCATABLE  :: HupInt(:)
  REAL(KREAL), ALLOCATABLE  :: HS(:), Num(:,:)
  REAL(KREAL) :: Phi, Num3, Den, Den2,NormDS
  CHARACTER(120) :: fmt,fmt2,Line
  INTEGER(KINT) :: i,j, idx

  LOGICAL debug,valid
  EXTERNAL valid

  debug=valid("Hupdate").OR.Valid("Hupdate_MS")

  if (debug) Call Header("Entering Hupdate_MS")

  ALLOCATE(HessOld(nfree,nfree), HupMS(nfree,nfree),  &
       Hup(nfree,nfree), &
       HupInt(nfree), HS(nfree),  &
       Num(nfree,nfree))

  HessOld=Hess

  if (debug) THEN
     WRITE(*,*) 'DBG Hupdate HessOld'
     Idx=min(12,Nfree)
     DO I=1,NFree
        WRITE(*,'(12(1X,F8.4))') HessOld(I,1:Idx)
     END DO
     WRITE(*,*) 'DBG Hupdate ds'
     WRITE(*,'(12(1X,F8.4))') ds(1:Idx)
     WRITE(*,*) 'DBG Hupdate dGrad'
     WRITE(*,'(12(1X,F8.4))') dGrad(1:Idx)
  END IF

  NormDS=sqrt(DOT_PRODUCT(DS,DS))
  if (NormDS>=1e-6) THEN

     HS=0
     DO I=1,nfree
        DO J=1,nfree
           HS(I)=HS(I)+HessOld(i,j)*Ds(j)
        END DO
     END DO
     HupInt=DGrad-HS

     ! WE calculate the MS update
     Num=0.
     Den=0.
     DO I=1,nfree
        DO J=1,nfree
           Num(I,J)=HUpInt(i)*HupInt(j)
        END DO
        Den=Den+Hupint(i)*Ds(i)
     END DO

     HupMS=Num/Den

     Hess=HessOld+HupMS
  ELSE
     Hess=HessOld
  END IF
  !     WRITE(*,*) 'New hess'
  !     DO I=1,nfree
  !        WRITE(*,fmt) Hess(i,:)
  !     END DO

  DEALLOCATE(HessOld, HupMS,HupInt, HS, Num )

  if (debug) Call Header("Hupdate_MS Over")

END SUBROUTINE Hupdate_MS
