module kmap_mod
  !! K-domain mapping

  use down_mod
  use external_mod
  use type_mod
  !---------------
  implicit none
  integer, private, save :: nhx_use,nhy_use

  !! !!!!!!!!!!!!!!!!!!!!!!!!!!!!
  type(tkmap), public :: kmap
  !! !!!!!!!!!!!!!!!!!!!!!!!!!!!!

contains
  !----------------------------------------------------------------
  subroutine kmap_init()
    integer :: imx,imy,er
    real :: a

    allocate(kmap%kx(down%amx%n),stat=er)
    if(er/=0) call seperr('cant allocate kx')
    call klinemap(kmap%kx,down%amx%n,down%amx%d,0)

    allocate(kmap%ky(down%amy%n),stat=er)
    if(er/=0) call seperr('cant allocate ky')
    call klinemap(kmap%ky,down%amy%n,down%amy%d,0)

    call kmap_report()
    a=4*size(kmap%kx)+4*size(kmap%ky)
    down%mem=down%mem+a

  end subroutine kmap_init
!----------------------------------------------------------------
  subroutine kmap_report()
    if (run%verb.lt.4) return
    write(run%io,*)'        ************************************************'
    write(run%io,*)"        *  Wavenumber report"
    write(run%io,*)'        *                [n]      [o]       [d]'
    write(run%io,'(a,i4,2f11.6)')"         *            kx:",size(kmap%kx),kmap%kx(1),kmap%kx(2)-kmap%kx(1)
    if (size(kmap%ky) .gt. 1) then
       write(run%io,'(a,i4,2f11.6)')"         *            ky:",size(kmap%ky),kmap%ky(1),kmap%ky(2)-kmap%ky(1)
    end if
    write(run%io,*)'        ************************************************'
  end subroutine kmap_report
!----------------------------------------------------------------
  subroutine klinemap(k,n,d,shift)
    real, dimension(:) :: k
    integer, intent(in) :: n,shift
    real,    intent(in) :: d
    integer             :: i,m

    k=0.
    if(n/=1) then
       m = n/2
       do i=1,m+1
          k(i+shift)=i-1
       end do
       do i=m+2,n
          k(i+shift)=i-n-1
       end do
    else
       k=0. !! make sure k=0 if n=1
    end if

    k = k / (n*d)      !! 1/length
    k = 2 * pi * k !! radians

  end subroutine klinemap
  !----------------------------------------------------------------
end module kmap_mod
