#include "Include_FixIff.h"
#include "prototypes.h"

VOID main(argc, argv)
int argc;
register UBYTE **argv;
{
	register int filiere;
	register USHORT i, j;

	struct BitMapHeader	*BMHD;
	struct CAMGHeader		*CAMG;
	UBYTE buf[2000];
	USHORT horiz, vert;

	if (argc < 2)
		printf("[1m[33mFixIff v1.0[0m  (c) 1993 Christian Warren\nUsage : FixIff [-L -H -I -N] <Ifffile>\n-L = LORES   -H = HIRES   -I = INTERLACE   -N = NOT INTERLACE\n\n");
	else
	{
		horiz = vert = 0;

		for (i = 1; argv[i][0] == '-'; i++)
		{
			switch(argv[i][1])
			{
				case 'l':
				case 'L':
					horiz = LO;
					break;
				case 'h':
				case 'H':
					horiz = HI;
					break;
				case 'i':
				case 'I':
					vert = INT;
					break;
				case 'n':
				case 'N':
					vert = NONINT;
					break;
			}
		}

		printf("[1m[33m%s[0m ", argv[i]);
		
		if ((filiere = open(argv[i], O_RDWR, 0)) != -1)
		{
			read(filiere, buf, sizeof(buf));

			j = 0;
			while (j < 2000)
			{
				if (!strnicmp(&buf[j], "BMHD", 4))
				{
					j += 4;
					BMHD = (struct BitMapHeader *) &buf[j];

					BMHD->pageWidth = ((BMHD->w <= 400) || (BMHD->nPlanes == 6))
											? 320 : 640;
					BMHD->pageHeight = (BMHD->h > 300) ? 400 : 200;

					if (horiz)
						BMHD->pageWidth =  (horiz == LO) ? 320 : 640;
					if (vert)
						BMHD->pageHeight = (vert == INT) ? 400 : 200;

					printf("( %d * %d * %d ) Screen ( %d * %d ) "
								, BMHD->w, BMHD->h, BMHD->nPlanes
								, BMHD->pageWidth, BMHD->pageHeight);
				}
				j++;
			}

			j = 0;
			while (j < 2000)
			{
				if (!strnicmp(&buf[j], "CAMG", 4))
				{
					j += 4;
					CAMG = (struct CAMGHeader *) &buf[j];

					CAMG->ViewMode = SPRITES + ((BMHD->pageWidth	== 640) << 15)
													+ ((BMHD->pageHeight	== 400) << 2)
													+ ((BMHD->nPlanes 	== 6)	<< 11);
				}
				j++;
			}

			lseek(filiere, 0, 0);
			write(filiere, buf, sizeof(buf));

			close(filiere);
		}
		else
			printf("I can't found the file!\n");
	}
	printf("\n");
	exit(0);
}
