//  Copyright (C) 2016, mituhiromatuura all right reserved.

#include <string.h>
#include "disp.h"

extern const unsigned char Font[FONT_NUM][FONT_SIZE_Y][FONT_SIZE_X / 8];
extern void display_area_set(int xs, int ys, int xe, int ye);
extern void pset(int color);

void display_from_font(int px, int py, int xl, int yl, char* p, int fcolor, int bcolor)
{
	display_area_set(py, (LCD_SIZE_X - FONT_SIZE_X - px), py + yl - 1, (LCD_SIZE_X - FONT_SIZE_X - px) + xl - 1);

	int x, y,n;
	int color;

	p += FONT_SIZE_Y * FONT_SIZE_X / 8 - 1;

	for(y = 0; y < yl; y++)
	{
		for(n = 0; n < 3; n++)
		{
			for(x = 0; x < xl / 3; x++)
			{
				color = (*(unsigned char*)p & (1 << (x))) ? fcolor : bcolor;
				pset(color);
			}
			p--;
		}
	}
	return;
} 

void lcd_putc(int x, int y, const char c, int fcolor, int bcolor)
{
	display_from_font(x * FONT_SIZE_X, y * FONT_SIZE_Y, FONT_SIZE_X, FONT_SIZE_Y, (char *)Font[(int)c - ' '], fcolor, bcolor);
	return;
}

void lcd_puts(int x, int y, const char *s, int fcolor, int bcolor)
{
	switch(x)
	{
	case LCD_RIGHT:
		x = LCD_SIZE_X/FONT_SIZE_X - strlen(s);
		break;
	case LCD_CENTER:
		x = (LCD_SIZE_X/FONT_SIZE_X - strlen(s)) / 2;
		break;
	case LCD_LEFT:
	default:
		break;
	}

	while(*s)
	{
		lcd_putc(x, y, *s++, fcolor, bcolor);
		x++;
		if(LCD_SIZE_X/FONT_SIZE_X < x + 1)
		{
			x = 0;
			y++;
		}
	}

	display_area_set(0, 0, 240 - 1, 320 - 1);
	return;
}

extern const unsigned char Font_s[256][10];

void display_from_font_s(int px, int py, int xl, int yl, char* p, int fcolor, int bcolor)
{
	display_area_set(py, (LCD_SIZE_X - FONT_SIZE_s_X - px), py + yl - 1, (LCD_SIZE_X - FONT_SIZE_s_X - px) + xl - 1);

	int x, y;
	int color;

	p += FONT_SIZE_s_Y * FONT_SIZE_s_X / 8 - 1;

	for(y = 0; y < yl; y++)
	{
		for(x = 0; x < xl; x++)
		{
			color = (*(unsigned char*)p & (1 << (7 - x))) ? fcolor : bcolor;
			pset(color);
		}
		p--;
	}
	return;
} 

void lcd_putc_s(int x, int y, const char c, int fcolor, int bcolor)
{
	display_from_font_s(x * FONT_SIZE_s_X, y * FONT_SIZE_s_Y, FONT_SIZE_s_X, FONT_SIZE_s_Y, (char *)Font_s[(int)c], fcolor, bcolor);
	return;
}

void lcd_puts_s(int x, int y, const char *s, int fcolor, int bcolor)
{
	while(*s)
	{
		lcd_putc_s(x, y, *s++, fcolor, bcolor);
		x++;
		if(LCD_SIZE_X/FONT_SIZE_s_X < x + 1)
		{
			x = 0;
			y++;
		}
	}

	display_area_set(0, 0, 240 - 1, 320 - 1);
	return;
}
