#include "game_types.h"

/* Text_Render @ 0x08014188 (real 200B) -- countdown render with flag dispatch loops. Mirrors src/matched/Text_Render.c. */
/* Countdown-gated render: ticks the halfword at +38, reloads from +36 at
   zero, then dispatches on bit 1 of the halfword at +40 -- set path bumps
   by 16 (clamping at 256 with countdown clear), clear path decrements and
   either fans LoadFromROM over the entries or runs the bit-stamp loop --
   finishing by retagging word 1 and clearing the countdown. */
extern void Image_LoadFromROM(int dummy, unsigned char *q);

void Text_Render(int *p)
{
    unsigned f;
    int n, i;
    char *e;
    if (*(unsigned short *)((char *)p + 36) == 0)
        return;
    (*(unsigned short *)((char *)p + 38))--;
    if (*(unsigned short *)((char *)p + 38) != 0)
        return;
    *(unsigned short *)((char *)p + 38) =
        *(unsigned short *)((char *)p + 36);
    f = *(unsigned short *)((char *)p + 40);
    if ((f & 2) != 0) {
        f += 16;
        *(unsigned short *)((char *)p + 40) = (unsigned short)f;
        if ((f & 0xFFFF) > 255) {
            *(unsigned short *)((char *)p + 40) = 256;
            *(unsigned short *)((char *)p + 36) = 0;
        }
    } else {
        f -= 16;
        if ((f & 0xFFFF) > 0)
            goto path2;
        n = ((unsigned char *)p)[8];
        e = (char *)p[11];
        if (n > 0) {
            do {
                Image_LoadFromROM(p, e);
                if ((*(unsigned short *)((char *)p + 40) & 1) == 0)
                    e[0] = 0;
                e += 80;
                n--;
            } while (n > 0);
        }
        if ((*(unsigned short *)((char *)p + 40) & 1) != 0)
            p[1] |= 0x8000000;
        else
            p[1] = 0x8000000;
        *(unsigned short *)((char *)p + 36) = 0;
        return;
    }
path2:
    n = ((unsigned char *)p)[8];
    e = (char *)p[11];
    for (i = 0; i < n; i++, e += 80) {
        if ((e[0] & 128) != 0) {
            e[19] = (char)(*(unsigned short *)((char *)p + 40) >> 2);
            e[0] = (char)(e[0] | 3);
        }
    }
}
