#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include "videoInput.h"

videoInput * video;
unsigned char *image, *prevFrame=0;
int *state;

void drawEverything(void);
float currentTime(void);
void checkGLError(char *);
void idle(void);
void key(unsigned char k, int x, int y);


int main(int argc, char *argv[])
    {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
    glutInitWindowSize(640, 480);
    glutCreateWindow("example");
    glutDisplayFunc(drawEverything);
    glutKeyboardFunc(key);
    glutIdleFunc(idle);

    video = new videoInput("/dev/video0");
    image = (unsigned char *)calloc(1, video->width()*video->height()*3);
    state = (int *)calloc(video->width()*video->height(), sizeof(int));

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-0.5, video->width()-0.5, -0.5, video->height()-0.5, -1.0, 1.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glPixelZoom(1.0, -1.0);

    glutMainLoop();
    return 0;
    }


void idle(void)
    {
    unsigned char *frame;
    video->grab();
    frame = video->currentFrame();
    if (prevFrame)
        {
        int i;
        for (i=0; i < video->width()*video->height(); i++)
            {
            if (abs(frame[i*3]-prevFrame[i*3]) > 48)
                state[i] = 31;
            }
        for (i=0; i < video->width()*video->height(); i++)
            if (state[i] == 0)
                {
                image[i*3] = frame[i*3];
                image[i*3+1] = frame[i*3+1];
                image[i*3+2] = frame[i*3+2];
                }
            else
                {
                image[i*3] = state[i]*8;
                image[i*3+1] = 255 - abs(state[i]-15)*15;
                image[i*3+2] = 255 - state[i]*8;
                state[i]--;
                }
        }
    prevFrame = frame;
    glutPostRedisplay();
    }


void drawEverything(void)
    {
    glRasterPos2i(0, video->height()-1);
    glDrawPixels(video->width(), video->height(), GL_BGR, GL_UNSIGNED_BYTE,
                image);

    glutSwapBuffers();
    checkGLError("end-of-frame");
    }


float currentTime(void)
    {
    static struct timeval startTime;
    static int firstCall=1;
    struct timeval t;
    if (firstCall)
        {
        firstCall = 0;
        gettimeofday(&startTime, NULL);
        }
    gettimeofday(&t,NULL);
    return (t.tv_sec-startTime.tv_sec) +
           (t.tv_usec - startTime.tv_usec) / 1000000.0;
    }


void checkGLError(char *prefix)
    {
    GLenum err = glGetError();
    if (err != GL_NO_ERROR)
        printf("%s GL error '%s'\n",prefix,gluErrorString(err));
    }


void key(unsigned char k, int x, int y)
    {
    if (k == 27)
        exit(0);
    }

