!======================================================================================
!
! Routines:
!
! (1) write_eigenvectors()      Originally By MLT       Last Modified 6/6/2008 (JRD)
!
! Sohrab Ismail-Beigi:  May 4, 2001
!
! This routine is called when we want to write eigenvectors of the BSE
! equations to file (i.e. the eigenvectors coefficients).  It will open
! a file called eigenvectors and write to it.
!
!=====================================================================================

#include "f_defs.h"

subroutine write_eigenvectors(xct,kg,nblock,pblock,neig,egv,egs,nwrite)

  use global_m
  implicit none

  type(xctinfo), intent(in) :: xct
  type(grid), intent(in) :: kg
  integer, intent(in) :: nblock,pblock,neig
  real(DP), intent(in) :: egv(neig)
  SCALAR, intent(in) :: egs(xct%nkpt_fi*nblock,pblock)
  integer, intent(inout) :: nwrite

  integer :: ieig,nmat,ii,jj,kk,peadd
  SCALAR, allocatable :: A(:)
  logical :: io

  PUSH_SUB(write_eigenvectors)

! Who can do io?

  if (peinf%inode.eq.0) then
    io = .true.
  else
    io = .false.
  endif

  if (nwrite.lt.0) nwrite=neig

! Get space for the A coeffs

  nmat = xct%nkpt_fi*nblock
  SAFE_ALLOCATE(A, (nmat))

! Open the file we will write to and write header information

  if (io) then
    write(6,*)
    write(6,*) 'Writing ',nwrite, ' eigenvectors to file "eigenvectors"'
    write(6,*) 'length of vectors = ',nmat
    write(6,*)
    call open_file(unit=200,file='eigenvectors',form='unformatted',status='replace')
!           rewind(200)
    write(200) xct%nspin
    write(200) xct%nvb_fi
    write(200) xct%ncb_fi
    write(200) xct%nkpt_fi
    write(200) ((kg%f(jj,kk),jj=1,3),kk=1,xct%nkpt_fi)
  endif

! Loop over states to be written

  do ieig=1,nwrite

! Figure out which processor (peadd) and column
! state ieig belongs to

    peadd_loop: do peadd=1,peinf%npes
      do jj=1,peinf%neig(peadd)
        if (peinf%peig(peadd,jj).eq.ieig) then

! Get the coeffs for state ieig into A (on all processors)
          if (peinf%inode+1.eq.peadd) then
            A(:) = egs(:,jj)
          endif
#ifdef MPI
          call MPI_BCAST(A,nmat,MPI_SCALAR,peadd-1,MPI_COMM_WORLD,mpierr)
#endif

! Write to file

          if (io) then
#ifdef VERBOSE
            write(6,*) 'Writing state',ieig,' energy=',egv(ieig)
#endif
            write(200) egv(ieig)
            write(200) (A(ii),ii=1,nmat)
          endif
        endif
      enddo
    enddo peadd_loop

  enddo ! of loop over states (ieig)
  
  if (io) call close_file(200)
  SAFE_DEALLOCATE(A)
  
  POP_SUB(write_eigenvectors)
  
  return
  
end subroutine write_eigenvectors
