#include "game_types.h"

/* Printf_FormatInt @ 0x0801B558 (real 110B) -- formats a signed int with explicit sign. Mirrors src/matched/Printf_FormatInt.c. */
/* Writes c, then the sign ('-'/' +'), then the decimal digits (minimum two
   digits: small values emit '0' first) via the FixedDiv/Log2
   remainder+quotient pair over a 308-byte stack buffer. Returns the length.
   Merged with the shared Printf_WriteChar epilogue in the asm. */
extern int Math_FixedDiv(int a, int b);
extern unsigned Math_Log2(unsigned a, unsigned b);

int Printf_FormatInt(unsigned char *buf, int num, unsigned char c)
{
    unsigned char *p = buf;
    char tmp[308];
    char *t;
    int v = num;
    *p++ = c;
    if (v < 0) {
        v = -v;
        *p++ = '-';
    } else {
        *p++ = '+';
    }
    if (v > 9) {
        t = tmp + sizeof tmp;
        do {
            *--t = (char)(Math_FixedDiv(v, 10) + 48);
            v = (int)Math_Log2((unsigned)v, 10);
        } while (v > 9);
        *--t = (char)(v + 48);
        while (t < tmp + sizeof tmp)
            *p++ = *t++;
    } else {
        *p++ = '0';
        *p++ = (char)(v + 48);
    }
    return (int)(p - buf);
}
