//---------------------------------------------------------------------------
// 2A_Ping_pong_Ssend.cpp 
//---------------------------------------------------------------------------
#if (defined __linux__) || (defined _AIX) || (defined __APPLE__)
	#include <sys/types.h>
	#include <sys/stat.h>
	#include <unistd.h>
#elif (defined _WIN32) || (defined _WIN64)
	#include <conio.h>
	#include <direct.h>
#endif

#include "mpi.h"
#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
	int i, j, rank, size;
	double time;
	int array0[10], array1[10];

	MPI_Init(&argc, &argv);
	MPI_Barrier(MPI_COMM_WORLD);
	time = -MPI_Wtime();

	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
	if (rank == 0) {
		cout << "There are " << size << " processes\n";
		std::fflush(stdout);
	}
	cout << "process " << rank << " is prepared" << endl;

	for (i = 0; i < 10; i++)
		array0[i] = 0;

	if (rank == 0) {
		cout << "\nprocess " << rank << " - Initial values of array0 are:" << endl;
		for (i = 0; i < 10; i++)
			cout << array0[i] << " ";
	}
	std::fflush(stdout);

	for (i = 0; i < 1000000; i++) {
		if (rank == 0) {
			//			for (j = 0; j < 10; j++)
			//				array0[j]--;
			MPI_Ssend(array0, 10, MPI_INT, 1, 0, MPI_COMM_WORLD);

			MPI_Recv(array0, 10, MPI_INT, 1, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
		}
		if (rank == 1) {
			MPI_Recv(array1, 10, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);

			for (j = 0; j < 10; j++)
				array1[j]++;
			MPI_Ssend(array1, 10, MPI_INT, 0, 1, MPI_COMM_WORLD);
		}
	}

	if (rank == 0) {
		cout << "\n\nprocess " << rank << " - Final values of array0 are:" << endl;
		for (i = 0; i < 10; i++)
			cout << array0[i] << " ";
	}

	time += MPI_Wtime();
	if (rank == 0)
		printf("\n\nTime = %10.6f s\n", time);

	std::fflush(stdout);
	MPI_Finalize();

	return 0;
}