#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 interpretData(filename,vertex,facelist)
/*to read a data file - assumes that vertex and facelist are initialised*/
char *filename;
Vertex *vertex;
FaceList *facelist;
{
	FILE *fp;
	int error,c,n,v,m;
	register int i,j;
	REAL x,y,z;
	Face *face;
	Shading *s;

	fp = fopen(filename,"r");
	error = ferror(fp);
	if(error) errorMessage("I could not open",filename);

	/*read the number of coordinates n*/
	c = fgetc(fp);
	while((!isdigit(c)) && (c != '+') && (c != '-'))
		c = getc(fp);
	/*here c is a digit or a + or a - so put back on the stream*/
	ungetc(c,fp);

	fscanf(fp,"%d",&n);
	if(n <= 0)  errorMessage("wrong number of coordinates in",filename);

	for(i=0;i<n;++i){
		fscanf(fp,"%lf %lf %lf\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);
	}

	/*read number of faces n*/
	c = fgetc(fp);
	while((!isdigit(c)) && (c != '+') && (c != '-'))
		c = getc(fp);
	/*here c is a digit or a + or a - so put back on the stream*/
	ungetc(c,fp);

	fscanf(fp,"%d",&n);
	if(n <= 0)  errorMessage("wrong number of faces in",filename);

	/*for each face read number of vertices, list of vertices, shading*/
	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);
		face = newFace(vertex,v);
		for(j=1;j<m;++j){
			fscanf(fp,"%d",&v);
			addToBackFace(face,v);
		}

		/*read the shading*/
		fscanf(fp,"%lf %lf %lf",&x,&y,&z);
		s = newShading(x,y,z);
		setShadingOfFace(face,s);
		atPutFaceList(facelist,NEXTFreeFaceList(facelist),face);
	}
	fclose(fp);
}



