#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include <iostream>
#include <CImg.h>

using namespace cimg_library;

void read(void *p, int s)
{
        while (s) {
                int r = fread(p, sizeof(unsigned char), s, stdin);
                p += r;
                s -= r;
        }
}

int catch_ffs()
{
        int i = 0;
        int x;
        unsigned char c;
        unsigned char buffer[4];

        for (x = 0; x < 4; x++)
                buffer[x] = 0;

        while (1) {
                read(&c, 1);

                buffer[i % 4] = c;

                i++;

                if (buffer[0] == 0xff
                        && buffer[1] == 0xff
                        && buffer[2] == 0xff
                        && buffer[3] == 0xff) {
                        return i;
                }
        }

        return -1;
}

int main(int argc, char **argv) {
        char buffer[900];
        CImg<unsigned char> image(120, 120, 1, 1);

        CImgDisplay display(image, "omview");

        fprintf(stderr, "waiting for initial synchronization... ");
        fflush(stderr);
        catch_ffs();
        fprintf(stderr, "done\n");

        while (!display.is_closed()) {
                read(buffer, 900);

                assert(catch_ffs() == 4);

                cimg_forXY(image, x, y) { image(x, y) = buffer[(y >> 2) * 30 + (x >> 2)] * 4; }

                image.display(display);

                fprintf(stderr, "new frame\n");
        }

        return 0;
}