static char rcsid[] = "$Header: /usr/jjc/dvitops/RCS/psfont.c,v 1.2 89/02/20 14:24:06 jjc Rel $";

#include "util.h"

#define LINE_MAX 512
char *program_name = "psfont";
static char *ws = " \n\r\t";	/* white space */
static char *psfonts;

#ifdef PROTO
int strprefix(char *s1, char *s2);
void fcopy(FILE *in, FILE *out);
void process_fonts(void);
#endif

/* is s1 a prefix of s2? */
int strprefix(s1, s2)
char *s1, *s2;
{
	while (*s1++ == *s2++)
		;
	return s1[-1] == '\0';
}

/* copy infp to outfp */
void fcopy(infp, outfp)
FILE *infp, *outfp;
{
	int c;
	while ((c = getc(infp)) != EOF)
		putc(c, outfp);
}
	
struct string_list {
	struct string_list *next;
	char *s;
	char *t;
};
struct string_list *document_fonts = NULL;

/* map PostScript names to file names */

void process_fonts()
{
	char buf[LINE_MAX];
	FILE *fp;
	fp = xfopen("psfonts.map", FALSE, psfonts, NULL);
	if (fp == 0)
		return;
	while (fgets(buf, LINE_MAX, fp) != 0) {
		char *s, *t;
		s = strchr(buf, '%');
		if (s != NULL)
			*s = '\0';
		s = strtok(buf, ws);
		t = strtok(NULL, ws);
		if (s != 0 && t != 0) {
			struct string_list *q;
			for (q = document_fonts; q != NULL; q = q->next)
				if (strcmp(q->s, s) == 0) {
					q->t = malloc(strlen(t) + 1);
					if (q->t == NULL)
						out_of_memory();
					strcpy(q->t, t);
				}
		}
	}
	fclose(fp);
}


int main(argc, argv)
int argc;
char **argv;
{
	int flag = FALSE;
	int cont = FALSE;
	char *ptr;
	char buf[LINE_MAX];
	psfonts = getenv("PSFONTS");
	if (psfonts == NULL)
		psfonts = PSFONTS;
	if (fgets(buf, LINE_MAX, stdin) == 0)
		exit(0);
	fputs(buf, stdout);
	if (strprefix("%!PS-Adobe-", buf))
		while (fgets(buf, LINE_MAX, stdin) != 0) {
			if (!strprefix("%%", buf)) {
				flag = TRUE;
				fputs("%%EndComments\n", stdout);
				break;
			}
			fputs(buf, stdout);
			if (strprefix("%%EndComments", buf))
				break;
			if (document_fonts == NULL && strprefix("%%DocumentFonts:", buf))
				ptr = strchr(buf, ':') + 1;
			else if (cont && strprefix("%%+", buf))
				ptr = buf + 3;
			else
				ptr = NULL;
			if (ptr != NULL) {
				for (ptr = strtok(ptr, ws);
					 ptr != 0;
					 ptr = strtok(NULL, ws)) {
					struct string_list *p;
					p = (struct string_list *)
						malloc(sizeof(struct string_list));
					if (p == 0)
						out_of_memory();
					p->s = malloc(strlen(ptr) + 1);
					p->t = NULL;
					if (p->s == 0)
						out_of_memory();
					strcpy(p->s, ptr);
					p->next = document_fonts;
					document_fonts = p;
				}
				cont = TRUE;
			}
			else
				cont = FALSE;
		}
	process_fonts();
	while (document_fonts != 0) {
		FILE *fp;
		char *s;
		if (document_fonts->t != NULL)
			s = document_fonts->t;
		else
			s = document_fonts->s;
		fp = xfopen(s, FALSE, psfonts, NULL);
		if (fp != 0) {
			printf("%%%%BeginFont: %s\n", document_fonts->s);
			fcopy(fp, stdout);
			fclose(fp);
			printf("%%%%EndFont\n");
		}
		document_fonts = document_fonts->next;
	}
	if (flag)
		fputs(buf, stdout);
	fcopy(stdin, stdout);
	exit(history);
}