module wei_xmap
  !! X-domain mapping

  use wei_pro
  use wei_type
  !---------------
  implicit none

  !! !!!!!!!!!!!!!!!!!!!!!!!!!!!!
  type(wexmap), public :: xmap
  !! !!!!!!!!!!!!!!!!!!!!!!!!!!!!

contains
  !----------------------------------------------------------------
  subroutine weixmap_init()
    integer :: imx,imy,ihx,ihy
    integer :: er
    character(len=128), parameter :: unit='weixmap_init'
#ifdef DEBUG
    if(wpro%dbg>0) call in(unit)
#endif

    !! mx
    call weimem_add(4,wpro%amx%n,unit)
    allocate(xmap%mx( wpro%amx%n),stat=er)
    if(er/=0) call seperr('cant allocate mx')
    do imx=1,wpro%amx%n
       xmap%mx(imx) = wpro%amx%o + (imx-1)* wpro%amx%d
    end do

    !! my
    call weimem_add(4,wpro%amy%n,unit)
    allocate(xmap%my( wpro%amy%n),stat=er)
    if(er/=0) call seperr('cant allocate my')
    do imy=1,wpro%amy%n
       xmap%my(imy) = wpro%amy%o + (imy-1)* wpro%amy%d
    end do

    !! hx
    call weimem_add(4,wpro%ahx%n,unit)
    allocate(xmap%hx( wpro%ahx%n),stat=er)
    if(er/=0) call seperr('cant allocate hx')
    do ihx=1,wpro%ahx%n
       xmap%hx(ihx) = wpro%ahx%o + (ihx-1)* wpro%ahx%d
    end do

    !! hy
    call weimem_add(4,wpro%ahy%n,unit)
    allocate(xmap%hy( wpro%ahy%n),stat=er)
    if(er/=0) call seperr('cant allocate hy')
    do ihy=1,wpro%ahy%n
       xmap%hy(ihy) = wpro%ahy%o + (ihy-1)* wpro%ahy%d
    end do

    !! sx,rx
    call weimem_add(4,wpro%amx%n*wpro%ahx%n,unit)
    allocate(xmap%sx( wpro%amx%n,wpro%ahx%n),stat=er)
    if(er/=0) call seperr('cant allocate sx')
    
    call weimem_add(4,wpro%amx%n*wpro%ahx%n,unit)
    allocate(xmap%rx( wpro%amx%n,wpro%ahx%n),stat=er)
    if(er/=0) call seperr('cant allocate rx')

    do ihx=1,wpro%ahx%n
       do imx=1,wpro%amx%n
          xmap%sx(imx,ihx) = xmap%mx(imx) - xmap%hx(ihx)
          xmap%rx(imx,ihx) = xmap%mx(imx) + xmap%hx(ihx)
       end do
    end do

    !! sy,ry
    call weimem_add(4,wpro%amy%n*wpro%ahy%n,unit)
    allocate(xmap%sy( wpro%amy%n,wpro%ahy%n),stat=er)
    if(er/=0) call seperr('cant allocate sy')

    call weimem_add(4,wpro%amy%n*wpro%ahy%n,unit)
    allocate(xmap%ry( wpro%amy%n,wpro%ahy%n),stat=er)
    if(er/=0) call seperr('cant allocate ry')

    do ihy=1,wpro%ahy%n
       do imy=1,wpro%amy%n
          xmap%sy(imy,ihy) = xmap%my(imy) - xmap%hy(ihy)
          xmap%ry(imy,ihy) = xmap%my(imy) + xmap%hy(ihy)
       end do
    end do

#ifdef DEBUG
    if(wpro%dbg>0) call out(unit)
#endif
  end subroutine weixmap_init
  !----------------------------------------------------------------
end module wei_xmap









