!-------------------------------------------------------
! Multiple Program Multiple Data Test Program
!   Test1 : Rank0(Random number generation,Send->Recv data)
!-------------------------------------------------------
      program teat1
      use mpi
c
      integer ierr,nprocs,myrank,icolor,key
      integer nprocs2,myrank2
      integer i,n,n2,istat
      integer STATUS(MPI_STATUS_SIZE)
      real(8),allocatable :: a(:),b(:)

      call MPI_Init(ierr)
      call MPI_Comm_Size(MPI_COMM_WORLD,nprocs,ierr)
      call MPI_Comm_Rank(MPI_COMM_WORLD,myrank,ierr)
      n = 8192
      n2= n/(nprocs-1)
c
      if(myrank.eq.0) then
        icolor = 0
        key = 0
      else
        do i = 1,nprocs-1
          icolor = 1
          key = i - 1
        enddo
      endif
      call MPI_Comm_Split(MPI_COMM_WORLD,icolor,key,MPI_COMM2,ierr)
      call MPI_Comm_Size(MPI_COMM2,nprocs2,ierr)
      call MPI_Comm_Rank(MPI_COMM2,myrank2,ierr)
c
      if(myrank.eq.0) then
        allocate(a(n))
        call random_number(a)
        do i = 1, nprocs-1
          call MPI_Send(a(n2*(i-1)+1:n2*i),n2,MPI_REAL8,i,1,
     +                  MPI_COMM_WORLD,ierr)
        enddo
        allocate(b(n))
        do i = 1, nprocs-1
          call MPI_Recv(b(n2*(i-1)+1:n2*i),n2,MPI_REAL8,i,2,
     +                  MPI_COMM_WORLD,STATUS,ierr)
        enddo
c --- Check
        istat=0
        do i=1,n
          if(a(i).ne.b(i)/2.0d0) istat=1
        enddo
        if(istat.eq.0) then
          write(6,*)"MPI communication was successful."
        else
          write(6,*)"MPI communication failed."
        endif
        deallocate(a,b)
      endif
c
      call MPI_Finalize(ierr)
      stop
      end
