/*
 * 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 <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "xml-schem.h"

char *progname;
char *inname;

static void
xmlcheck(struct xml_schem *schem)
{
	struct xml_schem_port *port;
	struct xml_schem_component *comp;
	struct xml_schem_port *pin;

	/* Check for unconnected ports. */
	for (port = schem->port_first; port; port = port->next) {
		for (comp = schem->comp_first; comp; comp = comp->next) {
			for (pin = comp->port_first; pin; pin = pin->next) {
				if (strcmp(port->signal, pin->signal) == 0) {
					goto used;
				}
			}
		}
		printf("WARNING: %s: port %s not connected.\n", progname,
				port->name);
	used:	;
	}
}

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

int
main(int argc, char **argv)
{
	FILE *fp;
	struct xml_schem *schem;
	int ret;

	/*
	 * Get program name.
	 */
	progname = *argv;
	argc--;
	argv++;

	/*
	 * Get options.
	 */
	/* FIXME */

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

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

	schem = xml_schem_read(fp);

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

	/*
	 * Check schem.
	 */
	xmlcheck(schem);

	return 0;
}
