IPS File Format by Jay (tennj@yahoo.com)
                Revision 1
----------------------------------------

There are hardly any docs out on the net that gives the format of the
IPS file so I decided to write one of my own.

The structure of the IPS file looks like this:

+-------------+
|  Signature  | 5 byte containing "PATCH"
+-------------+
|             |
| Data Blocks | Data Blocks (explained below)
|             |
+-------------+
|     EOF     | 3 bytes containing "EOF"
+-------------+

Signature
---------
The Signature field is the first 5 bytes of the IPS files. These 5
bytes will read "PATCH". Programmers should check this field to confirm
the validness of a IPS patch file.

Data Blocks
-----------
The remainder of the patch file will contain data blocks. The data
block looks like this:

+-------------+
|   Address   | 3 bytes (MSB) containing the address to patch
+-------------+
|   Length    | 2 bytes (MSB) containing the size of data to patch
+-------------+
|             |
|   Data....  | "Length" bytes containing the data to patch
|             |
+-------------+

The data block is repeated as necessary or until the address field
reads "EOF" (0x454F46 hex). The "Address" field is 3 bytes long and is
to be read in MSB order. This address specifies the location in the
file to patch. The "Length" field (also read in MSB order) is the size
of data to patch. The "Data" field is "Length" bytes long and contains
the bytes you should write to the address of the target file.

RLE Encoding
------------
Of all the IPS documents I've come across, none of them ever mentioned
the RLE ecoding scheme used in IPS file. The RLE encoding works this
way: if the "Length" field of the above data block = 0 then read in the
structure below:

(if Length = 0)
+-------------+
| Run Length  | 2 bytes (MSB) for the runlength
+-------------+
|  Dup Byte   | 1 byte (MSB) for the dup byte
+-------------+

The "Run Length" field (also MSB order) specifies how many times to
duplicate "Dup Byte". 2 bytes read for the run count, and 1 byte read
for the dup byte.

EOF
---
The "EOF" will appear at the end of the file. You may also use this
field to validate the IPS file.

Psuedo Code for using an IPS to patch a file
--------------------------------------------
This is some psuedo code to help you understand how to patch a file.

	IPS: Patch File
	FILE: File To Be Patched

	Sig <- Read 5 Bytes from IPS
	IF sig is not "PATCH" THEN exit with "Invalid IPS file" error
	DO
	   Address <- Read 3 Bytes (MSB)
	   Length <- Read 2 Bytes (MSB)
	   IF Address = "EOF" THEN exit
	   Seek to Address in FILE
	   IF Length = 0 THEN
	      RunCount <- Read 2 Bytes (MSB)
	      DupByte <- Read 1 Byte
	      Write the DupByte RunCount times to FILE
	   ELSE
	      Read Length bytes from IPS
	      Write Length bytes to FILE
	   ENDIF
	WHILE Address is not "EOF"