/* 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: n_gon.cc 9512 2010-02-28 22:24:19Z herr $
*/

#include <cmath>
#include <Matrix.h>
#include <polymake.h>

namespace polymake { namespace polytope {

perl::Object n_gon(int n, double r)
{
   if ((n < 3) || (r <= 0.0)) {
      throw std::runtime_error("n_gon: n >= 3 and r > 0 required\n");
   }

   perl::Object p("Polytope<Rational>");
   p.set_description() << n << "-gon with radius " << r << endl;
   
   // we have the dimensionality information (twice)

   Matrix<double> V(n,3);
   V.col(0).fill(1.0);

   const int iend= n%2 ? (n+1)/2 : (n+2)/4;
   const double factor = 2.0 * M_PI / n;

   V(0,1)=r;
   if (!(n%2)) {
      V(n/2,1)=-r;
      if (!(n%4)) {
	 V(n/4,2)=r;
	 V((3*n)/4,2)=-r;
      }
   }

   for (int i=1; i<iend; ++i) {
      const double x=r*cos(i*factor),
	           y=r*sin(i*factor);
      V(i,1)=x;
      V(i,2)=y;
      V(n-i,1)=x;
      V(n-i,2)=-y;
      if (!(n%2)) {
	 V(n/2-i,1)=-x;
	 V(n/2-i,2)=y;
	 V(n/2+i,1)=-x;
	 V(n/2+i,2)=-y;
      }
   }

   // don't try to be overly accurate
   p.take("AMBIENT_DIM") << 2;
   p.take("DIM") << 2;
   p.take("VERTICES") <<  V;
   p.take("N_VERTICES") << n;
   p.take("BOUNDED") << true;
   p.take("CENTERED") << true;
   return p;
}

UserFunction4perl("# @category Producing from scratch"
		  "# Produce a regular //n//-gon."
		  "# All vertices lie on a circle of radius //r//."
		  "# The radius defaults to 1."
		  "# @param Int n the number of vertices"
		  "# @param Double r the radius"
		  "# @return Polytope",
		  &n_gon,"n_gon($;$=1)");

} }
