#include <stdio.h>
#include "gcode_vm.h"
#include "gcode_exec.h"

gcode_prg_t prg;

static int ggetchar(gcode_prg_t *ctx)
{
	FILE *f = ctx->user_data;
	int chr = fgetc(f);
	return chr;
}

static int execute_code(gcode_prg_t *ctx, int code, double param)
{
	if (code == DO)
		printf("-- do\n");
	else
		printf("CALL %c %f\n", code, param);
	return 0;
}

static void error(gcode_prg_t *ctx, int runtime, const char *msg)
{
	fprintf(stderr, "g-code %s error:", runtime ? "runtime" : "compile");
	if (ctx->lineno >= 0) {
		fprintf(stderr, " (in N%d)\n", ctx->lineno);
		ctx->lineno = -1;
	}
	fprintf(stderr, "%s\n", msg);
}

static void travel(gcode_prg_t *prg, double x1, double y1, double z1, double x2, double y2, double z2)
{
	printf("TRAVEL %f;%f;%f -> %f;%f;%f\n", x1, y1, z1,  x2, y2, z2);
}

static void linear(gcode_prg_t *prg, double x1, double y1, double z1, double x2, double y2, double z2)
{
	printf("LINEAR %f;%f;%f -> %f;%f;%f\n", x1, y1, z1, x2, y2, z2);
}

static gcode_execute_op_t ops = {travel, linear};

int main(int argc, char *argv[])
{
	const char *fn = "a.gcode";
	FILE *fin = fopen(fn, "r");

	prg.get_char = ggetchar;
	prg.user_data = fin;
/*	prg.execute_code = execute_code;*/
	prg.error = error;
	if (gcodeparse(&prg) != 0)
		return 1;
	fclose(fin);

	printf("*** DUMP:\n");
	gcode_dump_prg("", &prg);

	printf("*** EXEC:\n");
	gcode_execute_init(&prg, &ops);
	gcode_execute(&prg);
	gcode_execute_uninit(&prg);

	return 0;
}
