Archive_DAT_Sango::Archive_DAT_Sango(stream::inout_sptr psArchive)
	:	FATArchive(psArchive, DAT_FIRST_FILE_OFFSET, 0)
{
	psArchive->seekg(0, stream::end);
	this->lenArchive = psArchive->tellg();

	if (this->lenArchive < DAT_FAT_ENTRY_LEN) throw stream::error("file too short");

	uint32_t offEndFAT;
	psArchive->seekg(0, stream::start);
	psArchive >> u32le(offEndFAT);

	uint32_t offCur = offEndFAT, offNext;
	for (int i = 0; offCur < this->lenArchive; i++) {
		psArchive >> u32le(offNext);

		FATEntry *fatEntry = new FATEntry();
		EntryPtr ep(fatEntry);

		fatEntry->iIndex = i;
		fatEntry->iOffset = offCur;
		fatEntry->lenHeader = 0;
		fatEntry->type = FILETYPE_GENERIC;
		fatEntry->fAttr = 0;
		fatEntry->bValid = true;
		fatEntry->storedSize = offNext - offCur;
		fatEntry->realSize = fatEntry->storedSize;
		this->vcFAT.push_back(ep);
		if (i >= DAT_SAFETY_MAX_FILECOUNT) {
			throw stream::error("too many files or corrupted archive");
		}

		offCur = offNext;
	}
}
Tileset_MonsterBashSprite::Tileset_MonsterBashSprite(stream::inout_sptr data)
	:	Tileset_FAT(data, MB_FIRST_TILE_OFFSET)
{
	// Skip signature byte
	data->seekg(1, stream::start);
	stream::pos offset = 1;
	stream::len lenRemaining = this->data->size() - 1;

	int i = 0;
	while (lenRemaining >= MB_SPR_EFAT_ENTRY_LEN) {
		uint16_t lenBlock;
		data >> u16le(lenBlock);
		lenRemaining -= 2;

		FATEntry *fat = new FATEntry();
		EntryPtr ep(fat);
		fat->valid = true;
		fat->attr = 0;
		fat->index = i;
		fat->offset = offset;
		fat->size = lenBlock;
		fat->lenHeader = MB_SPR_EFAT_ENTRY_LEN;
		this->items.push_back(ep);
		if (lenBlock > lenRemaining) {
			std::cerr << "Warning: Ignoring incomplete image in Monster Bash sprite "
				"(image is " << lenBlock << " bytes, but file only contains another "
				<< lenRemaining << " bytes)" << std::endl;
			break;
		}
		data->seekg(lenBlock, stream::cur);
		lenRemaining -= lenBlock;
		offset += lenBlock + MB_SPR_EFAT_ENTRY_LEN; // MB_SPR_EFAT_ENTRY_LEN == sizeof(uint16le)
		i++;
	}

}