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