#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <ogcsys.h>
#include <gccore.h>
#include <unistd.h>

#include "dvd.h"
#include "loadapp.h"
#include "gameloader.h"
#include "loadmios.h"
#include "screen.h"
#include "loader.h"
#include "debugprintf.h"
#include "dvd.h"
#include "background.h"

#define HOMEBREW_MAGIC 0x807FFFE0

static void *xfb = NULL;
static GXRModeObj *rmode = NULL;

void clearScreen(void)
{
	//VIDEO_ClearFrameBuffer(rmode, xfb, COLOR_BLACK);
	printf("\x1b[J");
}

void check_for_homebrew(void)
{
	char *magic = (char *) HOMEBREW_MAGIC;

	if (strncmp(magic, "gchomebrew dol", 32) == 0) {
		/* Start homebrew. */
		load_dol();
	}
}

int main(int argc, char **argv)
{
	PAD_Init();
	VIDEO_Init();

	rmode = VIDEO_GetPreferredMode(0);
	xfb = MEM_K0_TO_K1(SYS_AllocateFramebuffer(rmode));
	VIDEO_Configure(rmode);
	VIDEO_SetNextFramebuffer(xfb);
	VIDEO_SetBlack(FALSE);
	VIDEO_Flush();
	VIDEO_WaitVSync();
	if(rmode->viTVMode&VI_NON_INTERLACE) VIDEO_WaitVSync();

 	CON_InitEx(rmode, 24, 212, rmode->fbWidth -32, rmode->xfbHeight -212 -32);

	VIDEO_ClearFrameBuffer(rmode, xfb, COLOR_BLACK);
	
	DrawBackground(rmode, (u32)xfb);

#ifdef MIOS_BACKUP
	/* When linked into MIOS, check first if homebrew should be started. */
	check_for_homebrew();
#endif

	if (dvd_read_id() != 0)
	{
		backuploading = true;
		//printf("Loading backup disc...\n");
	} else
	{
		backuploading = false;
		//printf("Loading retail disc...\n");
	}
	
	if (strcmp((char *)0x807FFF00, "GAMECUBELOADER01") == 0)
	{
		start_from_NeoGamma();
	}
	
	/* Start game directly. */
	start_backup_loader();

	clearScreen();

	/* Start MIOS without backup support. */
	call_mios();

	SYS_ResetSystem(SYS_RESTART, 0, 0);
	return 0;
}
