/*----------------------------------------------------------------*/
/* This file can be saved to your machine (almost) as you see it  */
/* by doing a "Save As..." from the File menu of your browser.    */
/*                                                                */
/* For this to work, you must TYPE a filename with .txt as the    */
/* file extent.  (Simply selecting .txt as the file type          */
/* doesn't seem to be sufficient.)  Remove the .txt extension     */
/* once the file is saved.  (IE inserts the page title as the     */
/* first line, which must be removed also.)                       */
/*----------------------------------------------------------------*/

#include <stdio.h>
#include <mpi.h>
#include <string.h>
main(int argc, char *argv[]){
    int i,myid, np, ierr,lnbr, rnbr,place;
    char sbuff[10],rbuff[10],store[4][10];
    MPI_Status status;
    ierr=MPI_Init(&argc, &argv);

    if (ierr != MPI_SUCCESS) {
        fprintf(stderr,"MPI init error");
        exit(1);
    }
    MPI_Comm_size(MPI_COMM_WORLD, &np);
    MPI_Comm_rank(MPI_COMM_WORLD, &myid);
    switch ( myid) {
    case 0: strcpy(sbuff,"con");break;
    case 1: strcpy(sbuff,"cat");break;
    case 2: strcpy(sbuff,"tin");break;
    case 3:strcpy(sbuff,"ate");break;
    }

    lnbr = (myid+np-1)%np;
    rnbr = (myid+1)%np;
    place=myid;
    strcpy(store[place],sbuff);
    for (i=0;i<np-1;i++) {
        MPI_Send(sbuff,4,MPI_CHAR,rnbr,0,MPI_COMM_WORLD);
        MPI_Recv(rbuff,4,MPI_CHAR,lnbr,0,MPI_COMM_WORLD,&status);
        place=(place+np-1)%np;
        strcpy(sbuff,rbuff);
        strcpy(store[place],sbuff);
    }
    for (i=1;i<np;i++)strcat(store[0],store[i]);
    printf("-------------------\nmy id is %i\nThe string is %s\n",myid,store[0]);

    MPI_Finalize();
}