deepstone
view src/record.c @ 39:f9b1ff21fd62
merged
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Mon, 10 Mar 2014 17:28:28 +0200 |
parents | |
children |
line source
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <errno.h>
5 #include "record.h"
7 struct event {
8 unsigned long tm;
9 float x, y, z;
10 float theta, phi;
12 struct event *next;
13 };
15 static struct event *head, *tail;
16 static struct event *iter;
17 static int num_events;
19 void rec_reset(void)
20 {
21 while(head) {
22 iter = head;
23 head = head->next;
24 free(iter);
25 }
26 num_events = 0;
27 }
29 int rec_load(const char *fname)
30 {
31 FILE *fp;
32 int i;
34 if(!(fp = fopen(fname, "rb"))) {
35 fprintf(stderr, "failed to open recording: %s: %s\n", fname, strerror(errno));
36 return -1;
37 }
38 fread(&num_events, sizeof num_events, 1, fp);
40 head = tail = 0;
42 for(i=0; i<num_events; i++) {
43 struct event *ev = malloc(sizeof *ev);
44 if(!ev) {
45 perror("failed to allocate event structure");
46 fclose(fp);
47 return -1;
48 }
49 if(fread(ev, sizeof *ev, 1, fp) < 1) {
50 perror("unexpected end of file");
51 fclose(fp);
52 return -1;
53 }
55 if(!head) {
56 head = tail = ev;
57 } else {
58 tail->next = ev;
59 tail = ev;
60 }
61 ev->next = 0;
62 }
63 iter = 0;
65 fclose(fp);
66 return 0;
67 }
69 int rec_save(const char *fname)
70 {
71 FILE *fp;
72 struct event *ev;
74 if(!(fp = fopen(fname, "wb"))) {
75 fprintf(stderr, "failed to open recording: %s: %s\n", fname, strerror(errno));
76 return -1;
77 }
78 fwrite(&num_events, sizeof num_events, 1, fp);
80 ev = head;
81 while(ev) {
82 fwrite(ev, sizeof *ev, 1, fp);
83 ev = ev->next;
84 }
86 fclose(fp);
87 return 0;
88 }
90 void rec_add(unsigned long tm, float x, float y, float z, float theta, float phi)
91 {
92 struct event *ev = malloc(sizeof *ev);
93 if(!ev) {
94 fprintf(stderr, "failed to append rec-event: %s\n", strerror(errno));
95 return;
96 }
97 ev->tm = tm;
98 ev->x = x;
99 ev->y = y;
100 ev->z = z;
101 ev->theta = theta;
102 ev->phi = phi;
104 ev->next = 0;
105 if(head) {
106 tail->next = ev;
107 tail = ev;
108 } else {
109 head = tail = ev;
110 }
112 num_events++;
113 }
115 void rec_get(unsigned long tm, float *x, float *y, float *z, float *theta, float *phi)
116 {
117 if(!iter || iter->tm > tm) {
118 iter = head;
119 }
121 while(iter && iter->next) {
122 if(iter->next->tm > tm) {
123 break;
124 }
125 iter = iter->next;
126 }
128 if(iter) {
129 *x = iter->x;
130 *y = iter->y;
131 *z = iter->z;
132 *theta = iter->theta;
133 *phi = iter->phi;
134 }
135 }