#include "stdio.h"

#define	NFILES	3
#define	NSRC	(NFILES-1)
#define MINBPS	4
#define	MAXBPS	16
#define	DSTFILE	2

static int		bps,fsize;
static char		*fname[NFILES];
static int		file[NFILES];
static char		buf[MAXBPS*2];


int closefh(_file, _name)
int	_file;
char*	_name;
{
	int result;

	result = SUCCESS;

	if (_file != ERROR)
	{
		if ((result = close(_file)) == ERROR)
			printf("Error closing %s\n",_name);
	}
	return result;
}




int closeall()
{
	int result;
	int i;

	result = SUCCESS;
	i=0;

	for (i=0; i<NFILES; ++i) result |= closefh(file[i],fname[i]);

	return result;
}

trouble(_text1,_text2)
char *_text1;
char *_text2;
{
	int result;
	if (_text2) printf("Error: %s %s\n",_text1,_text2);
	else printf("Error: %s\n",_text1);
	closeall();
	exit(1);
}


usage()
{
 printf("Perlin Production Co. Ltd. March 2012 [on-the-knee]\n");
 printf("Generates interleaved double-pass font binary file from two\n");
 printf("source files containing binary character representations of\n");
 printf("256 symbols for first and second passes respectively.\n");
 printf("Input file characters should have same Byte Per Symbol values.\n"); 
 printf("\nUsage: dblfnt BPS source1 source2 dest\n\n");
}


main(argc,argv)
int	argc;
char	**argv;
{
	register int	pos;
	int		i,j, bps2;
	char		*p;

	for (i=0; i<NFILES; ++i) file[i] = ERROR;
	
	if ( argc !=5 )
	{
		usage();
		trouble	( "Invalid number of parameters",0);
	}

	bps		= atoi(argv[1]);
	fname[0]	= argv[2];
	fname[1]	= argv[3];
	fname[DSTFILE]	= argv[4];

	if (!strcmp(fname[0],fname[1]))	trouble("Source files must differ",0);
	if (!strcmp(fname[0],fname[2]))	trouble("Source and destination files must differ",0);
	if (bps < MINBPS || bps > MAXBPS) trouble ("Bytes Per Symbol is out of range",0);


	fsize = bps * 0x100;

	for (i=0; i < NSRC; ++i)
	{
		if ( (file[i]=open(fname[i],FCB_READ)) == ERROR)
			trouble("Failed to open source file", fname[i]);

		seek(file[i],0,LAST);
		if ( (unsigned)tell(file[i]) < fsize )
			trouble("Too short file ",fname[i]);
	}

	unlink(fname[DSTFILE]);
	if ((file[DSTFILE]=creat(fname[DSTFILE],FCB_WRITE)) == ERROR)
		trouble("Failed to create destination file", fname[DSTFILE]);

	pos = 0;
	bps2= bps * 2;

	for (i=0; i < 0x100; ++i)
	{
		p = buf;

		for (j=0; j < NSRC; ++j)
		{
			if ((seek(file[j],pos,START)) == ERROR) trouble("Seek error in ",fname[j]);
			if ((read (file[j],p,bps)) != bps) trouble("Read error in ",fname[j]);
			p += bps;
		}
		if ((write(file[DSTFILE],buf,bps2)) != bps2) trouble("Write error in ",fname[DSTFILE]);
		pos += bps;
	}
	closeall();
}
