/* This file is part of the Neper software package. */
/* Copyright (C) 2003-2014, Romain Quey. */
/* See the COPYING file in the top-level directory. */

#include"net_polycomp_.h"
#include<ANN/ANN.h>

extern void PolyhedronCalculation (struct POLY Domain, struct SEEDSET SeedSet,
				   ANNkd_tree* kdTree, int PolyId,
				   struct POLY *pPoly, int* neighqty);

/* net_polycomp builds the set of Voronoi polyhedra from the set
 * of seed and the initial domain.
 */
void
net_polycomp (struct POLY Domain, struct SEEDSET SeedSet, struct POLY **pPoly,
	      int verbosity)
{
  int i, neighqty;
  double meanneighqty;
  char *message = (char*) calloc (10, sizeof (char));
  ANNkd_tree *kdTree;

  kdTree = new ANNkd_tree (SeedSet.SeedCoo + 1, SeedSet.N,
      SeedSet.Dim);

  // If *pPoly is not empty, free'ing
  neut_poly_array_free (pPoly, SeedSet.N);

  // Alloc'ing Poly
  (*pPoly) = (POLY *) calloc (SeedSet.N + 1, sizeof (POLY));

  // Calculating polys one by one
  meanneighqty = -1;
  neighqty = -1;
  for (i = 1; i <= SeedSet.N; i++)
  {
    neighqty = ut_num_d2ri (meanneighqty);

    PolyhedronCalculation (Domain, SeedSet, kdTree, i, &((*pPoly)[i]),
			   &neighqty);

    meanneighqty = (meanneighqty * (i - 1) + neighqty) / i;

    if (verbosity)
      ut_print_progress_nonl (stdout, i, SeedSet.N, "%3.0f%%", message);
  }

  delete kdTree;
  annClose ();

  free (message);

  return;
}
