#include "SDL.h"

int CharPos[520];
SDL_Surface *Font;

#define SPACE_WIDTH CharPos[2]-CharPos[1]

void InitFont(SDL_Surface *FontToUse)
{
    int x=0,i=0;

    Font=FontToUse;
    while (x<Font->w) {
	if (GetPixel(Font,x,0)==SDL_MapRGB(Font->format,255,0,255)) {
	    CharPos[i++]=x;
//	    printf("%d  ",x);
	    while (GetPixel(Font,x,0)==SDL_MapRGB(Font->format,255,0,255))
		x++;
	    CharPos[i++]=x;
//	    printf("%d  ",x);
	}
	x++;
//	printf("%d-",GetPixel(Font,x,0));
    }
}


void PutString(SDL_Surface *Surface, int x, int y, char *text)
{
    unsigned char ofs;
    int i=0;
    SDL_Rect srcrect,dstrect;
    
    while (text[i]!='\0') {
	if (text[i]==' ') {
	    x+=SPACE_WIDTH;
	    i++;
	} else {
	    ofs=(text[i]-33)*2+1;
//	    printf("printing %c %d\n",text[i],ofs);
    	    srcrect.w=dstrect.w=(CharPos[ofs+2]+CharPos[ofs+1])/2-(CharPos[ofs]+CharPos[ofs-1])/2;
    	    srcrect.h=dstrect.h=Font->h-1;
    	    srcrect.x=(CharPos[ofs]+CharPos[ofs-1])/2;
    	    srcrect.y=1;
    	    dstrect.x=x;
	    dstrect.y=y;
    	    SDL_BlitSurface( Font, &srcrect, Surface, &dstrect);
	    x+=CharPos[ofs+1]-CharPos[ofs];
	    i++;
	}
    }    
}

int TextWidth(char *text)
{
    int x=0,i=0;
    unsigned char ofs;

#ifdef __riscos__
    /* Uses undefined ofs variable below which can cause a crash */
    if (*text == '\0') return;
#endif

    while (text[i]!='\0') {
	if (text[i]==' ') {
	    x+=SPACE_WIDTH;
	    i++;
	} else {
	    ofs=(text[i]-33)*2+1;
	    x+=CharPos[ofs+1]-CharPos[ofs];
	    i++;
	}
    }
    return x+CharPos[ofs+2]-CharPos[ofs+1];
}

void XCenteredString(SDL_Surface *Surface, int y, char *text)
{
    PutString(Surface, Surface->w/2-TextWidth(text)/2, y, text);
}