extern unsigned char msx[];
static int bufferwidth;
static int pixelformat;
static void * vram;
static int mode;

int font_init(void) {
	int pwidth, pheight, unk;
	sceDisplayGetMode(&unk, &pwidth, &pheight);
	sceDisplayGetFrameBuf(&vram, &bufferwidth, &pixelformat, &unk);
	vram = (void *)(((unsigned long)vram) | 0x40000000);

	// Kill if Bufferwidth is invalid
	if(bufferwidth == 0) return -1;

	// Check for valid Pixelformat
	if((pixelformat == PSP_DISPLAY_PIXEL_FORMAT_565) || (pixelformat == PSP_DISPLAY_PIXEL_FORMAT_5551) || (pixelformat == PSP_DISPLAY_PIXEL_FORMAT_4444) || (pixelformat == PSP_DISPLAY_PIXEL_FORMAT_8888)) {
		mode = pixelformat;
		return pixelformat;
	}
	return -1;
}

int blit_string(int sx,int sy,const char *msg,int bg) {
	// Kill Process if Bufferwidth aint playing along...
	if(bufferwidth == 0) return -1;

	// Needed Variables
	int p = 0;
	int x = 0;
	int y = 0;
	int ox = sx;

	// Decide what to do... 16bit? 32bit?...
	if(mode == PSP_DISPLAY_PIXEL_FORMAT_8888) {
		// Convert Pointer to 32bit
		unsigned int * vram32 = (unsigned int *)vram;

		// Get to work...
		for(x = 0; msg[x]; x++) {
			u8 code = msg[x] & 0x7f;
			for(y = 0; y < 8; y ++) {
				int offset = (sy + y) * bufferwidth + ox;
				u8 pmap = msx[code * 8 + y];
				for(p = 0; p < 6; p ++) {
					if(pmap & 0x80) {
						vram32[offset] = 0x00000000;
						//vram32[offset] = 0x00FFFFFF;
					} else {
						if(bg == 1)
							//vram32[offset] = 0x00FFFFFF;
							vram32[offset] = 0xFFEDEDED;
					}
					pmap <<= 1;
					offset ++;
				}
			}
			ox += 6;
		}
	} else if((pixelformat == PSP_DISPLAY_PIXEL_FORMAT_565) || (pixelformat == PSP_DISPLAY_PIXEL_FORMAT_5551) || (pixelformat == PSP_DISPLAY_PIXEL_FORMAT_4444)) {
		// Convert Pointer to 16bit
		unsigned short * vram16 = (unsigned short *)vram;

		// Get to work...
		for(x = 0; msg[x]; x++) {
			u8 code = msg[x] & 0x7f;
			for(y = 0; y < 8; y ++) {
				int offset = (sy + y) * bufferwidth + ox;
				u8 pmap = msx[code * 8 + y];
				for(p = 0; p < 6; p ++) {
					if(pmap & 0x80) {
						//vram16[offset] = 0x0000;
						vram16[offset] = 0xFFFF;
					} else {
						if(bg==1)
							//vram16[offset] = 0xFFFF;
							vram16[offset] = 0x0000;
					}
					pmap <<= 1;
					offset ++;
				}
			}
			ox += 6;
		}
	}
	
	return x;
}
