/*
 * outmap.c -- Routine to read output translation map
 */

# include	<stdio.h>

# include	"tokenscan.h"

# include	"rtf.h"


/*
 * Read in a file describing the relation between the standard character set
 * and an RTF translator's corresponding output sequences.  Each line consists
 * of a standard character name and the output sequence for that character.
 *
 * outMap is an array of strings into which the sequences should be placed.
 * It should be declared like this in the calling program:
 *
 *	char *outMap[rtfSC_MaxChar];
 *
 * reinit should be non-zero if outMap should be initialized before reading the
 * file, zero otherwise.  (This allows the map to be constructed by reading
 * several files.)  It's assumed that any existing strings in the map were
 * allocated by RTFStrSave().  The map is initialized BEFORE any attempt is
 * made to read the file.
 *
 * If the filename is an absolute pathname, look in the specified location
 * only.  Otherwise try to find the file in the current directory or the
 * library directory.
 */

int
RTFReadOutputMap (file, outMap, reinit)
char	*file;
char	*outMap[];
int	reinit;
{
FILE	*f;
char	buf[rtfBufSiz];
char	*name, *seq;
int	stdCode;
int	i;
TSScanner	scanner;
char		*scanEscape;

	/* clobber current mapping */

	if (reinit)
	{
		for (i = 0; i < rtfSC_MaxChar; i++)
		{
			RTFFree (outMap[i]);
			outMap[i] = (char *) NULL;
		}
	}

	if ((f = fopen (file, "r")) == (FILE *) NULL)
	{
		/* if abolute pathname, give up, else look in library */
		if (file[0] == rtfPathSep)
			return (0);
		sprintf (buf, "%s%s", RTFGetLibPrefix (), file);
		if ((f = fopen (buf, "r")) == (FILE *) NULL)
			return (0);
	}

	/*
	 * Turn off scanner's backslash escape mechanism while reading
	 * file.  Restore it later.
	 */
	TSGetScanner (&scanner);
	scanEscape = scanner.scanEscape;
	scanner.scanEscape = "";
	TSSetScanner (&scanner);

	/* read file */

	while (fgets (buf, (int) sizeof (buf), f) != (char *) NULL)
	{
		if(buf[0] == '#')	/* skip comment lines */
			continue;
		TSScanInit (buf);
		if ((name = TSScan ()) == (char *) NULL)
			continue;	/* skip blank lines */
		if ((stdCode = RTFStdCharCode (name)) < 0)
		{
			fprintf (stderr, "RTFReadOutputMap: ");
			fprintf (stderr, "unknown character name: %s\n", name);
			continue;
		}
		if ((seq = TSScan ()) == (char *) NULL)
		{
			fprintf (stderr, "RTFReadOutputMap: ");
			fprintf (stderr, "malformed output sequence line ");
			fprintf (stderr, "for character %s\n", name);
			continue;
		}
		if ((seq = RTFStrSave (seq)) == (char *) NULL)
		{
			fprintf (stderr, "RTFReadOutputMap: ");
			fprintf (stderr, "out of memory\n");
			exit (1);
		}
		outMap[stdCode] = seq;
	}
	scanner.scanEscape = scanEscape;
	TSSetScanner (&scanner);
	fclose(f);
	return (1);
}
