/* Step 7: run the 8-bit model the way a small car chip does.
   Inside the network there are only whole numbers, no decimals.
   Build it and run it:
     cc -o car car.c
     ./car
*/
#include <stdio.h>
#include <string.h>
#include "model.h"

static const char *CLASSES[] = {"accelerate", "cruise", "brake"};

/* Round to the nearest whole number, the same way quantize.py does. */
static int to_int(double v) {
    double f = v + 0.5;
    int i = (int)f;
    if (f < i) i--; /* (int) cuts towards zero, so fix negative numbers */
    return i;
}

int main(void) {
    FILE *f = fopen("windows.csv", "r");
    if (!f) {
        printf("car: can't open windows.csv. Run python3 windows.py first.\n");
        return 1;
    }
    char line[128];
    char answer[16];
    double x[N_IN];
    int n = 0, tested = 0, right = 0;
    if (!fgets(line, sizeof line, f)) return 1; /* skip the header */
    printf("window  car says     real answer\n");
    while (fgets(line, sizeof line, f)) {
        if (sscanf(line, "%lf,%lf,%lf,%lf,%15s", &x[0], &x[1], &x[2], &x[3], answer) != 5) continue;
        if (n++ % 4 != 0) continue; /* only the test windows */

        int qx[N_IN];
        for (int i = 0; i < N_IN; i++) {
            int q = to_int(x[i] * 127);
            qx[i] = q > 127 ? 127 : q < -127 ? -127 : q;
        }
        long long hidden[N_HID];
        for (int j = 0; j < N_HID; j++) {
            long long acc = B1[j];
            for (int i = 0; i < N_IN; i++) acc += W1[j][i] * qx[i];
            if (acc < 0) acc = 0;
            long long h = (acc * M1) >> 16;
            hidden[j] = h > 127 ? 127 : h;
        }
        int pick = 0;
        long long top = 0;
        for (int k = 0; k < N_OUT; k++) {
            long long acc = B2[k];
            for (int j = 0; j < N_HID; j++) acc += W2[k][j] * hidden[j];
            if (k == 0 || acc > top) {
                top = acc;
                pick = k;
            }
        }
        tested++;
        if (strcmp(CLASSES[pick], answer) == 0) right++;
        printf("%6d  %-11s  %s\n", n - 1, CLASSES[pick], answer);
    }
    fclose(f);
    printf("The car got %d of %d test windows right, using only whole numbers.\n", right, tested);
    return 0;
}
