
! Copyright (C) 2020 J. K. Dewhurst and S. Sharma.
! This file is distributed under the terms of the GNU General Public License.
! See the file COPYING for license details.

subroutine bornectd
use modmain
use modphonon
use modtddft
use modstore
use modmpi
implicit none
! local variables
integer ip
real(8) vc(3),bec(3),t1
character(256) fext
! allocatable arrays
real(8), allocatable :: jt(:,:),f(:)
! external functions
real(8), external :: splint
! store original parameters
atposl_(:,:,:)=atposl(:,:,:)
! no shifting of atomic basis allowed
tshift=.false.
! initialise universal variables
call init0
atposc_(:,:,:)=atposc(:,:,:)
! generate a zero A-field
npulse=0
nramp=0
if (mp_mpi) call genafieldt
! synchronise MPI processes
call mpi_barrier(mpicom,ierror)
! initial ground-state run should start from atomic densities
trdstate=.false.
! begin new Born effective charge task
10 continue
call bectask(80,fext)
! if nothing more to do then restore original input parameters and return
if (isph.eq.0) then
  filext='.OUT'
  atposl(:,:,:)=atposl_(:,:,:)
  tshift=tshift_
  return
end if
if (mp_mpi) then
  write(*,'("Info(bornectd): working on ",A)') 'BEC'//trim(fext)
end if
! dry run: just generate empty BEC files
if (task.eq.209) goto 10
! break the crystal symmetry for the displaced atom
atposl(:,:,:)=atposl_(:,:,:)
atposc(:,:,:)=atposc_(:,:,:)
vc(:)=atposc(:,iaph,isph)
vc(ipph)=vc(ipph)-0.5d0*deltaph
call r3mv(ainv,vc,atposl(:,iaph,isph))
! run the ground-state calculation
call gndstate
! subsequent calculations will read in the previous potential
trdstate=.true.
! write the atomic forces to file
call becforce
! run the time evolution calculation with Ehrenfest dynamics
task=462
call tddft
task=478
! read in the total current from file
allocate(jt(3,ntimes),f(ntimes))
call readjtot(jt)
! calculate the Born effective charge from the integrated current
do ip=1,3
  f(:)=jt(ip,:)
  t1=splint(ntimes,times,f)
  bec(ip)=t1/(deltaph*cos(tdphi))
end do
deallocate(jt,f)
! add the static and nuclear charge
t1=sum(chgsmt(iasph,1:3))/3.d0
bec(ipph)=bec(ipph)+t1+spzn(isph)
! write Born effective charge matrix row to file
if (mp_mpi) then
  do ip=1,3
    write(80,'(G18.10," : ip = ",I4)') bec(ip),ip
  end do
  close(80)
end if
! synchronise MPI processes
call mpi_barrier(mpicom,ierror)
goto 10
end subroutine

