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