
! Copyright (C) 2018 A. Davydov, J. K. Dewhurst, S. Sharma and E. K. U. Gross.
! This file is distributed under the terms of the GNU General Public License.
! See the file COPYING for license details.

!BOP
! !ROUTINE: gtwsum
! !INTERFACE:
pure complex(8) function gtwsum(gf,gl)
! !USES:
use modmain
use modgw
! !INPUT/OUTPUT PARAMETERS:
!   gf : first point of the Green's function (in,complex)
!   gl : last point of the Green's function (in,complex)
! !DESCRIPTION:
!   Sums the tails of the Green's function over the Matsubara frequencies as
!   part of the evaluation of the density matrix. Thus if the Green's function
!   $G(ij{\bf k},\omega_n)$ has been determined numerically over all Fermionic
!   Matsubara frequencies up to $\pm \omega_{n_{\rm max}}$, then the density
!   matrix is approximated by
!   $$ \gamma_{ij{\bf k}}=\frac{1}{\beta}\sum_{n\;{\rm odd}}^{\pm n_{\rm max}}
!    \left[G(ij{\bf k},\omega_n)+\frac{a_2}{\omega_n^2}\right]
!    +\frac{1}{2}a_1-\frac{\beta}{4}a_2, $$
!   where $a_1$ and $a_2$ are chosen so that the Green's function is equal to
!   $$ g(z)=\frac{a_1}{z}+\frac{a_2}{z^2} $$
!   at the first and last points $z=\pm i\omega_{n_{\rm max}}$.
!
! !REVISION HISTORY:
!   Created April 2018 (A. Davydov)
!EOP
!BOC
implicit none
! arguments
complex(8), intent(in) :: gf,gl
! local variables
integer iw
real(8) b,sm
complex(8) a1,a2,z1
z1=wfm(0)
a1=0.5d0*(gf-gl)*z1
a2=0.5d0*(gf+gl)*z1**2
b=1.d0/(kboltz*tempk)
gtwsum=b*(0.5d0*a1-0.25d0*b*a2)
sm=0.d0
!$OMP SIMD REDUCTION(+:sm) SIMDLEN(8)
do iw=0,nwfm
  sm=sm+1.d0/aimag(wfm(iw))**2
end do
gtwsum=gtwsum+sm*a2
end function
!EOC
