/* XYZto3DV  -  convert XYZ editor binary (.3DL) output to 3DV */

/* Oscar Garcia <garciao@mof.govt.nz>, May 1992 */

#include <stdlib.h>
#include <stdio.h>
#include <io.h>
#include <alloc.h>
#include <fcntl.h>

#define USAGE "usage: XYZto3DV [infile [outfile]]\n\
\tIf file names are omitted, the standard i/o streams are used.\n"

#define ERROR(msg) {fputs(msg,stderr),exit(1);}
#define PERROR(msg) {perror(msg),exit(1);}


void main(int argc, char* argv[])
{
	unsigned i, j, m, n;
	int  *x;
	unsigned long memory;
	FILE *input = stdin, *output = stdout;

	/* open files */
	if (argc > 3)
		ERROR(USAGE);   /* wrong arguments */
	if (argc > 1)
	{	input = fopen(argv[1], "rb");
		if (input == NULL)
		{	fputs("Can't open input file\n", stderr);
			ERROR(USAGE);
		}
	}
	else
		setmode(0, O_BINARY);
	if (argc > 2)
	{	output = fopen(argv[2], "wt");
		if (output == NULL)
			ERROR("Can't open output file");
	}

	/* get points */
	memory = coreleft() - 999;
#ifdef __MSDOS__
	if (memory > 0xfff0U)
		memory = 0xfff0U;
#endif
	m = memory / sizeof(int);
	x = (int*)malloc(m * sizeof(int));
	for (i = 0; feof(input) == NULL && i < m; i++)
		x[i] = getw(input);
	if (ferror(input))
		PERROR("Input error");
	fclose(input);
	if (i >= m)
		ERROR("Out of memory");
	n = (i-1)/7;	/* number of segments */
	m = 7 * n;
	if (m != i-1)
		fputs("Warning! Wrong number of items in input\n", stderr);

	/* output points */
	fprintf(output, "%d\n", 2 * n);		/* number of points */
	for (i = 0; i < m; i += 7)
		fprintf(output, "%d %d %d\n%d %d %d\n", x[i], x[i+1], x[i+2],
			x[i+3], x[i+4], x[i+5]);

	/* output lines */
	fprintf(output, "%d\n", 2 * n);		/* number of moves/draws */
	for (i = 6, j = 1; i < m; i += 7, j += 2)
		fprintf(output, "%d 0\n%d %d\n", j, j+1, x[i]);

	if (ferror(output))
		PERROR("Error on output");
	fclose(output);
}
