/*
 *  splitmb by Davide Libenzi (mailbox file format splitter)
 *  Copyright (C) 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>

static void usage(char *prg) {

	fprintf(stderr, "use: %s [--basename nam] [--basenum num]\n", prg);
}

int main(int argc, char *argv[]) {
	int i, n = 1;
	FILE *fil;
	char *basename = "msg-";
	char lnbuf[2048];

	for (i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "--basename")) {
			if (++i < argc)
				basename = argv[i];
		} else if (!strcmp(argv[i], "--basenum")) {
			if (++i < argc)
				n = atoi(argv[i]);
		} else {
			usage(argv[0]);
			return 2;
		}
	}
	for (fil = NULL; fgets(lnbuf, sizeof(lnbuf) - 1, stdin);) {
		if (!strncmp(lnbuf, "From ", 5)) {
			if (fil)
				fclose(fil);
			sprintf(lnbuf, "%s%d", basename, n++);
			if (!(fil = fopen(lnbuf, "w"))) {
				perror(lnbuf);
				return 1;
			}
		} else if (fil) {
			fputs(lnbuf, fil);
		}
	}
	if (fil)
		fclose(fil);

	return 0;
}

