#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;
};

int main(int argc, char *argv[]) {
    static struct v3 pos;
    unsigned long event_count = 0;
    
    printf("#ISO 8601 timestamp of accelerometer event;x;y;z\n");
    for (;;) {
        struct input_event e;
        int ret;
        
        ret = fread(&e, sizeof(struct input_event), 1, stdin);
        if (ret != 1) {
            return;
        }
        
        if (e.type == 3) {
            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) {
            struct tm *timeinfo;

            if (event_count++ > 3) {
                timeinfo = gmtime(&e.time.tv_sec);
                printf("%04d-%02d-%02dT%02d:%02d:%02d,%06lu+0000;%d;%d;%d\n",
                       timeinfo->tm_year + 1900,
                       timeinfo->tm_mon + 1,
                       timeinfo->tm_mday,
                       timeinfo->tm_hour,
                       timeinfo->tm_min,
                       timeinfo->tm_sec,
                       e.time.tv_usec,
                       pos.x,
                       pos.y,
                       pos.z);
            }
        } else {
            fprintf(stderr, "unknown type %d\n", e.type);
            exit(1);
        }
    }
    return 0;
}
