/*
 * File:   main.cpp
 * Author: ollbert
 *
 * Created on 15. März 2010
 */

#include <cstring>
#include <cstdlib>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

void writesol(const string tblname, const string lpsname, const string target) {
    ifstream tbl(tblname.c_str());
    int number;
    string s;
    tbl >> s >> number;
    vector<string> names(number);
    for (int j = 0; j < number; ++j) {
        int i;
        tbl >> s >> i;
        names[i] = s;
    }

    ifstream lps(lpsname.c_str());
    string answer, solution, optimization;
    ofstream sol(target.c_str());
		bool optimum = false;
    while(!lps.eof()){
		    getline(lps, s);
				if (s.substr(0,7).compare("Answer:") == 0) {
						answer = s;
						getline(lps, solution);
			      getline(lps, optimization);
						optimum = false;
				}
				else if(s.compare("OPTIMUM FOUND") == 0) optimum = true;
		    else if(s.compare("UNSATISFIABLE") == 0){
		        sol << "FAIL" << endl << endl << "# UNSATISFIABLE" << endl;
        		return;
				}
    }
		if(answer.length() == 0){
	       sol << "FAIL" << endl << endl << "# INTERRUPTED" << endl;
     		return;
		}

    size_t pos = 0;
    while((pos = solution.find("in(", pos)) != string::npos){
        int pos2 = solution.find(",", pos);
        int pos3 = solution.find(")", pos2);
        string first = solution.substr(pos + 3, pos2 - pos - 3);
        string second = solution.substr(pos2 + 1, pos3 - pos2 - 1);
        int i = atoi(first.c_str());
        int j = atoi(second.c_str());
				sol << "package: " << names[i] << endl;
				sol << "version: " << j << endl;
				sol << "installed: true" << endl;
				sol << endl;
        pos = pos3;
    }
	
		sol << "# " << answer << endl;
		sol << "# " << optimization << endl;
		if(optimum) sol << "# " << "OPTIMUM FOUND" << endl;
}

/*
 *
 */
int main(int argc, char **argv) {

    if(argc != 4) {
        cout << "using: " << argv[0] << "tablein solin cudfout" << endl;
        exit(1);
    }

    writesol(argv[1], argv[2], argv[3]);

    return 0;
}
