/*
    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 "GensimMatrixReader.h"
#include "../matrices_headers.h"
#include "filesystem_error.h"

static log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("SuperMatrix.matrices.io.GensimMatrixReader"));

namespace Matrices
{
	namespace IO
	{
		GensimMatrixReader::GensimMatrixReader(std::string &path, SuperMatrixPtr m):
							m_pMatrix(m)
		{
			dirpath=path;
		}

		void GensimMatrixReader::LoadGensimToSuperMatrix()
		{

			CRSMatrixPtr crs;
			std::string line;
			std::vector<std::string> tokens;
			LOG4CXX_INFO(logger,"Loading gensim file in Super Matrix...");
			std::ifstream mmCorpus(dirpath.c_str());
			if(!mmCorpus)
				throw std::runtime_error("Cannot open results file from gensim\n");
			std::getline(mmCorpus,line);
			if(!line.compare(0, line.length()-1, "%%MatrixMarket matrix coordinate real general"))
				throw std::runtime_error("File with gensim matrix has wrong format\n");
			std::getline(mmCorpus,line);
			boost::split(tokens,line,boost::is_any_of(" "));
			size_t mRows = atoi(tokens[0].c_str());
			size_t mCols = atoi(tokens[1].c_str());
			size_t nz= atoi(tokens[2].c_str());
			crs = Matrices::CRSMatrixPtr(new Matrices::CRSMatrix("gensim Matrix",mRows,mCols));
			for(size_t i=0;i<nz;i++)
			{
				if(!(std::getline(mmCorpus,line)))
					throw std::runtime_error("Unexpected end of gensim matrix file\n");
				boost::split(tokens,line,boost::is_any_of(" "));
				crs->SetCell((double)atof(tokens[2].c_str()),atoi(tokens[0].c_str())-1,atoi(tokens[1].c_str())-1);
			}
			mmCorpus.close();

			Matrices::CCSMatrixPtr ccsMatrix (new Matrices::CCSMatrix("crs",1,1));
			crs->Clone(ccsMatrix.get());
			Matrices::FeatureVectorPtr colFeatures(new Matrices::FeatureVector());
			for(size_t i =0;i<crs->NumberOfColumns();i++)
			{
				std::stringstream ss;
				ss<<i;
				colFeatures->push_back(Matrices::Feature(ss.str(),0,0,0,-1));

			}
			std::map<size_t,std::string> bound;
			m_pMatrix->SetCRS(crs);
			m_pMatrix->SetCCS(ccsMatrix);
			m_pMatrix->SetColumnFeatures(colFeatures);

			LOG4CXX_INFO(logger,"Loading gensim file in Super Matrix... done...");
		}

		void ReadGensimToSuperMatrixFromFile(const std::string &path, SuperMatrixPtr m)
		{
			std::string p = path;
			GensimMatrixReader reader(p,m);
			reader.LoadGensimToSuperMatrix();
		}
	}
}
