#include "stdio.h"
#include "stdlib.h"
#include "math.h"

/*
	The basis of a converter from these simple Super3D files to other formats
	This is by no means a Super3D translator
	The files have been left in Super3D format as that was the original
	authors choice.
	Each output line consists of the number of vertices then the vertices 
	themselves. If the number of vertices is 2 then it's a line, otherwise
	ot's a facet with the corresponding number of vertices.
*/

int ReadLine(FILE *,char *,int);

typedef struct {
	double x,y,z;
} XYZ;

#define NPMAX 20

int main(int argc,char **argv)
{
	int i,np=0,nface=0;
	char fname[64];
	char aline[130],cmd[32];
	XYZ n,p[NPMAX];
	FILE *fout,*fptr;

	/* Check command line arguments */
	if (argc < 2) {
		fprintf(stderr,"Usage: %s super3dfilename\n",argv[0]);
		exit(-1);
	}

	/* Attempt to open the file */
	if ((fptr = fopen(argv[1],"r")) == NULL) {
		fprintf(stderr,"Unable to open input file\n");
		exit(-1);
	}

	/* Attempt to open the output file */
	strcpy(fname,argv[1]);
	for (i=0;i<strlen(fname);i++)
		if (fname[i] == '.')
			fname[i] = '\0';
	strcat(fname,".raw");
	if ((fout = fopen(fname,"w")) == NULL) {
		fprintf(stderr,"Unable to open output file\n");
		exit(-1);
	}
	fprintf(stderr,"Creating %s\n",fname);

	/* Read and deal with each line in turn */
	while (ReadLine(fptr,aline,128)) {
		if (strstr(aline,"normal") != NULL || 
			 strstr(aline,"return") != NULL ||
			 strstr(aline,"start")  != NULL) {
			if (sscanf(aline,"%s %lf %lf %lf",cmd,&n.x,&n.y,&n.z) != 4) {
				fprintf(stderr,"Unexpected \"normal\" syntax\n");
				exit(-1);
			}
			fprintf(stderr,"%d ",np);
			if (np > 1) {
				fprintf(fout,"%d ",np);
				for (i=0;i<np;i++) 
					fprintf(fout,"%g %g %g ",p[i].x,p[i].y,p[i].z);
				fprintf(fout,"\n");
				nface++;
			} else if (np > 0) {
				fprintf(stderr,"Didn't expect just one vertex\n");
				exit(-1);
			}
			if (strstr(aline,"start")  != NULL) {
				p[0] = n;
				np = 1;
			} else {
				np = 0;
			}
		}
		if (strstr(aline,"polygon") != NULL ||
			 strstr(aline,"line")    != NULL) {
			if (sscanf(aline,"%s %lf %lf %lf",cmd,
				&(p[np].x),&(p[np].y),&(p[np].z)) != 4) {
            fprintf(stderr,"Unexpected \"polygon\" syntax\n");
            exit(-1);
         }
			np++;
			if (np >= NPMAX) {
				fprintf(stderr,"Polygon unexpectedly long\n");
				exit(-1);
			}
		}
	}
	fclose(fout);
	fclose(fptr);
	fprintf(stderr,"\nRead %d faces\n",nface);
}

int ReadLine(FILE *fptr,char *s,int lmax)
{
   int i=0,c;

   s[0] = '\0';
   while ((c = fgetc(fptr)) != '\n' && c != '\r') {
      if (c == EOF)
         return(FALSE);
      s[i] = c;
      i++;
      s[i] = '\0';
      if (i >= lmax)
         break;
   }
   return(TRUE);
}


