
! 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 :: smat(:,:,:,:)
if (.not.spinpol) return
fname=trim(seedname)//'.spn'
open(50,file=trim(fname),action='WRITE',form='FORMATTED')
write(50,'("Generated by Elk version ",I1.1,".",I1.1,".",I2.2)') version
write(50,'(3I8)') num_bands,nkptnr
allocate(smat(2,2,nstsv,nstsv))
do ik=1,nkptnr
! generate the spin operator matrix elements
  call gensmatk(vkl(:,ik),smat)
  do j=1,num_bands
    jst=idxw90(j)
    do i=1,j
      ist=idxw90(i)
      z1=smat(1,2,ist,jst)+smat(2,1,ist,jst)
      write(50,'(2G18.10)') z1
      z1=smat(2,1,ist,jst)-smat(1,2,ist,jst)
      z1=cmplx(-aimag(z1),dble(z1),8)
      write(50,'(2G18.10)') z1
      z1=smat(1,1,ist,jst)-smat(2,2,ist,jst)
      write(50,'(2G18.10)') z1
    end do
  end do
end do
deallocate(smat)
close(50)
write(*,*)
write(*,'("Info(writew90spn): created file ",A)') trim(fname)
end subroutine

