#include <string.h>
#include <stdio.h>
#include "font.h"

int Font::Load(char *name)
{
	FILE *ifile;
	unsigned int fntSize;

	ifile=fopen(name,"rb");
	if (!ifile)
		return NULL;

	fseek(ifile,0,SEEK_END);
	fntSize=(unsigned int)ftell(ifile);
	fseek(ifile,0,SEEK_SET);

	if(fontptr!=0) delete[] fontptr;
	fontptr=new unsigned char [fntSize];

	if (!fontptr)
	{
		fclose(ifile);
		return NULL;
	}
	if (fread(fontptr,sizeof(unsigned char),fntSize,ifile)!=fntSize)
	{
		fclose(ifile);
		return NULL;
	}
	fclose(ifile);
	return 1;
}

void Font::PutCh(unsigned int x, unsigned int y, char ch, unsigned char col1, unsigned char col2)
{
	unsigned char a, b, w = shifts ? fontptr[firstshift + ch] : width;
	unsigned char bit[8] = { 128, 64, 32, 16, 8, 4, 2, 1 };

	for (a = 0; a < height; a++)
		for (b = 0; b < w; b++)
			if ((fontptr[(ch*height*widthb) + (a*widthb) + (b > 7 ? 1 : 0)] & bit[b > 7 ? b - 8 : b]))
				screen[(x + b)+ (y + a)*320]=col1;
			else
				if (col2 != 0)
					screen[(x + b)+ (y + a)*320]=col2;
}

void Font::PrintAt(unsigned int x, unsigned int y, char *text, unsigned char col1, unsigned char col2)
{
	unsigned int a, xx = x, yy = y;
	for (a = 0; a < strlen(text); a++)
		switch (text[a]) {
			case 10	:	yy += height;
								xx = x;
								break;
			default:	PutCh(xx, yy, text[a] - startchar, col1, col2);
								xx += shifts ? fontptr[firstshift + (text[a]-startchar)] : width;
								break;
		};
}


void Font::operator << (char* string)
{
	if(xpos>=320-width)
	{
		xpos=0;
		ypos+=height;
	}
	if(ypos>=200-height)
	{
		ypos=0;
		xpos=0;
	}
	Print(string, xpos, ypos, 15, 0);

	for (int i = 0; i < strlen(string); i++)
		if(string[i]==10)
		{
			ypos+=height;
			xpos=0;
		}
		else xpos+=width;
}
void Font::operator << (char character)
{
	if(xpos>=320-width)
	{
		xpos=0;
		ypos+=height;
	}
	if(ypos>=200-height)
	{
		ypos=0;
		xpos=0;
	}
	Print(character, xpos, ypos, 15, 0);
	if(character==10) ypos+=height;
	else xpos+=width;
}

void Font::operator << (int integer)
{
	if(xpos>=320-width)
	{
		xpos=0;
		ypos+=height;
	}
	if(ypos>=200-height)
	{
		ypos=0;
		xpos=0;
	}

	char* txtbuf="\0";
	sprintf(txtbuf,"%i",integer);
	Print(txtbuf, xpos, ypos, 15, 0);
	xpos+=strlen(txtbuf)*width;
}

