#include<stdio.h>
#include <mpi.h>

int main(int argc, char *argv[])
{
  int num = 99; // message a faire circuler
  int rank, size, tag, prochain, avant;
  //MPI::Status status;
  MPI_Status status;

  // Debut 
  //MPI::Init(argc, argv);
  MPI_Init(argc, argv);
  
  // MPI::Comm_rank(MPI_COMM_WORLD,&rank);
  MPI_Comm_rank(MPI_COMM_WORLD,&rank);
  MPI_Comm_size(MPI_COMM_WORLD, &size);
 
  tag = 232; // tag aléatoire
  prochain = (rank + 1) % size; // mon voisin modulo taille (pourquoi?)
  avant = (rank + size - 1) % size; // celui qui m'envoie le message

  // c'est le processeur 0 qui commence tout
  if (rank == 0) {
    printf("Processeur %d envoie %d to %d\n", rank, num, prochain);
    MPI_Send(&num, 1, MPI_INT, prochain, tag, MPI_COMM_WORLD);
  }
  // et on se met en attente d'un message
  MPI_Recv(&num, 1, MPI_INT, avant, tag,MPI_COMM_WORLD, &status);
  printf("Processeur %d, recoit %d\n", rank, num);
  
  // tout le monde sauf le proc 0 attend, si on arrive a 0 on a fini
  if (rank == 0) {
      printf("Le tour a termine\n");
  }
  else 
    // on passe le message
    MPI_Send(&num, 1, MPI_INT, prochain, tag, MPI_COMM_WORLD);
  }

  // finalisation
  MPI_Finalize();
  return 0;
}
