#include "node.h"
#include "points.h"

char *psbold, *psroman, *psitalic;

#define FWSIZE 256
float fwbold[FWSIZE];
float fwroman[FWSIZE];
float fwitalic[FWSIZE];
float *sizefont;

float fontnwid, fontmwid, fontspacewid, interfragspace;

static int fontisset;
char fontcheck[] = "font";
#define nfontcheck (sizeof(fontcheck) - 1)
struct fontwhich {
	char *fwtag;
	char **fwname;
	float *fwval;
} fontwhich[] = {
	"roman", &psroman, fwroman,
	"italic", &psitalic, fwitalic,
	"bold", &psbold, fwbold,
	NULL, NULL, NULL,
};

setfont() {
	FILE *fp;
	char linebuf[BUFSIZ + 2], *cp, *dp, *ep;
	struct fontwhich *fwp;
	int gotfont;

	if (fontisset)
		return;

	fp = openini(PSFONTS);
	while(fgets(linebuf, sizeof(linebuf)-1, fp)) {
		if (linebuf[0] == '#')
			continue;
		ep = linebuf + strlen(linebuf);
		while (--ep >= linebuf) {
			if (*ep != '\n' && *ep != '\r')
				break;
			*ep = 0;
		}
		if (linebuf[0] == '0')
			continue;
		if (strncmp(linebuf, fontcheck, nfontcheck) == 0) {
			cp = linebuf + nfontcheck + 1;
			for (dp = cp; *dp; dp++) {
				if (isspace(*dp))
					break;
			}
			while(*dp && isspace(*dp))
				*dp++ = 0;
			gotfont = 0;
			for (fwp = fontwhich; fwp -> fwtag; fwp++) {
				if (strncmp(cp, fwp -> fwtag,
				strlen(fwp -> fwtag)) == 0) {
/* fprintf(stderr, "font %s:%s:\n", fwp -> fwtag, dp); /**/
			getfont(fwp -> fwval, fp, fwp -> fwname, dp);
					gotfont++;
					break;
				}
			}
			if (!gotfont) {
				(void) fprintf(stderr,
					"Spurious font : %s\n", linebuf);
				exit(1);
			}
		}
	}
	(void)fclose(fp);
	sizefont = fwbold;
	fontnwid = sizefont['n'];
	fontmwid = sizefont['m'];
	fontspacewid = sizefont[' '];
	interfragspace = fontspacewid * NINTERFRAGSPACE;
/* fprintf(stderr, "m %g n %g\n", fontmwid, fontnwid); */
	fontisset = 1;
}

getfont(thisfont, fp, fname, fnameval)
float *thisfont;
FILE *fp;
char **fname, *fnameval;
{
	extern double atof();
	char linebuf[BUFSIZ + 2];
	int i = 0;

	*fname = malloc((unsigned)strlen(fnameval) + 1);
	(void)strcpy(*fname, fnameval);
	while(i < FWSIZE && fgets(linebuf, sizeof(linebuf)-1, fp)) {
		thisfont[i] = atof(linebuf);
		i++;
	}
	thisfont[' '] *= 1.6;	/* kludge! */
}
