/* ---------------------------------------------------------------------

	Name:	mgsplit.c

	Ver:	1.0
	Date:	1996-05-27
	Author:	Marcus Geelnard

	Syntax:
		mgsplit <infile> <outname> <maxsize>

	Function:
		Splits a file into several smaller files, with the maximum
		size <maxsize> bytes.

   --------------------------------------------------------------------- */

#include  <stdio.h>
#include  <stdlib.h>
#include  <string.h>
#include  <sys/types.h>

#define MIN_SPLIT_SIZE 1L

#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif

/* typedef unsigned char u_char;    * defined in <sys/types.h> */


/*-----------------------------------------------------------------------
	main()
  -----------------------------------------------------------------------*/


int main(int argc, char *argv[])
{
	long	bufsize, i;
	int	splitnr, a;
	short	splitdone, filedone;
	u_char	*buffer, *bufptr;
	FILE	*infile, *outfile;
	char	outname[200];


	printf("MGSplit v1.0 ©1996 by Marcus Geelnard\n\n");

	if(argc<4) {
		fprintf(stderr,"Usage: %s <file> <destination name> <splitsize>\n",argv[0]);
		exit(1);
	}

	bufsize=atol(argv[3]);
	if(bufsize<MIN_SPLIT_SIZE) {
		fprintf(stderr,"Error: Minimum splitsize is %ld bytes\n",MIN_SPLIT_SIZE);
		exit(1);
	}

	buffer=(u_char *)malloc((size_t)bufsize);
	if(buffer==NULL) {
		fprintf(stderr,"Error: Could not allocate memory for buffer (%ld bytes)\n",bufsize);
		exit(1);
	}

	if((infile=fopen(argv[1],"rb"))==NULL) {
		fprintf(stderr,"Error: Could not open input file\n");
		exit(1);
	}

	splitnr=0; filedone=FALSE;

	while(filedone==FALSE) {
	    sprintf(outname,"%s.%d",argv[2],splitnr);
	    if((outfile=fopen(outname,"wb"))==NULL) {
		fprintf(stderr,"Error: Could not open output file nr. %d\n",splitnr);
		exit(1);
	    }
	    printf(".");
	    i=0; bufptr=buffer;
	    while((filedone==FALSE)&&(i<bufsize)) {
		a=fgetc(infile);
		if(a==EOF) filedone=TRUE;
		else {
		    *bufptr++=(u_char)a;
		    i++;
		}
	    }
	    (void) fwrite((void *)buffer,(size_t)1,(size_t)i,outfile);
	    fclose(outfile);
	    splitnr++;
	}

	printf("\n\"%s\" was split into %d files.\n",argv[1],splitnr);

	free(buffer);
	fclose(infile);

	return(0);
}

