/* 11_shared_file.c - every rank writes its block into one shared file with collective MPI-IO,
 * and the file can be read back by any number of processes.
 * Build: mpicc -O2 -o 11_shared_file 11_shared_file.c
 * Run:   mpirun -np 4 ./11_shared_file write data.bin
 *        mpirun -np 3 ./11_shared_file read  data.bin
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mpi.h>

#define N 1000   /* ints written by each rank */

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 (argc < 3) {
        if (rank == 0) fprintf(stderr, "usage: %s write|read <file>\n", argv[0]);
        MPI_Abort(MPI_COMM_WORLD, 1);
    }
    MPI_File fh;

    if (strcmp(argv[1], "write") == 0) {
        int buf[N];
        for (int i = 0; i < N; i++) buf[i] = rank * N + i;    /* global index of each value */

        MPI_File_open(MPI_COMM_WORLD, argv[2], MPI_MODE_CREATE | MPI_MODE_WRONLY,
                      MPI_INFO_NULL, &fh);
        MPI_Offset offset = (MPI_Offset)rank * N * sizeof(int);
        /* Collective: all ranks call it together, so the library can merge requests. */
        MPI_File_write_at_all(fh, offset, buf, N, MPI_INT, MPI_STATUS_IGNORE);
        MPI_File_close(&fh);
        if (rank == 0) printf("%d ranks wrote %d ints each\n", size, N);
    } else {
        MPI_File_open(MPI_COMM_WORLD, argv[2], MPI_MODE_RDONLY, MPI_INFO_NULL, &fh);
        MPI_Offset bytes;
        MPI_File_get_size(fh, &bytes);
        MPI_Offset total = bytes / sizeof(int);

        /* Split the file into nearly equal parts, whatever the number of readers. */
        MPI_Offset first = total * rank / size;
        MPI_Offset last  = total * (rank + 1) / size;
        int count = (int)(last - first);
        int *buf = malloc(sizeof(int) * (count > 0 ? count : 1));
        MPI_File_read_at_all(fh, first * sizeof(int), buf, count, MPI_INT, MPI_STATUS_IGNORE);
        MPI_File_close(&fh);

        int ok = 1;
        for (int i = 0; i < count; i++) if (buf[i] != first + i) ok = 0;
        printf("rank %d read values %lld..%lld: %s\n", rank, (long long)first,
               (long long)last - 1, ok ? "correct" : "WRONG");
        free(buf);
    }
    MPI_Finalize();
    return 0;
}
