// Built with : 
// CCPSX.EXE -O2 -Xo0x80010000 hellow.c -o hellow.cpe
// CPE2X.EXE /ce hellow.cpe
// Upload with :
// nops /fast /exe HELLOW.EXE /dev/ttyUSB0
// HW :
// Unirom 8b6 cart
// Ftdi simple serail cable
// SCPH-7502 PAL with Psnee modchip
// SCPH-5502 PAL with Psnee modchip

#include <sys/types.h>
#include <stdio.h>
#include <libetc.h>
#include <libgte.h>
#include <libgpu.h>


// set DOUBLE FB with 2 DISPENV and 2 DRAWENV
DISPENV disp[2];
DRAWENV draw[2];
// counter to know on which FB we are
int db;

void init(void){

	// Reset GPU and enable interrupts
	ResetGraph(0);
	
	
	//Let's create 2 320x240 display area, one at 0,0, one at 0,240 
	SetDefDispEnv(&disp[0], 0, 0, 320, 240); // This one TOP
	SetDefDispEnv(&disp[1], 0, 240, 320, 240); // This one BOTTOM
	
	//Same with 2 drawing area. They are inverted compared to the display area : 
	SetDefDrawEnv(&draw[0], 0, 240, 320, 240); // This one BOTTOM
	SetDefDrawEnv(&draw[1], 0, 0, 320, 240); // This one TOP
	
	// Optional : PAL SETUP
	
	//~ disp[0].screen.y = 24;
	//~ disp[1].screen.y = disp[0].screen.y;
	
	//~ SetVideoMode(MODE_PAL);
	
	
	setRGB0(&draw[0], 49, 177, 255); // Set the first DRAWENV primitive's color
	setRGB0(&draw[1], 49, 177, 55); // Set the second "					"
	
	// Set Clear Flag so that we don't get funny effects
	draw[0].isbg = 1; 
	draw[1].isbg = 1;
	
	// Set the Envs Up for the first time
	PutDispEnv(&disp[0]);
	PutDrawEnv(&draw[0]);
	
	// Initialize counter
	db = 0;

	
	// Font system init AFTER graphics setup
	FntLoad(960, 0);
	FntOpen(8, 8, 320, 240, 0, 100);
	

}

void display(void){
	DrawSync(0); // Block execution until all drawing is done
	VSync(0);    // Block execution until next vblank

	db = !db;    // flip value
	
	PutDispEnv(&disp[db]); // Set what buffer we are displaying 
	PutDrawEnv(&draw[db]); // 
	
	SetDispMask(1); // Make visible

}

int main(){
	
	// Init
	init();
	
	// Infinite execution
	while (1){
		
		//Print in the loooop
		FntPrint("HELLOOOOOWW");
		FntFlush(-1);
		
		display();
	}
	
	return 0;
}
