#include <stdint.h>

enum { WIDTH = 320, HEIGHT = 240, STRIDE = 512 };
#define VIDEO ((volatile uint32_t *)(uintptr_t)0xff203020u)

static volatile uint16_t *pixels;

static void put(int x, int y, uint16_t rgb)
{
    pixels[y * STRIDE + x] = rgb;
}

static void clear_frame(void)
{
    for (int y = 0; y < HEIGHT; ++y)
        for (int x = 0; x < WIDTH; ++x)
            put(x, y, 0);
}

static void vertical_blank(void)
{
    VIDEO[0] = 1u;
    while ((VIDEO[3] & 1u) != 0u) { }
}

#define INITIAL_ROW 2

static void stripe(int y, uint16_t rgb)
{
    for (int x = 72; x <= 247; ++x) put(x, y, rgb);
}

static int next_row(int y, int *direction)
{
    if (y == 0) *direction = 0; /* TODO: reflect at the upper edge. */
    if (y == HEIGHT - 1) *direction = -1;
    return y + *direction;
}

int main(void)
{
    int y = INITIAL_ROW;
    int direction = INITIAL_ROW < HEIGHT / 2 ? -1 : 1;
    pixels = (volatile uint16_t *)(uintptr_t)VIDEO[0];
    clear_frame();
    for (;;) {
        stripe(y, 0xffe0);
        vertical_blank();
        int following = next_row(y, &direction);
        stripe(y, 0);
        y = following;
    }
}
