module wei_xmap
  !! X-domain mapping

  use wei_process
  use wei_type
  !---------------
  implicit none

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

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

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

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

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

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

    !! sx,rx
    allocate(xmap%sx(pro%amx%n,pro%ahx%n),stat=er)
    if(er/=0) call seperr('cant allocate sx')
    allocate(xmap%rx(pro%amx%n,pro%ahx%n),stat=er)
    if(er/=0) call seperr('cant allocate rx')
    do ihx=1,pro%ahx%n
       do imx=1,pro%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
    allocate(xmap%sy(pro%amy%n,pro%ahy%n),stat=er)
    if(er/=0) call seperr('cant allocate sy')
    allocate(xmap%ry(pro%amy%n,pro%ahy%n),stat=er)
    if(er/=0) call seperr('cant allocate ry')
    do ihy=1,pro%ahy%n
       do imy=1,pro%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(pro%debug) call out(unit)
#endif
  end subroutine weixmap_init
  !----------------------------------------------------------------
end module wei_xmap
