
/*
 *  UUSPLIT.C
 *
 *  uusplit file [outprefix] [-b #bytes] [-v]
 *
 *  $Header: Beta:src/uucp/src/MUtil/RCS/uusplit.c,v 1.1 90/03/19 14:06:36 dillon Exp Locker: dillon $
 *
 *  take the binary 'file' and split into sections of 50KBytes each, uuencoding
 *  each section independantly.  Result:
 *
 *	outprefix.01.uue,   outprefix.02.uue ,etc...  uuencoding
 *	outprefix.01,	    outprefix.02, etc...
 *
 *  File segments are uuencoded.  uuencode must be in your path.    Calculate
 *  a 1.5 expansion uuencoding the file.
 */

#include <stdio.h>
#include <stdlib.h>
#include "version.h"

IDENT(".00");

Local void DumpSegment(FILE *, short, long, char *);
Local void run_cmd(char *);
Local void help(void);

short	Verbose;

main(ac, av)
char *av[];
{
    long bytes = 50000;
    short i;
    char *file	= NULL;
    char *outpf = NULL;
    FILE *fi;
    long size;
    long n;

    for (i = 1; i < ac; ++i) {
	char *ptr = av[i];
	if (*ptr == '-') {
	    ptr += 2;
	    switch(ptr[-1]) {
	    case 'v':
		Verbose = 1;
		break;
	    case 'b':
		if (*ptr)
		    bytes = atoi(ptr);
		else
		    bytes = atoi(av[++i]);
		break;
	    default:
		help();
	    }
	} else {
	    if (file == NULL)
		file = ptr;
	    else if (outpf == NULL)
		outpf = ptr;
	    else
		help();
	}
    }

    bytes = bytes * 2 / 3;	/*  assume uuencode expands file 1.5x	*/

    if (file == NULL)
	help();
    if (outpf == NULL)
	outpf = file;

    fi = fopen(file, "r");
    if (fi == NULL) {
	printf("couldn't open %s\n", file);
	exit(1);
    }
    fseek(fi, 0L, 2);
    size = ftell(fi);
    for (i = n = 0; n < size; n += bytes) {
	long b = size - n;

	if (b > bytes)
	    b = bytes;
	fseek(fi, n, 0);
	DumpSegment(fi, (short)(i + 1), b, outpf);
	++i;
    }
    fclose(fi);
    return(0);
}

void
help()
{
    puts("uusplit file [outprefix] [-b bytes] [-v]");
    exit(1);
}

void
DumpSegment(fi, i, bytes, outprefix)
FILE *fi;
short i;
long bytes;
char *outprefix;
{
    static char Name1[256];
    static char Name2[256];
    static char Name3[256];
    static char Buf[4096];
    long n;
    FILE *fo;

    sprintf(Name1, "T:uusplit.%02d", i);
    sprintf(Name2, "%s.%02d", outprefix, i);
    sprintf(Name3, "%s.%02d.uue", outprefix, i);

    fo = fopen(Name1, "w");
    if (fo == NULL) {
	printf("couldn't create %s\n", Name1);
	exit(1);
    }

    while (bytes) {
	n = (bytes > sizeof(Buf)) ? sizeof(Buf) : bytes;
	fread(Buf, 1, n, fi);
	fwrite(Buf, 1, n, fo);
	bytes -= n;
    }
    fclose(fo);
    sprintf(Buf, "uuencode >%s %s %s", Name3, Name1, Name2);
    run_cmd(Buf);
    remove(Name1);
}

void
run_cmd(buf)
char *buf;
{
    if (Verbose) {
	puts(buf);
	fflush(stdout);
    }
    Execute(buf, NULL, NULL);
}

