PROGRAM Reduce
!--------------------------------------------------------------------------------
! Parallel sum.
! An instance of MPI reduction functions working with a binary tree decomposition.
! Remark: for optimal usage, the number elements to sum should be a 
! multiple of the number of elements
!--------------------------------------------------------------------------------

IMPLICIT NONE
INCLUDE "mpif.h"
INTEGER:: err, myid, nproc

INTEGER,PARAMETER:: N=4     ! N elements per processor
INTEGER:: i, root
REAL,DIMENSION(N):: a, s

CALL MPI_INIT (err)
CALL MPI_COMM_SIZE (MPI_COMM_WORLD, nproc, err)
CALL MPI_COMM_RANK (MPI_COMM_WORLD, myid, err)

a = (/ (myid*N+i, i=1,N) /)  ! Generate the data in every processor
WRITE(*,*) "process", myid, " has:", a

root = 0
CALL MPI_REDUCE (a, s, N, MPI_REAL, & ! S/D buff., count, type
                 MPI_SUM, root,     & ! Operation, destination node
	         MPI_COMM_WORLD, err)

IF (myid==root) WRITE(*,*) "The sum is", s

CALL MPI_FINALIZE (err)
END PROGRAM Reduce

