#include <gccore.h>
#include <ogcsys.h>
#include <malloc.h>

#include "../gbcore/gb.h"
#include "../screen.h"
#include "GRRLIB.h"

int isVPAL;
int screen_w, screen_h;
extern u16 *GRRLIB_buffer;

inline u16 screen_color_from_rgb(u8 r, u8 g, u8 b)
{
	return GRRLIB_Conv888_565(r, g, b);
}


void screen_init()
{
	screen_w = 640;
	screen_h = 480;
	isVPAL = 0;
	GRRLIB_buffer=(u16 *)malloc(640*480*2);
	VIDEO_Init();
	GRRLIB_InitVideo();
	GRRLIB_Start();
	VIDEO_WaitVSync();
}

void screen_clear()
{
	GRRLIB_FillScreen(0x00);
}
void screen_render()
{
	GRRLIB_Render();
	VIDEO_WaitVSync();
}
void screen_put_pixel(int x, int y, u16 color)
{
	GRRLIB_PutPixel(x, y, color);
}
void screen_draw_imagex2(int xpos, int ypos, int width, int high, const u16 data[])
{
	int x, y;
	u16 *v1, *v2, *d;
	d = &data[0];
	for(y=0;y<high;y++){
		v1 = &GRRLIB_buffer[ypos + y*2*screen_w + xpos];
		v2 = v1+screen_w;
                for(x=0;x<width;x++){
			if(*d!=0xf01e){ //if not is magenta
				*v1++ = *v2++ = *d;
				*v1++ = *v2++ = *d;
			}
                        d++;
                }
        }	
}
void screen_draw_imagex3(int xpos, int ypos, int width, int high, const u16 data[])
{
	int y,x;
	u16 *v1, *v2, *v3, *d;
	int correctionx = -xpos/3;
	int correctiony = -ypos/3;

	for(y=correctiony;y<high-correctiony;y++){
		d = &data[y*width+correctionx];
		v1 = &GRRLIB_buffer[(y-correctiony)*3*screen_w];
		v2 = v1+screen_w;
		v3 = v2+screen_w;
                for(x=correctionx;x<width-correctionx;x++){
			if(*d!=0xf01e){ //if not is magenta
				*v1++ = *v2++ = *v3++ = *d;
				*v1++ = *v2++ = *v3++ = *d;
				*v1++ = *v2++ = *v3++ = *d;
			}
                        d++;
                }
        }	
}
