#include "toaplan.h"

unsigned char* ExtraTROM;
unsigned char* ExtraTRAM;
unsigned char* ExtraTOffset;
unsigned char* ExtraTScroll;

int	nExtraTXOffset = 0x9999;
int nTileXPos;

static unsigned char* pTile;
static unsigned char* pTileData;
static unsigned int* pTilePalette;

typedef void (*RenderTileFunction)();
static RenderTileFunction RenderTile[2];

static int nLastBPP = 0;

#define ROT 270

#define DOCLIP 0

#define BPP 16
#include "toa_extratext.h"
#undef BPP

#define BPP 24
#include "toa_extratext.h"
#undef BPP

#define BPP 32
#include "toa_extratext.h"
#undef BPP

#undef DOCLIP
#define DOCLIP 1

#define BPP 16
#include "toa_extratext.h"
#undef BPP

#define BPP 24
#include "toa_extratext.h"
#undef BPP

#define BPP 32
#include "toa_extratext.h"
#undef BPP

#undef DOCLIP

#undef ROT

int ToaExtraTextLayer()
{
	unsigned char *pCurrentRow;
	int x, y;
	unsigned int* pTextPalette = &ToaPalette[0x0400];

	if (nLastBPP != nBurnBpp ) {
		nLastBPP = nBurnBpp;

		switch (nBurnBpp) {
			case 2:
				RenderTile[0] = *RenderTile16_ROT270_NOCLIP;
				RenderTile[1] = *RenderTile16_ROT270_CLIP;
				break;
			case 3:
				RenderTile[0] = *RenderTile24_ROT270_NOCLIP;
				RenderTile[1] = *RenderTile24_ROT270_CLIP;
				break;
			case 4:
				RenderTile[0] = *RenderTile32_ROT270_NOCLIP;
				RenderTile[1] = *RenderTile32_ROT270_CLIP;
				break;
			default:
				return 1;
		}
	}

	int nTileLeft = nBurnColumn << 3;
	int nTileDown = nBurnRow << 3;
	unsigned short* pTileRow;
	int nStartX;

	int nOffset = ((*((unsigned short*)ExtraTOffset) + nExtraTXOffset) & 0x01FF);
	if (nOffset > 0xC0) {
		nStartX = (1 + ((0x01FF - nOffset) >> 3)) & 0x03F;
		nOffset = (nOffset + (nStartX << 3)) & 0x01FF;
	} else {
		nStartX = 0;
	}
	pTileRow = (unsigned short*)(ExtraTRAM + ((nOffset >> 3) << 1));
	pCurrentRow = pBurnBitmap - (nOffset & 7) * nBurnColumn;

	for (y = 0; y < 30; y++, pCurrentRow += nTileDown, pTileRow += 0x40) {
		for (x = 0, pTile = pCurrentRow; x < 41; x++, pTile += nTileLeft) {
			unsigned int nTile = pTileRow[(x - nStartX) & 0x3F];
			if (nTile && nTile != 0x20) {
				pTileData = ExtraTROM + ((nTile & 0x3FF) << 5);
				pTilePalette = &pTextPalette[((nTile >> 6) & 0x03F0)];
				if (x == 0 || x == 40) {
					nTileXPos =  -(nOffset & 7) + (x << 3);
					RenderTile[1]();
				} else {
					RenderTile[0]();
				}
			}
		}
	}
	return 0;
}

int ToaExtraTextInit()
{
	if (nExtraTXOffset == 0x9999) {
		nExtraTXOffset = 0x2B;
	}
	return 0;
}

void ToaExtraTextExit()
{
	nExtraTXOffset = 0x9999;
}

