#include <process.h>
#include <conio.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <sys\types.h>
#include <sys\stat.h>

main ()
{
	int fil, i;
	long fileng, offs;
	unsigned char ch, tempbuf[9];

	puts("");
	puts("KENBUILD: force old Pentium code         by Kenneth Silverman (06/25/2000)");
	puts("");
	puts("Do you want to continue patching GAME.EXE? (Y/N)");

	do
	{
		ch = getch();
	} while ((ch != 'n') && (ch != 'N') && (ch != 'y') && (ch != 'Y') && (ch != 27));
	if ((ch == 'n') || (ch == 'N') || (ch == 27))
	{
		puts("Operation aborted");
		exit(0);
	}

		//   size:    date:      time:   offset:
		// 415,571   06/20/2000 07:56p  0x6565A  //û

	if ((fil = open("GAME.EXE",O_BINARY|O_RDWR,S_IREAD)) == -1)
		{ puts("ERROR 1: Can't read GAME.EXE: Make sure it is in the current directory."); exit(0); }
	fileng = filelength(fil);

	offs = -1;
	if (fileng == 415571) offs = 0x6565a;
	if (offs == -1) { puts("ERROR 2: GAME.EXE unrecognized or not currently supported."); exit(0); }

	lseek(fil,offs,SEEK_SET);
	read(fil,tempbuf,9);
	close(fil);

	if ((tempbuf[0] == 0xc3) && (tempbuf[1] == 0x58) && (tempbuf[2] == 0x89) &&
		 (tempbuf[3] == 0xc3) && (tempbuf[4] == 0x35) && (tempbuf[5] == 0x00) &&
		 (tempbuf[6] == 0x00) && (tempbuf[7] == 0x20) && (tempbuf[8] == 0x00))
	{
		puts("This patch has already been applied to GAME.EXE.");
		exit(0);
	}

	if ((tempbuf[0] != 0x9c) || (tempbuf[1] != 0x58) || (tempbuf[2] != 0x89) ||
		 (tempbuf[3] != 0xc3) || (tempbuf[4] != 0x35) || (tempbuf[5] != 0x00) ||
		 (tempbuf[6] != 0x00) || (tempbuf[7] != 0x20) || (tempbuf[8] != 0x00))
	{
		puts("ERROR 3: GAME.EXE unrecognized, or not currently supported.");
		exit(0);
	}

		//Actually modify the exe here:
	if ((fil = open("GAME.EXE",O_BINARY|O_RDWR,S_IWRITE)) == -1)
		{ puts("ERROR 4: Can't write to GAME.EXE: Make sure it has write priviledges."); exit(0); }
	lseek(fil,offs,SEEK_SET);
	tempbuf[0] = 0xc3;
	write(fil,tempbuf,1);
	close(fil);
	puts("SUCCESS! GAME.EXE has been patched to force Pentium-optimized assembly.");
}
