/*
 *  rbuild by Davide Libenzi ( email to XMail spool format converter )
 *  Copyright (C) 1999,..,2002  Davide Libenzi
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *  Davide Libenzi <davidel@xmailserver.org>
 *
 */


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


#define MAIL_DATA_TAG	"<<MAIL-DATA>>"


int main(int argc, char * argv[]) {
	int ii, rcode = 1;
	FILE *pfin = stdin, *pfout = stdout, *pfhdr = NULL;
	char *fnin = NULL, *fnout = NULL, *fnhdr = NULL;
	char buffer[2048];

	for (ii = 1; ii < argc; ii++) {
		if (strcmp(argv[ii], "--hdrfile") == 0) {
			if (++ii < argc)
				fnhdr = argv[ii];
			continue;
		}
		if (strcmp(argv[ii], "--input") == 0) {
			if (++ii < argc)
				fnin = argv[ii];
			continue;
		}
		if (strcmp(argv[ii], "--output") == 0) {
			if (++ii < argc)
				fnout = argv[ii];
			continue;
		}
	}
	if (!fnhdr) {
		fprintf(stderr, "%s: header file not specified.\n", argv[0]);
		goto clean_exit;
	}
	rcode = 2;
	if (!(pfhdr = fopen(fnhdr, "rb"))) {
		perror(fnhdr);
		goto clean_exit;
	}
	if (fnin && !(pfin = fopen(fnin, "rb")))
		pfin = stdin;
	if (fnout && !(pfout = fopen(fnout, "wb")))
		pfout = stdout;
	rcode = 3;
	while (fgets(buffer, sizeof(buffer) - 1, pfhdr)) {
		buffer[strlen(buffer) - 1] = '\0';
		if (fputs(buffer, pfout) == EOF || fputs("\r\n", pfout) == EOF)
			goto clean_exit;
		if (strcmp(buffer, MAIL_DATA_TAG) == 0) {
			fclose(pfhdr), pfhdr = NULL;
			break;
		}
	}
	rcode = 4;
	if (pfhdr)
		goto clean_exit;
	rcode = 5;
	do {
		unsigned int rsize = fread(buffer, 1, sizeof(buffer), pfin);

		if (rsize && fwrite(buffer, 1, rsize, pfout) != rsize)
			goto clean_exit;
	} while (!feof(pfin));
	rcode = 0;
clean_exit:
	if (pfhdr) fclose(pfhdr);
	if (pfin != stdin) fclose(pfin);
	if (pfout != stdout) fclose(pfout);
	return rcode;
}

