display-name: "Games/Captain Comic II"
meta: {"Working": "Some images" }

if (file.name like "frpak.???")
{
	interpret-as "captaincomic1-fullscreen"
}

if (file.name like "fr???.1")
{
	folder: "Levels"
	unsigned16 num-parts
	unsigned16 unknown

	original-name: file.name

	file [num-parts]: i
	{
		unsigned16 width
		unsigned16 height
		unsigned16 offset
		name: "part " + i
		size: width * height

		compressed "comic2-tiles"

		folder: ""
		interpret-as "cc2-level-part"
	}
}

file-format cc2-level-part
{
	width: width
	height: height

	level
	{
		level-layer
		{
			grid-x: 16
			grid-y: 16
			data-type: "unsigned8"
			order: 1
			layer-image: (original-name - 1) + "0"
		}
	}	
}

if (file.name like "fr???.3")
{
	folder: "Text"
	encrypted "comic2-text"

	unsigned16 first-element
	element-count: first-element / 2

	at 0:
	unsigned16[element-count + 1] offsets
	offsets[element-count] = file.size

	loop (element-count): i
	{
		at offsets[i]
		{
			unsigned8 width
			unsigned8 height
			text
			{
				string-len: offsets[i + 1] - offsets[i] - 2
				if (i == (element-count - 1))
				{
					string-len = string-len - 1
				}

				fixed-string(string-len) _string-data 
				string-data: _string-data + "\r\n"
			}
			
		}
	}
}

if (file.name like ["fr???.2", "frdemo.?", "frdata.?"])
{
	folder: "Sprites"

	loop while (file.remaining-bytes > 0)
	{
		unsigned16 width
		unsigned16 height
		alpha-mask: 1
		bit-stride: width * height

		plane-start: file.position

		unsigned16 plane-size

		if (plane-size != ((width * height) / 8))
		{
			at plane-start: 

			image
			{
				format: "I4"
			}
		}
		else
		{
			image
			{
				format: "A1I4"
			}
		}
	}
}

//Do hacks because of Wombat bug where compressed block doesn't capture new file.size :/
if (file.name like "fr???.0")
{
	folder: "Tiles"

	compressed "comic2-tiles-hack"
	//unsigned16 last-blocking-tile
	//unsigned16 last-standing-tile
	//unsigned16 last-water-tile

	//compressed[file.remaining-bytes] "comic2-tiles"
	//{
		image
		{
			format: "I4"
			width: 16
			height: 16
			data-size: file.size
			tiles-across: 8
			bit-stride: width * height
		}
	//}
}

function comic2-tiles
{
	finished: false
	loop while(finished == false)
	{
		read unsigned8 token
		if (token == 0)
		{
			finished = true
		}
		else if ((token & 0x80) != 0)
		{
			read unsigned8 repeat
			loop (256 - token)
			{
				write unsigned8 repeat
			}
		}
		else
		{
			loop (token)
			{
				read unsigned8 val
				write unsigned8 val
			}

		}
	}
}

function comic2-tiles-hack
{
	data(6) unknown //hack

	finished: false
	loop while(finished == false)
	{
		read unsigned8 token
		if (token == 0)
		{
			finished = true
		}
		else if ((token & 0x80) != 0)
		{
			read unsigned8 repeat
			loop (256 - token)
			{
				write unsigned8 repeat
			}
		}
		else
		{
			loop (token)
			{
				read unsigned8 val
				write unsigned8 val
			}

		}
	}
}

function comic2-text
{
	loop (file.size)
	{
		read unsigned8 enc
		write unsigned8 (enc ^ 0x25)
	}
}

