/*
** Send a token around a ring
** Copyright Rolf Riesen 2008
** 
** 
*/
#include <stdio.h>
#include <unistd.h>	/* For sleep() */
#include <mpi.h>



int
main(int argc, char *argv[])
{

int my_rank, nproc;
int i;
int token;
int tag;
int rounds;
int left, right;
MPI_Status status;


    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &nproc);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

    /* Initialize some variables */
    token= 0;
    tag= 0;
    rounds= 2;

    right= (my_rank + 1) % nproc;
    left= (my_rank - 1 + nproc) % nproc;


    /* Rank 0 starts the token */
    if (my_rank == 0)   {
	MPI_Send(&token, 1, MPI_INT, right, tag, MPI_COMM_WORLD);
    }

    for (i= 0; i < rounds; i++)   {
	MPI_Recv(&token, 1, MPI_INT, left, tag,
	    MPI_COMM_WORLD, &status);
	printf("Rank %3d: received token %2d from rank %3d.\n",
	    my_rank, token, left);

	token= token + 1;
	sleep(1);

	if ((my_rank != 0) || (i < (rounds - 1)))   {
	    /*
	    ** Only send it on if we are not rank 0,
	    ** or there are more rounds to go.
	    **/
	    MPI_Send(&token, 1, MPI_INT, right, tag,
		MPI_COMM_WORLD);
	}
    }

    MPI_Finalize();
    return 0;

}  /* end of main() */
