program ringtopo 

include 'mpif.h' 
integer numtasks, rank, next, prev, buf(2), tag1, tag2, ierr 

integer stats(MPI_STATUS_SIZE,4), reqs(4) 
tag1 = 1; tag2 = 2 

call MPI_INIT(ierr) 
call MPI_COMM_RANK(MPI_COMM_WORLD, rank, ierr) 
call MPI_COMM_SIZE(MPI_COMM_WORLD, numtasks, ierr) 

prev = rank - 1; next = rank + 1
if (rank == 0) prev = numtasks - 1 
if (rank == numtasks - 1)  next = 0
 
call MPI_IRECV(buf(1), 1, MPI_INTEGER, prev, tag1, MPI_COMM_WORLD, reqs(1), ierr) 
call MPI_IRECV(buf(2), 1, MPI_INTEGER, next, tag2,  MPI_COMM_WORLD, reqs(2), ierr) 
call MPI_ISEND(rank, 1, MPI_INTEGER, prev, tag2,  MPI_COMM_WORLD, reqs(3), ierr) 
call MPI_ISEND(rank, 1, MPI_INTEGER, next, tag1,  MPI_COMM_WORLD, reqs(4), ierr) 


! do some work


call MPI_WAITALL(4, reqs, stats, ierr)
call MPI_FINALIZE(ierr) 

stop
end 
