/*
 *  Copyright (c) 1994, Riley Rainey,  riley@netcon.com
 *
 *  Permission to use, copy, modify and distribute (without charge) this
 *  software, documentation, images, etc. is granted, provided that this 
 *  comment and the author's name is retained.
 *
 *  This software is provided by the author as is, and without any expressed
 *  or implied warranties, including, but not limited to, the implied
 *  warranties of merchantability and fitness for a particular purpose.  In no
 *  event shall the author be liable for any direct, indirect, incidental, or
 *  consequential damages arising in any way out of the use of this software.
 */

#include <string.h>

#include "../util/memory.h"

#define VReadObject_IMPORT
#include "VReadObject.h"


VObject *VReadObject2(FILE *f)
{
	short   I, J, vertex, vertices, NumPts, NumPolys;
	float   x, y, z;
	char    str[64], name[128];
	VPoint  *tmpPts, pts[VmaxVP];
	VPolygon **polygons;
	VObject *object;

	fscanf(f, "%s\n", name);
	fscanf(f, "%hd", &NumPts);
	fscanf(f, "%hd", &NumPolys);

	tmpPts = (VPoint *) memory_allocate(NumPts * sizeof(VPoint), NULL);
	polygons = (VPolygon **) memory_allocate(NumPolys * sizeof(VPolygon *), NULL);

	for (I=0; I<NumPts; ++I) {
		fscanf(f, "%hd", &J);
		fscanf(f, "%f", &x);
		fscanf(f, "%f", &y);
		fscanf(f, "%f", &z);
		tmpPts[I].x = x;
		tmpPts[I].y = y;
		tmpPts[I].z = z;
	}

	for (I=0; I<NumPolys; ++I) {
		fscanf(f, "%s %hd", str, &(vertices));
		for (J=0; J<vertices; ++J) {
			fscanf(f, "%hd", &(vertex));
			pts[J] = tmpPts[vertex - 1];
		}
		polygons[I] = VCreatePolygon (vertices, pts, VColor_getByName(str, 0));
	}

	object = (VObject *) memory_allocate(sizeof(VObject), NULL);
	object->name = memory_strdup (name);
	object->numPolys = NumPolys;
	object->polygon = polygons;

	memory_dispose(tmpPts);
	return ferror(f) ? (VObject *) 0 : object;
}
