
/*
 *  SPLITMBOX.C
 *
 *  SPLITMBOX outemplate bytes filetemplate [outstart [filestart]]
 */

#include <stdio.h>
/*#include "config.h"*/
#include "version.h"

IDENT(".01");

static int TNo;

main(ac, av)
char *av[];
{
    short i;
    short j;
    long bytes;
    FILE *fi;
    char buf[128];

    if (ac <= 3) {
	puts("SPLITMBOX outtemplate bytes intemplate [outstart# [instart#]]");
	exit(1);
    }
    bytes = atoi(av[2]);

    if (ac >= 5)
	TNo = atoi(av[4]) - 1;

    if (ac >= 6)
	j = atoi(av[5]);
    else
	j = 1;

    for (;; ++j) {
	sprintf(buf, "%s.%03d", av[3], j);

	if (fi = fopen(buf, "r")) {
	    printf("%s\n", buf);
	    Dump(fi, bytes, av[1]);
	    fclose(fi);
	} else {
	    printf("Unable to open %s\n", buf);
	    break;
	}
    }
    return(0);
}

Dump(fi, bytes, tpl)
FILE *fi;
long bytes;
char *tpl;
{
    static long bytecnt;
    static FILE *fo;
    static char Buf[2048];

    strcpy(Buf, "\n");
    while (fgets(Buf, sizeof(Buf), fi)) {
	if (strncmp(Buf, "From ", 5) == 0) {
	    if (bytecnt >= bytes) {
		if (fo)
		    fclose(fo);
		fo = NULL;
	    }
	}
	if (fo == NULL) {
	    char buf[64];

	    sprintf(buf, "%s.%03d", tpl, ++TNo);
	    fo = fopen(buf, "w");
	    if (fo == NULL) {
		printf("Unable to create %s\n", buf);
		break;
	    }
	    bytecnt -= bytes;
	    if (bytecnt < 0 || bytecnt > bytes / 2)
		bytecnt = 0;
	}
	fputs(Buf, fo);
	bytecnt += strlen(Buf);
    }
    if (Buf[0] != '\n')
	fputs("\n", fo);
}

