/*
 * 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.
 */

#define	_GNU_SOURCE /* for asprintf */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

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


static void fped_add_lib(struct lib *lib, const char *path)
{
	FILE *file;
	char buf[1024]; /* @@@ */
	char *tmp, *nl;

	asprintf(&tmp, "fped -k '%s' -", path);
	file = popen(tmp, "r");
	if (!file) {
		perror(path);
		exit(1);
	}

	while (fgets(buf, sizeof(buf), file)) {
		if (strncmp(buf, "$MODULE ", 8))
			continue;
		nl = strchr(buf, '\n');
		if (nl)
			*nl = 0;
		add_name(new_entry(lib, 1), buf+8);
	}

	pclose(file);
}


static void fped_ps_entry(FILE *file, const struct lib *lib,
    const struct entry *e, int unit, int landscape)
{
	fprintf(file, "0 -40 translate\n");
	run_cmd("fped -P -K -s x200 '%s' -1 '%s' '%s'",
	    e->file->path, e->names->s, "tmp.ps");
	run_cmd("sed -i -e '/OUT pdfmark/d' tmp.ps");
	cat(file, "tmp.ps");
}


struct lib fped_lib = {
	.ext		= ".fpd",
	.add_lib	= fped_add_lib,
	.ps_entry	= fped_ps_entry,
};