#include <mpi.h>
#include <iostream>
#include <sstream>
#include "FileIO.h"
#include "ComputationEngine.h"
#include "ScopedTimer.h"

int main(int argc, char** argv)
{

	int rank;
	int size;
	char hostName[128];
	int hostLen;

	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
	MPI_Get_processor_name(hostName, &hostLen);

	int srNum = 0;

	if (rank == 0) //
	{
		srNum = 5;
		cout << "Possible file names:" << endl;
		FileIO::PrintInputFileNames();
		cout << "\nEnter file name to read:" << endl;

		

		MPI_Send(&srNum, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
	}
	else if(rank == 1)
	{
		string fn;

		cin >> fn;
		cin.ignore(numeric_limits<streamsize>::max(), '\n'); //flush the rest of the buffer.

		if (!FileIO::FileExists(FileIO::PrependDir("input", fn)))
		{
			cout << "No such file.  Press <Enter> to exit." << endl;
			getchar();
			exit(-1);
		}

			

		MPI_Recv(&srNum, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);

		
	}

	MPI_Finalize();
	

	
	double* arr;
	size_t size;

	ScopedTimer *wp = new ScopedTimer("Entire Program");

	ScopedTimer *fr = new ScopedTimer("File Read");
	FileIO::ReadFile(fn, &arr, &size);
	delete(fr);

	ScopedTimer *cp = new ScopedTimer("Computation");
	ComputationEngine *ce = new ComputationEngine(&arr, size);
	ce->Initialise();
	ce->SetA();
	ce->SetB();
	ce->SetABDash();
	ce->SetCD();
	ce->SetE();
	ce->SetResults();
	delete(cp);

	ScopedTimer *fw = new ScopedTimer("File write");
	stringstream ss;
	ss << "output_";
	ss << size;
	ss << ".txt";

	FileIO::WriteFile(ss.str(), ce->GetResults(), size);
	delete(fw);

	ce->Deallocate();
	delete(ce);

	delete(wp);

	cout << "Complete.  Press <Enter> to exit." << endl;
	getchar();
}