/* Automata */

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

int myid, numprocs;


void parwrite(char c)
/* write values from all processors */
{ char allval[100]; /* max 100 processes */
  int i;

  MPI_Gather(&c, 1, MPI_CHAR, allval, 1, MPI_CHAR, 0, MPI_COMM_WORLD);

  if (myid == 0)
  {  for (i=0; i<numprocs; i++) printf("%c", allval[i]);
     printf("\n");
  }
}



int main(int argc, char *argv[])
{   int l;
    char c, right, left;
    bool val;
    MPI_Status mstatus;

    MPI_Init(&argc,&argv);
    MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD,&myid);
		
    val = (myid == numprocs/2);			
    if (val) c='X'; else c=' ';

    for (l=0; l< numprocs/2; l++)
    { parwrite(c);
      /* data exchange to the right */
      if (myid<numprocs-1) MPI_Send(&c, 1, MPI_CHAR, myid+1, 0, MPI_COMM_WORLD);
      if (myid>0)          MPI_Recv(&left, 1, MPI_CHAR, myid-1, 0, MPI_COMM_WORLD, &mstatus);
        else left=' ';

      /* data exchange to the left */
      if (myid>0)          MPI_Send(&c, 1, MPI_CHAR, myid-1, 0, MPI_COMM_WORLD);
      if (myid<numprocs-1) MPI_Recv(&right, 1, MPI_CHAR, myid+1, 0, MPI_COMM_WORLD, &mstatus);
        else right=' ';

      val = (left != right);			
      if (val) c='X'; else c=' ';
    }

    MPI_Finalize();
    return 0;
}
