#include "game_types.h"

/* Object_WrapPosition @ 0x08000448 (real 122B) -- wraps X/Y into fixed-point bounds with do-until loops. Mirrors src/matched/Object_WrapPosition.c. */
/* Wraps p[0] into [0, p[4]<<12] and the incoming w into [0, p[5]<<12] with
   do-until add/subtract loops (each loop stores only when taken). When the
   flag byte c is set, snapshots pos/prev into +8/+12 and words 10-13 into
   +24..+36. */
void Object_WrapPosition(int *p, int v, int w, int c)
{
    int boundX = p[4] << 12;
    int boundY = p[5] << 12;
    int x, y;
    p[2] = p[0];
    p[3] = p[1];
    p[0] = v;
    x = v;
    if (x < 0) {
        do {
            x += boundX;
        } while (x < 0);
        p[0] = x;
    } else if (boundX < x) {
        do {
            x -= boundX;
        } while (boundX < x);
        p[0] = x;
    }
    p[1] = w;
    y = w;
    if (y < 0) {
        do {
            y += boundY;
        } while (y < 0);
        p[1] = y;
    } else if (boundY < y) {
        do {
            y -= boundY;
        } while (boundY < y);
        p[1] = y;
    }
    if ((c & 0xFF) == 0)
        return;
    p[2] = p[0];
    p[3] = p[1];
    p[6] = p[10];
    p[7] = p[11];
    p[8] = p[12];
    p[9] = p[13];
}
