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