!===============================================================================
!
! BQCD -- Berlin Quantum ChromoDynamics program
!
! Author: Hinnerk Stueben <stueben@zib.de>
!
! Copyright (C) 1998-2005, Hinnerk Stueben, Zuse-Institut Berlin
!
!-------------------------------------------------------------------------------
!
! reduction_shmem.F90 - reduction operations in shmem
!
!-------------------------------------------------------------------------------
# include "defs.h"
# include "shmem.h"

!-------------------------------------------------------------------------------
function global_sum(local_sum)
 
  implicit none
  include 'mpp/shmem.fh'

  REAL              :: global_sum, local_sum
  REAL, save        :: source, target
  integer           :: n_pes
  integer, external :: num_pes   
  REAL, save        :: pWrk(2 + shmem_reduce_min_wrkdata_size)
  integer, save     :: pSync(shmem_reduce_sync_size)


  TIMING_START(timing_bin_global_sum)

  n_pes = num_pes()

  if (n_pes == 1) then
     global_sum = local_sum
     return
  endif

  source = local_sum

  call shmem_real8_sum_to_all(target, source, 1, 0, 0, n_pes, pWrk, pSync)

  global_sum = target

  TIMING_STOP(timing_bin_global_sum)
end

!-------------------------------------------------------------------------------
function global_min(local_min)
 
  implicit none
  include 'mpp/shmem.fh'

  real              :: global_min, local_min
  real, save        :: source, target
  integer           :: n_pes
  integer, external :: num_pes   
  real, save        :: pWrk(2 + shmem_reduce_min_wrkdata_size)
  integer, save     :: pSync(shmem_reduce_sync_size)

  n_pes = num_pes()

  if (n_pes == 1) then
     global_min = local_min
     return
  endif

  source = local_min

  call shmem_real8_min_to_all(target, source, 1, 0, 0, n_pes, pWrk, pSync)

  global_min = target
end

!-------------------------------------------------------------------------------
function global_max(local_max)
 
  implicit none
  include 'mpp/shmem.fh'

  real              :: global_max, local_max
  real, save        :: source, target
  integer           :: n_pes
  integer, external :: num_pes   
  real, save        :: pWrk(2 + shmem_reduce_min_wrkdata_size)
  integer, save     :: pSync(shmem_reduce_sync_size)

  n_pes = num_pes()

  if (n_pes == 1) then
     global_max = local_max
     return
  endif

  source = local_max

  call shmem_real8_max_to_all(target, source, 1, 0, 0, n_pes, pWrk, pSync)

  global_max = target
end

!-------------------------------------------------------------------------------
subroutine global_sum_vec(n, sum)
 
  implicit none

  integer, intent(in)    :: n
  REAL,    intent(inout) :: sum(n)

  TIMING_START(timing_bin_global_sum_vec)

  call die("global_sum_vec(): shmem version not implemented yet.")

  TIMING_STOP(timing_bin_global_sum_vec)
end

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