#include "view.h"
#include <ctype.h>
#include <stdio.h>

static void errorMessage(message,filename)
char *filename,*message;
{
	printf("%s",message);
	printf(" file %s\n",filename);
	EXIT;
}
	

void readShape(filename,vertex,facelist,colour)
/*to read a data file - assumes facelist is initialised*/
char *filename;
Vertex **vertex;
FaceList *facelist;
Colour *colour;
{
	FILE *fp;
	int error,n,m,v;
	register int i,j;
	float x,y,z;
	Face *face;
	Shading *s;
	int list[100];
	
	fp = fopen(filename,"r");
	error = ferror(fp);
	if(error) errorMessage("I could not open",filename);
	else printf("Reading file %s\n",filename);
	
	/*read the number of coordinates m and the number of polygons n*/
	fscanf(fp,"%d %d",&m,&n);
	
	/*create a vertex of the appropriate size*/
	*vertex = newVertex(8*m);
	error = ferror(fp);
	if(error) errorMessage("something wrong with number of points in",filename);
	
	/*read the vertex data*/
	for(i=0;i<m;++i){
		fscanf(fp,"%f %f %f\n",&x,&y,&z);
		error = ferror(fp);
		if(error) errorMessage("something wrong with coordinates in",filename);
		else atPutCoordVertex(*vertex,i,(REAL)x,(REAL)y,(REAL)z);
		/*this REAL stuff is a fix for THINK C*/
	}
	
	/*for each face read number of vertices, list of vertices*/
	for(i=0;i<n;++i){
		fscanf(fp,"%d",&m);
		if(m < 3) errorMessage("wrong number of vertices in a face in",filename);
		
		/*read the first vertex*/
		fscanf(fp,"%d",&v);
		list[0] = v-1;
		for(j=1;j<m;++j){
			fscanf(fp,"%d",&v);
			list[j] = v-1;
		}
		
		face = newFace(*vertex,list[0]);
		for(j=1;j<m;++j){
			addToBackFace(face,list[j]);
		}
		
		/*set the shading*/
		s = newShading(colour->red,colour->green,colour->blue);
		setShadingOfFace(face,s);
		atPutFaceList(facelist,NEXTFreeFaceList(facelist),face);
	}
	printf("Finished reading file %s\n",filename);
}

	
	
