      program alltoall
      implicit none
      include "mpif.h"

      integer ierror, rank, size

      integer nrecvd, sum, i, index
      logical flag
      integer, dimension(MPI_STATUS_SIZE) :: send_status, recv_status
      integer request(0:9), in(0:9)
  
      call MPI_Init(ierror)
  
      call MPI_Comm_rank(MPI_COMM_WORLD, rank, ierror)
      call MPI_Comm_size(MPI_COMM_WORLD, size, ierror)
      
  
      do i = 0, size-1
         call MPI_Isend(rank+i, 1, MPI_INTEGER, i, 7, MPI_COMM_WORLD,
     .              request(i), ierror)
      enddo
    
      do i = 0, size-1
         call MPI_Recv(in(i), 1, MPI_INTEGER, i, 7, MPI_COMM_WORLD, 
     .              recv_status, ierror)
      enddo
    
      nrecvd = 0
      do while( nrecvd < size)
         flag = .false.
         call MPI_Testany(size, request, index, flag,send_status,ierror)
     
         if(flag) then
            nrecvd = nrecvd+1
            write(*,'( i2," finished sending to "i2)') rank, index-1
         else
            write(*,'(i2," waiting ...")') rank
         endif
      enddo
  
      write(*, '("PE",i1,": in = ",10i4)') rank, in(0:size-1)
  
      call MPI_Finalize(ierror)

      stop
      end 

