display-name: "Games/Dark Ages"
meta: {"Working": ["Images", "Levels"], "Thanks to": "K1n9 Duk3"}

if (file.name like ["file01.da?", "file02.da?", "file03.da?", "file04.da?"])
{
	interpret-as "image-PCX"
}

if (file.name like "file05.da?")
{
	file[10]: i
	{
		name: "Level " + file.name[9] + "-" + (i + 1)
		offset: i * 1152
		size: 1152
		interpret-as "da-level"
	}	
}

file-format da-level
{
	level-bg-ega: 0
	level
	{
		width: 128
		height: 9

		grid-x: 16
		grid-y: 16

		compressed[128 * 9] "da-remap-tiles"
		{
			level-layer
			{
				layer-name: "Background"
				data-type: "unsigned8"
				layer-image: ["file06.da" + file.name[6], "file07.da" + file.name[6], "file08.da" + file.name[6],
						  	  "file09.da" + file.name[6], "file10.da" + file.name[6], "file11.da" + file.name[6],
						      "file12.da" + file.name[6] ]
			}
		}

		at 0:
		compressed[128 * 9] "da-remap-objects"
		{
			level-layer
			{
				layer-name: "Objects"
				data-type: "unsigned16"
				ignore-tile: 0
				//layer-image: "debug"

				layer-image: ["file06.da" + file.name[6], "file07.da" + file.name[6], "file08.da" + file.name[6],
						  	  "file09.da" + file.name[6], "file10.da" + file.name[6], "file11.da" + file.name[6],
						      "file12.da" + file.name[6] ]
			}
		}
	}
}

da-remap-list : [251, 258, 268, 274, 284, 288, 290, 294, 300, 330,
				 335, 336, 339, 342, 346, 350, 351, 352, 353, 354,
				 254, 255, 256, 257, 362, 364, 358, 359, 360, 373,
				 374, 375, 100, 380, 381, 382, 383, 385, 386, 390,
				 282, 397, 280, 400]

da-remap-offset: [1, 1, 1, 1, -128, -128, 1, 1, -128, 1,
                  -128, 1, 1, 1, 1, 128, 128, -128, -128, 1,
                  -1, -1, -1, -1, 0x0, 128, -128, -128, -128, -1,
                  -1, -1, 0x0, 1, -1, -1, -1, 1, 1, 1,
                  -1, -128, 1, -128]

function da-remap-tiles
{
	read unsigned8[128 * 9] decompressed

	loop (file.size): i
	{
		if (decompressed[i] == 124)
		{
			decompressed[i] = 29
		}
		else if (decompressed[i] == 132)
		{
			decompressed[i] = 81
		}
		else if ((decompressed[i] >= 100) and (decompressed[i] <= 143))
		{
			decompressed[i] = decompressed[i + da-remap-offset[decompressed[i] - 100]]
		}

		if (decompressed[i] == 119)
		{
			decompressed[i + 128] = decompressed[i + 129]
		}
		else if (decompressed[i] == 137)
		{
			decompressed[i - 128] = decompressed[i - 127]
		}
	}

	write unsigned8 decompressed
}

function da-remap-objects
{
	loop (file.size)
	{
		read unsigned8 tile

		if ((tile >= 100) and (tile <= 143))
		{
			write unsigned16 (da-remap-list[tile - 100] - 100)
		}
		else
		{
			write unsigned16 0
		}
	}
}

if (file.name like ["file06.da?", "file07.da?", "file08.da?", "file09.da?", "file10.da?", "file11.da?", "file12.da?"])
{
	//TODO: this is like crystal caves maybe?
	data(3) unknown
	image
	{		
		format: "A1I4"
		width: 16
		height: 16
		data-size: file.size - 3
           		tiles-across: 20
		bit-stride: 8
	}
}

if (file.name like "file??.da?")
{
	folder: "Music"
}