/* A first simple MPMD example program using MPI.                 */
/* This is the same program as in code3.c, but it uses a MPMD     */
/* programming style.                                             */

/* The program consists of on receiver process, in the file       */
/* code5.c, and N-1 sender processes described in the file        */
/* code4.c. The sender processes send a message consisting        */
/* of their process identifier (id) and the total number of       */
/* processes (ntasks) to the receiver. The receiver process       */
/* prints out the values it receives in the messeges from the     */
/* senders.                                                       */

/* Compile the programs with 'mpicc -o code4 code4.c' and         */
/* 'mpicc -o code5 code5.c'                                       */
/* To run the program, using four computers you have to build a   */
/* procgroup file describing the placement of the tasks to        */
/* processors. An example of a procgroup file can be found in     */
/* the file named 'procgrp'. This assumes that you are logged in  */
/* to the machine tiny.cankaya.edu.tr and place the receiver      */
/* process on this machine.  To run the program do                */
/* 'mpirun -p4pg procgrp code5'                                   */

#include <stdio.h>
#include <mpi.h>
#include "code4-5defs.h"                   /* Common declarations */

main(int argc, char *argv[])
{
  int id, ntasks, source_id, dest_id, err, i;
  MPI_Status status;
  int msg[2];			/* Message array */
  
  err = MPI_Init(&argc, &argv);	/* Initialize MPI */
  if (err != MPI_SUCCESS) {
    printf("MPI initialization failed!\n");
    exit(1);
  }
  err = MPI_Comm_size(MPI_COMM_WORLD, &ntasks);	/* Get nr of tasks */
  err = MPI_Comm_rank(MPI_COMM_WORLD, &id);	/* Get id of this process */
  if (ntasks < 2) {
    printf("You have to use at least 2 processors to run this program\n");
    MPI_Finalize();		   /* Quit if there is only one processor */
    exit(0);
  }
  
  printf("Sender process has id %d\n", id);
  for (i=1; i<ntasks; i++) {
    err = MPI_Recv(msg, 2, MPI_INT, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, \
		   &status);          /* Receive a message */
    source_id = status.MPI_SOURCE;	/* Get id of sender */
    printf("Received message %d %d from sender process %d\n", msg[0], msg[1], \
	   source_id);
  }
  
  err = MPI_Finalize();	         /* Terminate MPI */
  if (id==0) printf("Ready\n");
  exit(0);
}

