subroutine turbomole_gradlatt(mol, fname, energy, sigma, stat)
!DEC$ ATTRIBUTES DLLEXPORT :: turbomole_gradlatt
type(structure_type),intent(in) :: mol
character(len=*),intent(in) :: fname
real(wp),intent(in) :: energy
real(wp),intent(in) :: sigma(3,3)
integer, intent(out) :: stat
character(len=:),allocatable :: line
integer :: i,j,icycle,line_number
integer :: err
integer :: igrad ! file handle
logical :: exist
real(wp) :: escf
real(wp) :: glat(3,3), inv_lat(3,3), gradlatt(3, 3)
real(wp) :: dlat(3,3)
stat = 0
inv_lat = matinv_3x3(mol%lattice)
do i = 1, 3
do j = 1, 3
gradlatt(i,j) = sigma(i,1)*inv_lat(j,1) &
& + sigma(i,2)*inv_lat(j,2) &
& + sigma(i,3)*inv_lat(j,3)
enddo
enddo
icycle = 1
i = 0
escf = 0.0_wp
inquire(file=fname,exist=exist)
if (exist) then
open(newunit=igrad,file=fname)
read_file: do
call getline(igrad,line,iostat=err)
if (err.ne.0) exit read_file
i=i+1
if (index(line,'cycle') > 0) line_number = i
enddo read_file
if (line_number < 2) then
stat = 1
return
endif
rewind(igrad)
skip_lines: do i = 1, line_number-1
read(igrad,'(a)')
enddo skip_lines
call getline(igrad,line)
read(line(10:17),*,iostat=err) icycle
read(line(33:51),*,iostat=err) escf
do i = 1, 3
call getline(igrad,line)
read(line,*,iostat=err) dlat(1,i),dlat(2,i),dlat(3,i)
enddo
if (any(abs(dlat-mol%lattice) > 1.0e-8_wp)) then
stat = 1
return
endif
do i = 1, 3
call getline(igrad,line)
read(line,*,iostat=err) glat(1,i),glat(2,i),glat(3,i)
enddo
do i = 1, 3
backspace(igrad)
backspace(igrad)
enddo
backspace(igrad)
else
open(newunit=igrad,file=fname)
write(igrad,'("$gradlatt")')
endif
write(igrad,'(2x,"cycle =",1x,i6,4x,"SCF energy =",f18.11,3x,'//&
'"|dE/dlatt| =",f10.6)') &
icycle, energy+escf, norm2(gradlatt+glat)
do i = 1, 3
write(igrad,'(3(F20.14,2x))') mol%lattice(1,i),mol%lattice(2,i),mol%lattice(3,i)
enddo
do i = 1, 3
write(igrad,'(3D22.13)') gradlatt(1,i)+glat(1,i),gradlatt(2,i)+glat(2,i),gradlatt(3,i)+glat(3,i)
enddo
write(igrad,'("$end")')
close(igrad)
end subroutine turbomole_gradlatt