/*
 *                            COPYRIGHT
 *
 *  camv-rnd - electronics-related CAM viewer - low level gerber parser
 *  Copyright (C) 2019 Tibor 'Igor2' Palinkas
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 31 Milk Street, # 960789 Boston, MA 02196 USA.
 *
 *  Contact:
 *    Project page: http://repo.hu/projects/camv-rnd
 *    lead developer: http://repo.hu/projects/camv-rnd/contact.html
 *    mailing list: pcb-rnd (at) list.repo.hu (send "subscribe")
 */

#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#include "geparse.h"

/*** hidlib emulation (glue) ***/
#undef rnd_message
#undef rnd_message_level
enum rnd_message_level {RND_MSG_DUMMY};
void rnd_message(enum rnd_message_level ignored, const char *fmt, ...)
{
	va_list args;

	va_start(args, fmt);
	vfprintf(stderr, fmt, args);
	va_end(args);
}

/* Implementation idea borrowed from an old gcc (GPL'd) */
double rnd_round(double x)
{
	double t;

/* We should check for inf here, but inf is not in C89; if we'd have isinf(),
   we'd have round() as well and we wouldn't be here at all. */

	if (x >= 0.0) {
		t = ceil(x);
		if (t - x > 0.5)
			t -= 1.0;
		return t;
	}

	t = ceil(-x);
	if ((t + x) > 0.5)
		t -= 1.0;
	return -t;
}


/*** parser ***/
static int ge_getchar(geparse_ctx_t *ctx)
{
	return fgetc(stdin);
}


int main()
{
	geparse_ctx_t ctx;
	ge_parse_res_t res;

	memset(&ctx, 0, sizeof(ctx));
	ctx.get_char = ge_getchar;
	while((res = geparse(&ctx)) == GEP_NEXT) ;
	if (res == GEP_ERROR) {
		fprintf(stderr, "parse error at %ld:%ld: %s\n", ctx.line, ctx.col, ctx.errmsg);
		geparse_free(&ctx);
		return 1;
	}

	gedraw_dump_code(stderr, &ctx.draw);

	geparse_free(&ctx);
	return 0;
}
