/* depends on buffering */
/* Under most MPI implementations, the  program  shown  will
 * run to completion. However,  if  the  message  sizes  are 
 * increased, sooner or later  the  program  will  deadlock. 
 * This behavior is sometimes seen in computational codes -- 
 * a code will run to completion when given a small problem, 
 * but  deadlock  when  given  a  large  problem.  This   is 
 * inconvenient  and  undesirable.  The   inconvenience   is 
 * increased when the original authors of the  code  are  no 
 * longer available to maintain it. 
 *
 * In general, depending on MPI  internal  buffer  to  avoid  
 * deadlock makes a program less portable and less scalable. 
 * The best practice  is  to  write  programs  that  run  to 
 * completion regardless of the availability of MPI internal 
 * buffer.
 * */
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

int main (int argc, char **argv) {

   int i,myrank,
       count=1,
       nproc;
   MPI_Status status;
   double *a, *b;

   MPI_Init(&argc, &argv);  /* Initialize MPI */
   MPI_Comm_rank(MPI_COMM_WORLD, &myrank); /* Get rank */
   MPI_Comm_size(MPI_COMM_WORLD, &nproc );

   if ( nproc != 2 ) {
        fprintf(stderr,"ERROR: Number of processors MUST BE 2!\n");
        MPI_Abort(MPI_COMM_WORLD, 99);
   }
   for (i=0; i<argc; i++){
        if (argv[i][0] == '-'){
            if (argv[i][1] == 'c')
                count=atoi(argv[++i]);
        }
   }
   a=(double *)malloc(sizeof(double)*count);
   b=(double *)malloc(sizeof(double)*count);

   if( myrank == 0 ) {
     /* Send a message, then receive one */
     MPI_Send( a, count, MPI_DOUBLE, 1, 17, MPI_COMM_WORLD );
     fprintf(stdout,"Rank (%d): Send \n",myrank);
     MPI_Recv( b, count, MPI_DOUBLE, 1, 19, MPI_COMM_WORLD, &status );
     fprintf(stdout,"Rank (%d): Received \n",myrank);
   }
   else if( myrank == 1 ) {
     /* Send a message, then receive one */
     MPI_Send( a, count, MPI_DOUBLE, 0, 19, MPI_COMM_WORLD );
     fprintf(stdout,"Rank (%d): Send \n",myrank);
     MPI_Recv( b, count, MPI_DOUBLE, 0, 17, MPI_COMM_WORLD, &status );   
     fprintf(stdout,"Rank (%d): Received \n",myrank);
   }

   MPI_Finalize();          /* Terminate MPI */
   
}
