/*
 * cameo.c - Toolpath adaptation and machine control
 *
 * Written 2010 by Werner Almesberger
 * Copyright 2010 Werner Almesberger
 *
 * 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.
 */


#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include "path.h"
#include "ops.h"
#include "gnuplot.h"
#include "gerber.h"


extern int yyparse(void);
extern FILE *yyin;


static void run_script(const char *file)
{

	if (file) {
		yyin = fopen(file, "r");
		if (!yyin) {
			perror(file);
			exit(1);
		}
	}
	yyparse();
}


static void usage(const char *name)
{
	fprintf(stderr,
"usage: %s [-d] r_mm [in.gnuplot [out.gnuplot]]\n"
"       %s -g [-d] r_mm [in.gerber [out.gnuplot]]\n"
"       %s [script]\n\n"
"  -d  put a dog-bone notch in each concave external corner\n"
"  -g  input format is KiCad Gerber, not gnuplot\n"
    , name, name, name);
	exit(1);
}


int main(int argc, char **argv)
{
	char *in = NULL, *out = NULL;
	char *end;
	int gerber = 0, dog_bone = 0;
	double r;
	struct path *paths;
	int c;

	while ((c = getopt(argc, argv, "dg")) != EOF)
		switch (c) {
		case 'd':
			dog_bone = 1;
			break;
		case 'g':
			gerber = 1;
			break;
		default:
			usage(*argv);
		}

	switch (argc-optind) {
	case 3:
		out = argv[optind+2];
		/* fall through */
	case 2:
		in = argv[optind+1];
		/* fall through */
	case 1:
		r = strtod(argv[optind], &end);
		if (*end) {
			if (argc-optind != 1)
				usage(*argv);
			run_script(argv[optind]);
			return 0;
		}
		break;
	case 0:
		run_script(NULL);
		return 0;
	default:
		usage(*argv);
	}

	if (gerber)
		paths = gerber_read(in, r);
	else
		paths = gnuplot_read(in, r);
	tool_comp_paths(paths, dog_bone, 0);
	gnuplot_write(out, paths);

	return 0;
}