
! Copyright (C) 2023 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 writejw
use modmain
use modtddft
implicit none
! local variables
integer its,iw,i
real(8) w1,w2,t1,t2
complex(8) eta,z1
! allocatable arrays
real(8), allocatable :: w(:),wt(:),jt(:,:)
real(8), allocatable :: f1(:),f2(:)
! initialise global variables
call init0
call init1
! generate energy grid (always non-negative)
allocate(w(nwplot))
w1=max(wplot(1),0.d0)
w2=max(wplot(2),w1)
t1=(w2-w1)/dble(nwplot)
do iw=1,nwplot
  w(iw)=w1+t1*dble(iw-1)
end do
! i divided by the complex relaxation time
eta=cmplx(0.d0,swidth,8)
! determine the weights for the spline integration
allocate(wt(ntimes))
call wsplint(ntimes,times,wt)
! read in the total current from file
allocate(jt(3,ntimes))
call readjtot(jt)
! divide by the unit cell volume
jt(:,:)=jt(:,:)/omega
! filter the high-frequency components from the current
do its=1,ntimes
  t1=exp(-swidth*times(its))
  jt(:,its)=t1*jt(:,its)
end do
! Fourier transform the current
allocate(f1(ntimes),f2(ntimes))
open(50,file='JTOTW.OUT',form='FORMATTED')
do i=1,3
  do iw=1,nwplot
    do its=1,ntimes
      t1=jt(i,its)
      t2=w(iw)*times(its)
      f1(its)=t1*cos(t2)
      f2(its)=t1*sin(t2)
    end do
    t1=dot_product(wt(:),f1(:))
    t2=dot_product(wt(:),f2(:))
    z1=cmplx(t1,t2,8)
    write(50,'(3G18.10)') w(iw),z1
  end do
  write(50,*)
end do
close(50)
write(*,*)
write(*,'("Info(writejw):")')
write(*,'(" Fourier transformed total current J(ω) written to JTOTW.OUT")')
deallocate(w,wt,jt,f1,f2)
end subroutine

