// gcc motion-detector.c -o motion-detector -lm -Wall -O2
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include <sys/time.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <math.h>
#include <unistd.h>
#include <stdlib.h>

struct input_event {
    struct timeval time;
    uint16_t type;
    uint16_t code;
    int32_t value;
};

struct v3 {
    int x;
    int y;
    int z;
};

static double vector_diff(struct v3 a, struct v3 b) {
    double dx, dy, dz;
    dx = a.x - b.x;
    dy = a.y - b.y;
    dz = a.z - b.z;
    return (dx*dx + dy*dy + dz*dz);
}

void vector_print(struct v3 a) {
    printf("(%d %d %d)", a.x, a.y, a.z);
}

static void handle_event(struct v3 pos) {
    static unsigned int i = 0;
    static struct v3 lockpos;
    double d;

    if (i <= 256) {
        i++;
        if (i == 256) {
            lockpos = pos;
        }
        return;
    }

    d = vector_diff(lockpos, pos);
    //vector_print(lockpos);
    //vector_print(pos);
    //printf("%f\n", d);
    if (d > 45.0*45.0) {
        printf("%f\n", d);
        exit(0);
    }
}

int main(int argc, char *argv[]) {
    static struct v3 pos;
    struct input_event e;
    FILE *fp;
    char *dev = "/dev/input/event2";
    int ret;

    if (argc == 2) {
        dev = argv[1];
    }
    
    fp = fopen(dev, "r");
    assert(fp);

    for (;;) {
        ret = fread(&e, sizeof(struct input_event), 1, fp);
        assert(ret == 1);
        
        if (e.type == 2) {
            if (e.code == 0) {
                pos.x = e.value;
            } else if (e.code == 1) {
                pos.y = e.value;
            } else if (e.code == 2) {
                pos.z = e.value;
            }
        } else if (e.type == 0 && e.code == 0) {
            handle_event(pos);
        }
    }
    return 0;
}
