#include "stdio.h"

#define LINESIZ	128
#define	PALSIZ	16

static char buf[LINESIZ];
static char palfn[20];
static char dstfn[20];
static char palette[PALSIZ];

main(argc,argv)
int	argc;
char	**argv;
{
	int		dst,i,j;
	FILE		*palfile;
	unsigned	location;
	char		*p;

	if ( argc !=2 )
	{
		puts("SetPal v.2.0, Perlin Production Co. Ltd. 2011 (c)\n");
		puts("This program changes palette in any COM file\n");
		puts("Usage: SETPAL palfn[.PAL]\n");
		puts("Format of palfn file:\n");
		puts("Destination_filename[.COM]\nLocation (HEX)\n");
		puts("Color_1 (HEX)\n...\n...\nColor_16 (HEX)\n<<<EOF>>>\n");
		exit(0);
	}
	strncpy(palfn,argv[1],PALSIZ);
	if ( index(palfn,'.') == NULL )	strcat(palfn,".PAL");
	if ( (palfile=fopen(palfn,"r",128)) == NULL )
			problem("Can't open palette file",palfn);
	if (fgets(dstfn,19,palfile) == NULL)
		problem("Can't read Destination_filename from",palfn);
	if ( index(dstfn,'.') == NULL ) strcat(dstfn,".COM");
	if ((dst=open(dstfn,FCB_R_W)) == ERROR )
			problem("Can't open destination file",dstfn);
	if (fscanf(palfile,"%x\n",&location) == ERROR)
		problem("Can't read location from",palfn);
	for (i=0 ; i<PALSIZ ; i++)
	{
		if (fgets(buf,LINESIZ,palfile) == NULL)
		{
			sprintf(buf,"Can`t read color number %d from",i);
			problem(buf,palfn);
		}

#ifdef _DEBUG
			printf ("Read:%s, Converted to:",buf);
#endif

		for (p = buf; isnumeric(toupper(*p),16); ++p);
		*p = 0;

#ifdef _DEBUG
			printf("%s\n",buf);
#endif

		/*
			if (fscanf(palfile,"%x\n",&(palette[i])) == ERROR )
		*/
		if (sscanf(buf,"%2x",&(palette[i])) == ERROR )
		{
			printf("Can't interpret color number %d",i);
			exit(1);
		}
	}
	if ( seek(dst,location,START)  == ERROR )
			problem("Can't seek to this location for file",dstfn);
	if ( write(dst,palette,PALSIZ) == ERROR )
			problem("Can't write palette to",dstfn);
	if ( close(dst) == ERROR )
			problem("Can't close",dstfn);
	printf("PALETTE:\n");
	for (i=0 ; i<PALSIZ ; i++ ) printf("%2x  ",palette[i]);
	printf("\nwritten to %s at hex location %4x", dstfn, location);
}


problem(ts,fns)
char	*ts,*fns;
{
	if (errno)
	{
		printf("%s ",ts);
		perror(fns);
	}
	else	printf("%s %s",ts,fns);
	puts("\007");
	exit(1);
}
