/* stream.c - deal with an unbuffered BBS attribute stream
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "actions.h"
#include "mstring.h"

void conv_text(char *, long);
void conv_html(char *, long);
void conv_html_strip(char *, long, int);


/* Process input stream "fptr" to output type "out", attributes only, and
 * formatting to an output width of "width" characters.
 *
 * Returns nonzero on error, and the error is not reported.
 */
int mtrib_stream(FILE * fptr, int out, int width)
{
	char *buf;
	long bufsize;
	char *a;

	setbuf(fptr, NULL);

	bufsize = 1024;
	if (width > 256)
		bufsize = width * 4;

	buf = malloc(bufsize);
	if (!buf)
		return (1);

	do {
		buf[0] = 0;
		fgets(buf, bufsize / 4, fptr);
		if (buf[0] == 0)
			continue;

		if (out == MT_OUTPUT_HTML)
			conv_html_strip(buf, bufsize, 0);

		mtagexpand(buf, bufsize, width, 0,
			   (out == MT_OUTPUT_HTML) ? 1 : 0);

		a = strchr(buf, 10);	    /* turn off attributes at line end */
		if (a)
			strcpy(a, "\035CA\035Ca\035a\n");

		switch (out) {
		case MT_OUTPUT_ANSI:
			mstrtoansi(buf, bufsize);
			break;
		case MT_OUTPUT_TEXT:
			conv_text(buf, bufsize);
			break;
		case MT_OUTPUT_HTML:
			conv_html(buf, bufsize);
			break;
		default:
			break;
		}

		printf("%s", buf);
		if (out == MT_OUTPUT_ANSI)
			printf("\r");

	} while ((!ferror(fptr)) && (!feof(fptr)));

	free(buf);

	if (ferror(fptr))
		return (1);
	return (0);
}

/* EOF */
