/* linefeed.c - deal with a linefeed
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "vt100.h"


void ansi_monoify(char *, unsigned char *, unsigned short *, int, int);
void ansi_checkline(char *, int);


/* Deal with a linefeed character by converting the current terminal row
 * to ANSI colour text then converting that to BBS attributes and
 * sending it to stdout.
 *
 * Subject:, From: and To: lines have initial control codes stripped, and
 * datestamps are turned back into Message: tags.
 */
void mtrib_ansi_linefeed(vt_info vt)
{
	static unsigned short *a = 0;	 /*  --- KLUDGE  ALERT ---  */
	static unsigned char *t = 0;	 /* ...see comment below... */
	static char *b = 0;
	static int l = 0;
	int x, y, rows, cols;
	int i;

	/* The above kludge of using static variables is so that for any
	 * one file, buffers are only allocated once instead of inviting
	 * disaster by repeatedly allocating and freeing. Reallocation is
	 * only done if the new terminal width is wider than the old one.
	 *
	 * The only small disadvantage is that these buffers are never
	 * finally freed, but this shouldn't be a problem since as it says
	 * in the previous paragraph buffers are reused across files if
	 * possible.
	 */

	vt100_get_size(vt, &rows, &cols);
	vt100_get_pos(vt, &x, &y);

	if ((l < cols) || (!a) || (!t) || (!b)) {	/* allocate buffers */
		if (a)
			free(a);
		if (t)
			free(t);
		if (b)
			free(b);
		a = calloc(cols + 2, sizeof(unsigned short));
		t = calloc(cols + 2, 1);
		b = calloc(cols * 5, 1);    /* plenty of room for attributes */
		if ((!a) || (!t) || (!b))
			return;
		for (l = 0; l < (cols + 2); l++) {
			a[l] = VT_COLOUR_WHITE << VT_FOREGROUND_SHIFT;
		}
		l = cols;
	}

	*t = 0;
	vt100_get_text(vt, t, 1, y, cols);
	vt100_get_attr(vt, a, 1, y, cols);

	ansi_monoify(b, t, a, cols * 5, cols);

	i = strlen(b) - 1;
	while ((i >= 0) && (b[i] == ' ')) { /* strip trailing spaces */
		b[i--] = 0;
	}

	ansi_checkline(b, cols * 5);	    /* handle special lines */

	printf("%s\n", b);
}

/* EOF */
