
! Copyright (C) 2015 Manh Duc Le, 2017-18 Arsenii Gerasimov, Yaroslav Kvashnin
! and Lars Nordstrom. This file is distributed under the terms of the GNU
! General Public License. See the file COPYING for license details.

subroutine writew90spn
use modmain
use modw90
implicit none
! local variables
integer ik,ist,jst,i,j
complex(8) z1
character(256) fname
! allocatable arrays
complex(8), allocatable :: evecsv(:,:),smat(:,:,:,:)
if (.not.spinpol) return
fname=trim(seedname)//'.spn'
open(50,file=trim(fname),action='WRITE',form='FORMATTED')
write(50,'("Generated by Elk version ",I0,".",I0,".",I0)') version
write(50,'(3I8)') num_bands,nkptnr
allocate(evecsv(nstsv,nstsv),smat(nstsv,nstsv,2,2))
do ik=1,nkptnr
! generate the spin operator matrix elements
! (note that smat is *not* a density matrix)
  call getevecsv(filext,0,vkl(:,ik),evecsv)
  call gensmatk(evecsv,smat)
  do j=1,num_bands
    jst=idxw90(j)
    do i=1,j
      ist=idxw90(i)
      z1=smat(ist,jst,1,2)+smat(ist,jst,2,1)
      write(50,'(2G18.10)') z1
      z1=smat(ist,jst,1,2)-smat(ist,jst,2,1)
      z1=cmplx(z1%im,-z1%re,8)
      write(50,'(2G18.10)') z1
      z1=smat(ist,jst,1,1)-smat(ist,jst,2,2)
      write(50,'(2G18.10)') z1
    end do
  end do
end do
deallocate(evecsv,smat)
close(50)
write(*,*)
write(*,'("Info(writew90spn): created file ",A)') trim(fname)
end subroutine

