display-name: "Games/Gateworld"
meta: {"Working": ["Images", "Tiles", "Sprites"]}

if (file.name like "*data.gw?")
{
	fixed-string(20) signature

	data(14) unknown
	unsigned32 file-count
	data(26) unknown

	file [file-count]
	{
		fixed-string(12) name
		data(4) unknown
		unsigned32 offset
		unsigned32 size
		data(8) unknown
	}
}

if (file.name like "*.hpa")
{
	data(64) unknown
	palette
	{
		size: 256
		format: "R6G6B6"
	}
}

palette: "gtwrld1.hpa"

if (file.name like "*.hpi")
{
	data(32) unknown
	unsigned16 width
	data(4) unknown
	unsigned16 height
	data(24) unknown

	palette
	{
		size: 256
		format: "R6G6B6"
	}

	compressed [file.remaining-bytes] "GateWorldRLE"
	{
		image
		{
			format: "I8"
		}
	}
}

if (file.name like "*.hse")
{
	data(32) unknown //header
	unsigned16 unknown2
	unsigned16 file-count
	unsigned16 unknown3

	data(0x1A) padding

	header-size: (file-count * (0x10 + 5)) + 0x40

	//TODO: complex type arrays!
	//fixed-string(0x10)[file-count] names
	names: [](file-count)
	loop(file-count): i
	{
		fixed-string(0x10) name
		names[i] = name
	}
	unsigned16[file-count] offsets

	file[file-count]: i
	{
		name: names[i]
		offset: offsets[i] + header-size
		interpret-as "sound-PC-APOGEE"
	}
}

if (file.name like "*.hsk" and (file.name != "score.hsk") and (file.name != "piercer3.hsk")) //TODO: work out piercer3 + score.hsk
{
	folder: "Sprites"

	data(64) unknown

	image-layout-width: 320

	image-layout
	{
		loop while (file.remaining-bytes > 0)
		{
			data(12) unknown
			unsigned16 width
			unsigned16 height

			image
			{
				format: "I8"
				transparent-index: 255
			}
		}
	}
}

if (file.name like "*.hti")
{
	data(64) unknown
	image
	{
		format: "I8"
		data-size: file.size - 64
		width: 8
		height: 8
		tiles-across: 32
	}
}

if (file.name like "*.hic")
{
	folder: "Tiles"

	ignore-length: 11428
	data(ignore-length) unknown
	image 
	{
		format: "I8"
		data-size: 270500 - ignore-length
		width: 16
		height: 16
		tiles-across: 32
	}
}

if (file.name like "*.hle")
{
	folder: "Levels"

	/*data(34) unknown
	unsigned16 width
	unsigned16 height

	data(26) unknown
	
	level
	{
		grid-x: 16
		grid-y: 16

		level-layer
		{
			data-type: "unsigned16"
			layer-image: "gtwrld1.hic"
		}
	}*/
}

if (file.name like "*.xmi")
{
	folder: "Music"
}

function GateWorldRLE
{
	loop while (file.remaining-bytes > 0)
	{
		read unsigned8 control

		if ((control & 0x80) != 0)
		{
			read unsigned8 dataToDraw

			//replace when fill command is done -> fill [control & 0x7f] with dataToDraw
			loop (control & 0x7F)
			{
				write unsigned8 dataToDraw
			}
		}
		else
		{
			//replace when copy command is done -> copy [control]

			loop (control)
			{
				read unsigned8 pixel
				write unsigned8 pixel
			}
		}
	}
}