/* tagexpand.c - expand special tags in a line
 */

#include <stdio.h>
#include <string.h>
#include <time.h>
#include "mstring.h"


/* Replace the line in "buf" with a datestamp.
 */
void mtagexpand_datestamp(char *buf, long bufsize, int width, int h)
{
	char tmp[32];
	time_t t;
	int n;

	buf[bufsize - 1] = 0;		    /* make sure it's null terminated */

	if (buf[8] < 32)
		t = 0;
	else
		t = mstrtol(buf + 9);

	strcpy(buf, "\035B\035R\035Cb");

	if (t < 1) {			    /* blank datestamp */
		for (n = 0; (n < width - 1) && (n < (bufsize - 128)); n++)
			buf[n + 7] = '-';
		strcpy(buf + n + 7, "\n");
	} else {			    /* valid timestamp */
		for (n = 0; (n < width - 29) && (n < (bufsize - 128)); n++)
			buf[n + 7] = '-';
		strcpy(buf + n + 7, "[\035a\035R");
		strftime(buf + strlen(buf), bufsize - strlen(buf),
			 "%a %b %d %H:%M:%S %Y", localtime(&t));
		strcat(buf, "\035B]--\n");
		if (h) {		    /* add HTML anchor */
			sprintf(tmp, "<A NAME=\"%08lX\"></A>", t);
			n = 0;
			mstrinsert(buf, tmp, &n, bufsize);
		}
	}
}


/* Make the text after From: bold green, stripping the accountname if "anon"
 * is nonzero.
 */
void mtagexpand_from(char *buf, long bufsize, int anon)
{
	int n;

	n = 6;
	mstrinsert(buf, "\035B\035CG", &n, bufsize);

	if (anon) {			    /* strip accountname */
		buf = strrchr(buf, '(');
		if (buf)
			strcpy(buf, "\n");
	}
}


/* Make recipients green, or strip them if "anon" is nonzero.
 */
void mtagexpand_to(char *buf, long bufsize, int anon)
{
	int n;

	if (anon) {			    /* strip recipients */
		strcpy(buf + 3, "\n");
	} else {			    /* make recipients green */
		n = 4;
		mstrinsert(buf, "\035CG", &n, bufsize);
	}
}


/* Add ]U]CC to make the subject line underlined cyan.
 */
void mtagexpand_subject(char *buf, long bufsize)
{
	int n = 8;

	while ((buf[n] == ' ') || (buf[n] == 9))
		n++;			    /* skip spaces */
	mstrinsert(buf, "\035U\035CC", &n, bufsize);
}


/* Check the buffer "buf", of maximum size "size", for special lines, and
 * deal with them by expanding. The output width is "width", and if "anon"
 * is set, account names are stripped from "From" lines and recipients from
 * "To" lines.
 *
 * Datestamps will have an HTML anchor prepended if the "html" flag is set.
 */
void mtagexpand(char *buf, long size, int width, int anon, int html)
{
	if (!strncmp(buf, "Message:", 8)) { /* datestamp */
		mtagexpand_datestamp(buf, size, width, html);
	} else if (!strncmp(buf, "From:", 5)) {	/* from line */
		mtagexpand_from(buf, size, anon);
	} else if (!strncmp(buf, "To:", 3)) {	/* to line */
		mtagexpand_to(buf, size, anon);
	} else if (!strncmp(buf, "Subject:", 8)) {	/* subject line */
		mtagexpand_subject(buf, size);
	}
}

/* EOF */
