/**************************************************************************
file:	merge.c
author:	scott arrington
date:	april 1999
description:
	merge a bunch of given files into one.  companion to split...
**************************************************************************/

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

#define BLOCKSIZE	4096

/*#define VERBOSE*/

/*
 * i think it's bad form to make gratuitous globals, but i consider it worse
 * to allocate large buffers on the stack...  old habits from the days of
 * writing code for... less well-endowed systems.
 */
unsigned char buf[BLOCKSIZE];

#ifdef VERBOSE
int lastsize;
#endif

int main ( int argc, char * argv[] )
{
	FILE *in, *out;
	int count;
	int numread;

	if (argc < 3) {
		printf("usage: %s mergedfilename inputfiles...\n",argv[0]);
		exit(1);
	}
	
	out = fopen( argv[1], "wb" );
	if (out == NULL) {
		perror(argv[1]);
		exit(EXIT_FAILURE);
	}
	
	printf("created %s\n",argv[1]);

	for (count=2; count < argc; count++) {
		in = fopen( argv[count], "rb" );
		if (in == NULL) {
			perror(argv[count]);
			exit(EXIT_FAILURE);
		}
		printf("appending %s\n",argv[count]);
		while (!feof(in)) {
			numread = fread(buf,1,BLOCKSIZE,in);
			fwrite(buf,1,numread,out);
		}
		fclose(in);
#ifdef VERBOSE
		printf("\toutputfile:   %ld\n",ftell(out));
		printf("\tlast segment: %ld\n",ftell(out)-lastsize);
		lastsize=ftell(out);
#endif
	}


	fclose(out);
	return 0;
}

