#include <stdio.h>
#include <mpi.h>

main(int argc, char* argv[]) {

    MPI_Comm GlobalComm, LocComm, InterComm;
    MPI_Status stat;
    int colour, numproc, id, lid, root, idinter, flag, np;

    int val, lsum, gsum;

    MPI_Init(&argc, &argv);
    MPI_Comm_dup(MPI_COMM_WORLD,&GlobalComm);
    MPI_Comm_size(GlobalComm, &numproc);
    MPI_Comm_rank(GlobalComm, &id);

    /* Divide processes in 2 groups */
    colour = id % 2;

    MPI_Comm_split(GlobalComm, colour, id, &LocComm);
    MPI_Comm_rank(LocComm, &lid);

    printf("Process %d in global comm is process %d in local comm\n",id,lid);

    /* Generate inter communicator between 2 leaders */
    if ( colour == 0 ) {
       MPI_Intercomm_create(LocComm, 0, GlobalComm, 1, 01, &InterComm);
    } else {
       MPI_Intercomm_create(LocComm, 0, GlobalComm, 0, 01, &InterComm);
    }
	if ( lid == 0 ) {
		fprintf(stdout,"Check if InterComm is an inter-communicator: ");
       MPI_Comm_test_inter(InterComm, &flag);
       fprintf(stdout,"flag = %d\n",flag);
		fprintf(stdout,"Check if LocComm is an inter-communicator: ");
       MPI_Comm_test_inter(LocComm, &flag);
       fprintf(stdout,"flag = %d\n",flag);
       fprintf(stdout,"Check size of InterComm: ");
       MPI_Comm_remote_size(InterComm,&np);
       fprintf(stdout,"size = %d\n",np);
    }
    /* Sum of values:  each group computes a partial sum */
    val = 1; lsum = 0;
    MPI_Reduce(&val,&lsum,1,MPI_INT,MPI_SUM,0,LocComm);
    if ( lid == 0 ) printf("Local sum = %d\n",lsum);

    /* Compute global sum */
    MPI_Comm_size(InterComm, &numproc);
    MPI_Comm_rank(InterComm, &idinter);

    /* Remote leader sends local sum to root process */
    if ( idinter == 0 ) {
       if ( colour == 1) {
          MPI_Send(&lsum,1,MPI_INT,0,101,InterComm);
       } else {
       	  gsum = lsum;
          MPI_Recv(&val,1,MPI_INT,0,101,InterComm,&stat);
          /* Global sum */
          gsum = gsum + val;
       }
    }

    MPI_Barrier(GlobalComm);
    MPI_Comm_free(&InterComm);
    MPI_Comm_free(&LocComm);
    MPI_Comm_free(&GlobalComm);
    if ( id == 0 ) {
       printf("Sum equals %d\n", gsum);
    }

    MPI_Finalize();

    return(0);
}
