#include <SDL/SDL.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "main.h"
#include "images.h"
#include "render.h"

unsigned char fontgfx[22016],chcor[256];
image font[86];

extern SDL_Surface *screen;

void FontsToImages()
{
	int i, j, c, k=0;
	for (i=0; i<86; i++)
	{
		font[i].width = font[i].height = 16;
		font[i].size = font[i].width * font[i].height;
		font[i].bits = 32;
		font[i].data = (unsigned int*)malloc(font[i].size * sizeof(unsigned int));
		for (j=0; j<256; j++)
		{
			c = fontgfx[k]*17;
			*(font[i].data + j) = (c<<24) | (c<<16) | (c<<8) | c;
			k++;
		}
	}
}

void LoadFonts()
{
	int i;
	FILE *fontdata;
	fontdata=fopen("./Data/Fonts/fonts16.bin","rb");

	for (i=0;i<256;i++)
		chcor[i]=fgetc(fontdata);

	for (i=0;i<22016;i++)
		fontgfx[i]=fgetc(fontdata);

	fclose(fontdata);
}

void DrawFont(int px, int py, unsigned char c)
{
	unsigned int *vram = (unsigned int*)screen->pixels;
	RenderSprite(px - 8, py - 8, &font[chcor[c]], vram, ScreenWidth, ScreenHeight);
}

void DrawText(int px, int py, char text[], unsigned char spc, int way)
{
	int i;
	float t = SDL_GetTicks()/256.0;

    switch (way)
    {
		case 0:
			for (i=0; i<strlen(text); i++)
			{
			    DrawFont(px + i*(16+spc), py, text[i]);
			}
		break;

		case 1:
			for (i=0; i<strlen(text); i++)
			{
			    DrawFont(px + i*(16+spc), py + sin((float)i/2.0 + (float)t) * 16, text[i]);
			}
		break;

		default:
		break;
	}
}

void InitFonts()
{
	LoadFonts();
	FontsToImages();
}
