!===============================================================================
!
! field_mpi.F90
!
!-------------------------------------------------------------------------------
!
! Copyright (C) 2016 Hinnerk Stueben
!
! This file is part of BQCD -- Berlin Quantum ChromoDynamics program
!
! BQCD is free software: you can redistribute it and/or modify
! it under the terms of the GNU General Public License as published by
! the Free Software Foundation, either version 3 of the License, or
! (at your option) any later version.
!
! BQCD is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
! GNU General Public License for more details.
!
! You should have received a copy of the GNU General Public License
! along with BQCD.  If not, see <http://www.gnu.org/licenses/>.
!
!-------------------------------------------------------------------------------
# include "defs.h"

!-------------------------------------------------------------------------------
module module_comm_field

  implicit none
  include 'mpif.h'
  integer, save :: comm_field  ! communicator for an (x,y)-plane
  integer :: ierr

end

!-------------------------------------------------------------------------------
subroutine comm_field_create(rank)

  use module_comm_field
  use module_lattice
  implicit none
  integer, intent(out) :: rank
  integer :: i_pe(DIM)
  integer :: colour, key
  integer, external :: ilex

  call my_coord(i_pe)

  key    = ilex(2, i_pe(1:2), npe(1:2))
  colour = ilex(2, i_pe(3:4), npe(3:4))

  call mpi_comm_split(MPI_COMM_WORLD, colour, key, comm_field, ierr)

  call mpi_comm_rank(comm_field, rank, ierr)

  CHECK(rank == key)

  if (rank == 0) then
     CHECK(i_pe(1) == 0)
     CHECK(i_pe(2) == 0)
  endif

  if (i_pe(1) == 0 .and. i_pe(2) == 0) then
     CHECK(rank == 0)
  endif

end

!-------------------------------------------------------------------------------
subroutine comm_field_broadcast_i4(i, n)

  use module_comm_field
  implicit none
  integer, intent(in)       :: n
  integer(4), intent(inout) :: i(n)

  call mpi_bcast(i, n, MPI_INTEGER4, 0, comm_field, ierr)
end

!-------------------------------------------------------------------------------
subroutine comm_field_free()

  use module_comm_field
  implicit none

  call mpi_comm_free(comm_field, ierr)
end

!===============================================================================
