/* SHDto3DV.c  -  convert "shaded" format to 3DV */

/* Oscar Garcia <garciao@mof.govt.nz>, May 1992 */

/* uses getopt */
int getopt(int argc, char *argv[], char *options);
extern  int optind;
extern char *optarg;

#include <stdlib.h>
#include <stdio.h>
#include <alloc.h>

#define USAGE "usage: SHDto3DV [/cn] [infile] [outfile]\n\
\tIf file names are omitted, the standard i/o streams are used.\n\
\tOptions (with defaults):\n\
\t\t/c9  -  colour\n"

#define ERROR(msg) {fputs(msg,stderr),exit(1);}
#define PERROR(msg) {perror(msg),exit(1);}

void main(int argc, char* argv[])
{
	int npoints, nfaces, i, n, m, p, *a, colour = 9;
	unsigned long memory;
	FILE *infile = stdin, *outfile = stdout;
	char line[82];
	char options[] = "c:";

	/* get options */
	while ((n = getopt(argc, argv, options)) != EOF)
	{	if (n == '?')
			ERROR(USAGE)
		else
			colour = atoi(optarg);
	}

	/* open files */
	if (optind < argc - 2)
		ERROR(USAGE);	/* too many */
	if (optind < argc)
	{	infile = fopen(argv[optind], "rt");
		if (infile == NULL)
			ERROR("Can't open input file");
		if (++optind < argc)
		{	outfile = fopen(argv[optind], "wt");
			if (outfile == NULL)
				ERROR("Can't open output file");
		}
	}

	/* first line (counts) */
	if (2 != fscanf(infile, "%d %d", &npoints, &nfaces) ||
			NULL == fgets(line,81,infile))
		ERROR("error reading first line");
	fprintf(outfile, "%d\n", npoints);

	/* skip second line (limits) */
	if (NULL == fgets(line, 81, infile))
		ERROR("error reading second line");

	/* copy coordinates */
	for (i = 1; i <= npoints; i++)
	{	if (NULL == fgets(line, 81, infile))
		{	fprintf(stderr, "error reading point #%d", i);
			exit(1);
		}
		fputs(line, outfile);
	}

	/* process faces */
	memory = coreleft() - 999;
#ifdef __MSDOS__
	if (memory > 0xfff0U)
		memory = 0xfff0U;
#endif
	memory = memory / sizeof(int);
	a = (int*) malloc(memory * sizeof(int));
	if (a == NULL)
		ERROR("memory allocation failure");
	n = 0;
	for (n = 0; nfaces > 0 && n < memory; nfaces--)
	{	fscanf(infile, "%d %d", &m, &p);
		a[n++] = -p;	/* flag move with - */
		while (--m > 0)
			fscanf(infile, "%d", &a[n++]);
		a[n++] = p;		/* close the face */
	}
	if (n >= memory)
		ERROR("out of memory");
	if (ferror(infile))
		PERROR("error reading file");
	if (feof(infile))
		ERROR("unexpected end of file on input");
	fclose(infile);


	/* output lines */
	fprintf(outfile, "%d\n", n);
	for (i = 0; i < n; i++)
	{	if (a[i] < 0)
			fprintf(outfile, "%d %d\n", -a[i], 0); /* move */
		else
			fprintf(outfile, "%d %d\n", a[i], colour); /* draw */
	}
	if (ferror(outfile))
		PERROR("eror writing output");
	fclose(outfile);

}
