#include <LINK/userobj/PostAnalyze.h>


void
Extract_SaveGraphs(int num_verts, double prob, int percent,
		      int number_graphs, int flag, int deviation, int rand_seed)
{

	Sequence<Vertex*> vs;
	Graph* g;
	Graph* gr;
	int done = 0;
	int count = 0;
	int counter = 0;

	Link_setSeed(rand_seed);

	while(!done)
	{
	g = GenRandomGraph(num_verts, prob);

	vs = PostAnalyze(g);
	gr = Extract(g, percent, flag, vs, deviation);

	//delete g;
	count++;
	cout << "loop# " << count << endl;
	if (gr != NULL) {
		counter++;
		write_graph(gr, num_verts, prob, flag, counter, percent, rand_seed);
		//delete gr;
		cout << "total times looped: " << count << endl;
		if (counter == number_graphs) done = 1; 
		count = 0;
	}
	}
}

void
write_graph(Graph* g, int num_verts, double prob, int type, int num_graph, int percent, int seed)
{
	char* buf;
	char* wr = "h";
	char* ng_g = "g";

	if (percent > 5) wr = "bh";

	if (type == 1) ng_g = "ng"; 

	buf = get_path(num_verts, prob, num_graph, wr, ng_g, seed);
	buf = attempt_file(buf, num_verts, prob, num_graph, wr, ng_g, seed);
//cout << "path " << buf << endl;	
	SaveGraph(g, buf);
}


char*
get_path(int num_verts, double prob, int num_graph, char* wr,
	 char* ng_g, int seed)
{
	ostrstream pss;
	ostrstream uss;
	ostrstream oss;
	char* t;
	char* s;
	
	if (wr == "bh") s = "B_HUMP_";
	else s = "HUMP_";
	if (ng_g == "ng") t = "N_GREEDY";
	else t = "GREEDY";
        uss << prob;
        uss << ends;
        char* y = uss.str();

	pss << "NGDIST_" << s << t;  //eg.. NGDIST_B_HUMP_N_GREEDY
	pss << ends;
	char* env_path = pss.str();
	char* path = getenv(env_path);
        oss << path << "/" << num_verts;
        oss << y + 1 << "_" << num_graph << "-" << wr << "-" << ng_g << "-" << seed << ".g";
        oss << ends;

	char* buf = oss.str();
//cout << "In get path - buf " << buf << endl;
	return buf;
}

char*
attempt_file(char* path, int num_verts, double prob, int num_graph, 
		char* wr, char* ng_g, int seed)
{
	ifstream file;
	int done = 0;
//cout << "In attempt " << path << endl;

	while (!done) 
	{
		file.open(path, ios::in);
		if (file.fail()) break;
		path = get_path(num_verts, prob, num_graph, 
			        wr, ng_g, seed);
		num_graph = num_graph + 1;
		file.close();
	}
	return path;
}


/*
void
main(int argc, char* argv[])
{
if (argc < 8) 
	{
	cout << "Error: bad number of arguments entered!!" << endl;
	cout << "Must Enter: num_verts, probability, percent, flag,";
	cout << " num_graphs, deviation, seed" << endl;
	return 0;
	} 
int n_verts = atoi(argv[1]);
double prob = atof(argv[2]);
int percent = atoi(argv[3]);
int flag = atoi(argv[4]);
int num_graphs = atoi(argv[5]);
int deviation = atoi(argv[6]);
int seed = atoi(argv[7]);

Extract_SaveGraphs(n_verts, prob, percent, num_graphs, flag, deviation, seed);

cout << endl << endl << "----------------------------------" << endl;

}
*/
