/*
    Copyright (C) 2012 Bartosz Broda, Jacek Bochenek, Łukasz Biłeńkij, 
    Damian Jaworski, Wojciech Mazur, Dominik Piasecki, Maciej Piasecki, 
    Radosław Ramocki
    
    This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your option)
any later version.

    This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. 

    See the LICENSE and COPYING files for more details.
*/

#include <iostream>

#include "Dictionary.h"
#include "parallelArchitect.h"


/**
  * Function flushing connection
  * \param myRank Rank of node
  * \param stat MPI_Status for communication
  */

void antiGridError(int myRank,MPI_Status* stat)
{
	int message;
	int numOfNodes;
	MPI_Comm_size(MPI_COMM_WORLD,&numOfNodes);
	if(myRank==0)
	{
		for(int i=1;i<numOfNodes;i++)
		{
			MPI_Recv(&message,1,MPI_INT,i,0,MPI_COMM_WORLD,stat);
			//                std::cout<<"Sent message to node "<<i<<std::endl;
		}
		
	}
	else
	{
		message=1;
		MPI_Send(&message,1,MPI_INT,0,0,MPI_COMM_WORLD);
		//            std::cout<<"Received "<<message<<" on node X\n";
	}
}

int main(int ac, char *av[])
{

	try
	{
		me_architect::Config::init(ac,av);
		
		MPI_Init(&ac,&av);
		int myRank;
		MPI_Comm_rank(MPI_COMM_WORLD,&myRank);
		
		MPI_Status stat;
		antiGridError(myRank,&stat);
		
		
		if(me_architect::Config::GetInstance()->dictOnly)
		{
			if(myRank==0)
			{
				parallelMasterDict(&stat);
			}
			else
			{
				parallelSlaveDict(&stat);
			}
			
		}
		else
		{
			if(myRank==0)
			{
				parallelArchitectMaster(ac,av,&stat);
			}
			
			else
			{
				parallelArchitectSlave(ac,av,&stat);
			}
		}
		MPI_Finalize();
		std::cout<<"Node "<<myRank<<" finished.\n";
		return 0;
	}
	catch(std::exception &e)
	{
		std::cerr << "Error: " << e.what() << std::endl;
	}
	return -1;
	
}

