/*
    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 "parallelhal.h"
#include "Config.h"
#include "Architect.h"

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

void antiGridError(int myRank)
{
	parallel::MPI_Handler mpiHandler;
	int message;
	int numOfNodes;
	MPI_Comm_size(MPI_COMM_WORLD,&numOfNodes);
	if(myRank==0)
	{
		for(int i=1;i<numOfNodes;i++)
		{
			mpiHandler.recvItem(message,MPI_INT,i);
		}

	}
	else
	{
		message=1;
		mpiHandler.sendItem(message,MPI_INT,0);
	}
}

static log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("SuperMatrix.parallel.hal_architect.hal_architect"));

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

	hal_architect::Config::Initalize(ac,av);

	MPI_Init(&ac,&av);
	int myRank;
	MPI_Comm_rank(MPI_COMM_WORLD,&myRank);

	antiGridError(myRank);
	try
	{
		if(myRank==0)
		{
			parallel::hal_architect::ParallelHalMaster master;
			master.Init();
			master.Start();
			master.Finalize();
		}
		else
		{
			parallel::hal_architect::ParallelHalSlave slave;
			slave.Init(myRank);
			slave.Start();
		}
		LOG4CXX_INFO(logger,"Exiting on node "<<myRank);

	}
	catch(std::exception &e)
	{
		LOG4CXX_ERROR(logger, "Error: " << e.what());
		return -1;
	}

	hal_architect::Config::Delete();
	MPI_Finalize();
	return 0;
}

