#include <stdio.h>
#include <string.h>
#include "panel.h"

#define PW 960
#define PH 540

static uint8_t grey[PW * PH];   // 0..15 accumulated grey (0 = white, 15 = black)
static int cur_row;
static long rows_total;         // for stats

void panel_frame_reset(void) { cur_row = 0; }

void panel_row(const uint8_t *data, int len) {
    if (cur_row < 0 || cur_row >= PH) { cur_row++; return; }
    uint8_t *g = &grey[cur_row * PW];
    int px = 0;
    // 4 pixels per byte; pixel j occupies bits [j*2+1 : j*2]. 240 data bytes cover
    // the 960-pixel row; any trailing pad bytes just run off the end (px >= PW).
    for (int b = 0; b < len && px < PW; b++) {
        uint8_t byte = data[b];
        for (int j = 0; j < 4 && px < PW; j++, px++) {
            int code = (byte >> (j * 2)) & 3;            if (code == 1)      { if (g[px] < 15) g[px]++; }   // drive toward black
            else if (code == 2) { if (g[px] > 0)  g[px]--; }   // drive toward white
        }
    }
    cur_row++;
    rows_total++;
}

const uint8_t *panel_get(int *w, int *h) { if (w) *w = PW; if (h) *h = PH; return grey; }

void panel_dump(const char *path) {
    FILE *f = fopen(path, "wb");
    if (!f) return;
    fprintf(f, "P5\n%d %d\n255\n", PW, PH);
    for (int i = 0; i < PW * PH; i++)
        fputc((uint8_t)(255 - grey[i] * 17), f);   // 0->255 white, 15->0 black
    fclose(f);
}
