/* Changed to add charset support -- P.Saratxaga */ 
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include "xutil.h"
#include "lutil.h"
#include "rfcmsg.h"
#include "config.h"
#include "bwrite.h"
#include "mime.h"
#include "charset.h"
#include "charconv.h"
#include "version.h"
#include "hash.h"

#define TEXTBODY 0
#define NONTEXTBODY 1
#define MESSAGEBODY 2
#define MULTIPARTBODY 3

extern char *bgets(char *,int,FILE *);

void putbody(level,msg,fp,pkt,forbidsplit,hdrsize,incode,outcode,qp_or_base64)
int level;
rfcmsg *msg;
FILE *fp;
FILE *pkt;
int forbidsplit;
int hdrsize;
int incode;
int outcode;
int qp_or_base64;
{
	int splitpart=0;
	int needsplit=0;
	int datasize=0;
	char buf[BUFSIZ];
	char *p,*q;
	int bodytype=TEXTBODY;

	if (level == 0) {
		splitpart=0;
		needsplit=0;
	}

	if (needsplit) {
#ifndef FSC_0047
		fprintf(pkt," * Continuation %d of a split message *\r\r",
				splitpart);
#endif
			needsplit=0;
	}
	switch (bodytype) {
	case TEXTBODY:
		if ((p=hdr("X-Body-Start",msg)) && !needsplit) {
			datasize += strlen(p);
			if (qp_or_base64==1)
				cwrite(strkconv(qp_decode(p), incode, outcode), pkt);
			else if (qp_or_base64==2)
				cwrite(strkconv(b64_decode(p), incode, outcode), pkt);
			else
				cwrite(strkconv(p, incode, outcode), pkt);
		}
		while (!(needsplit=(!forbidsplit) &&
			(((splitpart &&
			   (datasize > maxmsize)) ||
			  (!splitpart &&
			   ((datasize+hdrsize) > maxmsize))))
								) &&
			(bgets(buf,sizeof(buf)-1,fp)))
		{
			debug(19,"putmessage body %s",buf);
			datasize += strlen(buf);
			if (qp_or_base64==1)
				cwrite(strkconv(qp_decode(buf), incode, outcode), pkt);
			else if (qp_or_base64==2)
				cwrite(strkconv(b64_decode(buf), incode, outcode), pkt);
			else
				cwrite(strkconv(buf, incode, outcode), pkt);
		}
		break;
	}
	if (needsplit) {
#ifndef FSC_0047
		fprintf(pkt,"\r * Message split, to be continued *\r");
#endif
		splitpart++;
	}
	else if ((p=hdr("X-PGP-Signed",msg)))
	{
		fprintf(pkt,PGP_SIG_BEGIN"\r");
		if ((q=hdr("X-PGP-Version",msg)))
		{
			fprintf(pkt,"Version:");
			cwrite(q,pkt);
		}
		if ((q=hdr("X-PGP-Charset",msg)))
		{
			fprintf(pkt,"Charset:");
			cwrite(q,pkt);
		}
		if ((q=hdr("X-PGP-Comment",msg)))
		{
			fprintf(pkt,"Comment:");
			cwrite(q,pkt);
		}
		fprintf(pkt,"\r");
		p=xstrcpy(p);
		q=strtok(p," \t\n");
		fprintf(pkt,"%s\r",q);
		while ((q=(strtok(NULL," \t\n"))))
			fprintf(pkt,"%s\r",q);
		fprintf(pkt,PGP_SIG_END"\r");
	}
}
