/* cart2d.c - a 2D process grid with neighbour exchange and row communicators.
 * Build: mpicc -O2 -o cart2d cart2d.c
 * Run:   mpirun -np 6 ./cart2d
 */
#include <stdio.h>
#include <mpi.h>

int main(int argc, char **argv)
{
    int size, rank;
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    /* 1. Let MPI choose a balanced 2D shape for the available processes. */
    int dims[2] = {0, 0};
    MPI_Dims_create(size, 2, dims);

    /* 2. Build the grid: periodic in x, not periodic in y; allow rank reordering. */
    int periods[2] = {1, 0};
    MPI_Comm grid;
    MPI_Cart_create(MPI_COMM_WORLD, 2, dims, periods, 1, &grid);
    MPI_Comm_rank(grid, &rank);            /* rank may differ from MPI_COMM_WORLD */

    int coords[2];
    MPI_Cart_coords(grid, rank, 2, coords);

    /* 3. Find neighbours. Missing neighbours at a non-periodic edge are MPI_PROC_NULL. */
    int west, east, north, south;
    MPI_Cart_shift(grid, 0, 1, &west, &east);    /* along dimension 0 */
    MPI_Cart_shift(grid, 1, 1, &north, &south);  /* along dimension 1 */

    /* 4. Halo exchange: send my value east, receive from west (and the same north-south).
     *    MPI_Sendrecv pairs the operations, so this can never deadlock, and
     *    communication with MPI_PROC_NULL simply does nothing. */
    double mine = rank, from_west = -1, from_north = -1;
    MPI_Sendrecv(&mine, 1, MPI_DOUBLE, east,  0, &from_west,  1, MPI_DOUBLE, west,  0, grid, MPI_STATUS_IGNORE);
    MPI_Sendrecv(&mine, 1, MPI_DOUBLE, south, 1, &from_north, 1, MPI_DOUBLE, north, 1, grid, MPI_STATUS_IGNORE);

    /* 5. Split the grid into rows: keep dimension 0, drop dimension 1. */
    int keep[2] = {1, 0};
    MPI_Comm row;
    MPI_Cart_sub(grid, keep, &row);
    double row_sum;
    MPI_Allreduce(&mine, &row_sum, 1, MPI_DOUBLE, MPI_SUM, row);

    char nb[4][8];
    int ids[4] = {west, east, north, south};
    for (int i = 0; i < 4; i++) {
        if (ids[i] == MPI_PROC_NULL) snprintf(nb[i], sizeof nb[i], "-");
        else snprintf(nb[i], sizeof nb[i], "%d", ids[i]);
    }
    printf("rank %d at (%d,%d): W %s E %s N %s S %s | from W %.0f, from N %.0f | row sum %.0f\n",
           rank, coords[0], coords[1], nb[0], nb[1], nb[2], nb[3], from_west, from_north, row_sum);

    MPI_Comm_free(&row);
    MPI_Comm_free(&grid);
    MPI_Finalize();
    return 0;
}
