]> git.tdb.fi Git - ext/subsurface.git/blob - parse-xml.c
Remove suunto parsing hacks from parse-xml.c
[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 <unistd.h>
7 #define __USE_XOPEN
8 #include <time.h>
9 #include <libxml/parser.h>
10 #include <libxml/tree.h>
11 #ifdef XSLT
12 #include <libxslt/transform.h>
13 #endif
14
15 #include "dive.h"
16 #include "uemis.h"
17
18 int verbose;
19
20 struct dive_table dive_table;
21
22 /*
23  * Add a dive into the dive_table array
24  */
25 void record_dive(struct dive *dive)
26 {
27         int nr = dive_table.nr, allocated = dive_table.allocated;
28         struct dive **dives = dive_table.dives;
29
30         if (nr >= allocated) {
31                 allocated = (nr + 32) * 3 / 2;
32                 dives = realloc(dives, allocated * sizeof(struct dive *));
33                 if (!dives)
34                         exit(1);
35                 dive_table.dives = dives;
36                 dive_table.allocated = allocated;
37         }
38         dives[nr] = fixup_dive(dive);
39         dive_table.nr = nr+1;
40 }
41
42 static void start_match(const char *type, const char *name, char *buffer)
43 {
44         if (verbose > 2)
45                 printf("Matching %s '%s' (%s)\n",
46                         type, name, buffer);
47 }
48
49 static void nonmatch(const char *type, const char *name, char *buffer)
50 {
51         if (verbose > 1)
52                 printf("Unable to match %s '%s' (%s)\n",
53                         type, name, buffer);
54         free(buffer);
55 }
56
57 typedef void (*matchfn_t)(char *buffer, void *);
58
59 static int match(const char *pattern, int plen,
60                  const char *name, int nlen,
61                  matchfn_t fn, char *buf, void *data)
62 {
63         if (plen > nlen)
64                 return 0;
65         if (memcmp(pattern, name + nlen - plen, plen))
66                 return 0;
67         fn(buf, data);
68         return 1;
69 }
70
71
72 struct units input_units;
73
74 /*
75  * We're going to default to SI units for input. Yes,
76  * technically the SI unit for pressure is Pascal, but
77  * we default to bar (10^5 pascal), which people
78  * actually use. Similarly, C instead of Kelvin.
79  */
80 const struct units SI_units = {
81         .length = METERS,
82         .volume = LITER,
83         .pressure = BAR,
84         .temperature = CELSIUS,
85         .weight = KG
86 };
87
88 const struct units IMPERIAL_units = {
89         .length = FEET,
90         .volume = CUFT,
91         .pressure = PSI,
92         .temperature = FAHRENHEIT,
93         .weight = LBS
94 };
95
96 /*
97  * Dive info as it is being built up..
98  */
99 static struct dive *dive;
100 static struct sample *sample;
101 static struct {
102         int active;
103         duration_t time;
104         int type, flags, value;
105         const char *name;
106 } event;
107 static struct tm tm;
108 static int cylinder_index;
109
110 static enum import_source {
111         UNKNOWN,
112         LIBDIVECOMPUTER,
113         UEMIS,
114         DIVINGLOG,
115         UDDF,
116 } import_source;
117
118 time_t utc_mktime(struct tm *tm)
119 {
120         static const int mdays[] = {
121             0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
122         };
123         int year = tm->tm_year;
124         int month = tm->tm_mon;
125         int day = tm->tm_mday;
126
127         /* First normalize relative to 1900 */
128         if (year < 70)
129                 year += 100;
130         else if (year > 1900)
131                 year -= 1900;
132
133         /* Normalized to Jan 1, 1970: unix time */
134         year -= 70;
135
136         if (year < 0 || year > 129) /* algo only works for 1970-2099 */
137                 return -1;
138         if (month < 0 || month > 11) /* array bounds */
139                 return -1;
140         if (month < 2 || (year + 2) % 4)
141                 day--;
142         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0)
143                 return -1;
144         return (year * 365 + (year + 1) / 4 + mdays[month] + day) * 24*60*60UL +
145                 tm->tm_hour * 60*60 + tm->tm_min * 60 + tm->tm_sec;
146 }
147
148 static void divedate(char *buffer, void *_when)
149 {
150         int d,m,y;
151         time_t *when = _when;
152         int success = 0;
153
154         success = tm.tm_sec | tm.tm_min | tm.tm_hour;
155         if (sscanf(buffer, "%d.%d.%d", &d, &m, &y) == 3) {
156                 tm.tm_year = y;
157                 tm.tm_mon = m-1;
158                 tm.tm_mday = d;
159         } else if (sscanf(buffer, "%d-%d-%d", &y, &m, &d) == 3) {
160                 tm.tm_year = y;
161                 tm.tm_mon = m-1;
162                 tm.tm_mday = d;
163         } else {
164                 fprintf(stderr, "Unable to parse date '%s'\n", buffer);
165                 success = 0;
166         }
167
168         if (success)
169                 *when = utc_mktime(&tm);
170
171         free(buffer);
172 }
173
174 static void divetime(char *buffer, void *_when)
175 {
176         int h,m,s = 0;
177         time_t *when = _when;
178
179         if (sscanf(buffer, "%d:%d:%d", &h, &m, &s) >= 2) {
180                 tm.tm_hour = h;
181                 tm.tm_min = m;
182                 tm.tm_sec = s;
183                 if (tm.tm_year)
184                         *when = utc_mktime(&tm);
185         }
186         free(buffer);
187 }
188
189 /* Libdivecomputer: "2011-03-20 10:22:38" */
190 static void divedatetime(char *buffer, void *_when)
191 {
192         int y,m,d;
193         int hr,min,sec;
194         time_t *when = _when;
195
196         if (sscanf(buffer, "%d-%d-%d %d:%d:%d",
197                 &y, &m, &d, &hr, &min, &sec) == 6) {
198                 tm.tm_year = y;
199                 tm.tm_mon = m-1;
200                 tm.tm_mday = d;
201                 tm.tm_hour = hr;
202                 tm.tm_min = min;
203                 tm.tm_sec = sec;
204                 *when = utc_mktime(&tm);
205         }
206         free(buffer);
207 }
208
209 union int_or_float {
210         double fp;
211 };
212
213 enum number_type {
214         NEITHER,
215         FLOAT
216 };
217
218 static enum number_type integer_or_float(char *buffer, union int_or_float *res)
219 {
220         char *end;
221         long val;
222         double fp;
223
224         /* Integer or floating point? */
225         val = strtol(buffer, &end, 10);
226         if (val < 0 || end == buffer)
227                 return NEITHER;
228
229         /* Looks like it might be floating point? */
230         if (*end == '.') {
231                 errno = 0;
232                 fp = strtod(buffer, &end);
233                 if (!errno) {
234                         res->fp = fp;
235                         return FLOAT;
236                 }
237         }
238
239         res->fp = val;
240         return FLOAT;
241 }
242
243 static void pressure(char *buffer, void *_press)
244 {
245         double mbar;
246         pressure_t *pressure = _press;
247         union int_or_float val;
248
249         switch (integer_or_float(buffer, &val)) {
250         case FLOAT:
251                 /* Just ignore zero values */
252                 if (!val.fp)
253                         break;
254                 switch (input_units.pressure) {
255                 case PASCAL:
256                         mbar = val.fp / 100;
257                         break;
258                 case BAR:
259                         /* Assume mbar, but if it's really small, it's bar */
260                         mbar = val.fp;
261                         if (mbar < 5000)
262                                 mbar = mbar * 1000;
263                         break;
264                 case PSI:
265                         mbar = val.fp * 68.95;
266                         break;
267                 }
268                 if (mbar > 5 && mbar < 500000) {
269                         pressure->mbar = mbar + 0.5;
270                         break;
271                 }
272         /* fallthrough */
273         default:
274                 printf("Strange pressure reading %s\n", buffer);
275         }
276         free(buffer);
277 }
278
279 static void depth(char *buffer, void *_depth)
280 {
281         depth_t *depth = _depth;
282         union int_or_float val;
283
284         switch (integer_or_float(buffer, &val)) {
285         case FLOAT:
286                 switch (input_units.length) {
287                 case METERS:
288                         depth->mm = val.fp * 1000 + 0.5;
289                         break;
290                 case FEET:
291                         depth->mm = val.fp * 304.8 + 0.5;
292                         break;
293                 }
294                 break;
295         default:
296                 printf("Strange depth reading %s\n", buffer);
297         }
298         free(buffer);
299 }
300
301 static void temperature(char *buffer, void *_temperature)
302 {
303         temperature_t *temperature = _temperature;
304         union int_or_float val;
305
306         switch (integer_or_float(buffer, &val)) {
307         case FLOAT:
308                 /* Ignore zero. It means "none" */
309                 if (!val.fp)
310                         break;
311                 /* Celsius */
312                 switch (input_units.temperature) {
313                 case KELVIN:
314                         temperature->mkelvin = val.fp * 1000;
315                         break;
316                 case CELSIUS:
317                         temperature->mkelvin = (val.fp + 273.15) * 1000 + 0.5;
318                         break;
319                 case FAHRENHEIT:
320                         temperature->mkelvin = (val.fp + 459.67) * 5000/9;
321                         break;
322                 }
323                 break;
324         default:
325                 printf("Strange temperature reading %s\n", buffer);
326         }
327         free(buffer);
328 }
329
330 static void sampletime(char *buffer, void *_time)
331 {
332         int i;
333         int min, sec;
334         duration_t *time = _time;
335
336         i = sscanf(buffer, "%d:%d", &min, &sec);
337         switch (i) {
338         case 1:
339                 sec = min;
340                 min = 0;
341         /* fallthrough */
342         case 2:
343                 time->seconds = sec + min*60;
344                 break;
345         default:
346                 printf("Strange sample time reading %s\n", buffer);
347         }
348         free(buffer);
349 }
350
351 static void duration(char *buffer, void *_time)
352 {
353         sampletime(buffer, _time);
354 }
355
356 static void percent(char *buffer, void *_fraction)
357 {
358         fraction_t *fraction = _fraction;
359         union int_or_float val;
360
361         switch (integer_or_float(buffer, &val)) {
362         case FLOAT:
363                 if (val.fp <= 100.0)
364                         fraction->permille = val.fp * 10 + 0.5;
365                 break;
366
367         default:
368                 printf("Strange percentage reading %s\n", buffer);
369                 break;
370         }
371         free(buffer);
372 }
373
374 static void gasmix(char *buffer, void *_fraction)
375 {
376         /* libdivecomputer does negative percentages. */
377         if (*buffer == '-')
378                 return;
379         if (cylinder_index < MAX_CYLINDERS)
380                 percent(buffer, _fraction);
381 }
382
383 static void gasmix_nitrogen(char *buffer, void *_gasmix)
384 {
385         /* Ignore n2 percentages. There's no value in them. */
386 }
387
388 static void cylindersize(char *buffer, void *_volume)
389 {
390         volume_t *volume = _volume;
391         union int_or_float val;
392
393         switch (integer_or_float(buffer, &val)) {
394         case FLOAT:
395                 volume->mliter = val.fp * 1000 + 0.5;
396                 break;
397
398         default:
399                 printf("Strange volume reading %s\n", buffer);
400                 break;
401         }
402         free(buffer);
403 }
404
405 static void utf8_string(char *buffer, void *_res)
406 {
407         *(char **)_res = buffer;
408 }
409
410 /*
411  * Uemis water_pressure. In centibar. And when converting to
412  * depth, I'm just going to always use saltwater, because I
413  * think "true depth" is just stupid. From a diving standpoint,
414  * "true depth" is pretty much completely pointless, unless
415  * you're doing some kind of underwater surveying work.
416  *
417  * So I give water depths in "pressure depth", always assuming
418  * salt water. So one atmosphere per 10m.
419  */
420 static void water_pressure(char *buffer, void *_depth)
421 {
422         depth_t *depth = _depth;
423         union int_or_float val;
424         double atm, cm;
425
426         switch (integer_or_float(buffer, &val)) {
427         case FLOAT:
428                 if (!val.fp)
429                         break;
430                 /* cbar to atm */
431                 atm = bar_to_atm(val.fp * 10);
432                 /*
433                  * atm to cm. Why not mm? The precision just isn't
434                  * there.
435                  */
436                 cm = 100 * atm + 0.5;
437                 if (cm > 0) {
438                         depth->mm = 10 * (long)cm;
439                         break;
440                 }
441         default:
442                 fprintf(stderr, "Strange water pressure '%s'\n", buffer);
443         }
444         free(buffer);
445 }
446
447 #define MATCH(pattern, fn, dest) \
448         match(pattern, strlen(pattern), name, len, fn, buf, dest)
449
450 static void get_index(char *buffer, void *_i)
451 {
452         int *i = _i;
453         *i = atoi(buffer);
454         free(buffer);
455 }
456
457 static void centibar(char *buffer, void *_pressure)
458 {
459         pressure_t *pressure = _pressure;
460         union int_or_float val;
461
462         switch (integer_or_float(buffer, &val)) {
463         case FLOAT:
464                 pressure->mbar = val.fp * 10 + 0.5;
465                 break;
466         default:
467                 fprintf(stderr, "Strange centibar pressure '%s'\n", buffer);
468         }
469         free(buffer);
470 }
471
472 static void decicelsius(char *buffer, void *_temp)
473 {
474         temperature_t *temp = _temp;
475         union int_or_float val;
476
477         switch (integer_or_float(buffer, &val)) {
478         case FLOAT:
479                 temp->mkelvin = (val.fp/10 + 273.15) * 1000 + 0.5;
480                 break;
481         default:
482                 fprintf(stderr, "Strange julian date: %s", buffer);
483         }
484         free(buffer);
485 }
486
487 static int uemis_fill_sample(struct sample *sample, const char *name, int len, char *buf)
488 {
489         return  MATCH(".reading.dive_time", sampletime, &sample->time) ||
490                 MATCH(".reading.water_pressure", water_pressure, &sample->depth) ||
491                 MATCH(".reading.active_tank", get_index, &sample->cylinderindex) ||
492                 MATCH(".reading.tank_pressure", centibar, &sample->cylinderpressure) ||
493                 MATCH(".reading.dive_temperature", decicelsius, &sample->temperature) ||
494                 0;
495 }
496
497 /*
498  * Divinglog is crazy. The temperatures are in celsius. EXCEPT
499  * for the sample temperatures, that are in Fahrenheit.
500  * WTF?
501  *
502  * Oh, and I think Diving Log *internally* probably kept them
503  * in celsius, because I'm seeing entries like
504  *
505  *      <Temp>32.0</Temp>
506  *
507  * in there. Which is freezing, aka 0 degC. I bet the "0" is
508  * what Diving Log uses for "no temperature".
509  *
510  * So throw away crap like that.
511  */
512 static void fahrenheit(char *buffer, void *_temperature)
513 {
514         temperature_t *temperature = _temperature;
515         union int_or_float val;
516
517         switch (integer_or_float(buffer, &val)) {
518         case FLOAT:
519                 /* Floating point equality is evil, but works for small integers */
520                 if (val.fp == 32.0)
521                         break;
522                 temperature->mkelvin = (val.fp + 459.67) * 5000/9;
523                 break;
524         default:
525                 fprintf(stderr, "Crazy Diving Log temperature reading %s\n", buffer);
526         }
527         free(buffer);
528 }
529
530 /*
531  * Did I mention how bat-shit crazy divinglog is? The sample
532  * pressures are in PSI. But the tank working pressure is in
533  * bar. WTF^2?
534  *
535  * Crazy stuff like this is why subsurface has everything in
536  * these inconvenient typed structures, and you have to say
537  * "pressure->mbar" to get the actual value. Exactly so that
538  * you can never have unit confusion.
539  */
540 static void psi(char *buffer, void *_pressure)
541 {
542         pressure_t *pressure = _pressure;
543         union int_or_float val;
544
545         switch (integer_or_float(buffer, &val)) {
546         case FLOAT:
547                 pressure->mbar = val.fp * 68.95 + 0.5;
548                 break;
549         default:
550                 fprintf(stderr, "Crazy Diving Log PSI reading %s\n", buffer);
551         }
552         free(buffer);
553 }
554
555 static int divinglog_fill_sample(struct sample *sample, const char *name, int len, char *buf)
556 {
557         return  MATCH(".p.time", sampletime, &sample->time) ||
558                 MATCH(".p.depth", depth, &sample->depth) ||
559                 MATCH(".p.temp", fahrenheit, &sample->temperature) ||
560                 MATCH(".p.press1", psi, &sample->cylinderpressure) ||
561                 0;
562 }
563
564 static int uddf_fill_sample(struct sample *sample, const char *name, int len, char *buf)
565 {
566         return  MATCH(".divetime", sampletime, &sample->time) ||
567                 MATCH(".depth", depth, &sample->depth) ||
568                 MATCH(".temperature", temperature, &sample->temperature) ||
569                 0;
570 }
571
572 static void eventtime(char *buffer, void *_duration)
573 {
574         duration_t *duration = _duration;
575         sampletime(buffer, duration);
576         if (sample)
577                 duration->seconds += sample->time.seconds;
578 }
579
580 static void try_to_fill_event(const char *name, char *buf)
581 {
582         int len = strlen(name);
583
584         start_match("event", name, buf);
585         if (MATCH(".event", utf8_string, &event.name))
586                 return;
587         if (MATCH(".name", utf8_string, &event.name))
588                 return;
589         if (MATCH(".time", eventtime, &event.time))
590                 return;
591         if (MATCH(".type", get_index, &event.type))
592                 return;
593         if (MATCH(".flags", get_index, &event.flags))
594                 return;
595         if (MATCH(".value", get_index, &event.value))
596                 return;
597         nonmatch("event", name, buf);
598 }
599
600 /* We're in samples - try to convert the random xml value to something useful */
601 static void try_to_fill_sample(struct sample *sample, const char *name, char *buf)
602 {
603         int len = strlen(name);
604
605         start_match("sample", name, buf);
606         if (MATCH(".sample.pressure", pressure, &sample->cylinderpressure))
607                 return;
608         if (MATCH(".sample.cylpress", pressure, &sample->cylinderpressure))
609                 return;
610         if (MATCH(".sample.cylinderindex", get_index, &sample->cylinderindex))
611                 return;
612         if (MATCH(".sample.depth", depth, &sample->depth))
613                 return;
614         if (MATCH(".sample.temp", temperature, &sample->temperature))
615                 return;
616         if (MATCH(".sample.temperature", temperature, &sample->temperature))
617                 return;
618         if (MATCH(".sample.sampletime", sampletime, &sample->time))
619                 return;
620         if (MATCH(".sample.time", sampletime, &sample->time))
621                 return;
622
623         switch (import_source) {
624         case UEMIS:
625                 if (uemis_fill_sample(sample, name, len, buf))
626                         return;
627                 break;
628
629         case DIVINGLOG:
630                 if (divinglog_fill_sample(sample, name, len, buf))
631                         return;
632                 break;
633
634         case UDDF:
635                 if (uddf_fill_sample(sample, name, len, buf))
636                         return;
637                 break;
638
639         default:
640                 break;
641         }
642
643         nonmatch("sample", name, buf);
644 }
645
646 static const char *country, *city;
647
648 static void divinglog_place(char *place, void *_location)
649 {
650         char **location = _location;
651         char buffer[256], *p;
652         int len;
653
654         len = snprintf(buffer, sizeof(buffer),
655                 "%s%s%s%s%s",
656                 place,
657                 city ? ", " : "",
658                 city ? city : "",
659                 country ? ", " : "",
660                 country ? country : "");
661
662         p = malloc(len+1);
663         memcpy(p, buffer, len+1);
664         *location = p;
665
666         city = NULL;
667         country = NULL;
668 }
669
670 static int divinglog_dive_match(struct dive **divep, const char *name, int len, char *buf)
671 {
672         struct dive *dive = *divep;
673
674         return  MATCH(".divedate", divedate, &dive->when) ||
675                 MATCH(".entrytime", divetime, &dive->when) ||
676                 MATCH(".depth", depth, &dive->maxdepth) ||
677                 MATCH(".tanksize", cylindersize, &dive->cylinder[0].type.size) ||
678                 MATCH(".presw", pressure, &dive->cylinder[0].type.workingpressure) ||
679                 MATCH(".comments", utf8_string, &dive->notes) ||
680                 MATCH(".buddy.names", utf8_string, &dive->buddy) ||
681                 MATCH(".country.name", utf8_string, &country) ||
682                 MATCH(".city.name", utf8_string, &city) ||
683                 MATCH(".place.name", divinglog_place, &dive->location) ||
684                 0;
685 }
686
687 static int buffer_value(char *buffer)
688 {
689         int val = atoi(buffer);
690         free(buffer);
691         return val;
692 }
693
694 static void uemis_length_unit(char *buffer, void *_unused)
695 {
696         input_units.length = buffer_value(buffer) ? FEET : METERS;
697 }
698
699 static void uemis_volume_unit(char *buffer, void *_unused)
700 {
701         input_units.volume = buffer_value(buffer) ? CUFT : LITER;
702 }
703
704 static void uemis_pressure_unit(char *buffer, void *_unused)
705 {
706 #if 0
707         input_units.pressure = buffer_value(buffer) ? PSI : BAR;
708 #endif
709 }
710
711 static void uemis_temperature_unit(char *buffer, void *_unused)
712 {
713         input_units.temperature = buffer_value(buffer) ? FAHRENHEIT : CELSIUS;
714 }
715
716 static void uemis_weight_unit(char *buffer, void *_unused)
717 {
718         input_units.weight = buffer_value(buffer) ? LBS : KG;
719 }
720
721 static void uemis_time_unit(char *buffer, void *_unused)
722 {
723 }
724
725 static void uemis_date_unit(char *buffer, void *_unused)
726 {
727 }
728
729 /* Modified julian day, yay! */
730 static void uemis_date_time(char *buffer, void *_when)
731 {
732         time_t *when = _when;
733         union int_or_float val;
734
735         switch (integer_or_float(buffer, &val)) {
736         case FLOAT:
737                 *when = (val.fp - 40587) * 86400;
738                 break;
739         default:
740                 fprintf(stderr, "Strange julian date: %s", buffer);
741         }
742         free(buffer);
743 }
744
745 /*
746  * Uemis doesn't know time zones. You need to do them as
747  * minutes, not hours.
748  *
749  * But that's ok, we don't track timezones yet either. We
750  * just turn everything into "localtime expressed as UTC".
751  */
752 static void uemis_time_zone(char *buffer, void *_when)
753 {
754 #if 0 /* seems like this is only used to display it correctly
755        * the stored time appears to be UTC */
756
757         time_t *when = _when;
758         signed char tz = atoi(buffer);
759
760         *when += tz * 3600;
761 #endif
762 }
763
764 static void uemis_ts(char *buffer, void *_when)
765 {
766         struct tm tm;
767         time_t *when = _when;
768
769         memset(&tm, 0, sizeof(tm));
770         sscanf(buffer,"%d-%d-%dT%d:%d:%d",
771                 &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
772                 &tm.tm_hour, &tm.tm_min, &tm.tm_sec);
773         tm.tm_mon  -= 1;
774         tm.tm_year -= 1900;
775         *when = utc_mktime(&tm);
776
777 }
778
779 static void uemis_duration(char *buffer, void *_duration)
780 {
781         duration_t *duration = _duration;
782         duration->seconds = atof(buffer) * 60 + 0.5;
783 }
784
785 /* 0 - air ; 1 - nitrox1 ; 2 - nitrox2 ; 3 = nitrox3 */
786 static int uemis_gas_template;
787
788 /*
789  * Christ. Uemis tank data is a total mess.
790  *
791  * We're passed a "virtual cylinder" (0 - 6) for the different
792  * Uemis tank cases ("air", "nitrox_1", "nitrox_2.{bottom,deco}"
793  * and "nitrox_3.{bottom,deco,travel}". We need to turn that
794  * into the actual cylinder data depending on the gas template,
795  * and ignore the ones that are irrelevant for that template.
796  *
797  * So for "template 2" (nitrox_2), we ignore virtual tanks 0-1
798  * (which are "air" and "nitrox_1" respectively), and tanks 4-6
799  * (which are the three "nitrox_3" tanks), and we turn virtual
800  * tanks 2/3 into actual tanks 0/1.
801  *
802  * Confused yet?
803  */
804 static int uemis_cylinder_index(void *_cylinder)
805 {
806         cylinder_t *cylinder = _cylinder;
807         unsigned int index = cylinder - dive->cylinder;
808
809         if (index > 6) {
810                 fprintf(stderr, "Uemis cylinder pointer calculations broken\n");
811                 return -1;
812         }
813         switch(uemis_gas_template) {
814         case 1: /* Dive uses tank 1 */
815                 index -= 1;
816         /* Fallthrough */
817         case 0: /* Dive uses tank 0 */
818                 if (index)
819                         index = -1;
820                 break;
821         case 2: /* Dive uses tanks 2-3 */
822                 index -= 2;
823                 if (index > 1)
824                         index = -1;
825                 break;
826         case 3: /* Dive uses tanks 4-6 */
827                 index -= 4;
828                 if (index > 2)
829                         index = -1;
830                 break;
831         }
832         return index;
833 }
834
835 static void uemis_cylindersize(char *buffer, void *_cylinder)
836 {
837         int index = uemis_cylinder_index(_cylinder);
838         if (index >= 0)
839                 cylindersize(buffer, &dive->cylinder[index].type.size);
840 }
841
842 static void uemis_percent(char *buffer, void *_cylinder)
843 {
844         int index = uemis_cylinder_index(_cylinder);
845         if (index >= 0)
846                 percent(buffer, &dive->cylinder[index].gasmix.o2);
847 }
848
849 static int uemis_dive_match(struct dive **divep, const char *name, int len, char *buf)
850 {
851         struct dive *dive = *divep;
852
853         return  MATCH(".units.length", uemis_length_unit, &input_units) ||
854                 MATCH(".units.volume", uemis_volume_unit, &input_units) ||
855                 MATCH(".units.pressure", uemis_pressure_unit, &input_units) ||
856                 MATCH(".units.temperature", uemis_temperature_unit, &input_units) ||
857                 MATCH(".units.weight", uemis_weight_unit, &input_units) ||
858                 MATCH(".units.time", uemis_time_unit, &input_units) ||
859                 MATCH(".units.date", uemis_date_unit, &input_units) ||
860                 MATCH(".date_time", uemis_date_time, &dive->when) ||
861                 MATCH(".time_zone", uemis_time_zone, &dive->when) ||
862                 MATCH(".ambient.temperature", decicelsius, &dive->airtemp) ||
863                 MATCH(".gas.template", get_index, &uemis_gas_template) ||
864                 MATCH(".air.bottom_tank.size", uemis_cylindersize, dive->cylinder + 0) ||
865                 MATCH(".air.bottom_tank.oxygen", uemis_percent, dive->cylinder + 0) ||
866                 MATCH(".nitrox_1.bottom_tank.size", uemis_cylindersize, dive->cylinder + 1) ||
867                 MATCH(".nitrox_1.bottom_tank.oxygen", uemis_percent, dive->cylinder + 1) ||
868                 MATCH(".nitrox_2.bottom_tank.size", uemis_cylindersize, dive->cylinder + 2) ||
869                 MATCH(".nitrox_2.bottom_tank.oxygen", uemis_percent, dive->cylinder + 2) ||
870                 MATCH(".nitrox_2.deco_tank.size", uemis_cylindersize, dive->cylinder + 3) ||
871                 MATCH(".nitrox_2.deco_tank.oxygen", uemis_percent, dive->cylinder + 3) ||
872                 MATCH(".nitrox_3.bottom_tank.size", uemis_cylindersize, dive->cylinder + 4) ||
873                 MATCH(".nitrox_3.bottom_tank.oxygen", uemis_percent, dive->cylinder + 4) ||
874                 MATCH(".nitrox_3.deco_tank.size", uemis_cylindersize, dive->cylinder + 5) ||
875                 MATCH(".nitrox_3.deco_tank.oxygen", uemis_percent, dive->cylinder + 5) ||
876                 MATCH(".nitrox_3.travel_tank.size", uemis_cylindersize, dive->cylinder + 6) ||
877                 MATCH(".nitrox_3.travel_tank.oxygen", uemis_percent, dive->cylinder + 6) ||
878                 MATCH(".dive.val.float", uemis_duration, &dive->duration) ||
879                 MATCH(".dive.val.ts", uemis_ts, &dive->when) ||
880                 MATCH(".dive.val.bin", uemis_parse_divelog_binary, divep) ||
881                 0;
882 }
883
884 /*
885  * Uddf specifies ISO 8601 time format.
886  *
887  * There are many variations on that. This handles the useful cases.
888  */
889 static void uddf_datetime(char *buffer, void *_when)
890 {
891         char c;
892         int y,m,d,hh,mm,ss;
893         time_t *when = _when;
894         struct tm tm = { 0 };
895         int i;
896
897         i = sscanf(buffer, "%d-%d-%d%c%d:%d:%d", &y, &m, &d, &c, &hh, &mm, &ss);
898         if (i == 7)
899                 goto success;
900         ss = 0;
901         if (i == 6)
902                 goto success;
903
904         i = sscanf(buffer, "%04d%02d%02d%c%02d%02d%02d", &y, &m, &d, &c, &hh, &mm, &ss);
905         if (i == 7)
906                 goto success;
907         ss = 0;
908         if (i == 6)
909                 goto success;
910 bad_date:
911         printf("Bad date time %s\n", buffer);
912         free(buffer);
913         return;
914
915 success:
916         if (c != 'T' && c != ' ')
917                 goto bad_date;
918         tm.tm_year = y;
919         tm.tm_mon = m - 1;
920         tm.tm_mday = d;
921         tm.tm_hour = hh;
922         tm.tm_min = mm;
923         tm.tm_sec = ss;
924         *when = utc_mktime(&tm);
925         free(buffer);
926 }
927
928 static int uddf_dive_match(struct dive **divep, const char *name, int len, char *buf)
929 {
930         struct dive *dive = *divep;
931
932         return  MATCH(".datetime", uddf_datetime, &dive->when) ||
933                 MATCH(".diveduration", duration, &dive->duration) ||
934                 MATCH(".greatestdepth", depth, &dive->maxdepth) ||
935                 0;
936 }
937
938 static void gps_location(char *buffer, void *_dive)
939 {
940         int i;
941         struct dive *dive = _dive;
942         double latitude, longitude;
943
944         i = sscanf(buffer, "%lf %lf", &latitude, &longitude);
945         if (i == 2) {
946                 dive->latitude = latitude;
947                 dive->longitude = longitude;
948         }
949         free(buffer);
950 }
951
952 /* We're in the top-level dive xml. Try to convert whatever value to a dive value */
953 static void try_to_fill_dive(struct dive **divep, const char *name, char *buf)
954 {
955         int len = strlen(name);
956
957         start_match("dive", name, buf);
958
959         switch (import_source) {
960         case UEMIS:
961                 if (uemis_dive_match(divep, name, len, buf))
962                         return;
963                 break;
964
965         case DIVINGLOG:
966                 if (divinglog_dive_match(divep, name, len, buf))
967                         return;
968                 break;
969
970         case UDDF:
971                 if (uddf_dive_match(divep, name, len, buf))
972                         return;
973                 break;
974
975         default:
976                 break;
977         }
978
979         struct dive *dive = *divep;
980
981         if (MATCH(".number", get_index, &dive->number))
982                 return;
983         if (MATCH(".date", divedate, &dive->when))
984                 return;
985         if (MATCH(".time", divetime, &dive->when))
986                 return;
987         if (MATCH(".datetime", divedatetime, &dive->when))
988                 return;
989         if (MATCH(".maxdepth", depth, &dive->maxdepth))
990                 return;
991         if (MATCH(".meandepth", depth, &dive->meandepth))
992                 return;
993         if (MATCH(".depth.max", depth, &dive->maxdepth))
994                 return;
995         if (MATCH(".depth.mean", depth, &dive->meandepth))
996                 return;
997         if (MATCH(".duration", duration, &dive->duration))
998                 return;
999         if (MATCH(".divetime", duration, &dive->duration))
1000                 return;
1001         if (MATCH(".divetimesec", duration, &dive->duration))
1002                 return;
1003         if (MATCH(".surfacetime", duration, &dive->surfacetime))
1004                 return;
1005         if (MATCH(".airtemp", temperature, &dive->airtemp))
1006                 return;
1007         if (MATCH(".watertemp", temperature, &dive->watertemp))
1008                 return;
1009         if (MATCH(".temperature.air", temperature, &dive->airtemp))
1010                 return;
1011         if (MATCH(".temperature.water", temperature, &dive->watertemp))
1012                 return;
1013         if (MATCH(".cylinderstartpressure", pressure, &dive->cylinder[0].start))
1014                 return;
1015         if (MATCH(".cylinderendpressure", pressure, &dive->cylinder[0].end))
1016                 return;
1017         if (MATCH(".gps", gps_location, dive))
1018                 return;
1019         if (MATCH(".location", utf8_string, &dive->location))
1020                 return;
1021         if (MATCH(".notes", utf8_string, &dive->notes))
1022                 return;
1023         if (MATCH(".divemaster", utf8_string, &dive->divemaster))
1024                 return;
1025         if (MATCH(".buddy", utf8_string, &dive->buddy))
1026                 return;
1027
1028         if (MATCH(".cylinder.size", cylindersize, &dive->cylinder[cylinder_index].type.size))
1029                 return;
1030         if (MATCH(".cylinder.workpressure", pressure, &dive->cylinder[cylinder_index].type.workingpressure))
1031                 return;
1032         if (MATCH(".cylinder.description", utf8_string, &dive->cylinder[cylinder_index].type.description))
1033                 return;
1034         if (MATCH(".cylinder.start", pressure, &dive->cylinder[cylinder_index].start))
1035                 return;
1036         if (MATCH(".cylinder.end", pressure, &dive->cylinder[cylinder_index].end))
1037                 return;
1038
1039         if (MATCH(".o2", gasmix, &dive->cylinder[cylinder_index].gasmix.o2))
1040                 return;
1041         if (MATCH(".n2", gasmix_nitrogen, &dive->cylinder[cylinder_index].gasmix))
1042                 return;
1043         if (MATCH(".he", gasmix, &dive->cylinder[cylinder_index].gasmix.he))
1044                 return;
1045
1046         nonmatch("dive", name, buf);
1047 }
1048
1049 /*
1050  * File boundaries are dive boundaries. But sometimes there are
1051  * multiple dives per file, so there can be other events too that
1052  * trigger a "new dive" marker and you may get some nesting due
1053  * to that. Just ignore nesting levels.
1054  */
1055 static void dive_start(void)
1056 {
1057         if (dive)
1058                 return;
1059         dive = alloc_dive();
1060         memset(&tm, 0, sizeof(tm));
1061 }
1062
1063 static void sanitize_gasmix(struct gasmix *mix)
1064 {
1065         unsigned int o2, he;
1066
1067         o2 = mix->o2.permille;
1068         he = mix->he.permille;
1069
1070         /* Regular air: leave empty */
1071         if (!he) {
1072                 if (!o2)
1073                         return;
1074                 /* 20.9% or 21% O2 is just air */
1075                 if (o2 >= 209 && o2 <= 210) {
1076                         mix->o2.permille = 0;
1077                         return;
1078                 }
1079         }
1080
1081         /* Sane mix? */
1082         if (o2 <= 1000 && he <= 1000 && o2+he <= 1000)
1083                 return;
1084         fprintf(stderr, "Odd gasmix: %d O2 %d He\n", o2, he);
1085         memset(mix, 0, sizeof(*mix));
1086 }
1087
1088 /*
1089  * See if the size/workingpressure looks like some standard cylinder
1090  * size, eg "AL80".
1091  */
1092 static void match_standard_cylinder(cylinder_type_t *type)
1093 {
1094         double cuft;
1095         int psi, len;
1096         const char *fmt;
1097         char buffer[20], *p;
1098
1099         /* Do we already have a cylinder description? */
1100         if (type->description)
1101                 return;
1102
1103         cuft = ml_to_cuft(type->size.mliter);
1104         cuft *= to_ATM(type->workingpressure);
1105         psi = to_PSI(type->workingpressure);
1106
1107         switch (psi) {
1108         case 2300 ... 2500:     /* 2400 psi: LP tank */
1109                 fmt = "LP%d";
1110                 break;
1111         case 2600 ... 2700:     /* 2640 psi: LP+10% */
1112                 fmt = "LP%d";
1113                 break;
1114         case 2900 ... 3100:     /* 3000 psi: ALx tank */
1115                 fmt = "AL%d";
1116                 break;
1117         case 3400 ... 3500:     /* 3442 psi: HP tank */
1118                 fmt = "HP%d";
1119                 break;
1120         case 3700 ... 3850:     /* HP+10% */
1121                 fmt = "HP%d+";
1122                 break;
1123         default:
1124                 return;
1125         }
1126         len = snprintf(buffer, sizeof(buffer), fmt, (int) (cuft+0.5));
1127         p = malloc(len+1);
1128         if (!p)
1129                 return;
1130         memcpy(p, buffer, len+1);
1131         type->description = p;
1132 }
1133
1134
1135 /*
1136  * There are two ways to give cylinder size information:
1137  *  - total amount of gas in cuft (depends on working pressure and physical size)
1138  *  - physical size
1139  *
1140  * where "physical size" is the one that actually matters and is sane.
1141  *
1142  * We internally use physical size only. But we save the workingpressure
1143  * so that we can do the conversion if required.
1144  */
1145 static void sanitize_cylinder_type(cylinder_type_t *type)
1146 {
1147         double volume_of_air, atm, volume;
1148
1149         /* If we have no working pressure, it had *better* be just a physical size! */
1150         if (!type->workingpressure.mbar)
1151                 return;
1152
1153         /* No size either? Nothing to go on */
1154         if (!type->size.mliter)
1155                 return;
1156
1157         if (input_units.volume == CUFT) {
1158                 /* confusing - we don't really start from ml but millicuft !*/
1159                 volume_of_air = cuft_to_l(type->size.mliter);
1160                 atm = to_ATM(type->workingpressure);            /* working pressure in atm */
1161                 volume = volume_of_air / atm;                   /* milliliters at 1 atm: "true size" */
1162                 type->size.mliter = volume + 0.5;
1163         }
1164
1165         /* Ok, we have both size and pressure: try to match a description */
1166         match_standard_cylinder(type);
1167 }
1168
1169 static void sanitize_cylinder_info(struct dive *dive)
1170 {
1171         int i;
1172
1173         for (i = 0; i < MAX_CYLINDERS; i++) {
1174                 sanitize_gasmix(&dive->cylinder[i].gasmix);
1175                 sanitize_cylinder_type(&dive->cylinder[i].type);
1176         }
1177 }
1178
1179 static void dive_end(void)
1180 {
1181         if (!dive)
1182                 return;
1183         sanitize_cylinder_info(dive);
1184         record_dive(dive);
1185         dive = NULL;
1186         cylinder_index = 0;
1187 }
1188
1189 static void event_start(void)
1190 {
1191         memset(&event, 0, sizeof(event));
1192         event.active = 1;
1193 }
1194
1195 static void event_end(void)
1196 {
1197         if (event.name && strcmp(event.name, "surface") != 0)
1198                 add_event(dive, event.time.seconds, event.type, event.flags, event.value, event.name);
1199         event.active = 0;
1200 }
1201
1202 static void cylinder_start(void)
1203 {
1204 }
1205
1206 static void cylinder_end(void)
1207 {
1208         cylinder_index++;
1209 }
1210
1211 static void sample_start(void)
1212 {
1213         sample = prepare_sample(&dive);
1214 }
1215
1216 static void sample_end(void)
1217 {
1218         if (!dive)
1219                 return;
1220
1221         finish_sample(dive, sample);
1222         sample = NULL;
1223 }
1224
1225 static void entry(const char *name, int size, const char *raw)
1226 {
1227         char *buf = malloc(size+1);
1228
1229         if (!buf)
1230                 return;
1231         memcpy(buf, raw, size);
1232         buf[size] = 0;
1233         if (event.active) {
1234                 try_to_fill_event(name, buf);
1235                 return;
1236         }
1237         if (sample) {
1238                 try_to_fill_sample(sample, name, buf);
1239                 return;
1240         }
1241         if (dive) {
1242                 try_to_fill_dive(&dive, name, buf);
1243                 return;
1244         }
1245 }
1246
1247 static const char *nodename(xmlNode *node, char *buf, int len)
1248 {
1249         if (!node || !node->name)
1250                 return "root";
1251
1252         buf += len;
1253         *--buf = 0;
1254         len--;
1255
1256         for(;;) {
1257                 const char *name = node->name;
1258                 int i = strlen(name);
1259                 while (--i >= 0) {
1260                         unsigned char c = name[i];
1261                         *--buf = tolower(c);
1262                         if (!--len)
1263                                 return buf;
1264                 }
1265                 node = node->parent;
1266                 if (!node || !node->name)
1267                         return buf;
1268                 *--buf = '.';
1269                 if (!--len)
1270                         return buf;
1271         }
1272 }
1273
1274 #define MAXNAME 64
1275
1276 static void visit_one_node(xmlNode *node)
1277 {
1278         int len;
1279         const unsigned char *content;
1280         char buffer[MAXNAME];
1281         const char *name;
1282
1283         content = node->content;
1284         if (!content)
1285                 return;
1286
1287         /* Trim whitespace at beginning */
1288         while (isspace(*content))
1289                 content++;
1290
1291         /* Trim whitespace at end */
1292         len = strlen(content);
1293         while (len && isspace(content[len-1]))
1294                 len--;
1295
1296         if (!len)
1297                 return;
1298
1299         /* Don't print out the node name if it is "text" */
1300         if (!strcmp(node->name, "text"))
1301                 node = node->parent;
1302
1303         name = nodename(node, buffer, sizeof(buffer));
1304
1305         entry(name, len, content);
1306 }
1307
1308 static void traverse(xmlNode *root);
1309
1310 static void traverse_properties(xmlNode *node)
1311 {
1312         xmlAttr *p;
1313
1314         for (p = node->properties; p; p = p->next)
1315                 traverse(p->children);
1316 }
1317
1318 static void visit(xmlNode *n)
1319 {
1320         visit_one_node(n);
1321         traverse_properties(n);
1322         traverse(n->children);
1323 }
1324
1325 static void uemis_importer(void)
1326 {
1327         import_source = UEMIS;
1328         input_units = SI_units;
1329 }
1330
1331 static void DivingLog_importer(void)
1332 {
1333         import_source = DIVINGLOG;
1334
1335         /*
1336          * Diving Log units are really strange.
1337          *
1338          * Temperatures are in C, except in samples,
1339          * when they are in Fahrenheit. Depths are in
1340          * meters, an dpressure is in PSI in the samples,
1341          * but in bar when it comes to working pressure.
1342          *
1343          * Crazy f*%^ morons.
1344          */
1345         input_units = SI_units;
1346 }
1347
1348 static void uddf_importer(void)
1349 {
1350         import_source = UDDF;
1351         input_units = SI_units;
1352         input_units.pressure = PASCAL;
1353         input_units.temperature = KELVIN;
1354 }
1355
1356 /*
1357  * I'm sure this could be done as some fancy DTD rules.
1358  * It's just not worth the headache.
1359  */
1360 static struct nesting {
1361         const char *name;
1362         void (*start)(void), (*end)(void);
1363 } nesting[] = {
1364         { "dive", dive_start, dive_end },
1365         { "Dive", dive_start, dive_end },
1366         { "sample", sample_start, sample_end },
1367         { "waypoint", sample_start, sample_end },
1368         { "SAMPLE", sample_start, sample_end },
1369         { "reading", sample_start, sample_end },
1370         { "event", event_start, event_end },
1371         { "gasmix", cylinder_start, cylinder_end },
1372         { "cylinder", cylinder_start, cylinder_end },
1373         { "P", sample_start, sample_end },
1374
1375         /* Import type recognition */
1376         { "Divinglog", DivingLog_importer },
1377         { "pre_dive", uemis_importer },
1378         { "dives", uemis_importer },
1379         { "uddf", uddf_importer },
1380
1381         { NULL, }
1382 };
1383
1384 static void traverse(xmlNode *root)
1385 {
1386         xmlNode *n;
1387
1388         for (n = root; n; n = n->next) {
1389                 struct nesting *rule = nesting;
1390
1391                 do {
1392                         if (!strcmp(rule->name, n->name))
1393                                 break;
1394                         rule++;
1395                 } while (rule->name);
1396
1397                 if (rule->start)
1398                         rule->start();
1399                 visit(n);
1400                 if (rule->end)
1401                         rule->end();
1402         }
1403 }
1404
1405 /* Per-file reset */
1406 static void reset_all(void)
1407 {
1408         /*
1409          * We reset the units for each file. You'd think it was
1410          * a per-dive property, but I'm not going to trust people
1411          * to do per-dive setup. If the xml does have per-dive
1412          * data within one file, we might have to reset it per
1413          * dive for that format.
1414          */
1415         input_units = SI_units;
1416         import_source = UNKNOWN;
1417 }
1418
1419 void parse_xml_file(const char *filename, GError **error)
1420 {
1421         xmlDoc *doc;
1422
1423         doc = xmlReadFile(filename, NULL, 0);
1424         if (!doc) {
1425                 fprintf(stderr, "Failed to parse '%s'.\n", filename);
1426                 if (error != NULL)
1427                 {
1428                         *error = g_error_new(g_quark_from_string("subsurface"),
1429                                              DIVE_ERROR_PARSE,
1430                                              "Failed to parse '%s'",
1431                                              filename);
1432                 }
1433                 return;
1434         }
1435         /* we assume that the last (or only) filename passed as argument is a 
1436          * great filename to use as default when saving the dives */ 
1437         set_filename(filename);
1438         reset_all();
1439         dive_start();
1440 #ifdef XSLT
1441         doc = test_xslt_transforms(doc);
1442 #endif
1443         traverse(xmlDocGetRootElement(doc));
1444         dive_end();
1445         xmlFreeDoc(doc);
1446         xmlCleanupParser();
1447 }
1448
1449 void parse_xml_init(void)
1450 {
1451         LIBXML_TEST_VERSION
1452 }
1453
1454 #ifdef XSLT
1455
1456 /* Maybe we'll want a environment variable that can override this.. */
1457 static const char *xslt_path = XSLT ":xslt:.";
1458
1459 static xsltStylesheetPtr try_get_stylesheet(const char *path, int len, const char *name)
1460 {
1461         xsltStylesheetPtr ret;
1462         int namelen = strlen(name);
1463         char *filename = malloc(len+1+namelen+1);
1464
1465         if (!filename)
1466                 return NULL;
1467
1468         memcpy(filename, path, len);
1469         filename[len] = G_DIR_SEPARATOR;
1470         memcpy(filename + len + 1, name, namelen+1);
1471
1472         ret = NULL;
1473         if (!access(filename, R_OK))
1474                 ret = xsltParseStylesheetFile(filename);
1475         free(filename);
1476
1477         return ret;
1478 }
1479
1480 static xsltStylesheetPtr get_stylesheet(const char *name)
1481 {
1482         const char *path = xslt_path, *next;
1483
1484         do {
1485                 int len;
1486                 xsltStylesheetPtr ret;
1487
1488                 next = strchr(path, ':');
1489                 len = strlen(path);
1490                 if (next) {
1491                         len = next - path;
1492                         next++;
1493                 }
1494                 ret = try_get_stylesheet(path, len, name);
1495                 if (ret)
1496                         return ret;
1497         } while ((path = next) != NULL);
1498
1499         return NULL;
1500 }
1501
1502 static struct xslt_files {
1503         const char *root;
1504         const char *file;
1505 } xslt_files[] = {
1506         { "SUUNTO", "SuuntoSDM.xslt" },
1507         { "JDiveLog", "jdivelog2subsurface.xslt" },
1508         { NULL, }
1509 };
1510
1511 xmlDoc *test_xslt_transforms(xmlDoc *doc)
1512 {
1513         struct xslt_files *info = xslt_files;
1514         xmlDoc *transformed;
1515         xsltStylesheetPtr xslt = NULL;
1516         xmlNode *root_element = xmlDocGetRootElement(doc);
1517
1518         while ((info->root) && (strcasecmp(root_element->name, info->root) != 0)) {
1519                 info++;
1520         }
1521
1522         if (info->root) {
1523                 xmlSubstituteEntitiesDefault(1);
1524                 xslt = get_stylesheet(info->file);
1525                 if (xslt == NULL)
1526                         return doc;
1527                 transformed = xsltApplyStylesheet(xslt, doc, NULL);
1528                 xmlFreeDoc(doc);
1529                 xsltFreeStylesheet(xslt);
1530                 return transformed;
1531         }
1532         return doc;
1533 }
1534 #endif