display-name: "Games/Doom"
meta: {"Working": ["Packed file extraction", "Some images"], "Thanks to": "Matt Fell"}

if (file.name like "*.wad")
{
	file-format doom-wad
	{
		data(4) header //IWAD

		index-name: file.name //for palette hack :/	WM3 - which won't work now with lack of variable propagation

		unsigned32 file-count
		unsigned32 directory-offset	

		directory: ""

		at directory-offset:

		file [file-count]
		{
			unsigned32 offset
			unsigned32 size
			fixed-string(8) short-name
			name: directory + short-name

			if (directory like ["f1*", "f2*"])
			{
				interpret-as "doom-flat"
			}

			if (directory like ["p1*", "p2*", "s*"])
			{
				interpret-as "doom-sprite"
			}

			if (size == 0)
			{
				directory = short-name + "\\"
			}

			skip-if (size == 0)
		}
	}
}

if (file.name == "playpal")
{
	file-number: 0

	file[file.size / 768]
	{
		name: "palette-" + file-number
		size: 768
		offset: file-number * 768
		interpret-as "DOOM-Pal"

		file-number = file-number + 1
	}
}

file-format DOOM-Pal
{
	palette
	{
		size: 256
		format: "R8G8B8"
	}
}

if (file.name == "endoom")
{
	b800-text
}

file-format doom-flat
{
	image
	{
		format: "I8"
		width: 64
		height: 64

		palette: index-name + "\\playpal\\palette-0"
	}
}

file-format doom-sprite
{
	unsigned16 width
	unsigned16 height
	unsigned16 doom-left-offset
	unsigned16 doom-top-offset

	compressed[file.remaining-bytes] "doom-sprite-compression"
	{
		image
		{
			format: "I8"
			palette: index-name + "\\playpal\\palette-0"
			transparent-index: 255
		}
	}
}

function doom-sprite-compression
{
	decompressed: [](width * height)
	loop (width * height): i
	{
		decompressed[i] = 255
	}

	loop (width): x
	{
		unsigned32 column-offset

		at column-offset - 8
		{
			loop
			{
				unsigned8 row
				unsigned8 pixels

				if ((row != 0xFF) or (pixels != 0xFF))
				{
					if (row == 0xFF)
					{
						row = 0
					}

					/*loop (row): i
					{
						if (i < height)
						{
						decompressed[i * width + x] = 255
						}
					}*/

					read unsigned8 discard
					loop (pixels): y
					{
						read unsigned8 pixel

						if ((y + row) < height) {
							decompressed[((y + row) * width) + x] = pixel
						}

					}
					read unsigned8 discard
					read unsigned8 ff-check
					at file.position - 1:
				}
			} while (ff-check != 0xFF)
		}
	}

	write unsigned8 decompressed
}