      program alltoall
      implicit none
      include "mpif.h"

      integer ierror, rank, size

      integer nrecvd, sum, i, index
      logical flag
      integer, dimension(MPI_STATUS_SIZE,13) :: send_status, recv_status
C      integer request(0:12), in(0:12), out(0:12)
      integer request(13), in(13), out(13)  
      call MPI_Init(ierror)

      call MPI_Comm_rank(MPI_COMM_WORLD, rank, ierror)
      call MPI_Comm_size(MPI_COMM_WORLD, size, ierror)

      if (size .gt. 13) goto 999
      do i = 0, size-1
         out(i+1) = rank+i
         call MPI_Isend(out(i+1), 1, MPI_INTEGER, i, 7, MPI_COMM_WORLD,
     .              request(i+1), ierror)
C	 call MPI_Send(rank+i, 1, MPI_INTEGER, i, 7, MPI_COMM_WORLD,
C     .  	    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

C --- Another possible solution
C      do i = 0, size-1
C         call MPI_WAIT(request(i+1),send_status(1,i+1), ierror)
C      enddo

      write(*, '("PE",i3,": in = ",12i4)') rank, in(0:size-1)
999   call MPI_Finalize(ierror)

      stop
      end 
