/* 03_exchange.c - swap a buffer between two ranks in three safe ways.
 * Build: mpicc -O2 -o 03_exchange 03_exchange.c
 * Run:   mpirun -np 2 ./03_exchange <count> <method>   method = order | sendrecv | nonblocking
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mpi.h>

int main(int argc, char **argv)
{
    int rank, size;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    if (size != 2 || argc < 3) {
        if (rank == 0) fprintf(stderr, "usage: mpirun -np 2 %s <count> order|sendrecv|nonblocking\n", argv[0]);
        MPI_Abort(MPI_COMM_WORLD, 1);
    }

    int count = atoi(argv[1]);
    const char *method = argv[2];
    int other = 1 - rank;
    double *out = malloc(sizeof(double) * count);
    double *in  = malloc(sizeof(double) * count);
    for (int i = 0; i < count; i++) out[i] = rank;

    if (strcmp(method, "order") == 0) {
        /* 1. Break the symmetry: one side sends first, the other receives first. */
        if (rank == 0) {
            MPI_Send(out, count, MPI_DOUBLE, other, 0, MPI_COMM_WORLD);
            MPI_Recv(in,  count, MPI_DOUBLE, other, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        } else {
            MPI_Recv(in,  count, MPI_DOUBLE, other, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            MPI_Send(out, count, MPI_DOUBLE, other, 0, MPI_COMM_WORLD);
        }
    } else if (strcmp(method, "sendrecv") == 0) {
        /* 2. Let MPI pair the send and the receive for you. */
        MPI_Sendrecv(out, count, MPI_DOUBLE, other, 0,
                     in,  count, MPI_DOUBLE, other, 0,
                     MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    } else {
        /* 3. Post both operations, then wait for both. */
        MPI_Request req[2];
        MPI_Irecv(in,  count, MPI_DOUBLE, other, 0, MPI_COMM_WORLD, &req[0]);
        MPI_Isend(out, count, MPI_DOUBLE, other, 0, MPI_COMM_WORLD, &req[1]);
        /* ... independent computation can run here ... */
        MPI_Waitall(2, req, MPI_STATUSES_IGNORE);
    }

    printf("rank %d received %d doubles from rank %d (first value %.0f) using %s\n",
           rank, count, other, in[0], method);
    free(out);
    free(in);
    MPI_Finalize();
    return 0;
}
