/*
 * gcc -o hpgl2wav hpgl2wav.c
 */

#include <stdint.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *args[])
{
	FILE *infp;
	FILE *outfp;
	char c;
	int rStat = -1;
	
	char cmd[3];	/* Command string */
	char cx[8];	/* Coordinate X */
	char cy[8];	/* Coordinate Y */
	int cp = 0, cmdp = 0;
	int xy = 0;
	
	int x0, y0, x1, y1;
	int px, py;
	int dx, dy, sx, sy;
	int err, e2;
	int16_t outx, outy;

	if (argc < 2) {
		fprintf(stderr, "Usage:\n");
		fprintf(stderr, "  %s infile.hpgl [outfile.raw]\n\n", args[0]);
		fprintf(stderr, "Sends to stdout if outfile.raw is omitted.\n");
		return 1;
	}
	
	if (argc == 2) { 
		outfp = stdout;
	} else {
		outfp = fopen(args[2], "w");
	}
	
	infp = fopen(args[1], "r");

	//fprintf(stderr, "File: %s\n", args[1]);
	for(;;) {
		cp = 0;
		cmdp = 0;
		xy = 0;
		for (;;) {
			rStat = fread(&c, 1, 1, infp);
			if(rStat == 0) break;
			if (c == ';') {
				y0 = y1;
				y1 = atoi(cy)/14 - 96;
				for (cp=0; cp<8; cp++) cy[cp] = 0;
				cp = 0;
				break;
			}
			if (c == ',') {
				x0 = x1;
				x1 = atoi(cx)/14 - 96;
				for (cp=0; cp<8; cp++) cx[cp] = 0;
				cp = 0;
				xy = 1;
			}
			if (c >= '0' && c <= '9' || c == '-') {
				if (xy) {
					cy[cp++] = c;
				} else {
					cx[cp++] = c;
				}
			}
			if (c >= 'A' && c <= 'Z') {
				cmd[cmdp++] = c;
				if (cmdp>3) {
					fprintf(stderr, "Command error, '%s'\n", cmd);
					return 1;
				}
				cmd[2] = 0;
			}
				
		}
		if (rStat == 0) break;
		//fprintf (stderr, "c:'%s' x0:%i y0:%i x1:%i y1:%i\n", cmd, x0, y0, x1, y1);
		if (strcmp("PU", cmd) == 0) {
			x0 = x1;
			y0 = y1;
		}
		if (strcmp("PD", cmd) == 0) {
			px = x0;
			py = y0;
			dx = abs(x1-x0);
			dy = abs(y1-y0);
			sx = x0<x1 ? 1 : -1;
			sy = y0<y1 ? 1 : -1;
			err = (dx>dy ? dx : -dy)/2;
			for(;;) {
				outx = px * 256;
				outy = py * 256;
				fwrite(&outx, sizeof(outx), 1, outfp);
				fwrite(&outy, sizeof(outy), 1, outfp);
				if (px == x1 && py == y1) break;
				e2 = err;
				if (e2 > -dx) {
					err -= dy;
					px += sx;
				}
				if (e2 < dy) {
					err += dx;
					py += sy;
				}
			}
		}
	}
	return 0;
}

