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