]> git.tdb.fi Git - ext/subsurface.git/blob - parse-xml.c
Make the import source an enumeration
[ext/subsurface.git] / parse-xml.c
1 #include <stdio.h>
2 #include <ctype.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <errno.h>
6 #include <time.h>
7 #include <libxml/parser.h>
8 #include <libxml/tree.h>
9
10 #include "dive.h"
11
12 int verbose;
13
14 struct dive_table dive_table;
15
16 /*
17  * Add a dive into the dive_table array
18  */
19 static void record_dive(struct dive *dive)
20 {
21         int nr = dive_table.nr, allocated = dive_table.allocated;
22         struct dive **dives = dive_table.dives;
23
24         if (nr >= allocated) {
25                 allocated = (nr + 32) * 3 / 2;
26                 dives = realloc(dives, allocated * sizeof(struct dive *));
27                 if (!dives)
28                         exit(1);
29                 dive_table.dives = dives;
30                 dive_table.allocated = allocated;
31         }
32         dives[nr] = fixup_dive(dive);
33         dive_table.nr = nr+1;
34 }
35
36 static void start_match(const char *type, const char *name, char *buffer)
37 {
38         if (verbose > 2)
39                 printf("Matching %s '%s' (%s)\n",
40                         type, name, buffer);
41 }
42
43 static void nonmatch(const char *type, const char *name, char *buffer)
44 {
45         if (verbose > 1)
46                 printf("Unable to match %s '%s' (%s)\n",
47                         type, name, buffer);
48         free(buffer);
49 }
50
51 typedef void (*matchfn_t)(char *buffer, void *);
52
53 static int match(const char *pattern, int plen,
54                  const char *name, int nlen,
55                  matchfn_t fn, char *buf, void *data)
56 {
57         if (plen > nlen)
58                 return 0;
59         if (memcmp(pattern, name + nlen - plen, plen))
60                 return 0;
61         fn(buf, data);
62         return 1;
63 }
64
65 /*
66  * We keep our internal data in well-specified units, but
67  * the input may come in some random format. This keeps track
68  * of the incoming units.
69  */
70 static struct units {
71         enum { METERS, FEET } length;
72         enum { LITER, CUFT } volume;
73         enum { BAR, PSI } pressure;
74         enum { CELSIUS, FAHRENHEIT } temperature;
75         enum { KG, LBS } weight;
76 } units;
77
78 /* We're going to default to SI units for input */
79 static const struct units SI_units = {
80         .length = METERS,
81         .volume = LITER,
82         .pressure = BAR,
83         .temperature = CELSIUS,
84         .weight = KG
85 };
86
87 /*
88  * Dive info as it is being built up..
89  */
90 static int alloc_samples;
91 static struct dive *dive;
92 static struct sample *sample;
93 static struct tm tm;
94 static int event_index, cylinder_index;
95
96 static enum import_source {
97         UNKNOWN,
98         LIBDIVECOMPUTER,
99         SUUNTO,
100         UEMIS,
101 } import_source;
102
103 static time_t utc_mktime(struct tm *tm)
104 {
105         static const int mdays[] = {
106             0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
107         };
108         int year = tm->tm_year;
109         int month = tm->tm_mon;
110         int day = tm->tm_mday;
111
112         /* First normalize relative to 1900 */
113         if (year < 70)
114                 year += 100;
115         else if (year > 1900)
116                 year -= 1900;
117
118         /* Normalized to Jan 1, 1970: unix time */
119         year -= 70;
120
121         if (year < 0 || year > 129) /* algo only works for 1970-2099 */
122                 return -1;
123         if (month < 0 || month > 11) /* array bounds */
124                 return -1;
125         if (month < 2 || (year + 2) % 4)
126                 day--;
127         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0)
128                 return -1;
129         return (year * 365 + (year + 1) / 4 + mdays[month] + day) * 24*60*60UL +
130                 tm->tm_hour * 60*60 + tm->tm_min * 60 + tm->tm_sec;
131 }
132
133 static void divedate(char *buffer, void *_when)
134 {
135         int d,m,y;
136         time_t *when = _when;
137         int success = 0;
138
139         success = tm.tm_sec | tm.tm_min | tm.tm_hour;
140         if (sscanf(buffer, "%d.%d.%d", &d, &m, &y) == 3) {
141                 tm.tm_year = y;
142                 tm.tm_mon = m-1;
143                 tm.tm_mday = d;
144         } else if (sscanf(buffer, "%d-%d-%d", &y, &m, &d) == 3) {
145                 tm.tm_year = y;
146                 tm.tm_mon = m-1;
147                 tm.tm_mday = d;
148         } else {
149                 fprintf(stderr, "Unable to parse date '%s'\n", buffer);
150                 success = 0;
151         }
152
153         if (success)
154                 *when = utc_mktime(&tm);
155
156         free(buffer);
157 }
158
159 static void divetime(char *buffer, void *_when)
160 {
161         int h,m,s = 0;
162         time_t *when = _when;
163
164         if (sscanf(buffer, "%d:%d:%d", &h, &m, &s) >= 2) {
165                 tm.tm_hour = h;
166                 tm.tm_min = m;
167                 tm.tm_sec = s;
168                 if (tm.tm_year)
169                         *when = utc_mktime(&tm);
170         }
171         free(buffer);
172 }
173
174 /* Libdivecomputer: "2011-03-20 10:22:38" */
175 static void divedatetime(char *buffer, void *_when)
176 {
177         int y,m,d;
178         int hr,min,sec;
179         time_t *when = _when;
180
181         if (sscanf(buffer, "%d-%d-%d %d:%d:%d",
182                 &y, &m, &d, &hr, &min, &sec) == 6) {
183                 tm.tm_year = y;
184                 tm.tm_mon = m-1;
185                 tm.tm_mday = d;
186                 tm.tm_hour = hr;
187                 tm.tm_min = min;
188                 tm.tm_sec = sec;
189                 *when = utc_mktime(&tm);
190         }
191         free(buffer);
192 }
193
194 union int_or_float {
195         double fp;
196 };
197
198 enum number_type {
199         NEITHER,
200         FLOAT
201 };
202
203 static enum number_type integer_or_float(char *buffer, union int_or_float *res)
204 {
205         char *end;
206         long val;
207         double fp;
208
209         /* Integer or floating point? */
210         val = strtol(buffer, &end, 10);
211         if (val < 0 || end == buffer)
212                 return NEITHER;
213
214         /* Looks like it might be floating point? */
215         if (*end == '.') {
216                 errno = 0;
217                 fp = strtod(buffer, &end);
218                 if (!errno) {
219                         res->fp = fp;
220                         return FLOAT;
221                 }
222         }
223
224         res->fp = val;
225         return FLOAT;
226 }
227
228 static void pressure(char *buffer, void *_press)
229 {
230         double mbar;
231         pressure_t *pressure = _press;
232         union int_or_float val;
233
234         switch (integer_or_float(buffer, &val)) {
235         case FLOAT:
236                 /* Just ignore zero values */
237                 if (!val.fp)
238                         break;
239                 switch (units.pressure) {
240                 case BAR:
241                         /* Assume mbar, but if it's really small, it's bar */
242                         mbar = val.fp;
243                         if (mbar < 5000)
244                                 mbar = mbar * 1000;
245                         break;
246                 case PSI:
247                         mbar = val.fp * 68.95;
248                         break;
249                 }
250                 if (mbar > 5 && mbar < 500000) {
251                         pressure->mbar = mbar + 0.5;
252                         break;
253                 }
254         /* fallthrough */
255         default:
256                 printf("Strange pressure reading %s\n", buffer);
257         }
258         free(buffer);
259 }
260
261 static void depth(char *buffer, void *_depth)
262 {
263         depth_t *depth = _depth;
264         union int_or_float val;
265
266         switch (integer_or_float(buffer, &val)) {
267         case FLOAT:
268                 switch (units.length) {
269                 case METERS:
270                         depth->mm = val.fp * 1000 + 0.5;
271                         break;
272                 case FEET:
273                         depth->mm = val.fp * 304.8 + 0.5;
274                         break;
275                 }
276                 break;
277         default:
278                 printf("Strange depth reading %s\n", buffer);
279         }
280         free(buffer);
281 }
282
283 static void temperature(char *buffer, void *_temperature)
284 {
285         temperature_t *temperature = _temperature;
286         union int_or_float val;
287
288         switch (integer_or_float(buffer, &val)) {
289         case FLOAT:
290                 /* Ignore zero. It means "none" */
291                 if (!val.fp)
292                         break;
293                 /* Celsius */
294                 switch (units.temperature) {
295                 case CELSIUS:
296                         temperature->mkelvin = (val.fp + 273.15) * 1000 + 0.5;
297                         break;
298                 case FAHRENHEIT:
299                         temperature->mkelvin = (val.fp + 459.67) * 5000/9;
300                         break;
301                 }
302                 break;
303         default:
304                 printf("Strange temperature reading %s\n", buffer);
305         }
306         free(buffer);
307 }
308
309 static void sampletime(char *buffer, void *_time)
310 {
311         int i;
312         int min, sec;
313         duration_t *time = _time;
314
315         i = sscanf(buffer, "%d:%d", &min, &sec);
316         switch (i) {
317         case 1:
318                 sec = min;
319                 min = 0;
320         /* fallthrough */
321         case 2:
322                 time->seconds = sec + min*60;
323                 break;
324         default:
325                 printf("Strange sample time reading %s\n", buffer);
326         }
327         free(buffer);
328 }
329
330 static void duration(char *buffer, void *_time)
331 {
332         sampletime(buffer, _time);
333 }
334
335 static void percent(char *buffer, void *_fraction)
336 {
337         fraction_t *fraction = _fraction;
338         union int_or_float val;
339
340         switch (integer_or_float(buffer, &val)) {
341         case FLOAT:
342                 if (val.fp <= 100.0)
343                         fraction->permille = val.fp * 10 + 0.5;
344                 break;
345
346         default:
347                 printf("Strange percentage reading %s\n", buffer);
348                 break;
349         }
350         free(buffer);
351 }
352
353 static void gasmix(char *buffer, void *_fraction)
354 {
355         /* libdivecomputer does negative percentages. */
356         if (*buffer == '-')
357                 return;
358         if (cylinder_index < MAX_CYLINDERS)
359                 percent(buffer, _fraction);
360 }
361
362 static void gasmix_nitrogen(char *buffer, void *_gasmix)
363 {
364         /* Ignore n2 percentages. There's no value in them. */
365 }
366
367 static void cylindersize(char *buffer, void *_volume)
368 {
369         volume_t *volume = _volume;
370         union int_or_float val;
371
372         switch (integer_or_float(buffer, &val)) {
373         case FLOAT:
374                 volume->mliter = val.fp * 1000 + 0.5;
375                 break;
376
377         default:
378                 printf("Strange volume reading %s\n", buffer);
379                 break;
380         }
381         free(buffer);
382 }
383
384 static void utf8_string(char *buffer, void *_res)
385 {
386         *(char **)_res = buffer;
387 }
388
389 /*
390  * Uemis water_pressure. In centibar. And when converting to
391  * depth, I'm just going to always use saltwater, because I
392  * think "true depth" is just stupid. From a diving standpoint,
393  * "true depth" is pretty much completely pointless, unless
394  * you're doing some kind of underwater surveying work.
395  *
396  * So I give water depths in "pressure depth", always assuming
397  * salt water. So one atmosphere per 10m.
398  */
399 static void water_pressure(char *buffer, void *_depth)
400 {
401         depth_t *depth = _depth;
402         union int_or_float val;
403         double atm, cm;
404
405         switch (integer_or_float(buffer, &val)) {
406         case FLOAT:
407                 if (!val.fp)
408                         break;
409                 /* cbar to atm */
410                 atm = (val.fp / 100) / 1.01325;
411                 /*
412                  * atm to cm. Why not mm? The precision just isn't
413                  * there.
414                  */
415                 cm = 100 * (atm - 1) + 0.5;
416                 if (cm > 0) {
417                         depth->mm = 10 * (long)cm;
418                         break;
419                 }
420         default:
421                 fprintf(stderr, "Strange water pressure '%s'\n", buffer);
422         }
423         free(buffer);
424 }
425
426 #define MATCH(pattern, fn, dest) \
427         match(pattern, strlen(pattern), name, len, fn, buf, dest)
428
429 static void get_index(char *buffer, void *_i)
430 {
431         int *i = _i;
432         *i = atoi(buffer);
433         free(buffer);
434 }
435
436 static void centibar(char *buffer, void *_pressure)
437 {
438         pressure_t *pressure = _pressure;
439         union int_or_float val;
440
441         switch (integer_or_float(buffer, &val)) {
442         case FLOAT:
443                 pressure->mbar = val.fp * 10 + 0.5;
444                 break;
445         default:
446                 fprintf(stderr, "Strange centibar pressure '%s'\n", buffer);
447         }
448         free(buffer);
449 }
450
451 static void decicelsius(char *buffer, void *_temp)
452 {
453         temperature_t *temp = _temp;
454         union int_or_float val;
455
456         switch (integer_or_float(buffer, &val)) {
457         case FLOAT:
458                 temp->mkelvin = (val.fp/10 + 273.15) * 1000 + 0.5;
459                 break;
460         default:
461                 fprintf(stderr, "Strange julian date: %s", buffer);
462         }
463         free(buffer);
464 }
465
466 static int uemis_fill_sample(struct sample *sample, const char *name, int len, char *buf)
467 {
468         return  MATCH(".reading.dive_time", sampletime, &sample->time) ||
469                 MATCH(".reading.water_pressure", water_pressure, &sample->depth) ||
470                 MATCH(".reading.active_tank", get_index, &sample->cylinderindex) ||
471                 MATCH(".reading.tank_pressure", centibar, &sample->cylinderpressure) ||
472                 MATCH(".reading.dive_temperature", decicelsius, &sample->temperature) ||
473                 0;
474 }
475
476 /* We're in samples - try to convert the random xml value to something useful */
477 static void try_to_fill_sample(struct sample *sample, const char *name, char *buf)
478 {
479         int len = strlen(name);
480
481         start_match("sample", name, buf);
482         if (MATCH(".sample.pressure", pressure, &sample->cylinderpressure))
483                 return;
484         if (MATCH(".sample.cylpress", pressure, &sample->cylinderpressure))
485                 return;
486         if (MATCH(".sample.depth", depth, &sample->depth))
487                 return;
488         if (MATCH(".sample.temp", temperature, &sample->temperature))
489                 return;
490         if (MATCH(".sample.temperature", temperature, &sample->temperature))
491                 return;
492         if (MATCH(".sample.sampletime", sampletime, &sample->time))
493                 return;
494         if (MATCH(".sample.time", sampletime, &sample->time))
495                 return;
496
497         switch (import_source) {
498         case UEMIS:
499                 if (uemis_fill_sample(sample, name, len, buf))
500                         return;
501                 break;
502
503         default:
504                 break;
505         }
506
507         nonmatch("sample", name, buf);
508 }
509
510 /*
511  * Crazy suunto xml. Look at how those o2/he things match up.
512  */
513 static int suunto_dive_match(struct dive *dive, const char *name, int len, char *buf)
514 {
515         return  MATCH(".o2pct", percent, &dive->cylinder[0].gasmix.o2) ||
516                 MATCH(".hepct_0", percent, &dive->cylinder[0].gasmix.he) ||
517                 MATCH(".o2pct_2", percent, &dive->cylinder[1].gasmix.o2) ||
518                 MATCH(".hepct_1", percent, &dive->cylinder[1].gasmix.he) ||
519                 MATCH(".o2pct_3", percent, &dive->cylinder[2].gasmix.o2) ||
520                 MATCH(".hepct_2", percent, &dive->cylinder[2].gasmix.he) ||
521                 MATCH(".o2pct_4", percent, &dive->cylinder[3].gasmix.o2) ||
522                 MATCH(".hepct_3", percent, &dive->cylinder[3].gasmix.he) ||
523                 MATCH(".cylindersize", cylindersize, &dive->cylinder[0].type.size) ||
524                 MATCH(".cylinderworkpressure", pressure, &dive->cylinder[0].type.workingpressure) ||
525                 0;
526 }
527
528 static int buffer_value(char *buffer)
529 {
530         int val = atoi(buffer);
531         free(buffer);
532         return val;
533 }
534
535 static void uemis_length_unit(char *buffer, void *_unused)
536 {
537         units.length = buffer_value(buffer) ? FEET : METERS;
538 }
539
540 static void uemis_volume_unit(char *buffer, void *_unused)
541 {
542         units.volume = buffer_value(buffer) ? CUFT : LITER;
543 }
544
545 static void uemis_pressure_unit(char *buffer, void *_unused)
546 {
547 #if 0
548         units.pressure = buffer_value(buffer) ? PSI : BAR;
549 #endif
550 }
551
552 static void uemis_temperature_unit(char *buffer, void *_unused)
553 {
554         units.temperature = buffer_value(buffer) ? FAHRENHEIT : CELSIUS;
555 }
556
557 static void uemis_weight_unit(char *buffer, void *_unused)
558 {
559         units.weight = buffer_value(buffer) ? LBS : KG;
560 }
561
562 static void uemis_time_unit(char *buffer, void *_unused)
563 {
564 }
565
566 static void uemis_date_unit(char *buffer, void *_unused)
567 {
568 }
569
570 /* Modified julian day, yay! */
571 static void uemis_date_time(char *buffer, void *_when)
572 {
573         time_t *when = _when;
574         union int_or_float val;
575
576         switch (integer_or_float(buffer, &val)) {
577         case FLOAT:
578                 *when = (val.fp - 40587.5) * 86400;
579                 break;
580         default:
581                 fprintf(stderr, "Strange julian date: %s", buffer);
582         }
583         free(buffer);
584 }
585
586 /*
587  * Uemis doesn't know time zones. You need to do them as
588  * minutes, not hours.
589  *
590  * But that's ok, we don't track timezones yet either. We
591  * just turn everything into "localtime expressed as UTC".
592  */
593 static void uemis_time_zone(char *buffer, void *_when)
594 {
595         time_t *when = _when;
596         signed char tz = atoi(buffer);
597
598         *when += tz * 3600;
599 }
600
601 /* 0 - air ; 1 - nitrox1 ; 2 - nitrox2 ; 3 = nitrox3 */
602 static int uemis_gas_template;
603
604 /*
605  * Christ. Uemis tank data is a total mess.
606  *
607  * We're passed a "virtual cylinder" (0 - 6) for the different
608  * Uemis tank cases ("air", "nitrox_1", "nitrox_2.{bottom,deco}"
609  * and "nitrox_3.{bottom,deco,travel}". We need to turn that
610  * into the actual cylinder data depending on the gas template,
611  * and ignore the ones that are irrelevant for that template.
612  *
613  * So for "template 2" (nitrox_2), we ignore virtual tanks 0-1
614  * (which are "air" and "nitrox_1" respectively), and tanks 4-6
615  * (which are the three "nitrox_3" tanks), and we turn virtual
616  * tanks 2/3 into actual tanks 0/1.
617  *
618  * Confused yet?
619  */
620 static int uemis_cylinder_index(void *_cylinder)
621 {
622         cylinder_t *cylinder = _cylinder;
623         unsigned int index = cylinder - dive->cylinder;
624
625         if (index > 6) {
626                 fprintf(stderr, "Uemis cylinder pointer calculations broken\n");
627                 return -1;
628         }
629         switch(uemis_gas_template) {
630         case 1: /* Dive uses tank 1 */
631                 index -= 1;
632         /* Fallthrough */
633         case 0: /* Dive uses tank 0 */
634                 if (index)
635                         index = -1;
636                 break;
637         case 2: /* Dive uses tanks 2-3 */
638                 index -= 2;
639                 if (index > 1)
640                         index = -1;
641                 break;
642         case 3: /* Dive uses tanks 4-6 */
643                 index -= 4;
644                 if (index > 2)
645                         index = -1;
646                 break;
647         }
648         return index;
649 }
650
651 static void uemis_cylindersize(char *buffer, void *_cylinder)
652 {
653         int index = uemis_cylinder_index(_cylinder);
654         if (index >= 0)
655                 cylindersize(buffer, &dive->cylinder[index].type.size);
656 }
657
658 static void uemis_percent(char *buffer, void *_cylinder)
659 {
660         int index = uemis_cylinder_index(_cylinder);
661         if (index >= 0)
662                 percent(buffer, &dive->cylinder[index].gasmix.o2);
663 }
664
665 static int uemis_dive_match(struct dive *dive, const char *name, int len, char *buf)
666 {
667         return  MATCH(".units.length", uemis_length_unit, &units) ||
668                 MATCH(".units.volume", uemis_volume_unit, &units) ||
669                 MATCH(".units.pressure", uemis_pressure_unit, &units) ||
670                 MATCH(".units.temperature", uemis_temperature_unit, &units) ||
671                 MATCH(".units.weight", uemis_weight_unit, &units) ||
672                 MATCH(".units.time", uemis_time_unit, &units) ||
673                 MATCH(".units.date", uemis_date_unit, &units) ||
674                 MATCH(".date_time", uemis_date_time, &dive->when) ||
675                 MATCH(".time_zone", uemis_time_zone, &dive->when) ||
676                 MATCH(".ambient.temperature", decicelsius, &dive->airtemp) ||
677                 MATCH(".gas.template", get_index, &uemis_gas_template) ||
678                 MATCH(".air.bottom_tank.size", uemis_cylindersize, dive->cylinder + 0) ||
679                 MATCH(".air.bottom_tank.oxygen", uemis_percent, dive->cylinder + 0) ||
680                 MATCH(".nitrox_1.bottom_tank.size", uemis_cylindersize, dive->cylinder + 1) ||
681                 MATCH(".nitrox_1.bottom_tank.oxygen", uemis_percent, dive->cylinder + 1) ||
682                 MATCH(".nitrox_2.bottom_tank.size", uemis_cylindersize, dive->cylinder + 2) ||
683                 MATCH(".nitrox_2.bottom_tank.oxygen", uemis_percent, dive->cylinder + 2) ||
684                 MATCH(".nitrox_2.deco_tank.size", uemis_cylindersize, dive->cylinder + 3) ||
685                 MATCH(".nitrox_2.deco_tank.oxygen", uemis_percent, dive->cylinder + 3) ||
686                 MATCH(".nitrox_3.bottom_tank.size", uemis_cylindersize, dive->cylinder + 4) ||
687                 MATCH(".nitrox_3.bottom_tank.oxygen", uemis_percent, dive->cylinder + 4) ||
688                 MATCH(".nitrox_3.deco_tank.size", uemis_cylindersize, dive->cylinder + 5) ||
689                 MATCH(".nitrox_3.deco_tank.oxygen", uemis_percent, dive->cylinder + 5) ||
690                 MATCH(".nitrox_3.travel_tank.size", uemis_cylindersize, dive->cylinder + 6) ||
691                 MATCH(".nitrox_3.travel_tank.oxygen", uemis_percent, dive->cylinder + 6) ||
692                 0;
693 }
694
695 /* We're in the top-level dive xml. Try to convert whatever value to a dive value */
696 static void try_to_fill_dive(struct dive *dive, const char *name, char *buf)
697 {
698         int len = strlen(name);
699
700         start_match("dive", name, buf);
701         if (MATCH(".date", divedate, &dive->when))
702                 return;
703         if (MATCH(".time", divetime, &dive->when))
704                 return;
705         if (MATCH(".datetime", divedatetime, &dive->when))
706                 return;
707         if (MATCH(".maxdepth", depth, &dive->maxdepth))
708                 return;
709         if (MATCH(".meandepth", depth, &dive->meandepth))
710                 return;
711         if (MATCH(".depth.max", depth, &dive->maxdepth))
712                 return;
713         if (MATCH(".depth.mean", depth, &dive->meandepth))
714                 return;
715         if (MATCH(".duration", duration, &dive->duration))
716                 return;
717         if (MATCH(".divetime", duration, &dive->duration))
718                 return;
719         if (MATCH(".divetimesec", duration, &dive->duration))
720                 return;
721         if (MATCH(".surfacetime", duration, &dive->surfacetime))
722                 return;
723         if (MATCH(".airtemp", temperature, &dive->airtemp))
724                 return;
725         if (MATCH(".watertemp", temperature, &dive->watertemp))
726                 return;
727         if (MATCH(".temperature.air", temperature, &dive->airtemp))
728                 return;
729         if (MATCH(".temperature.water", temperature, &dive->watertemp))
730                 return;
731         if (MATCH(".cylinderstartpressure", pressure, &dive->cylinder[0].start))
732                 return;
733         if (MATCH(".cylinderendpressure", pressure, &dive->cylinder[0].end))
734                 return;
735         if (MATCH(".location", utf8_string, &dive->location))
736                 return;
737         if (MATCH(".notes", utf8_string, &dive->notes))
738                 return;
739
740         if (MATCH(".cylinder.size", cylindersize, &dive->cylinder[cylinder_index].type.size))
741                 return;
742         if (MATCH(".cylinder.workpressure", pressure, &dive->cylinder[cylinder_index].type.workingpressure))
743                 return;
744         if (MATCH(".cylinder.description", utf8_string, &dive->cylinder[cylinder_index].type.description))
745                 return;
746         if (MATCH(".cylinder.start", pressure, &dive->cylinder[cylinder_index].start))
747                 return;
748         if (MATCH(".cylinder.end", pressure, &dive->cylinder[cylinder_index].end))
749                 return;
750
751         if (MATCH(".o2", gasmix, &dive->cylinder[cylinder_index].gasmix.o2))
752                 return;
753         if (MATCH(".n2", gasmix_nitrogen, &dive->cylinder[cylinder_index].gasmix))
754                 return;
755         if (MATCH(".he", gasmix, &dive->cylinder[cylinder_index].gasmix.he))
756                 return;
757
758         switch (import_source) {
759         case SUUNTO:
760                 if (suunto_dive_match(dive, name, len, buf))
761                         return;
762                 break;
763
764         case UEMIS:
765                 if (uemis_dive_match(dive, name, len, buf))
766                         return;
767                 break;
768
769         default:
770                 break;
771         }
772         nonmatch("dive", name, buf);
773 }
774
775 /*
776  * File boundaries are dive boundaries. But sometimes there are
777  * multiple dives per file, so there can be other events too that
778  * trigger a "new dive" marker and you may get some nesting due
779  * to that. Just ignore nesting levels.
780  */
781 static void dive_start(void)
782 {
783         unsigned int size;
784
785         if (dive)
786                 return;
787
788         alloc_samples = 5;
789         size = dive_size(alloc_samples);
790         dive = malloc(size);
791         if (!dive)
792                 exit(1);
793         memset(dive, 0, size);
794         memset(&tm, 0, sizeof(tm));
795 }
796
797 static void sanitize_gasmix(gasmix_t *mix)
798 {
799         unsigned int o2, he;
800
801         o2 = mix->o2.permille;
802         he = mix->he.permille;
803
804         /* Regular air: leave empty */
805         if (!he) {
806                 if (!o2)
807                         return;
808                 /* 20.9% or 21% O2 is just air */
809                 if (o2 >= 209 && o2 <= 210) {
810                         mix->o2.permille = 0;
811                         return;
812                 }
813         }
814
815         /* Sane mix? */
816         if (o2 <= 1000 && he <= 1000 && o2+he <= 1000)
817                 return;
818         fprintf(stderr, "Odd gasmix: %d O2 %d He\n", o2, he);
819         memset(mix, 0, sizeof(*mix));
820 }
821
822 /*
823  * See if the size/workingpressure looks like some standard cylinder
824  * size, eg "AL80".
825  */
826 static void match_standard_cylinder(cylinder_type_t *type)
827 {
828         int psi, cuft, len;
829         const char *fmt;
830         char buffer[20], *p;
831
832         /* Do we already have a cylinder description? */
833         if (type->description)
834                 return;
835
836         cuft = type->size.mliter / 1000;
837         psi = type->workingpressure.mbar / 68.95;
838
839         switch (psi) {
840         case 2300 ... 2500:     /* 2400 psi: LP tank */
841                 fmt = "LP%d";
842                 break;
843         case 2600 ... 2700:     /* 2640 psi: LP+10% */
844                 fmt = "LP%d+";
845                 break;
846         case 2900 ... 3100:     /* 3000 psi: ALx tank */
847                 fmt = "AL%d";
848                 break;
849         case 3400 ... 3500:     /* 3442 psi: HP tank */
850                 fmt = "HP%d";
851                 break;
852         case 3700 ... 3850:     /* HP+10% */
853                 fmt = "HP%d+";
854                 break;
855         default:
856                 return;
857         }
858         len = snprintf(buffer, sizeof(buffer), fmt, cuft);
859         p = malloc(len+1);
860         if (!p)
861                 return;
862         memcpy(p, buffer, len+1);
863         type->description = p;
864 }
865
866
867 /*
868  * There are two ways to give cylinder size information:
869  *  - total amount of gas in cuft (depends on working pressure and physical size)
870  *  - physical size
871  *
872  * where "physical size" is the one that actually matters and is sane.
873  *
874  * We internally use physical size only. But we save the workingpressure
875  * so that we can do the conversion if required.
876  */
877 static void sanitize_cylinder_type(cylinder_type_t *type)
878 {
879         double volume_of_air, atm, volume;
880
881         /* If we have no working pressure, it had *better* be just a physical size! */
882         if (!type->workingpressure.mbar)
883                 return;
884
885         /* No size either? Nothing to go on */
886         if (!type->size.mliter)
887                 return;
888
889         /* Ok, we have both size and pressure: try to match a description */
890         match_standard_cylinder(type);
891
892         /* .. and let's assume that the 'size' was cu ft of air */
893         volume_of_air = type->size.mliter * 28.317;     /* milli-cu ft to milliliter */
894         atm = type->workingpressure.mbar / 1013.25;     /* working pressure in atm */
895         volume = volume_of_air / atm;                   /* milliliters at 1 atm: "true size" */
896         type->size.mliter = volume + 0.5;
897 }
898
899 static void sanitize_cylinder_info(struct dive *dive)
900 {
901         int i;
902
903         for (i = 0; i < MAX_CYLINDERS; i++) {
904                 sanitize_gasmix(&dive->cylinder[i].gasmix);
905                 sanitize_cylinder_type(&dive->cylinder[i].type);
906         }
907 }
908
909 static void dive_end(void)
910 {
911         if (!dive)
912                 return;
913         sanitize_cylinder_info(dive);
914         record_dive(dive);
915         dive = NULL;
916         cylinder_index = 0;
917 }
918
919 static void suunto_start(void)
920 {
921         import_source = SUUNTO;
922         units = SI_units;
923 }
924
925 static void suunto_end(void)
926 {
927 }
928
929 static void uemis_start(void)
930 {
931         import_source = UEMIS;
932         units = SI_units;
933 }
934
935 static void uemis_end(void)
936 {
937 }
938
939 static void event_start(void)
940 {
941 }
942
943 static void event_end(void)
944 {
945         event_index++;
946 }
947
948 static void cylinder_start(void)
949 {
950 }
951
952 static void cylinder_end(void)
953 {
954         cylinder_index++;
955 }
956
957 static void sample_start(void)
958 {
959         int nr;
960
961         if (!dive)
962                 return;
963         nr = dive->samples;
964         if (nr >= alloc_samples) {
965                 unsigned int size;
966
967                 alloc_samples = (alloc_samples * 3)/2 + 10;
968                 size = dive_size(alloc_samples);
969                 dive = realloc(dive, size);
970                 if (!dive)
971                         return;
972         }
973         sample = dive->sample + nr;
974         memset(sample, 0, sizeof(*sample));
975         event_index = 0;
976 }
977
978 static void sample_end(void)
979 {
980         if (!dive)
981                 return;
982
983         sample = NULL;
984         dive->samples++;
985 }
986
987 static void entry(const char *name, int size, const char *raw)
988 {
989         char *buf = malloc(size+1);
990
991         if (!buf)
992                 return;
993         memcpy(buf, raw, size);
994         buf[size] = 0;
995         if (sample) {
996                 try_to_fill_sample(sample, name, buf);
997                 return;
998         }
999         if (dive) {
1000                 try_to_fill_dive(dive, name, buf);
1001                 return;
1002         }
1003 }
1004
1005 static const char *nodename(xmlNode *node, char *buf, int len)
1006 {
1007         if (!node || !node->name)
1008                 return "root";
1009
1010         buf += len;
1011         *--buf = 0;
1012         len--;
1013
1014         for(;;) {
1015                 const char *name = node->name;
1016                 int i = strlen(name);
1017                 while (--i >= 0) {
1018                         unsigned char c = name[i];
1019                         *--buf = tolower(c);
1020                         if (!--len)
1021                                 return buf;
1022                 }
1023                 node = node->parent;
1024                 if (!node || !node->name)
1025                         return buf;
1026                 *--buf = '.';
1027                 if (!--len)
1028                         return buf;
1029         }
1030 }
1031
1032 #define MAXNAME 64
1033
1034 static void visit_one_node(xmlNode *node)
1035 {
1036         int len;
1037         const unsigned char *content;
1038         char buffer[MAXNAME];
1039         const char *name;
1040
1041         content = node->content;
1042         if (!content)
1043                 return;
1044
1045         /* Trim whitespace at beginning */
1046         while (isspace(*content))
1047                 content++;
1048
1049         /* Trim whitespace at end */
1050         len = strlen(content);
1051         while (len && isspace(content[len-1]))
1052                 len--;
1053
1054         if (!len)
1055                 return;
1056
1057         /* Don't print out the node name if it is "text" */
1058         if (!strcmp(node->name, "text"))
1059                 node = node->parent;
1060
1061         name = nodename(node, buffer, sizeof(buffer));
1062
1063         entry(name, len, content);
1064 }
1065
1066 static void traverse(xmlNode *root);
1067
1068 static void traverse_properties(xmlNode *node)
1069 {
1070         xmlAttr *p;
1071
1072         for (p = node->properties; p; p = p->next)
1073                 traverse(p->children);
1074 }
1075
1076 static void visit(xmlNode *n)
1077 {
1078         visit_one_node(n);
1079         traverse_properties(n);
1080         traverse(n->children);
1081 }
1082
1083 /*
1084  * I'm sure this could be done as some fancy DTD rules.
1085  * It's just not worth the headache.
1086  */
1087 static struct nesting {
1088         const char *name;
1089         void (*start)(void), (*end)(void);
1090 } nesting[] = {
1091         { "dive", dive_start, dive_end },
1092         { "SUUNTO", suunto_start, suunto_end },
1093         { "sample", sample_start, sample_end },
1094         { "SAMPLE", sample_start, sample_end },
1095         { "reading", sample_start, sample_end },
1096         { "event", event_start, event_end },
1097         { "gasmix", cylinder_start, cylinder_end },
1098         { "cylinder", cylinder_start, cylinder_end },
1099         { "pre_dive", uemis_start, uemis_end },
1100         { NULL, }
1101 };
1102
1103 static void traverse(xmlNode *root)
1104 {
1105         xmlNode *n;
1106
1107         for (n = root; n; n = n->next) {
1108                 struct nesting *rule = nesting;
1109
1110                 do {
1111                         if (!strcmp(rule->name, n->name))
1112                                 break;
1113                         rule++;
1114                 } while (rule->name);
1115
1116                 if (rule->start)
1117                         rule->start();
1118                 visit(n);
1119                 if (rule->end)
1120                         rule->end();
1121         }
1122 }
1123
1124 /* Per-file reset */
1125 static void reset_all(void)
1126 {
1127         /*
1128          * We reset the units for each file. You'd think it was
1129          * a per-dive property, but I'm not going to trust people
1130          * to do per-dive setup. If the xml does have per-dive
1131          * data within one file, we might have to reset it per
1132          * dive for that format.
1133          */
1134         units = SI_units;
1135         import_source = UNKNOWN;
1136 }
1137
1138 void parse_xml_file(const char *filename)
1139 {
1140         xmlDoc *doc;
1141
1142         doc = xmlReadFile(filename, NULL, 0);
1143         if (!doc) {
1144                 fprintf(stderr, "Failed to parse '%s'.\n", filename);
1145                 return;
1146         }
1147
1148         reset_all();
1149         dive_start();
1150         traverse(xmlDocGetRootElement(doc));
1151         dive_end();
1152         xmlFreeDoc(doc);
1153         xmlCleanupParser();
1154 }
1155
1156 void parse_xml_init(void)
1157 {
1158         LIBXML_TEST_VERSION
1159 }