#include <mpi.h>
#include <iostream>
#include <cstdlib>
int main(int argc, char **argv)
{
  MPI_Init(&argc,&argv);

  int myrank;
  MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
  int worldsize;
  MPI_Comm_size(MPI_COMM_WORLD,&worldsize);
  if(worldsize != 4){
    if(myrank == 0) std::cout<<"Error: need exactly 4 MPI ranks, got "<<worldsize<<std::endl;
    MPI_Finalize();
    return EXIT_FAILURE;
  }

  const double coords[4][2] = {{0.0,0.0},{1.0,1.0},{0.5,0.5},{0.2,0.7}};
  double r[2] = {coords[myrank][0], coords[myrank][1]};
  double r_left[2], r_right[2];
  int left  = (myrank+worldsize-1)%worldsize;
  int right = (myrank+1)%worldsize;
  MPI_Request send_request, recv_request;

  // send to the left, receive from the right
  MPI_Isend(r,2,MPI_DOUBLE,left,101,MPI_COMM_WORLD,&send_request);
  MPI_Irecv(r_right,2,MPI_DOUBLE,right,101,MPI_COMM_WORLD,&recv_request);
  MPI_Wait(&send_request,MPI_STATUS_IGNORE);
  MPI_Wait(&recv_request,MPI_STATUS_IGNORE);

  // send to the right, receive from the left
  MPI_Isend(r,2,MPI_DOUBLE,right,101,MPI_COMM_WORLD,&send_request);
  MPI_Irecv(r_left,2,MPI_DOUBLE,left,101,MPI_COMM_WORLD,&recv_request);
  MPI_Wait(&send_request,MPI_STATUS_IGNORE);
  MPI_Wait(&recv_request,MPI_STATUS_IGNORE);

  double dx = r[0]-r_right[0], dy = r[1]-r_right[1];
  double local_energy = 0.5*(dx*dx+dy*dy);
  dx = r[0]-r_left[0]; dy = r[1]-r_left[1];
  local_energy += 0.5*(dx*dx+dy*dy);
  local_energy /= 2.0; // allow for double counting
#ifdef DEBUG
  std::cout<<"Node: "<<myrank<<" r_left: ("<<r_left[0]<<","<<r_left[1]<<") r_right: ("
           <<r_right[0]<<","<<r_right[1]<<") local energy: "<<local_energy<<std::endl;
#endif

  double energy = 0;
  MPI_Reduce(&local_energy,&energy,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);

  if(myrank == 0){
    std::cout<<"Total energy: "<<energy<<std::endl;
  }

  MPI_Finalize();

  return EXIT_SUCCESS;
}
