
! Copyright (C) 2024 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 writew90amn
use modmain
use modw90
use modrandom
use modomp
implicit none
! local variables
integer ik,ist,i,nthd
real(8) a,b
character(256) fname
! allocatable arrays
complex(8), allocatable :: amn(:,:,:)
! automatically generate the projections from the wavefunctions if required
if (projw90) then
  allocate(amn(num_bands,num_wann,nkptnr))
  call holdthd(nkptnr,nthd)
!$OMP PARALLEL DO DEFAULT(SHARED) &
!$OMP SCHEDULE(DYNAMIC) &
!$OMP NUM_THREADS(nthd)
  do ik=1,nkptnr
    call projkw90(ik,amn(:,:,ik))
  end do
!$OMP END PARALLEL DO
  call freethd(nthd)
end if
! write the projections to file
fname=trim(seedname)//'.amn'
open(50,file=trim(fname),action='WRITE',form='FORMATTED')
write(50,'("Generated by Elk version ",I0,".",I0,".",I0)') version
write(50,'(3I6)') num_bands,nkptnr,num_wann
do ik=1,nkptnr
  do i=1,num_wann
    do ist=1,num_bands
      if (projw90) then
! calculated projections
        a=amn(ist,i,ik)%re
        b=amn(ist,i,ik)%im
      else
! random projections
        a=0.5d0-randomu()
        b=0.5d0-randomu()
      end if
      write(50,'(3I8,2G18.10)') ist,i,ik,a,b
    end do
  end do
end do
close(50)
write(*,*)
write(*,'("Info(writew90amn): created file ",A)') trim(fname)
if (projw90) deallocate(amn)
end subroutine

