/*
    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 <vector>
#include <string>
#include <stdexcept>
#include <cstring>
#include <fstream>
#include <boost/algorithm/string.hpp>

void helpMsg(char* av)
{


	std::cout<<"Program taking file with domains and labeling it.\n"
			<<"Runtime format: "<<av<<" domain_file label_file output_file\n";
}
std::vector<std::string> readLabels(char* fileName)
{
	std::ifstream labelFile(fileName);
	if(!labelFile)
		throw std::runtime_error("Cannot open file with labels!\n");
	std::string line;
	std::vector<std::string> labels;
	while(std::getline(labelFile,line))
		labels.push_back(line);
	return labels;
}
void labelDomains(std::vector<std::string> labels,char* domainFilename, char* outputFilename)
{
	std::ifstream domainFile(domainFilename);
	if(!domainFile)
		throw std::runtime_error("Cannot open domain file!\n");
	std::ofstream outputFile(outputFilename);
	if(!outputFile)
		throw std::runtime_error("Cannot open file for output!\n");
	std::string line;
	//header
	std::getline(domainFile,line);
	outputFile<<line<<std::endl;
	for(size_t i=0;i<labels.size();i++)
	{
		std::getline(domainFile,line);
		if(line.size()==0)
		{
			outputFile<<labels[i]<<std::endl;
			continue;
		}
		std::vector<std::string> domain;
		boost::trim(line);
		boost::split(domain, line, boost::is_any_of(" ") );

		outputFile<<labels[i]<<": ";
		if(domain.size()>0)
			outputFile<<labels[atoi(domain[0].c_str())];
		for(size_t j=1;j<domain.size();j++)
			outputFile<<", "<<labels[atoi(domain[j].c_str())];
		outputFile<<std::endl;
	}
	domainFile.close();
	outputFile.close();

}

int main(int ac,char** av)
{
	if(ac>1 && strcmp(av[1],"--help")==0)
	{
		helpMsg(av[0]);
		return 1;
	}

	if(ac!=4)
	{
		helpMsg(av[0]);
		throw std::runtime_error("Invalid number of parameters!\n");
		return -1;
	}
	std::cout<<"Reading label file...\n";
	std::vector<std::string> labels = readLabels(av[2]);
	std::cout<<"Labeling...\n";
	labelDomains(labels,av[1],av[3]);



return 0;
}
