#include <stdio.h>
#include <ultra64.h>
#include <assert.h>
#include <fcntl.h>

#include "controller_api.h"

static int fd;
static int counter;

#define OFFSET 0x400

static void tas_init(void) {
    fd = open("cont.m64", O_RDONLY);
    if (fd != 0) {
        uint8_t buf[OFFSET];
        read(fd, buf, sizeof(buf));
        counter = 0;
    }
}

static void tas_read(OSContPad *pad) {
    if (fd != 0) {
        uint8_t bytes[4] = {0};
        int result = read(fd, bytes, 4);
        assert(result > 0);
        pad->button = (bytes[0] << 8) | bytes[1];
        pad->stick_x = bytes[2];
        pad->stick_y = bytes[3];
        counter+=4;
        printf("%x called %04x %d %d\n", (counter + OFFSET), pad->button, bytes[2], bytes[3]);
        fflush(stdout);
    }
}

struct ControllerAPI controller_recorded_tas = {
    tas_init,
    tas_read
};
