/* Copyright (c) 1997-2009
   Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Darmstadt, Germany)
   http://www.polymake.de

   This program is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 2, or (at your option) any
   later version: http://www.gnu.org/licenses/gpl.txt.

   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
   GNU General Public License for more details.
--------------------------------------------------------------------------------
   $Project: polymake $$Id: is_ball_or_sphere_h.cc 9298 2009-09-02 23:10:56Z gawrilow $
*/

#include <polymake.h>
#include <is_sphere_h.h>
#include <sstream>

namespace polymake { namespace topaz {

bool is_ball_or_sphere_client(perl::Object p, bool check_for_sphere, perl::OptionSet options)
{
   const HasseDiagram HD = p.give("HASSE_DIAGRAM");

   int strategy=options["strategy"];
   int n_stable_rounds;
   if (!(options["stable_rounds"] >> n_stable_rounds))
      n_stable_rounds=(HD.dim()-1) * 1000;
   
   bool verbose=options["verbose"];
   bool renew_seed=false;
   unsigned long seed;
   if (!(options["seed"] >> seed)) {
      seed=random_seed();
      renew_seed=true;
   }

   typedef bool (*check_func_t)(const HasseDiagram&, unsigned long, int, int);
   const check_func_t check_func= check_for_sphere ? (check_func_t)&is_sphere_h : (check_func_t)&is_ball_or_sphere_h;
   bool is_ball_or_sphere=check_func(HD,seed,strategy,n_stable_rounds);
   while (!is_ball_or_sphere && ++strategy <= 1) {
      if (verbose)
	 cout << "is_ball_or_sphere_h: after " << n_stable_rounds
	      << " iterations without improvement:\nUnable to determine, whether the complex is a ball or a sphere.\n"
	      << "Trying strategy " << strategy << "." << endl;
      if (renew_seed) seed=random_seed();
      is_ball_or_sphere = check_func(HD,seed,strategy,n_stable_rounds);
   }

   if (!is_ball_or_sphere) {
      std::ostringstream e;
      e << "is_ball_or_sphere_h: after " << n_stable_rounds
	<< " iterations without improvement:\nUnable to determine, whether the complex is a ball or a sphere.\n";
      throw std::runtime_error(e.str());
   }

   return true;
}

   Function4perl(&is_ball_or_sphere_client, "is_ball_or_sphere_h(SimplicialComplex $ { strategy=>0, stable_rounds=>undef, verbose=>0, seed=>undef })");

} }
