
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "writeri.h"

#ifdef PSP

#define XS 480
#define YS 272
#define FX 480
#define FY 308

#else

#define XS 320
#define YS 200
#define FX 320
#define FY 128

#endif

static char *chars="abcdefghijklmnopqrstuvwxyz1234567890!'";

static unsigned char fnt[FX*FY*3];

int writeri_init(char *font)
{
    FILE    *f;

    if((f=fopen(font,"rb"))==NULL)
        return(-1);

    fread(fnt,1,FX*FY*3,f);
    fclose(f);
    
    return(0);
}

void writeri_char(unsigned char *s,int x,int y,char c,int phase,unsigned char col)
{
    int i,n,xx,yy,off;

    for(i=0;i<strlen(chars);i++)
        if(chars[i]==c)
            break;
    if(i==strlen(chars))
        return;

    i=(i%10)*32+i/10*32*FX + FY*FX*phase;
    for(yy=0;yy<32;yy++)
    {
        off=x+y*XS+yy*XS;
        for(xx=0;xx<28;xx++,off++)
        {
            switch(fnt[i+yy*FX+xx])
            {
                case 0: s[off]=col; break;
                case 255: break;
                default: s[off]|=0x80; break;
            }
        }
    }
}

void writeri(unsigned char *s,int x,int y,char *text,int flag,int tid,unsigned char col)
{
    int n,xx=x,yy=y,center;

    center=strlen(text)*22/2+4;
    if(!flag)
        center=0;
    for(n=0;n<strlen(text);n++)
    {
        writeri_char(s,xx-center,yy-((flag)?16:0),text[n],(tid/140+n)%3,col);
        xx+=22;
    }
}
