/*
    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.
*/

#ifndef MAIN_CPP
#define MAIN_CPP
#include "matrices_all.h"
#include <cmath>

void helpMsg()
{
	std::cout<<"\nProgram quantifying a double precision matrix to a specified decimal precision \n"
			<<"Runtime format: "<<"quantify"<<" in_matrix out_matrix [fraction_digits]\n\n";
}

int main(int ac, char**av)
{
	Matrices::init_logging();
	if(ac==1)
	{
		helpMsg();
		return 1;
	}
	if(ac>0 && (strcmp(av[1],"--help")==0))
	{
		helpMsg();
		return 1;
	}
	if(ac!=3 && ac!=4)
	{
		helpMsg();
		throw std::runtime_error("Invalid number of parameters! Try using --help\n");
		return -1;
	}
	double factor;
	if (ac==4)
	{
		factor = std::pow(10,atof(av[3]));
	}
	else factor = 100;

	
	Matrices::CRSMatrixPtr inMatrix = Matrices::IO::ReadCRSFromSingleFile(av[1],"in_matrix");
	double quantified;
	for(size_t i=0;i<inMatrix->NumberOfRows();i++)
	{

		Matrices::STDoubleMapPtr rowValues = inMatrix->GetCompressedRow(i)->GetValues();
		if(rowValues->size()!=0)
		{
			for(Matrices::STDoubleMapIter iter = rowValues->begin();iter!=rowValues->end();++iter)
			{
				quantified = (double)round(iter->second * factor)/factor;
				inMatrix->SetCell(quantified,i,iter->first);
			}
		}
	}
	std::cout<<"Saving filtered matrix"<<std::endl;
	Matrices::IO::WriteToSingleFile(inMatrix,av[2]);
	return 0;
}

#endif // MAIN_CPP
