/*
 * bsplit.c - split binary files in manageable pieces.
 * usage is exactly like the split program.
 *
 * This program was written from scratch, without looking at the
 * sources of split.
 *
 * Copyright (C) 1988 P. Knoppers
 *                    Bilderdijkhof 59
 *                    2624 ZG  Delft
 *                    The Netherlands
 */

char copy0[] = "Copyright (C) 1988 P. Knoppers";
char copy1[] = "Permission to use and distribute copies of this";
char copy2[] = "program WITH SOURCE is granted to anyone, provided";
char copy3[] = "that it is NOT CHANGED in any way.";

#include <stdio.h>
#define DEFSIZE 50000
#define DEFPREFIX "x"
#define MAXNAME 200

char   *malloc ();

main (argc, argv)		/* bsplit - split binary file */
char   *argv[];
{
    char   *buf;
    char   *myname;
    int     bulksize = DEFSIZE;
    int     level;
    int     got;
    int     fno = 0;
    char    outfname[MAXNAME + 1];
    char    outbase[MAXNAME + 3];
    int     foundinname = 0;
    FILE * infile = stdin;
    FILE * outfile;

    myname = *argv;
    strcpy (outbase, DEFPREFIX);
    while (--argc > 0)
    {
	argv++;
	if ((*argv)[0] == '-')
	{
	    if ((*argv)[1] == '\0')
	    {
		if (foundinname != 0)
		{
		    fprintf (stderr,
			    "usage: %s [-size] [file [prefix]]\n",
			    myname);
		    exit (1);
		}
		foundinname++;
	    }
	    else
		if (sscanf (*argv, "-%d", &bulksize) != 1)
		{
		    fprintf (stderr,
			    "usage: %s [-size] [file [prefix]]\n",
			    myname);
		    exit (1);
		}
	}
	else
	    if (foundinname != 0)
	    {
		if (strlen (*argv) > MAXNAME)
		{
		    fprintf (stderr, "%s: prefix too long\n",
			    myname);
		    exit (1);
		}
		strcpy (outbase, *argv);
	    }
	    else
	    {
		if ((infile = fopen (*argv, "r")) == NULL)
		{
		    fprintf (stderr, "%s: cannot open %s\n",
			    myname, *argv);
		    exit (1);
		}
		foundinname++;
	    }
    }

    if ((buf = malloc (bulksize)) == NULL)
    {
	fprintf (stderr, "%s: malloc (%u) failed: ", myname, bulksize);
	perror ("");
	exit (1);
    }
    level = 0;
    while (1)
    {
	got = read (fileno (infile), &buf[level], bulksize - level);
	level += got;
	if ((level < bulksize) && (got > 0))
	    continue;
	if ((level == bulksize) || ((got == 0) && (level > 0)))
	{
	    sprintf (outfname, "%s%c%c", outbase, fno / 26 + 'a',
		    fno % 26 + 'a');
	    if ((outfile = fopen (outfname, "w")) == NULL)
	    {
		fprintf (stderr, "%s: cannot create %s\n", myname,
			outfname);
		exit (1);
	    }
	    if (write (fileno (outfile), buf, level) != level)
	    {
		fprintf (stderr, "%s: write failed\n", myname);
		exit (1);
	    }
	    fclose (outfile);
	    level = 0;
	    fno++;
	}
	if (got == 0)
	    break;
    }
}
