/* Copyright (c) 1997-2004
   Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Berlin, Germany)
   http://www.math.tu-berlin.de/polymake,  mailto:polymake@math.tu-berlin.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.
*/

#ident "$Project: polymake $$Id: n-gon.cc,v 1.11 2004/06/22 16:23:09 gawrilow Exp $"

#include <cstdlib>
#include <cmath>
#include <Poly.h>
#include <Matrix.h>

namespace polymake { namespace polytope {

void n_gon(Poly& p, int n, double r)
{
   // we have the dimensionality information (twice)
   p.take("AMBIENT_DIM") << 2;
   p.take("DIM") << 2;

   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("VERTICES") << std::setprecision(6) << V;
   p.take("N_VERTICES") << n;
   p.take("BOUNDED") << true;
   p.take("CENTERED") << true;
}

} }

using namespace polymake;

/** @file n-gon
 *
 *  Produce a regular $n$-gon.
 *
 *  All vertices lie on a circle of radius $r$.
 *  The radius defaults to $1$.
 *
 *  @synopsis n-gon <file> <n> [r]
 *
 *  @writing  AMBIENT_DIM, DIM, VERTICES, N_VERTICES, BOUNDED, CENTERED
 *
 *  @index clients Producing from scratch
 */

int main(int argc, char *argv[]) {
   if (argc<3 || argc>4) {
      cerr << "usage: " << argv[0] << " <file> <n> [r]" << endl;
      return 1;
   }
   try {
      int n = atoi(argv[2]);
      double r = argc>3 ? atof(argv[3]) : 1.0;

      // there is a certain restriction on the parameters
      if ((n < 3) || (r <= 0.0)) {
	 cerr << argv[0] << ": n-gon: n>=3 && r>0 " << endl;
	 return 1;
      }

      Poly p(argv[1], ios::out | ios::trunc);
      polytope::n_gon(p, n, r);
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
