/*
** mhl.c -- the nmh message listing program
**
** This code is Copyright (c) 2002, by the authors of nmh.  See the
** COPYRIGHT file in the root directory of the nmh distribution for
** complete copyright information.
*/

#include <h/mh.h>
#include <h/signals.h>
#include <h/addrsbr.h>
#include <h/fmt_scan.h>
#include <h/tws.h>
#include <h/utils.h>
#include <signal.h>
#include <ctype.h>
#include <sys/stat.h>
#include <locale.h>
#include <sysexits.h>

/*
** MAJOR BUG:
** for a component containing addresses, ADDRFMT, if COMPRESS is also
** set, then addresses get split wrong (not at the spaces between commas).
** To fix this correctly, putstr() should know about "atomic" strings that
** must NOT be broken across lines.  That's too difficult for right now
** (it turns out that there are a number of degernate cases), so in
** oneline(), instead of
**
**       (*onelp == '\n' && !onelp[1])
**
** being a terminating condition,
**
**       (*onelp == '\n' && (!onelp[1] || (flags & ADDRFMT)))
**
** is used instead.  This cuts the line prematurely, and gives us a much
** better chance of getting things right.
*/

#define ONECOMP  0
#define TWOCOMP  1
#define BODYCOMP 2

#define QUOTE  '\\'

static struct swit switches[] = {
#define FORMSW  0
	{ "form formfile", 0 },
#define WIDTHSW  1
	{ "width columns", 0 },
#define VERSIONSW  2
	{ "Version", 0 },
#define HELPSW  3
	{ "help", 0 },
#define FORW1SW  4
	{ "forward", -7 },
#define FORW2SW  5
	{ "forwall", -7 },
#define NBODYSW  6
	{ "nobody", -6 },
	{ NULL, 0 }
};

char *version=VERSION;

#define NOCOMPONENT 0x000001  /* don't show component name   */
#define UPPERCASE   0x000002  /* display in all upper case   */
#define CENTER      0x000004  /* center line                 */
#define CLEARTEXT   0x000008  /* cleartext                   */
#define EXTRA       0x000010  /* an "extra" component        */
#define HDROUTPUT   0x000020  /* already output              */
#define LEFTADJUST  0x000040  /* left justify multiple lines */
#define COMPRESS    0x000080  /* compress text               */
#define ADDRFMT     0x000100  /* contains addresses          */
#define DATEFMT     0x000200  /* contains dates              */
#define FORMAT      0x000400  /* parse address/date/RFC-2047 field */
#define INIT        0x000800  /* initialize component        */
#define SPLIT       0x001000  /* split headers (don't concatenate) */
#define NONEWLINE   0x002000  /* don't write trailing newline */
#define RTRIM       0x004000  /* trim trailing whitespace    */
#define RAW         0x008000  /* print the raw input         */
#define LBITS       "\020\01NOCOMPONENT\02UPPERCASE\03CENTER\04CLEARTEXT\05EXTRA\06HDROUTPUT\07LEFTADJUST\010COMPRESS\011ADDRFMT\012DATEFMT\013FORMAT\014INIT\015SPLIT\016NONEWLINE\017RTRIM\020RAW"
#define GFLAGS      (NOCOMPONENT | UPPERCASE | CENTER | LEFTADJUST | COMPRESS | SPLIT)

struct mcomp {
	char *c_name;  /* component name */
	char *c_text;  /* component text */
	char *c_ovtxt; /* text overflow indicator */
	char *c_fstr;   /* iff FORMAT */
	struct format *c_fmt;  /*  .. */
	int c_offset;  /* left margin indentation */
	int c_ovoff;   /* overflow indentation */
	int c_width;   /* width of field */
	int c_cwidth;  /* width of component */
	long c_flags;
	struct mcomp *c_next;
};

static struct mcomp *msghd = NULL;
static struct mcomp *msgtl = NULL;
static struct mcomp *fmthd = NULL;
static struct mcomp *fmttl = NULL;

static struct mcomp global = {
	NULL, NULL, NULL, NULL, NULL, 0, -1, 80, -1, 0, NULL
};

static struct mcomp holder = {
	NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0, NOCOMPONENT, NULL
};

struct pair {
	char *p_name;
	long p_flags;
};

static struct pair pairs[] = {
	{ "Date", DATEFMT },
	{ "From", ADDRFMT },
	{ "Sender", ADDRFMT },
	{ "Reply-To", ADDRFMT },
	{ "To", ADDRFMT },
	{ "Cc", ADDRFMT },
	{ "Bcc", ADDRFMT },
	{ "Resent-Date", DATEFMT },
	{ "Resent-From", ADDRFMT },
	{ "Resent-Sender", ADDRFMT },
	{ "Resent-Reply-To", ADDRFMT },
	{ "Resent-To", ADDRFMT },
	{ "Resent-Cc", ADDRFMT },
	{ "Resent-Bcc", ADDRFMT },
	{ NULL, 0 }
};

struct triple {
	char *t_name;
	long t_on;
	long t_off;
};

static struct triple triples[] = {
	{ "nocomponent",  NOCOMPONENT, 0 },
	{ "uppercase", UPPERCASE, RAW },
	{ "nouppercase", 0, UPPERCASE },
	{ "center", CENTER, RAW },
	{ "nocenter", 0, CENTER },
	{ "leftadjust", LEFTADJUST, RAW },
	{ "noleftadjust", 0, LEFTADJUST },
	{ "compress", COMPRESS, RAW },
	{ "nocompress", 0, COMPRESS },
	{ "split", SPLIT, 0 },
	{ "nosplit", 0, SPLIT },
	{ "rtrim", RTRIM, RAW },
	{ "nortrim", 0, RTRIM },
	{ "raw", RAW|SPLIT|NOCOMPONENT|NONEWLINE, UPPERCASE|CENTER|LEFTADJUST|COMPRESS|DATEFMT|ADDRFMT },
	{ "addrfield", ADDRFMT, DATEFMT|RAW },
	{ "datefield", DATEFMT, ADDRFMT|RAW },
	{ "newline", 0, NONEWLINE|RAW },
	{ "nonewline", NONEWLINE, 0 },
	{ NULL, 0, 0 }
};


static int dobody    = 1;
static int forwflg   = 0;
static int forwall   = 0;

static int exitstat = 0;
static int mhldebug = 0;

static unsigned int column;

static int lm;
static int ovoff;
static int term;
static unsigned int wid;

static char *ovtxt;

static unsigned char *onelp;

static char *parptr;

static int num_ignores = 0;
static char *ignores[MAXARGS];

volatile sig_atomic_t eflag = 0;

/*
** Redefine a couple of functions.
** These are undefined later in the code.
*/

/*
** prototypes
*/
static void mhl_format(char *, int);
static int evalvar(struct mcomp *);
static int ptoi(char *, int *);
static int ptos(char *, char **);
static char *parse(void);
static void process(char *, int, int);
static void mhlfile(FILE *, char *, int, int);
static int mcomp_flags(char *);
static char *mcomp_add(long, char *, char *);
static void mcomp_format(struct mcomp *, struct mcomp *);
static struct mcomp *add_queue(struct mcomp **, struct mcomp **,
		char *, char *, int);
static void free_queue(struct mcomp **, struct mcomp **);
static void putcomp(struct mcomp *, struct mcomp *, int);
static char *oneline(char *, long);
static void putstr(char *);
static void putch(char);
static void intrser(int);

int sc_width(void);  /* from termsbr.c */


int
main(int argc, char **argv)
{
	int i, width = 0, vecp = 0;
	char *cp, *form = NULL;
	char buf[BUFSIZ], *files[MAXARGS];
	char **argp, **arguments;

	setlocale(LC_ALL, "");
	invo_name = mhbasename(argv[0]);

	/* read user profile/context */
	context_read();

	arguments = getarguments(invo_name, argc, argv, 1);
	argp = arguments;

	if ((cp = getenv("MHLDEBUG")) && *cp)
		mhldebug++;

	while ((cp = *argp++)) {
		if (*cp == '-') {
			switch (smatch(++cp, switches)) {
			case AMBIGSW:
				ambigsw(cp, switches);
				exit(EX_USAGE);
			case UNKWNSW:
				adios(EX_USAGE, NULL, "-%s unknown\n", cp);

			case HELPSW:
				snprintf(buf, sizeof(buf), "%s [switches] [files ...]", invo_name);
				print_help(buf, switches, 1);
				exit(argc == 2 ? EX_OK : EX_USAGE);
			case VERSIONSW:
				print_version(invo_name);
				exit(argc == 2 ? EX_OK : EX_USAGE);

			case FORMSW:
				if (!(form = *argp++) || *form == '-')
					adios(EX_USAGE, NULL, "missing argument to %s",
							argp[-2]);
				continue;

			case WIDTHSW:
				if (!(cp = *argp++) || *cp == '-')
					adios(EX_USAGE, NULL, "missing argument to %s",
							argp[-2]);
				if ((width = atoi(cp)) < 1)
					adios(EX_USAGE, NULL, "bad argument %s %s",
							argp[-2], cp);
				continue;

			case FORW2SW:
				forwall++;  /* fall */
			case FORW1SW:
				forwflg++;
				continue;

			case NBODYSW:
				dobody = 0;
				continue;
			}
		}
		files[vecp++] = cp;
	}

	mhl_format(form ? form : mhlformat, width);

	if (vecp == 0) {
		process(NULL, 1, vecp = 1);
	} else {
		for (i = 0; i < vecp; i++)
			process(files[i], i + 1, vecp);
	}

	if (forwall) {
		printf("\n------- End of Forwarded Message%s\n\n",
				vecp > 1 ? "s" : "");
	}

	fflush(stdout);
	if (ferror(stdout)) {
		adios(EX_IOERR, "output", "error writing");
	}

	return exitstat;
}


static void
mhl_format(char *file, int width)
{
	int i;
	char *bp, *cp;
	char *ap, buffer[BUFSIZ], name[NAMESZ];
	struct mcomp *c1;
	struct stat st;
	FILE *fp;
	static dev_t dev = 0;
	static ino_t ino = 0;
	static time_t mtime = 0;

	if (fmthd != NULL) {
		if (stat(etcpath(file), &st) != NOTOK
			&& mtime == st.st_mtime
			&& dev == st.st_dev
			&& ino == st.st_ino)
			goto out;
		else
			free_queue(&fmthd, &fmttl);
	}

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

	if (fstat(fileno(fp), &st) != NOTOK) {
		mtime = st.st_mtime;
		dev = st.st_dev;
		ino = st.st_ino;
	}

	global.c_ovtxt = global.c_fstr = NULL;
	global.c_fmt = NULL;
	global.c_offset = 0;
	global.c_ovoff = -1;
	if ((i = sc_width()) > 5)
		global.c_width = i;
	global.c_cwidth = -1;
	global.c_flags = 0;
	*ignores = NULL;

	while (vfgets(fp, &ap) == OK) {
		bp = ap;
		if (*bp == ';')
			continue;

		if ((cp = strchr(bp, '\n')))
			*cp = 0;

		if (*bp == ':') {
			c1 = add_queue(&fmthd, &fmttl, NULL, bp + 1,
					CLEARTEXT);
			continue;
		}

		parptr = bp;
		strncpy(name, parse(), sizeof(name));
		switch(*parptr) {
		case '\0':
		case ',':
		case '=':
			/*
			** Split this list of fields to ignore, and copy
			** it to the end of the current "ignores" list.
			*/
			if (!mh_strcasecmp(name, "ignores")) {
				char **tmparray;
				int n = 0;

				/* split the fields */
				tmparray = brkstring(mh_xstrdup(++parptr), ",",
						NULL);
				/*
				** copy pointers to split fields
				** to ignores array
				*/
				while (tmparray[n] && num_ignores<MAXARGS-1) {
					ignores[num_ignores++] = tmparray[n++];
				}
				ignores[num_ignores] = NULL;
				continue;
			}
			parptr = bp;
			while (*parptr) {
				if (evalvar(&global))
					adios(EX_CONFIG, NULL, "format file syntax error: %s", bp);
				if (*parptr)
					parptr++;
			}
			continue;

		case ':':
			c1 = add_queue(&fmthd, &fmttl, name, NULL, INIT);
			while (*parptr == ':' || *parptr == ',') {
				parptr++;
				if (evalvar(c1))
					adios(EX_CONFIG, NULL, "format file syntax error: %s", bp);
			}
			if (!c1->c_fstr && global.c_fstr) {
				if ((c1->c_flags & DATEFMT) &&
						(global.c_flags & DATEFMT)) {
					c1->c_fstr = mh_xstrdup(global.c_fstr);
				} else if ((c1->c_flags & ADDRFMT) &&
						(global.c_flags & ADDRFMT)) {
					c1->c_fstr = mh_xstrdup(global.c_fstr);
				}
			}
			continue;

		default:
			adios(EX_CONFIG, NULL, "format file syntax error: %s", bp);
		}
	}
	fclose(fp);

	if (mhldebug) {
		for (c1 = fmthd; c1; c1 = c1->c_next) {
			fprintf(stderr, "c1: name=\"%s\" text=\"%s\" ovtxt=\"%s\"\n", c1->c_name, c1->c_text, c1->c_ovtxt);
			fprintf(stderr, "\tfstr=0x%x fmt=0x%x\n", (unsigned int)(unsigned long) c1->c_fstr, (unsigned int)(unsigned long) c1->c_fmt);
			fprintf(stderr, "\toffset=%d ovoff=%d width=%d cwidth=%d\n", c1->c_offset, c1->c_ovoff, c1->c_width, c1->c_cwidth);
			fprintf (stderr, "\tflags=%s\n", snprintb(buffer, sizeof(buffer), (unsigned) c1->c_flags, LBITS));
		}
	}

out:
	if (width)
		global.c_width = width;
	if (global.c_width < 5)
		global.c_width = 10000;
}


static int
evalvar(struct mcomp *c1)
{
	char *cp, name[NAMESZ];
	struct triple *ap;

	if (!*parptr)
		return 0;
	strncpy(name, parse(), sizeof(name));

	if (!mh_strcasecmp(name, "component")) {
		if (ptos(name, &c1->c_text))
			return 1;
		c1->c_flags &= ~NOCOMPONENT;
		return 0;
	}

	if (!mh_strcasecmp(name, "overflowtext"))
		return ptos(name, &c1->c_ovtxt);

	if (!mh_strcasecmp(name, "formatfield")) {
		char *fmtstr;

		if (ptos(name, &cp))
			return 1;
		cp = concat("=", cp, NULL);
		fmtstr = new_fs(cp, NULL);
		mh_free0(&cp);
		c1->c_fstr = mh_xstrdup(fmtstr);
		c1->c_flags |= FORMAT;
		return 0;
	}

	if (!mh_strcasecmp(name, "decode")) {
		char *fmtstr;

		fmtstr = new_fs("=%(decode{text})", NULL);
		c1->c_fstr = mh_xstrdup(fmtstr);
		c1->c_flags |= FORMAT;
		return 0;
	}

	if (!mh_strcasecmp(name, "offset"))
		return ptoi(name, &c1->c_offset);
	if (!mh_strcasecmp(name, "overflowoffset"))
		return ptoi(name, &c1->c_ovoff);
	if (!mh_strcasecmp(name, "width"))
		return ptoi(name, &c1->c_width);
	if (!mh_strcasecmp(name, "compwidth"))
		return ptoi(name, &c1->c_cwidth);

	for (ap = triples; ap->t_name; ap++)
		if (!mh_strcasecmp(ap->t_name, name)) {
			c1->c_flags |= ap->t_on;
			c1->c_flags &= ~ap->t_off;
			return 0;
		}

	return 1;
}


static int
ptoi(char *name, int *i)
{
	char *cp;

	if (*parptr++ != '=' || !*(cp = parse())) {
		advise(NULL, "missing argument to variable %s", name);
		return 1;
	}

	*i = atoi(cp);
	return 0;
}


static int
ptos(char *name, char **s)
{
	char c, *cp;

	if (*parptr++ != '=') {
		advise(NULL, "missing argument to variable %s", name);
		return 1;
	}

	if (*parptr != '"') {
		for (cp = parptr; *parptr && *parptr != ':' && *parptr != ',';
				parptr++)
			continue;
	} else {
		for (cp = ++parptr; *parptr && *parptr != '"'; parptr++)
			if (*parptr == QUOTE)
				if (!*++parptr)
					parptr--;
	}
	c = *parptr;
	*parptr = 0;
	*s = mh_xstrdup(cp);
	if ((*parptr = c) == '"')
		parptr++;
	return 0;
}


static char *
parse(void)
{
	int c;
	char *cp;
	static char result[NAMESZ];

	for (cp = result; *parptr && (cp - result < NAMESZ); parptr++) {
		c = *parptr;
		if (isalnum(c)
				|| c == '.'
				|| c == '-'
				|| c == '_'
				|| c == '['
				|| c == ']')
			*cp++ = c;
		else
			break;
	}
	*cp = '\0';

	return result;
}


static void
process(char *fname, int ofilen, int ofilec)
{
	FILE *fp = NULL;
	struct mcomp *c1;

	if (fname) {
		fp = fopen(fname, "r");
		if (fp == NULL) {
			advise(fname, "unable to open");
			exitstat++;
			return;
		}
	} else {
		fname = "(stdin)";
		fp = stdin;
	}
	SIGNAL(SIGINT, intrser);
	mhlfile(fp, fname, ofilen, ofilec);

	SIGNAL(SIGINT, SIG_IGN);
	if (fp != stdin)
		fclose(fp);
	if (holder.c_text) {
		mh_free0(&(holder.c_text));
	}
	free_queue(&msghd, &msgtl);
	for (c1 = fmthd; c1; c1 = c1->c_next)
		c1->c_flags &= ~HDROUTPUT;
}

static boolean
simplematch(char *pattern, char *b)
{
	char *match = strrchr(pattern, '*');
	char repl;
	boolean ret;

	/* check if pattern ends with a * and is not escaped witch a \ */
	if (!match || match[1] || (match > pattern && match[-1] == '\\')) {
		if (!match || match[1]) {
			return mh_strcasecmp(pattern, b) == 0;
		}
		match[0] = '\0';
		match[-1] = '*';
		ret = mh_strcasecmp(pattern, b)==0;
		match[-1] = '\\';
		match[0] = '*';
		return ret;
	}

	repl = b[match-pattern];
	b[match-pattern] = '\0';
	*match = '\0';
	ret = (mh_strcasecmp(pattern, b) == 0);
	b[match-pattern] = repl;
	*match = '*';
	return ret;
}

static void
mhlfile(FILE *fp, char *mname, int ofilen, int ofilec)
{
	enum state state;
	struct field f = {{0}};
	struct mcomp *c1, *c2, *c3;
	char **ip;

	if (forwall) {
		printf("\n-------");
		if (ofilen == 1) {
			printf(" Forwarded Message%s", ofilec > 1 ? "s" : "");
		} else {
			printf(" Message %d", ofilen);
		}
		printf("\n\n");
	} else if (ofilec > 1) {
		if (ofilen > 1) {
			printf("\n\n\n");
		}
		printf(">>> %s\n\n", mname);
	}

	for (state = FLD2; !eflag; ) {
		switch (state = m_getfld2(state, &f, fp)) {
		case FLD2:
			for (ip = ignores; *ip; ip++)
				if (simplematch(*ip, f.name)) {
					break;
				}
			if (*ip) {
				continue;
			}

			for (c2 = fmthd; c2; c2 = c2->c_next)
				if (mh_strcasecmp(c2->c_name, f.name)==0) {
					break;
				}
			c1 = NULL;
			if (!((c3 = c2 ? c2 : &global)->c_flags & SPLIT))
				for (c1 = msghd; c1; c1 = c1->c_next)
					if (mh_strcasecmp(c1->c_name,
							c3->c_name)==0) {
						c1->c_text = mcomp_add(c1->c_flags, f.value, c1->c_text);
						break;
					}
			if (c1 == NULL) {
				c1 = add_queue(&msghd, &msgtl, f.name, f.value, 0);
			}
			if (c2 == NULL) {
				c1->c_flags |= EXTRA;
			}
			continue;

		case BODY2:
		case FILEEOF2:
			column = 0;
			for (c1 = fmthd; c1; c1 = c1->c_next) {
				if (c1->c_flags & CLEARTEXT) {
					putcomp(c1, c1, ONECOMP);
					continue;
				}
				if (mh_strcasecmp(c1->c_name, "messagename")==0) {
					holder.c_text = concat("(Message ",
							mname, ")\n", NULL);
					putcomp(c1, &holder, ONECOMP);
					mh_free0(&(holder.c_text));
					continue;
				}
				if (mh_strcasecmp(c1->c_name, "extras")==0) {
					for (c2 = msghd; c2; c2 = c2->c_next) {
						if (c2->c_flags & EXTRA) {
							putcomp(c1, c2, TWOCOMP);
						}
					}
					continue;
				}
				if (dobody && mh_strcasecmp(c1->c_name, "body")==0) {
					holder.c_text = mh_xstrdup(f.value);
					while (state == BODY2) {
						putcomp(c1, &holder, BODYCOMP);
						state = m_getfld2(state, &f, fp);
						free(holder.c_text);
						holder.c_text = mh_xstrdup(f.value);
					}
					mh_free0(&(holder.c_text));
					continue;
				}
				for (c2 = msghd; c2; c2 = c2->c_next) {
					if (mh_strcasecmp(c2->c_name,
							c1->c_name)==0) {
						putcomp(c1, c2, ONECOMP);
						if (!(c1->c_flags & SPLIT)) {
							break;
						}
					}
				}
			}
			return;

		case LENERR2:
		case FMTERR2:
		case IOERR2:
			advise(NULL, "format error in message %s", mname);
			exitstat++;
			return;

		default:
			adios(EX_SOFTWARE, NULL, "getfld() returned %d", state);
		}
	}
}


static int
mcomp_flags(char *name)
{
	struct pair *ap;

	for (ap = pairs; ap->p_name; ap++)
		if (!mh_strcasecmp(ap->p_name, name))
			return (ap->p_flags);

	return 0;
}


static char *
mcomp_add(long flags, char *s1, char *s2)
{
	char *dp;

	if (!(flags & ADDRFMT))
		return add(s1, s2);

	if (s2 && *(dp = s2 + strlen(s2) - 1) == '\n')
		*dp = 0;

	return add(s1, add(",\n", s2));
}


struct pqpair {
	char *pq_text;
	char *pq_error;
	struct pqpair *pq_next;
};


static void
mcomp_format(struct mcomp *c1, struct mcomp *c2)
{
	int dat[5];
	char *ap, *cp;
	char buffer[BUFSIZ], error[BUFSIZ];
	struct comp *cptr;
	struct pqpair *p, *q;
	struct pqpair pq;
	struct mailname *mp;

	ap = c2->c_text;
	c2->c_text = NULL;
	dat[0] = 0;
	dat[1] = 0;
	dat[2] = 0;
	dat[3] = sizeof(buffer) - 1;
	dat[4] = 0;
	fmt_compile(c1->c_fstr, &c1->c_fmt);

	if (!(c1->c_flags & ADDRFMT)) {
		FINDCOMP(cptr, "text");
		if (cptr)
			cptr->c_text = ap;
		if ((cp = strrchr(ap, '\n')))  /* drop ending newline */
			if (!cp[1])
				*cp = 0;

		fmt_scan(c1->c_fmt, buffer, sizeof(buffer) - 1, dat);
		/* Don't need to append a newline, dctime() already did */
		c2->c_text = mh_xstrdup(buffer);

		mh_free0(&ap);
		return;
	}

	(q = &pq)->pq_next = NULL;
	while ((cp = getname(ap))) {
		p = mh_xcalloc(1, sizeof(*p));

		if ((mp = getm(cp, NULL, 0, AD_NAME, error)) == NULL) {
			p->pq_text = mh_xstrdup(cp);
			p->pq_error = mh_xstrdup(error);
		} else {
			p->pq_text = mh_xstrdup(mp->m_text);
			mnfree(mp);
		}
		q = (q->pq_next = p);
	}

	for (p = pq.pq_next; p; p = q) {
		FINDCOMP(cptr, "text");
		if (cptr)
			cptr->c_text = p->pq_text;
		FINDCOMP(cptr, "error");
		if (cptr)
			cptr->c_text = p->pq_error;

		fmt_scan(c1->c_fmt, buffer, sizeof(buffer) - 1, dat);
		if (*buffer) {
			if (c2->c_text)
				c2->c_text = add(",\n", c2->c_text);
			if (*(cp = buffer + strlen(buffer) - 1) == '\n')
				*cp = 0;
			c2->c_text = add(buffer, c2->c_text);
		}

		mh_free0(&(p->pq_text));
		if (p->pq_error)
			mh_free0(&(p->pq_error));
		q = p->pq_next;
		mh_free0(&p);
	}

	c2->c_text = add("\n", c2->c_text);
	free (ap);
}


static struct mcomp *
add_queue(struct mcomp **head, struct mcomp **tail, char *name,
		char *text, int flags)
{
	struct mcomp *c1;

	c1 = mh_xcalloc(1, sizeof(*c1));

	c1->c_flags = flags & ~INIT;
	if ((c1->c_name = name ? mh_xstrdup(name) : NULL))
		c1->c_flags |= mcomp_flags(c1->c_name);
	c1->c_text = text ? mh_xstrdup(text) : NULL;
	if (flags & INIT) {
		if (global.c_ovtxt)
			c1->c_ovtxt = mh_xstrdup(global.c_ovtxt);
		c1->c_offset = global.c_offset;
		c1->c_ovoff = global. c_ovoff;
		c1->c_width = 0;
		c1->c_cwidth = global.c_cwidth;
		c1->c_flags |= global.c_flags & GFLAGS;
	}
	if (*head == NULL)
		*head = c1;
	if (*tail != NULL)
		(*tail)->c_next = c1;
	*tail = c1;

	return c1;
}


static void
free_queue(struct mcomp **head, struct mcomp **tail)
{
	struct mcomp *c1, *c2;

	for (c1 = *head; c1; c1 = c2) {
		c2 = c1->c_next;
		if (c1->c_name)
			mh_free0(&(c1->c_name));
		if (c1->c_text)
			mh_free0(&(c1->c_text));
		if (c1->c_ovtxt)
			mh_free0(&(c1->c_ovtxt));
		if (c1->c_fstr)
			mh_free0(&(c1->c_fstr));
		if (c1->c_fmt)
			mh_free0(&(c1->c_fmt));
		mh_free0(&c1);
	}

	*head = *tail = NULL;
}

static void
putcomp(struct mcomp *c1, struct mcomp *c2, int flag)
{
	int count, cchdr;
	unsigned char *cp;
	char trimmed_prefix[BUFSIZ];

	strncpy(trimmed_prefix, c1->c_text ? c1->c_text : c1->c_name, sizeof(trimmed_prefix) - 1);
	rtrim(trimmed_prefix);
	cchdr = 0;
	lm = 0;
	wid = c1->c_width ? c1->c_width : global.c_width;
	ovoff = (c1->c_ovoff >= 0 ? c1->c_ovoff : global.c_ovoff)
			+ c1->c_offset;
	if ((ovtxt = c1->c_ovtxt ? c1->c_ovtxt : global.c_ovtxt) == NULL)
		ovtxt = "";
	if (wid < ovoff + strlen(ovtxt) + 5)
		adios(EX_SOFTWARE, NULL, "component: %s width(%d) too small for overflow(%d)", c1->c_name, wid, ovoff + strlen(ovtxt) + 5);
	onelp = NULL;

	if (c1->c_flags & CLEARTEXT) {
		putstr((c1->c_flags & RTRIM) ? rtrim(c1->c_text) : c1->c_text);
		putstr("\n");
		return;
	}

	if (c1->c_flags & RAW) {
		switch (flag) {
		case ONECOMP:
			printf("%s:%s", c1->c_name, c1->c_text);
			break;
		case TWOCOMP:
			printf("%s:%s", c2->c_name, c2->c_text);
			break;
		case BODYCOMP:
			fputs(c2->c_text, stdout);
			break;
		default:
			adios(EX_SOFTWARE, NULL, "BUG: putcomp() is called with a unknown flag");
		}
		return;
	}

	if (c1->c_fstr && (c1->c_flags & (ADDRFMT | DATEFMT | FORMAT)))
		mcomp_format(c1, c2);

	if (c1->c_flags & CENTER) {
		count = (c1->c_width ? c1->c_width : global.c_width)
				- c1->c_offset - strlen(c2->c_text);
		if (!(c1->c_flags & HDROUTPUT) && !(c1->c_flags & NOCOMPONENT))
			count -= strlen(c1->c_text ? c1->c_text : c1->c_name)
					+ 2;
		lm = c1->c_offset + (count / 2);
	} else {
		if (c1->c_offset)
			lm = c1->c_offset;
	}

	if (!(c1->c_flags & HDROUTPUT) && !(c1->c_flags & NOCOMPONENT)) {
		if (c1->c_flags & UPPERCASE)  /* uppercase component also */
			for (cp = (c1->c_text ? c1->c_text : c1->c_name); *cp; cp++)
				if (islower(*cp))
					*cp = toupper(*cp);
		if (*c2->c_text && *c2->c_text != '\n' && *c2->c_text != '\r') {
			putstr(c1->c_text ? c1->c_text : c1->c_name);
		} else {
			putstr(trimmed_prefix);
		}
		if (flag != BODYCOMP) {
			putstr(": ");
			if (!(c1->c_flags & SPLIT))
				c1->c_flags |= HDROUTPUT;

		cchdr++;
		if ((count = c1->c_cwidth -
			strlen(c1->c_text ? c1->c_text : c1->c_name) - 2) > 0)
			while (count--)
				putstr(" ");
		} else
			c1->c_flags |= HDROUTPUT;  /* for BODYCOMP */
	}

	if (flag == TWOCOMP && !(c2->c_flags & HDROUTPUT)
		&& !(c2->c_flags & NOCOMPONENT)) {
		if (c1->c_flags & UPPERCASE)
			for (cp = c2->c_name; *cp; cp++)
				if (islower(*cp))
					*cp = toupper(*cp);
		putstr(c2->c_name);
		putstr(": ");
		if (!(c1->c_flags & SPLIT))
			c2->c_flags |= HDROUTPUT;

		cchdr++;
		if ((count = c1->c_cwidth - strlen(c2->c_name) - 2) > 0)
			while (count--)
				putstr(" ");
	}
	if (c1->c_flags & UPPERCASE)
		for (cp = c2->c_text; *cp; cp++)
			if (islower(*cp))
				*cp = toupper(*cp);

	count = 0;
	if (cchdr) {
		if (flag == TWOCOMP)
			count = (c1->c_cwidth >= 0) ? c1->c_cwidth :
					(int)strlen(c2->c_name) + 2;
		else
			count = (c1->c_cwidth >= 0) ? (size_t)c1->c_cwidth :
					strlen(c1->c_text ?
					c1->c_text : c1->c_name) + 2;
	}
	count += c1->c_offset;

	if ((cp = oneline(c2->c_text, c1->c_flags))) {
		putstr((c1->c_flags & RTRIM) ? rtrim(cp) : cp);
	}
	if (term == '\n')
		putstr("\n");
	while ((cp = oneline(c2->c_text, c1->c_flags))) {
		lm = count;
		if (flag == BODYCOMP && !(c1->c_flags & NOCOMPONENT)) {
			if (*cp) {
				putstr(c1->c_text ? c1->c_text : c1->c_name);
			} else {
				putstr(trimmed_prefix);
			}
		}
		if (*cp)
			putstr((c1->c_flags & RTRIM) ? rtrim(cp) : cp);

		if (term == '\n')
			putstr("\n");
	}
	if (flag == BODYCOMP && term == '\n')
		c1->c_flags &= ~HDROUTPUT;  /* Buffer ended on a newline */
}

static char *
oneline(char *stuff, long flags)
{
	int spc;
	char *cp, *ret;

	if (onelp == NULL)
		onelp = stuff;
	if (*onelp == 0)
		return (onelp = NULL);

	ret = onelp;
	term = 0;
	if (flags & COMPRESS) {
		for (spc = 1, cp = ret; *onelp; onelp++)
			if (isspace(*onelp)) {
				if (*onelp == '\n' &&
						(!onelp[1] ||
						(flags & ADDRFMT))) {
					term = '\n';
					*onelp++ = 0;
					break;
				} else if (!spc) {
					*cp++ = ' ';
					spc++;
				}
			} else {
				*cp++ = *onelp;
				spc = 0;
			}

		*cp = 0;
	} else {
		while (*onelp && *onelp != '\n')
			onelp++;
		if (*onelp == '\n') {
			term = '\n';
			*onelp++ = 0;
		}
		if (flags & LEFTADJUST)
			while (*ret == ' ' || *ret == '\t')
				ret++;
	}
	if (*onelp == 0 && term == '\n' && (flags & NONEWLINE))
		term = 0;

	return ret;
}

static void
putstr(char *string)
{
	if (!column && lm > 0) {
		while (lm > 0)
			if (lm >= 8) {
				putch('\t');
				lm -= 8;
			} else {
				putch(' ');
				lm--;
			}
	}
	lm = 0;
	while (*string)
		putch(*string++);
}


static void
putch(char ch)
{
	switch (ch) {
	case '\t':
		column |= 07;
		column++;
		break;

	case '\b':
		column--;
		break;

	case '\n':
	case '\r':
		column = 0;
		break;

	default:
		/*
		** If we are forwarding this message, and the first
		** column contains a dash, then add a dash and a space.
		*/
		if (column == 0 && forwflg && ch == '-') {
			putchar('-');
			putchar(' ');
		}
		if (ch >= ' ')
			column++;
		break;
	}

	if (column >= wid) {
		putch('\n');
		if (ovoff > 0)
			lm = ovoff;
		putstr(ovtxt ? ovtxt : "");
		putch(ch);
		return;
	}

	putchar(ch);
}


static void
intrser(int i)
{
	eflag = 1;
}
