/*
 * test1.c sample of inline asm
 *
 *    N.B. this file does not use and headers or other module apart from gba_font (the chars)
 *         so it is completly self contained.
 */

/* basic font to allow printing of messages on bg0 */
#include "gba_font.h"

/* sets up the GBA redy for the test prog. */
static void initForTest();
static void msgPrint( int x, int y, const unsigned char * msg );
static void msgPrintHexWord( int x, int y, unsigned int value );

static unsigned int getValue( void );

int main()
{
	unsigned int value;
	initForTest();

	value = getValue();
	msgPrint( 1, 1, "hello world!" ); 

	msgPrint( 1, 3, "value returned : " ); 
	msgPrintHexWord( 18, 3, value ); 

	while(1);
}

/* test code */

static unsigned int getValue( void )
{
	return 0xC0DEF00D;
}

/* support routines for test prog */
static void initForTest()
{
	int i;
	unsigned short * dest;

	/* enable bg0 mode 0 and thats all */
	*((unsigned short*)(0x04000000)) = 0x0100;
	/* set bg0 to use tiles at 0x06004000 with a map base of 0x06000000 16 colour 32x32 */
	*((unsigned short*)(0x04000008)) = 0x0004;

	dest = ((unsigned short*)(0x06000000));
	/* clear the whole of the video vram (64K) N.B. i is a 16 bit index NOT a byte index */
	for( i = 0x7FFF; i >= 0; i-- )
	{
		dest[i] = 0;
	}
	/* load the base font starting at tile 32 */
	dest = ((unsigned short*)(0x06004400));
	for( i = 0x3FFF; i >= 0; i-- )
	{
		dest[i] = l8fontData[i];
	}
	
	/* load up the bg palette */
	dest = ((unsigned short*)(0x05000000));
	for( i = 0xFF; i >= 0; i-- )
	{
		dest[i] = l8fontPalette[i];
	}
}

static void 
msgPrint( int x, int y, const unsigned char * msg )
{
	unsigned short * mapbase;
	int index, end;

	/* unsigned comparison i.e ((y < 0) || (y >= tile height)) */
	if ( ((unsigned int)y) >= 32 )
	{
		return; /* no way can this cause display*/
	}
	if ( x > 32 )
	{
		return; /* no possibiliy to print */
	}
	/* scan to get the char on map */
	while( x < 0 )
	{
		if ( !(*msg) ) return; /* end of msg before we can print it */
		msg++; 
		x++;
	}
	/* sort out the index N.B. this is HalfWord NOT a Byte index */
	index = y * 32 + x;
	end = index + (32 - x);

	mapbase = ((unsigned short*)(0x06000000));
	while ( *msg )
	{
		if ( index == end ) return;
		mapbase[index++] = (*msg); // put in with palette 0
		msg++;
	}
}

static unsigned char buffer[11];
static const unsigned char * const digit = "0123456789ABCDEF";

static void msgPrintHexWord( int x, int y, unsigned int value )
{
	buffer[ 0] = '0';
	buffer[ 1] = 'x';
	buffer[ 2] = digit[(value>>28)&0xF];
	buffer[ 3] = digit[(value>>24)&0xF];
	buffer[ 4] = digit[(value>>20)&0xF];
	buffer[ 5] = digit[(value>>16)&0xF];
	buffer[ 6] = digit[(value>>12)&0xF];
	buffer[ 7] = digit[(value>> 8)&0xF];
	buffer[ 8] = digit[(value>> 4)&0xF];
	buffer[ 9] = digit[value&0xF];
	buffer[10] = 0;
	msgPrint( x, y, buffer );
}

