/*
    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 "matrices_all.h"
#include <fstream>
#include <algorithm>
#include <time.h>

std::set<size_t> getLabelsToRemove(std::string filename, Matrices::SuperMatrixPtr pMatrix)
{
	std::fstream ifile;
	std::cout<<"Opening file: "<<filename<<"\n";
	ifile.open(filename.c_str());
	if (!ifile)
	{
		std::cout<<"Error opening file.\n";
	}
	std::string line;
	std::set<std::size_t> removeset;
	while (getline(ifile,line))
	{
		std::cout<<"Read line: "<<line<<"\n";
		size_t ind = pMatrix->GetRowIndex(line);
		std::cout<<"Got index: "<<ind<<"\n";
		removeset.insert(ind);
	}
	return removeset;
}

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

	Matrices::init_logging();
	if(ac != 6)
	{
		std::cerr << "MLabelSubset. Author: Jacek Bochenek, 156482@student.pwr.wroc.pl\n"
				<< "Removes rows from matrix using labels.\n"
				<< "Usage:\n\tmlabel matrix_dir matrix_name label_file output_dir output_name\n\n";
		return -1;
	}

	std::string mdir = av[1];
	std::string mname = av[2];


	std::string outdir = av[4];
	std::string outname = av[5];

	std::set<size_t> row_indices_to_erase;
	std::set<size_t> column_indices_to_erase;

	Matrices::SuperMatrixPtr pInputMatrix = Matrices::IO::LoadSuperMatrix(mdir, mname, false, true);

	std::string labelfile = av[3];
	row_indices_to_erase = getLabelsToRemove(labelfile, pInputMatrix);

	Matrices::SuperMatrixPtr pOutputMatrix = Matrices::FilterSuperMatrix(pInputMatrix, row_indices_to_erase,
																   column_indices_to_erase);

	pOutputMatrix->SetNewName(outname);

	std::cout << "Writing output matrix (" << outname << ") to " << outdir << std::endl;
	Matrices::IO::WriteSuperMatrix(pOutputMatrix, outdir);

	std::cout << "All done" << std::endl;
	return 0;
}
