#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <stdlib.h>

using namespace std;
int main(int argc, char *argv[])
{
	bool **arc;
	string rule;
	ifstream graph;
	ofstream lp;
	string::size_type pos1, pos2, pos3;
	int s,t;

	int nvertices;
	int i,j;

	if (argc != 4)
	{
		cout<<"Usage:" << argv[0] << " <nVertices> <graphFile> <Output>" << endl;
		return 0;
	}
	nvertices = atoi(argv[1]);
	
	arc = new bool* [nvertices];
	for (i=0; i<nvertices; i++) arc[i] = new bool [nvertices];

	graph.open(argv[2]);
	lp.open(argv[3], ios::trunc);

	lp << "##function (vertex) vertex hc." << endl;
	for(i=0; i<nvertices; i++)
		for(j=0; j<nvertices; j++) arc[i][j] = false;

	while(getline(graph, rule)) 
	{
		lp << rule.c_str() << endl;
		if (rule.find("arc") == string::npos) continue;
		pos1 = rule.find("(");
		pos2 = rule.find(",");
		pos3 = rule.find(")");		
		s = atoi(rule.substr(pos1+1, pos2-pos1-1).c_str());
		t = atoi(rule.substr(pos2+1,pos3-pos2-1).c_str());
		arc[s][t] = true;

	}

	lp << "initial(0)." << endl;
	for(i=0; i<nvertices; i++)
		lp << ":- not reached(" << i << ")." << endl;

	for(i=0; i<nvertices; i++)
	{
		for(j=0; j<nvertices; j++)
		{	
			if (i==j || arc[i][j]) continue;
			lp << ":- " << j << "==hc(" << i << ")." << endl;
		}
	}


	for(i=1; i<nvertices; i++)
	{
		if (!arc[0][i]) continue;
		lp << "reached(" << i << ") :-"  << i << "==hc(0)." << endl;
	}

	for(i=0; i<nvertices; i++)
	{
		for(j=0; j<nvertices; j++)
		{	
			if (i==j || !arc[j][i]) continue;
			lp << "reached(" << i << ") :- reached(" << j << ")," << i << "==hc(" << j << ")." << endl;
		}
	}
		
	for(i=0; i<nvertices; i++) delete[] arc[i];
	return 0;
}

