/* 06_scatter_gather.c - normalise a vector in parallel.
 * Rank 0 owns the vector, MPI_Scatter hands each rank a piece, MPI_Allreduce computes
 * the global norm, every rank scales its piece, and MPI_Gather collects the result.
 * Build: mpicc -O2 -o 06_scatter_gather 06_scatter_gather.c -lm
 * Run:   mpirun -np 4 ./06_scatter_gather
 */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <mpi.h>

#define PER_RANK 4   /* elements per process, kept small so the output is readable */

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);

    int n = PER_RANK * size;
    double *full = NULL;
    if (rank == 0) {                                  /* only the root needs the whole vector */
        full = malloc(sizeof(double) * n);
        for (int i = 0; i < n; i++) full[i] = i + 1;
    }

    double part[PER_RANK];
    MPI_Scatter(full, PER_RANK, MPI_DOUBLE, part, PER_RANK, MPI_DOUBLE, 0, MPI_COMM_WORLD);

    double local = 0.0, global;
    for (int i = 0; i < PER_RANK; i++) local += part[i] * part[i];
    MPI_Allreduce(&local, &global, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);   /* all ranks get it */
    double norm = sqrt(global);
    for (int i = 0; i < PER_RANK; i++) part[i] /= norm;

    MPI_Gather(part, PER_RANK, MPI_DOUBLE, full, PER_RANK, MPI_DOUBLE, 0, MPI_COMM_WORLD);

    if (rank == 0) {
        double check = 0.0;
        for (int i = 0; i < n; i++) check += full[i] * full[i];
        printf("norm before = %.6f, first values after: %.4f %.4f %.4f, norm after = %.6f\n",
               norm, full[0], full[1], full[2], sqrt(check));
        free(full);
    }
    MPI_Finalize();
    return 0;
}
