#include "game_types.h"

/* Bignum_Multiply @ 0x0801CB88 (real 148B) -- schoolbook multiply-accumulate with grow. Mirrors src/matched/Bignum_Multiply.c. */
/* Multiplies q[5..] (q[4] digits) by m with carry-in d: split-halfword
   accumulate per digit, growing via GetDigits/MemCopyFast/ShiftRight when
   the carry overflows a full buffer, then storing the carry and count. */
extern int *Bignum_GetDigits(int ctx);
extern void Physics_MemCopyFast(int *dst, int *src, int n);
extern void Bignum_ShiftRight(int *a, int *b);

int *Bignum_Multiply(int ctx, int *q, unsigned m, unsigned d)
{
    unsigned n = (unsigned)q[4];
    unsigned carry = d;
    unsigned i;
    (void)ctx;
    for (i = 0; i < n; i++) {
        unsigned w = (unsigned)q[5 + i];
        unsigned lo = (w & 0xFFFF) * m + carry;
        unsigned hi = (w >> 16) * m + (lo >> 16);
        carry = hi >> 16;
        q[5 + i] = (int)((hi << 16) | (lo & 0xFFFF));
    }
    if (carry != 0) {
        if (n >= (unsigned)q[2]) {
            int *nq = Bignum_GetDigits(ctx);
            Physics_MemCopyFast(nq + 3, q + 3, (int)(n * 4 + 8));
            Bignum_ShiftRight(ctx, q);
            q = nq;
        }
        q[5 + n] = (int)carry;
        q[4] = (int)(n + 1);
    }
    return q;
}
