/* quick initial interface between ReverseSearch and mts */

#define MTS

#include "CommandlineOptions.hh"
#include "ComputeTriangs.hh"
#include "PlacingTriang.hh"
#include "ReverseSearch.hh"
#include <iostream>
#include <sstream>

// MtsErr mtsErr;
// StateOutput stateOutput;
using namespace std;

Chirotope chiro;
PointConfiguration points;
size_type no;
size_type rrank;
SymmetryGroup *symmetries;
SimplicialComplex seed;
SymmetryGroup *seed_symmetries;
ReverseSearchWrapper *r;
size_type N;

void put_output(const TriangNode& tn, size_type count, const gkz_type& gkz);

extern "C" {
	#include "mts.h"
	struct bts_data {
		mts_stream *output;
		mts_stream *err;
		int delta;
	};
	Node *n;
	bts_data *bdata;
	int procno;
	void from_node(Node *, TriangNode &);
	void to_node(Node *, const TriangNode &);
	char name[] = "mptopcom";
	/* option and number of parameters to option */
	const mtsoption bts_options[] = {{"--nosymmetries", 0},
                                    {"--flip_cache", 1},
                                    {"--regular", 0},
                                    {"-v", 0},
                                    {"--orbit_cache",1},
                                    {"-F", 0},
                                    {"--small_group", 0},
                                    {"--large_group", 0}};
	const int bts_options_size = 8;
	Node node;

void bts_finish(bts_data *b, shared_data *sdata, int size, int checkpointing)
{
	int i;
	unsigned long long tot_count = 1; /* include root ? */

	for (i=0; i<size; i++)
	{
		if (sdata[i].size_sdlong>0)
			tot_count += sdata[i].sdlong[0];
	}

	stream_printf(b->err, "Total triangulations: %llu\n", tot_count);
	return;
}

/* mts process startup */
bts_data *bts_init(int argc, char **argv, Data *in, int proc_no)
{
	procno = proc_no;
	const bool preprocess = false;

	bts_data *b = (bts_data *)malloc(sizeof(bts_data));
	bdata = b;

	b->output = open_stream(MTSOUT);
	b->err = open_stream(MTSERR);
   
   // Trigger redirect of output.
   cerrWrap.redirect();
   cerrFirstWorker.redirect();
   // This line lets TOPCOM read through the command line arguments to extract
   // its options.
   CommandlineOptions::init(argc, (const char **)argv);

	stringstream stb(string(in->input));

	if (!points.read(stb)) {
		freebdata(b);
		return NULL;
	}
	if ((points.no() < 2) || (points.rank() < 2)) {
		freebdata(b);
		return NULL;
	}
	if (points.rank() > points.no()) {
		freebdata(b);
		return NULL;
	}
	chiro = Chirotope(points, preprocess);
	no = chiro.no();
	rrank = chiro.rank();
	symmetries = new SymmetryGroup(no);
	if (!CommandlineOptions::ignore_symmetries()) {
		symmetries->read(stb);
	}
	if (!seed.read(stb)) {
		seed = PlacingTriang(chiro);
	}
   r = constructReverseSearch(points, chiro, *symmetries, false);
	gkz_type gkz(points, chiro);
	b->delta = gkz.size();
	return b;
}

/* get initial mts root */
Node *get_root(bts_data *b)
{
	Node *root = (Node *)malloc(sizeof(Node));
	root->vlong = NULL;
	root->size_vlong = 0;
	root->vint = NULL;
	root->size_vint = 0;
	root->vchar = NULL;
	root->size_vchar = 0;
	root->vfloat = NULL;
	root->size_vfloat = 0;
	root->vdouble = NULL;
	root->size_vdouble = 0;
	root->depth = 0;
	root->unexplored = 0;
	gkz_type gkz(points, chiro);
	const TriangNode initial_triang = r->get_initial_triang(no, rrank, seed);
	TriangNode lex_optimal = r->find_max_triang(initial_triang);
	to_node(root, lex_optimal);
	put_output(lex_optimal, 0, gkz);
	return root;
}

void freebdata(bts_data *b)
{
	free(b);
	delete r;
	delete symmetries;
	delete seed_symmetries;
	return;
}

long bts(bts_data *b, Node *node, long max_depth, long max_nodes,
	 shared_data *sdata, int rk, int size)
{
	unsigned long count;
	unsigned long startc = r->totalcount();
	long ret;
	n = node;
	TriangNode tn;
	from_node(node, tn);
	ret = r->generic_reverse_search(tn, b->delta, max_nodes, max_depth);
	count = r->totalcount();
	if (sdata[rk].size_sdlong<1)
	{
		sdata[rk].size_sdlong = 1;
		sdata[rk].sdlong = (long *)malloc(sizeof(long));
		sdata[rk].update_final = 1;
		sdata[rk].sdlong[0] = 0;
	}
	sdata[rk].sdlong[0] += (count-startc);
	return ret;
}

} /* extern "C" */

/* pack the TriangNode into an mts Node */
void to_node(Node *node, const TriangNode &tn)
{
	stringstream stb;
	stb << tn;
	string str = stb.str();
	const char *cs = str.c_str();
	char *buf;
	int len = strlen(cs);

	if (node->size_vchar <= len)
	{
		buf = (char *)realloc(node->vchar, sizeof(char)*(len+1));
		if (buf == NULL)
			emergencystop("No memory");
		node->vchar = buf;
	}

	strcpy(node->vchar, cs);
	node->size_vchar = len+1;
}

/* unpack the mts Node into the TriangNode */
void from_node(Node *node, TriangNode& tn)
{
	stringstream stb(node->vchar);
	stb >> tn;
}

/* over budget so return this one */
void mtstcreturn(const TriangNode& tn)
{
	to_node(n, tn);
	n->unexplored = 1;
	return_unexp(n);
}

void put_output(const TriangNode& tn, size_type count, const gkz_type& gkz)
{
   if(CommandlineOptions::verbose()){
      if(count % 1000 == 0){
        stringstream ste;
	ste <<  "Worker " << procno << " found " << count << " triangulations." << std::endl;
        string stre = ste.str();
	const char *ce = stre.c_str();
	stream_printf(bdata->err, "%s", ce);
      }
   }
	stringstream stb;
	stb << "(" << procno << "." << count << "):" << tn << " " << 
      gkz.gkz_as_string(tn) << endl;
	string str = stb.str();
	const char *cs = str.c_str();
	stream_printf(bdata->output, "%s", cs);
}

void put_error(const stringstream& stb)
{
	string str = stb.str();
	const char *cs = str.c_str();
	stream_printf(bdata->err, "%s", cs);
}

void report_state(const stringstream& stb)
{
   if(procno == MTS_FIRSTWORKER){
      string str = stb.str();
      const char *cs = str.c_str();
      stream_printf(bdata->err, "%s", cs);
   }
}
