/* 2DtoEXF  -  convert 2-D list to Evolution Computing (EasyCAD, FastCAD)
				Echange File Format (.EXF) */

/* Oscar Garcia <garciao@mof.govt.nz>, May 1992 */

#include <stdlib.h>
#include <stdio.h>

#define USAGE "usage: 2DtoEXF [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);}


#define RECLEN 81

void main(int argc, char* argv[])
{
	int c;
	double x, y, x0 = 0, y0 = 0;
	char comment[RECLEN + 1];
	FILE *input = stdin, *output = stdout;

	/* open files */
	if (argc > 3)
		ERROR(USAGE);   /* wrong arguments */
	if (argc > 1)
	{	input = fopen(argv[1], "rt");
		if (input == NULL)
		{	fputs("Can't open input file\n", stderr);
			ERROR(USAGE);
		}
	}
	if (argc > 2)
	{	output = fopen(argv[2], "wt");
		if (output == NULL)
			ERROR("Can't open output file");
	}

	/* fake file name */
	fputs("3DV.DWG\n\n", output);

	/* transfer comments */
	while ((c = getc(input)) == '#')
	{	fgets(comment, RECLEN, input);
		putc(';', output);
		fputs(comment, output);
	}
	if (ferror(input))
		PERROR("Bad file");
	ungetc(c, output);

	/* do it */
	while (3 == fscanf(input, "%lf %lf %d", &x, &y, &c))
	{	if (c != 0)
		{	/* draw */
			fprintf(output, "LINE\n1,%d,%g,%g,%g,%g,1\n\n",
				c, x0, y0, x, y);
		}
		x0 = x;
		y0 = y;
	}

	if (ferror(input))
		PERROR("Error on input");
	fclose(input);

	fputs("EOF\n", output);
	if (ferror(output))
		PERROR("Error on output");
	fclose(output);
}
