!**********************************************************************
program mpitest2

  use mpi

  integer n(4), myid, numprocs, i, rc, status(MPI_STATUS_SIZE)
  integer iroot, temp, temp1, ierr
 
  call MPI_INIT( ierr )
  call MPI_COMM_RANK( MPI_COMM_WORLD, myid, ierr )
  call MPI_COMM_SIZE( MPI_COMM_WORLD, numprocs, ierr )
  write(*,*) 'Process ', myid, ' of ', numprocs, ' is alive'
  
  iroot = 0
! initialize small array of values to 2, 4, 6, 8
  do i=1,4
     n(i) = 2*i
  end do
  
! root process sends first two values to process 1 and second two to process 2
  if ( myid == iroot) then    
     call MPI_SEND(N,2,MPI_INTEGER,1,0,MPI_COMM_WORLD,ierr)
     call MPI_SEND(N(3),2,MPI_INTEGER,2,0,MPI_COMM_WORLD,ierr)
     temp = 20
! root process receives added values of "temp" from other processes
     call MPI_REDUCE(temp,temp1,1,MPI_INTEGER,MPI_SUM,0,MPI_COMM_WORLD,ierr)
     write(*,*) 'Process ', myid, ' adding what it received'
     write(*,*) 'answer in ',myid,' is ',temp1
  else if (myid == 1) then
! process 1 receives first two values, adds, and allows sum to be reduced     
     call MPI_RECV(N,2,MPI_INTEGER,0,0,MPI_COMM_WORLD,status,ierr)
     temp = n(1)+n(2)
     call MPI_REDUCE(temp,temp1,1,MPI_INTEGER,MPI_SUM,0,MPI_COMM_WORLD,ierr)
     write(*,*) 'Process ', myid, ' adding what it received'
     write(*,*) 'answer in ',myid,' is ',temp
  else
! process 2 receives second two values, adds, and allows sum to be reduced     
     call MPI_RECV(N(3),2,MPI_INTEGER,0,0,MPI_COMM_WORLD,status,ierr)
     temp = n(3)+n(4)
     call MPI_REDUCE(temp,temp1,1,MPI_INTEGER,MPI_SUM,0,MPI_COMM_WORLD,ierr)
     write(*,*) 'Process ', myid, ' adding what it received'
     write(*,*) 'answer in ',myid,' is ',temp
  end if

  write(*,*) 'Process ', myid,' finishing work.'
  
  call MPI_FINALIZE(rc)
  stop
end program mpitest2





