/*****************************/
/* Inside The Machine - MKS  */
/*****************************/

//Includes
#include "Engine.h"
#include "SplashState.h"

int mp3Volume = 64;
int soundVolume = 32;
u8 soundData[784*1024];
int motion = 0;
u8 sndMenu[8192];
u8 sndFire[45056];
u8 sndDie[155648];
	
//Point d'entrée main
int main()
{	
	//Initialization of PA_Lib
	PA_Init();
	PA_InitVBL();

	//Initialization of µlibrary
	ulInit(UL_INIT_ALL);	
	ulInitGfx();
	ulInitText();
	ulSetMainLcd(1);
	/*motion = motion_init();
	motion_set_offs_x();
	motion_set_offs_y();
	motion_set_offs_gyro();*/
	
	int totalTime = 1;
	
	//Parametrage de la VRAM
		//512ko
	//ulSetTexVramParameters(UL_BANK_A | UL_BANK_B | UL_BANK_C | UL_BANK_D , VRAM_A, 512 << 10);
		//256ko
	ulSetTexVramParameters(UL_BANK_A | UL_BANK_B , VRAM_A, 256 << 10);
	
	//Création du moteur
	CEngine engine;
	engine.stman = new StateManager;
	
	ulDebug("Loading...");
	//Initialisation du système de fichiers	
	engine.IsFat = EFS_Init(EFS_AND_FAT, NULL);
	
	if(!engine.IsFat)
	{
		ulDebug("Can't Initialise EFS System, aborting program execution.");
		while(1); 
	}
	ulDebug(" Done.\n");
	
	//ASlib
	PA_InitASLibForMP3(AS_MODE_MP3 | AS_MODE_SURROUND | AS_MODE_16CH);
	
	//On paramètre les valeurs pas défout du volume
	AS_SetMP3Volume(mp3Volume);
	AS_SetMP3Loop(true);
 	AS_SetDefaultSettings(AS_PCM_8BIT, 22050, AS_NO_DELAY);
	//AS_SetSoundVolume(soundVolume);
		
	//Enregistrement du premier état
	engine.stman->ChangeState(SplashState::Instance() );
	
	//On charge les effets sonores
	LoadSnd("efs:/sounds/Menu.raw", sndMenu);
	LoadSnd("efs:/sounds/FireBall.raw", sndFire);
	LoadSnd("efs:/sounds/Boss1_Die.raw", sndDie);
	
	//Boucle Principale
	while(engine.IsRunning)
	{
	   //Initialize the timers to measure the framerate
	   TIMER1_CR = 0;
		TIMER1_DATA = 0;
		TIMER1_CR = TIMER_DIV_64 | TIMER_ENABLE;
		
	   //Event Handling
	   ulReadKeys(0);
	   engine.stman->HandleEvents();
	   
	   //Mise à jour
	   engine.stman->Update();
	   
		//Démarrage de l'affichage : ulib
		ulStartDrawing2D();
			engine.stman->Draw();
			//Calculate the CPU usage based on the timer value and total time per frame
			int cpuTime = (TIMER1_DATA * 1000) / totalTime;
			//ulPrintf_xy(100, 5, "CPU: %02i.%i%%", cpuTime / 10, cpuTime % 10);
		ulEndDrawing();
		
		//Fin de l'affichage
		ulEndFrame();
		PA_WaitForVBL();
		totalTime = TIMER1_DATA;
	}

	//Blabla
	return 0;
}
