/*
 * comp.c - Component libraries
 *
 * Copyright 2012 by 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 <ctype.h>
#include <string.h>

#include "run.h"
#include "libs.h"


static const char *field(const char *s, int n)
{
	while (n-- && *s) {
		while (*s && !isspace(*s))
			s++;
		while (*s && isspace(*s))
			s++;
	}
	return *s ? s : NULL;
}


static void comp_add_lib(struct lib *lib, const char *path)
{
	FILE *file;
	struct entry *e = NULL;
	char buf[1024]; /* @@@ */
	char *name, *spc;
	const char *s;

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

	while (fgets(buf, sizeof(buf), file)) {
		if (!strncmp(buf, "ALIAS ", 6) && e)
			add_name(e, buf+6);
		if (strncmp(buf, "DEF ", 4))
			continue;
		s = field(buf, 7);
		if (!s) {
			fprintf(stderr, "DEF record lacks units field in %s\n",
			     path);
			exit(1);
		}
		name = buf+4;
		if (*name == '~')
			name++;
		spc = strchr(name, ' ');
		if (!spc) {
			fprintf(stderr, "invalid DEF line in %s\n", path);
			exit(1);
		}
		*spc = 0;
		e = new_entry(lib, atoi(s));
		if (!e->units) {
			fprintf(stderr, "invalid number of units in %s\n",
			    path);
			exit(1);
		}
		add_name(e, name);
	}

	fclose(file);
}


static void comp_ps_entry(FILE *file, const struct lib *lib,
    const struct entry *e, int unit, int landscape)
{
	if (!landscape)
		fprintf(file, "-120 700 translate -90 rotate\n");
	run_cmd("sym2xps '%s' '%s' %d '%s' '%s'",
	    e->file->path, e->names->s, unit+1, "tmp", "tmp.ps");
	cat(file, "tmp.ps");
}


struct lib comp_lib = {
	.ext		= ".lib",
	.add_lib	= comp_add_lib,
	.ps_entry	= comp_ps_entry,
};