/*
**	NAME		= binsplit
**	VERSION	= 0.2
**	AUTHOR	= dbalster
**	COMMENT	= splits huge files into pieces
**
**	USAGE	(splitting a huge file)
**	---------------------------------
**	> gcc binsplit.c -o binsplit
**	> binsplit <sourcefile> <blocksize> <destinationfile basename>
**
**	USAGE	(joining the pieces)
**	------------------------------
**	in an unix shell type:
**	> cat piece.* > <huge file name>
**	in an amigados shell type:
**	> join piece.* TO <huge file name>
*/

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

int main (int argc, char **argv)
{
	FILE *in,*out;
	int size;
	int bytes;
	char buf[256];
	char *ptr;

	if (argc != 4)
	{
		printf("Usage: %s <source> <blocksize> <destination>\n"
			"where\n"
			" - blocksize means the number of bytes per block\n"
			" - source is the name of the file to split (read)\n"
			" - destination is the name of the file(s) to create\n"
			"\ndestination files were numbered <name>.0, <name>.1, ...\n\n",argv[0]);
		return 1;	/* error */
	}
	size = atoi(argv[2]);
	in = fopen(argv[1],"r");
	if (in==0) return 2;
	printf("Blocksize is: %ld\n\n",size);
	bytes = 0;
	if (ptr = malloc(size))
	{
		int block=0;
	
		while (!feof(in))
		{
			sprintf(buf,"%s.%ld",argv[3],block++);
			if (out=fopen(buf,"w"))
			{
				printf("Reading from \"%s\" %ld bytes\n",argv[1],size);
				bytes = fread(ptr,1,size,in);
				printf("Writing to \"%s\" %ld bytes\n",buf,bytes);
				fwrite(ptr,1,bytes,out);
				fclose(out);
			}
			if (ferror(in)) { printf("input file error!\n");break;}
			if (ferror(out)) { printf("output file error!\n");break;}
		}
	
		free(ptr);
	}
	
	fclose(in);

	return 0;
}
