
#include "stext.h"
#include "tcscr.h"

#include <stdarg.h>
#include <stdio.h>

static dword inks[3*256];

extern void InitInks(void) {
    int i;

    memset(inks, 0, 256*sizeof(*inks));
    for (i = 256; i < 2*256; i++)
        inks[i] = (i-256)*100/256*0x00401004;
    MemSetD(inks + i, 100*0x00401004, 256*sizeof(*inks));
}

extern int WriteChar(FONT_TFont *font, int x, int y, char c, int ink, int *ny) {
    int lmar = 0, rmar = TCS_Width;
    int i, j, width;
    byte *pc;
    dword *sc;

    width = FONT_Index(font, c, &pc);
    if (x > rmar - width) {     // Would go out of area? Next line.
        x = lmar;
        y += font->height+1;
    }
    if (pc != NULL && x <= (TCS_Width - width) && y <= (TCS_Height - font->height)) {
        int offs;

        offs = 1 - font->height*TCS_Width;
        sc = (TCS_Screen) + TCS_Width*y + x;

        for (i = 0; i < width; i++) {
            byte k;
            int ty = y;
            for (j = font->height; j > 0; j--) {
                if ( (k = *pc++) != 0/* && ty >= 0 && ty < TCS_Height*/) {
                    *sc = TCS_AddPixel(*sc, inks[ink+k]);
                }
                sc += TCS_Width;
                ty++;
            }
            sc += offs;
        }
        x += 2;
    }
    if (ny != NULL)
        *ny = y;
    return x + width;
}

extern int WriteText(FONT_TFont *font, int x, int y, const char *str, int ink) {
    byte c;

    assert(font != NULL);
    if (str == NULL || font->data == NULL)
        return x;

    while ( (c = (byte)*str++) != '\0') {
        x = WriteChar(font, x, y, c, ink, &y);
    }
    return x;
}

extern int DoPrintf(FONT_TFont *font, int x, int y, int ink, const char *fmt, ...) {
    char buf[300];
    va_list arg;

    va_start(arg, fmt);
    vsprintf(buf, fmt, arg);
    va_end(arg);
    return WriteText(font, x, y, buf, ink);
}

extern int GetTextExtent(FONT_TFont *font, const char *str) {
    int width;
    byte *pc;
    byte c;
    int x;

    x = 0;

    assert(font != NULL);
    if (str == NULL || font->data == NULL)
        return x;

    while ( (c = (byte)*str++) != '\0') {
            // Find char dimensions (and, conveniently, addr).
        width = FONT_Index(font, c, &pc);
        if (pc != NULL) { // x <= (TCS_Width - width)
            x += 2;
        }
        x += width;
    }
    return x;
}

