/*
 * Copyright (C) 2016 FAUmachine Team <info@faumachine.org>.
 * This program is free software. You can redistribute it and/or modify it
 * under the terms of the GNU General Public License, either version 2 of
 * the License, or (at your option) any later version. See COPYING.
 */

#include <assert.h>
#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "xml-schem.h"

const char *progname;
const char *inname;


static void
do_work(void)
{
	FILE *fp;
	int ret;
	struct xml_schem *schem;
	struct xml_schem_port *port;
	struct xml_schem_signal *sig;
	struct xml_schem_name *name;

	/*
	 * Read schematic.
	 */
	fp = fopen(inname, "r");
	if (! fp) {
		fprintf(stderr, "%s: %s: %s.\n", progname, inname,
				strerror(errno));
		exit(1);
	}

	schem = xml_schem_read(fp);

	ret = fclose(fp);
	assert(0 <= ret);

	/*
	 * Generate port list.
	 */
	for (port = schem->port_first; port; port = port->next) {
		for (sig = schem->sig_first; ; sig = sig->next) {
			assert(sig);
			if (strcmp(port->signal, sig->id) == 0) {
				break;
			}
		}

		printf("%s", port->name);
		for (name = sig->name_first; name; name = name->next) {
			printf(" %s", name->name);
		}
		printf("\n");
	}

	/*
	 * Free schematic.
	 */
#if 0
	xml_schem_free(schem);
#endif
}

static void __attribute__((noreturn))
usage(int retval)
{
	fprintf(stderr, "Usage: %s xml-file\n", progname);
	exit(retval);
}

int
main(int argc, char **argv)
{
	int c;

	/*
	 * Get program name.
	 */
	progname = *argv;

	/*
	 * Get options.
	 */
	while ((c = getopt(argc, argv, "")) != -1) {
		switch (c) {
		default:
			usage(1);
			/*NOTREACHED*/
		}
	}
	argc -= optind;
	argv += optind;

	/*
	 * Get arguments.
	 */
	if (0 < argc) {
		inname = *argv;
		argc--;
		argv++;
	} else {
		usage(1);
		/*NOTREACHED*/
	}

	/*
	 * Do work.
	 */
	do_work();
	
	return 0;
}
