#include <malloc.h>
#include "../screen.h"
#include "../menu.h"
#include "../gbcore/gb.h"

u16 gb_screen_data[SGBWIDTH*SGBHEIGHT];
float gb_screen_scale = 1.0;

void screen_render_ingame()
{
	screen_clear();
	//u16 colorline = screen_color_from_rgb(0x00, 0xFF, 0x00);
	//screen_printf(10, 15, colorline, "Emulating: scale x%.2f", gb_screen_scale);
	if(gb_screen_scale == 1.0)
		screen_draw_image((screen_w-SGBWIDTH)/2, (screen_h-SGBHEIGHT)/2, SGBWIDTH, SGBHEIGHT, gb_screen_data, 0.0, gb_screen_scale);
	if(gb_screen_scale == 2.0)
		screen_draw_imagex2((screen_w-SGBWIDTH*2)/2, (screen_h-SGBHEIGHT*2)/2, SGBWIDTH, SGBHEIGHT, gb_screen_data);
	if(gb_screen_scale == 3.0)
		screen_draw_imagex3((screen_w-SGBWIDTH*3)/2, (screen_h-SGBHEIGHT*3)/2, SGBWIDTH, SGBHEIGHT, gb_screen_data);

	screen_render();
}

void internal_paint_gb(unsigned long x,unsigned long y, unsigned long height, unsigned long width, u16 *d, int guardLine)
{
	u16 color;
	int r, g, b;
	unsigned long yy;
	unsigned long xx;
	
//x/=2;
	if(guardLine)
		d += GUARD_LINE;
	for (yy=0; yy<height; yy++) {
		u16 *v = &gb_screen_data[(yy+y)*SGBWIDTH+x];
		for (xx=0; xx<width; xx++){
			color = *d++;
			r = ((color      ) & 0x1F) << 3;
			g = ((color >>  5) & 0x1F) << 3;
			b = ((color >> 10) & 0x1F) << 3;
			
			//gb_screen_data[((yy+y)*SGBWIDTH)+xx+x] = screen_color_from_rgb(r, g, b);
			*v++ = screen_color_from_rgb(r, g, b);
			//screen_put_pixel(25+x+xx, 25+y+yy, screen_color_from_rgb(r, g, b));
		}
		if(guardLine)
			d+=GUARD_LINE*2;
	}
}

void screen_bitblt_sgb(unsigned long x,unsigned long y,u16 *d)
{
	internal_paint_gb(0, 0, SGBHEIGHT, SGBWIDTH, d, 0);
}

void screen_bitblt_gb(unsigned long x, unsigned long y, u16 *d)
{
	gb_screen_scale = 1.0 + setting.screensize;
	internal_paint_gb((SGBWIDTH-GBWIDTH)/2, (SGBHEIGHT-GBHEIGHT)/2, GBHEIGHT, GBWIDTH, d, 1);
}
