/*
 * msgform.c v2.0
 * see copyright.doc for copyright information
 * 
 * This is simply a filter that converts Citadel binary message format
 * to readable, formatted output.
 * 
 * If the -q (quiet or qwk) flag is used, only the message text prints, and
 * then it stops at the end of the first message it prints.
 * This is used by the QWK reader for Citadel/UX during message format
 * translation.
 */

#include <fcntl.h>
#include <stdio.h>
#include <ctype.h>
#include <time.h>

long atol();
long lseek();
long finduser();

int qwk = 0;

main(argc,argv)
int argc;
char *argv[]; {
	struct tm *tm;
	int a,b,e,mtype,aflag;
	char bbb[1024];
	FILE *fp;
	long now;

	if (argc==2) if (!strcmp(argv[1],"-q")) qwk = 1;

	fp=stdin;
TOP:	do {
		e=getc(fp);
		if (e<0) exit(0);
		} while(e!=255);
	mtype=getc(fp); aflag=getc(fp);
	if (qwk == 0) printf("\r ");

   do {
	b=getc(fp);
	if (b=='M') {
		if (qwk==0) printf("\n");
		if (aflag!=1) fmout(80,fp);
		   else while(a=getc(fp), a>0) {
			if (a==13) putc(10,stdout);
			else putc(a,stdout);
			}
		}
	if ((b!='M')&&(b>0)) fpgetfield(fp,bbb);
	if (qwk==0) {
		if (b=='A') printf("from %s ",bbb);
		if (b=='N') printf("@%s ",bbb);
		if (b=='O') printf("in %s> ",bbb);
		if (b=='R') printf("to %s ",bbb);
		if (b=='T') {
			now=atol(bbb);
			tm=(struct tm *)localtime(&now);
			strcpy(bbb,asctime(tm)); bbb[strlen(bbb)-1]=0;
			printf("%s ",&bbb[4]);
			}
		}
	   } while ((b!='M')&&(b>0));
	if (qwk==0) printf("\n"); 
	if (qwk==1) exit(0);
	goto TOP;
}

fpgetfield(fp,string)	/* level-2 break out next null-terminated string */
FILE *fp;
char string[];
{
int a,b;
strcpy(string,"");
a=0;
	do {
		b=getc(fp);
		if (b<1) { string[a]=0; return(0); }
		string[a]=b;
		++a;
		} while(b!=0);
	return(0);
}

fmout(width,fp)
int width;
FILE *fp;
	{
	int a,b,c,real,old;
	char aaa[140];
	
	strcpy(aaa,""); old=255;
	c=1; /* c is the current pos */
FMTA:	old=real; a=getc(fp); real=a;
	if (a<=0) goto FMTEND;
	
	if ( ((a==13)||(a==10)) && (old!=13) && (old!=10) ) a=32;
	if ( ((old==13)||(old==10)) && (isspace(real)) ) {
						printf("\n"); c=1; }
	if (a>126) goto FMTA;

	if (a>32) {
	if ( ((strlen(aaa)+c)>(width-5)) && (strlen(aaa)>(width-5)) )
		{ printf("\n%s",aaa); c=strlen(aaa); aaa[0]=0; }
	 b=strlen(aaa); aaa[b]=a; aaa[b+1]=0; }
	if (a==32) { 	if ((strlen(aaa)+c)>(width-5)) { 
							printf("\n");
							c=1;
							}
			printf("%s ",aaa); ++c; c=c+strlen(aaa);
			strcpy(aaa,""); goto FMTA; }
	if ((a==13)||(a==10)) {
				printf("%s\n",aaa); c=1;
				strcpy(aaa,""); goto FMTA; }
	goto FMTA;

FMTEND:	printf("\n");
	return(0);
}

