/****************************************************************************
** GMAF - The Geometry Modeling Algorithms Framework
**
** Created : 03112000
**
** Copyright (C) 2000 by Le-Jeng Shiue.  All rights reserved.
**
****************************************************************************/
#include <assert.h>

#include "cgalConfig.h"
#include <CGAL/predicates_on_points_3.h>

#include "cgalPolyhedronBuilder.h"


template <class HDS>
cgalPolyhedronBuilder<HDS>::cgalPolyhedronBuilder(std::istream* in) {
    assert(in != NULL);
    mpInFile = in;
    mpInDataStructure = NULL;
    mXmin = 0; mYmin = 0; mZmin = 0;
    mXmax = 0; mYmax = 0; mZmax = 0;
}


template <class HDS>
cgalPolyhedronBuilder<HDS>::~cgalPolyhedronBuilder() {
}


template <class HDS>
void cgalPolyhedronBuilder<HDS>::operator()(HDS& hds) {
    CGAL::Polyhedron_incremental_builder_3<HDS> pb( hds, true);

    importMesh(pb);
}

template <class HDS>
void cgalPolyhedronBuilder<HDS>::importMesh(CGAL::Polyhedron_incremental_builder_3<HDS>& pb) {
    assert(mpInFile);
 
    int numV = 0;

    *mpInFile >> numV;
    Point* pointL = new Point[numV+1];
    
    int idxV = 0;
    float x,y,z;
    for (int idx = 0; idx < numV; idx++) {
	*mpInFile >> idxV >> x >> y >> z;
	pointL[idxV] = Point(x,y,z);

	// Create the bounding box
	mXmin = mXmin < x ? mXmin : x;
	mYmin = mYmin < y ? mYmin : y;
	mZmin = mZmin < z ? mZmin : z;
	mXmax = mXmax > x ? mXmax : x;
	mYmax = mYmax > y ? mYmax : y;
	mZmax = mZmax > z ? mZmax : z;
    }

    int numF = 0;
    *mpInFile >> numF;

    
    int degreeF = 0;
    pb.begin_surface( numV, numF);
    {
	for (int idx = 1; idx <= numV; idx++) {
	     pb.add_vertex(pointL[idx]);
	}	
	for (int idx = 0; idx < numF; idx++) {
	    *mpInFile >> degreeF;
	    pb.begin_facet();  
	    {
		for (int n = 0; n < degreeF; n++) {
		    *mpInFile >> idxV;
		    pb.add_vertex_to_facet(idxV-1);
		}		
	    }
	    pb.end_facet();
	}
    }
    pb.end_surface();
}
