/*
 * r-font.c -- troffcvt reader font machinery.
 */

# include	<stdio.h>
# include	<ctype.h>
# ifndef	STRING_H
# define	STRING_H <string.h>
# endif
# include	STRING_H

# include	"etm.h"
# include	"memmgr.h"
# include	"tokenscan.h"

# include	"tcgen.h"
# include	"tcread.h"


TCRFont	*tcrFontList = (TCRFont *) NULL;


/*
 * Read font information file.  Format of lines is
 *
 * troff-font-name typeface attributes
 *
 * attributes is empty (plain), or some combination of "italic" or "bold",
 * indicating what style attributes the font has in relation to the plain
 * font for the typeface.  E.g.,
 *
 * R	Times
 * I	Times	italic
 * B	Times	bold
 * BI	Times	bold italic
 */

int
TCRReadFonts (char *filename)
{
FILE	*f;
char	buf[bufSiz];
TCRFont	*fp, *fp2;
char	*tName;
char	*face;
char	*p;
static int	fnum = 0;

	if ((f = TCROpenLibFile (filename, "r")) == (FILE *) NULL)
		return (0);
	while (TCRGetLine (buf, (int) sizeof (buf), f))
	{
		if (buf[0] == '#')	/* skip comments */
			continue;
		TSScanInit (buf);
		if ((tName = TSScan ()) == (char *) NULL
				|| (face = TSScan ()) == (char *) NULL)
			continue;
		fp = New (TCRFont);
		fp->tcrTroffName = StrAlloc (tName);
		fp->tcrTypeFace = StrAlloc (face);
		fp->tcrAtts = 0;		/* start with "plain" */
		while ((p = TSScan ()) != NULL)
		{
			if (strcmp (p, "italic") == 0)
				fp->tcrAtts |= tcrItal;
			else if (strcmp (p, "bold") == 0)
				fp->tcrAtts |= tcrBold;
			else
			{
				ETMMsg ("%s: unknown attribute for font %s: %s",
					"TCRReadFonts", fp->tcrTroffName, p);
			}
		}
		/*
		 * See if this is first font in family and assign
		 * new number if so; use existing number otherwise.
		 */
		for (fp2 = tcrFontList; fp2 != (TCRFont *) NULL; fp2 = fp2->nextTCRFont)
		{
			if (strcmp (fp2->tcrTypeFace, face) == 0)
				break;
		}
		if (fp2 == (TCRFont *) NULL)
			fp->tcrFontNum = ++fnum;
		else
			fp->tcrFontNum = fp2->tcrFontNum;
		fp->nextTCRFont = tcrFontList;
		tcrFontList = fp;
	}
	(void) fclose (f);
	return (1);
}


TCRFont *
TCRLookupFont (char *fontname)
{
TCRFont	*fp;

	for (fp = tcrFontList; fp != (TCRFont *) NULL; fp = fp->nextTCRFont)
	{
		if (strcmp (fontname, fp->tcrTroffName) == 0)
			break;
	}
	return (fp);		/* NULL if not found */
}
