//
//    File: feature_mesh.cc
//
//    (C) 2000-2008 Helmut Cantzler
//
//    Licensed under the terms of the Lesser General Public License.
//

#include "feature_mesh.h"

int FeatureMesh::read(FILE *f, int (*updateProgress)(int pos),
		      void (*setTotal)(int size))
{
  list<Vertex*> *shapeVertices;
  list<Edge*> *shapeEdges;
  Vertex *v1, *v2;
  Edge *e;
  char type;
  float x, y, z;

  fseek(f, 0, SEEK_END);
  (*setTotal)(ftell(f));
  fseek(f, 0, SEEK_SET);

  shapeVertices = new list<Vertex*>;
  shapeEdges = new list<Edge*>;

  while ((type=fgetc(f)) != EOF)
    if (type == '#')
      do    // Reads till end of the line
	{
	  type=fgetc(f);
	}
      while (type != EOF && type != '\n');
    else
      if ((type=fgetc(f)) != EOF)
	{
	  switch (type)
	    {
	    case 'v': case 'V':
	      if (fscanf(f," %f %f %f\n",&x,&y,&z) != 3)
		{
		  FILE_ERROR(f, "File format error: v");
		  return 3;
		}
	      v1 = new Vertex(x,y,z);
	      addVertex(v1);
	      shapeVertices->push_back(v1);
	      break;
	      
	    case 'e': case 'E':
	      if (fscanf(f," %f %f %f",&x,&y,&z) != 3)
		{
		  FILE_ERROR(f, "File format error: e1");
		  return 4;
		}
	      v1 = new Vertex(x,y,z);
	      addVertex(v1);
	      shapeVertices->push_back(v1);
	      
	      if (fscanf(f," %f %f %f\n",&x,&y,&z) != 3)
		{
		  FILE_ERROR(f, "File format error: e2");
		  return 5;
		}
	      v2 = new Vertex(x,y,z);
	      addVertex(v2);
	      shapeVertices->push_back(v2);
	      
	      e = new Edge(v1, v2);
	      addEdge(e);
	      shapeEdges->push_back(e);
	      break;
	    }
	  
	  if ((*updateProgress)(ftell(f)))
	    return 90;
	}

  shapes->push_back(new Shape(shapeEdges, shapeVertices));

  return 0;
}

void FeatureMesh::write(FILE *f, const char *comment)
{
  list<Edge*>::iterator ie;
  list<Vertex*>::iterator iv;
  Vertex v;

  fprintf(f, "#Features\n");
  fprintf(f, "# %s\n", comment);

  if (edgeNr > 0)
    for (ie=edges->begin(); ie != edges->end(); ie++)
      {
	calcOriginalCoordinates((*ie)->vertices[0], &v);
	fprintf(f, "fe %f %f %f ", v.x(), v.y(), v.z());
	calcOriginalCoordinates((*ie)->vertices[1], &v);
	fprintf(f, "%f %f %f\n", v.x(), v.y(), v.z());
      }
  else
    for (iv=vertices->begin(); iv != vertices->end(); iv++)
      {
	calcOriginalCoordinates(*iv, &v);
	fprintf(f, "fv %f %f %f\n", v.x(), v.y(), v.z());
      }
}
