
/*
 * fmt_new.c -- read format file/string and normalize
 *
 * $Id$
 */

#include <h/mh.h>

#define QUOTE '\\'

static char *formats = 0;

/*
 * static prototypes
 */
static void normalize (char *);


/*
 * MAJOR HACK: See MHCHANGES for discussion
 */

char *
new_fs (char *form, char *format, char *def)
{
    struct stat st;
    register FILE *fp;

    if (formats)
	free (formats);

    if (form) {
	if ((fp = fopen (etcpath (form), "r")) == NULL)
	    adios (form, "unable to open format file");

	if (fstat (fileno (fp), &st) == NOTOK)
	    adios (form, "unable to stat format file");

	if (!(formats = malloc ((size_t) st.st_size + 1)))
	    adios (form, "unable to allocate space for format");

	if (read (fileno(fp), formats, (int) st.st_size) != st.st_size)
	    adios (form, "error reading format file");

	formats[st.st_size] = '\0';

	fclose (fp);
    } else {
	formats = getcpy (format ? format : def);
    }

    normalize (formats);

    return formats;
}

#define	grot(y,z) case y: *dp++ = z; break;

static void
normalize (char *cp)
{
    register char *dp;

    for (dp = cp; *cp; cp++) {
	if (*cp != QUOTE) {
	    *dp++ = *cp;
	} else {
	    switch (*++cp) {
		grot ('b', '\b');
		grot ('f', '\f');
		grot ('n', '\n');
		grot ('r', '\r');
		grot ('t', '\t');

		case '\n':
		    break;

		case 0: 
		    cp--;	/* fall */
		default: 
		    *dp++ = *cp;
		    break;
	    }
	}
    }
    *dp = 0;
}
