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

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

IDENT(".02");

static int TNo;
char TmpBuf[256];
short CompressOpt = 0;

main(ac, av)
char *av[];
{
    short i;
    short j;
    short inNo = 1;
    long bytes;
    char *outTpl;
    char *inTpl;

    if (ac <= 3) {
	puts("SPLITMBOX [-c] outtemplate bytes intemplate [outstart# [instart#]]");
	exit(1);
    }
    for (j = 0, i = 1; i < ac; ++i) {
	char *ptr = av[i];
	if (*ptr == '-') {
	    ptr += 2;
	    switch(ptr[-1]) {
	    case 'c':
		CompressOpt = 1;
		break;
	    default:
		puts("Illegal option");
		exit(1);
	    }
	} else {
	    switch(j) {
	    case 0:
		outTpl = ptr;
		break;
	    case 1:
		bytes = atoi(ptr);
		break;
	    case 2:
		inTpl = ptr;
		break;
	    case 3:
		TNo = atoi(ptr) - 1;
		break;
	    case 4:
		inNo = atoi(ptr);
		break;
	    default:
		puts("Unexpected parameter");
		exit(1);
	    }
	    ++j;
	}
    }
    if (j < 3) {
	puts("not enough parameters");
	exit(1);
    }

    for (;; ++inNo) {
	FILE *fi;
	char buf[128];

	sprintf(buf, "%s.%03d", inTpl, inNo);

	if (fi = fopen(buf, "r")) {
	    printf("%s\n", buf);
	    Dump(fi, bytes, outTpl);
	    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);
		    if (CompressOpt) {
			sprintf(TmpBuf, "Compress <%s.%03d >%s.%03d.Z",
			    tpl, TNo, tpl, TNo
			);
			Execute(TmpBuf, NULL, NULL);
			sprintf(TmpBuf, "%s.%03d", tpl, TNo);
			remove(TmpBuf);
		    }
		}
		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);
}

