]> git.tdb.fi Git - ext/subsurface.git/blob - parse-xml.c
Improve uemis xml parsing a bit
[ext/subsurface.git] / parse-xml.c
1 #include <stdio.h>
2 #include <ctype.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <errno.h>
6 #include <time.h>
7 #include <libxml/parser.h>
8 #include <libxml/tree.h>
9
10 #include "dive.h"
11
12 int verbose;
13
14 struct dive_table dive_table;
15
16 /*
17  * Add a dive into the dive_table array
18  */
19 static void record_dive(struct dive *dive)
20 {
21         int nr = dive_table.nr, allocated = dive_table.allocated;
22         struct dive **dives = dive_table.dives;
23
24         if (nr >= allocated) {
25                 allocated = (nr + 32) * 3 / 2;
26                 dives = realloc(dives, allocated * sizeof(struct dive *));
27                 if (!dives)
28                         exit(1);
29                 dive_table.dives = dives;
30                 dive_table.allocated = allocated;
31         }
32         dives[nr] = dive;
33         dive_table.nr = nr+1;
34 }
35
36 static void start_match(const char *type, const char *name, char *buffer)
37 {
38         if (verbose > 2)
39                 printf("Matching %s '%s' (%s)\n",
40                         type, name, buffer);
41 }
42
43 static void nonmatch(const char *type, const char *name, char *buffer)
44 {
45         if (verbose > 1)
46                 printf("Unable to match %s '%s' (%s)\n",
47                         type, name, buffer);
48         free(buffer);
49 }
50
51 typedef void (*matchfn_t)(char *buffer, void *);
52
53 static int match(const char *pattern, int plen,
54                  const char *name, int nlen,
55                  matchfn_t fn, char *buf, void *data)
56 {
57         if (plen > nlen)
58                 return 0;
59         if (memcmp(pattern, name + nlen - plen, plen))
60                 return 0;
61         fn(buf, data);
62         return 1;
63 }
64
65 /*
66  * We keep our internal data in well-specified units, but
67  * the input may come in some random format. This keeps track
68  * of the incoming units.
69  */
70 static struct units {
71         enum { METERS, FEET } length;
72         enum { LITER, CUFT } volume;
73         enum { BAR, PSI } pressure;
74         enum { CELSIUS, FAHRENHEIT } temperature;
75         enum { KG, LBS } weight;
76 } units;
77
78 /* We're going to default to SI units for input */
79 static const struct units SI_units = {
80         .length = METERS,
81         .volume = LITER,
82         .pressure = BAR,
83         .temperature = CELSIUS,
84         .weight = KG
85 };
86
87 /*
88  * Dive info as it is being built up..
89  */
90 static int alloc_samples;
91 static struct dive *dive;
92 static struct sample *sample;
93 static struct tm tm;
94 static int suunto, uemis;
95 static int event_index, gasmix_index;
96
97 static time_t utc_mktime(struct tm *tm)
98 {
99         static const int mdays[] = {
100             0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
101         };
102         int year = tm->tm_year;
103         int month = tm->tm_mon;
104         int day = tm->tm_mday;
105
106         /* First normalize relative to 1900 */
107         if (year < 70)
108                 year += 100;
109         else if (year > 1900)
110                 year -= 1900;
111
112         /* Normalized to Jan 1, 1970: unix time */
113         year -= 70;
114
115         if (year < 0 || year > 129) /* algo only works for 1970-2099 */
116                 return -1;
117         if (month < 0 || month > 11) /* array bounds */
118                 return -1;
119         if (month < 2 || (year + 2) % 4)
120                 day--;
121         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0)
122                 return -1;
123         return (year * 365 + (year + 1) / 4 + mdays[month] + day) * 24*60*60UL +
124                 tm->tm_hour * 60*60 + tm->tm_min * 60 + tm->tm_sec;
125 }
126
127 static void divedate(char *buffer, void *_when)
128 {
129         int d,m,y;
130         time_t *when = _when;
131         int success = 0;
132
133         success = tm.tm_sec | tm.tm_min | tm.tm_hour;
134         if (sscanf(buffer, "%d.%d.%d", &d, &m, &y) == 3) {
135                 tm.tm_year = y;
136                 tm.tm_mon = m-1;
137                 tm.tm_mday = d;
138         } else if (sscanf(buffer, "%d-%d-%d", &y, &m, &d) == 3) {
139                 tm.tm_year = y;
140                 tm.tm_mon = m-1;
141                 tm.tm_mday = d;
142         } else {
143                 fprintf(stderr, "Unable to parse date '%s'\n", buffer);
144                 success = 0;
145         }
146
147         if (success)
148                 *when = utc_mktime(&tm);
149
150         free(buffer);
151 }
152
153 static void divetime(char *buffer, void *_when)
154 {
155         int h,m,s = 0;
156         time_t *when = _when;
157
158         if (sscanf(buffer, "%d:%d:%d", &h, &m, &s) >= 2) {
159                 tm.tm_hour = h;
160                 tm.tm_min = m;
161                 tm.tm_sec = s;
162                 if (tm.tm_year)
163                         *when = utc_mktime(&tm);
164         }
165         free(buffer);
166 }
167
168 /* Libdivecomputer: "2011-03-20 10:22:38" */
169 static void divedatetime(char *buffer, void *_when)
170 {
171         int y,m,d;
172         int hr,min,sec;
173         time_t *when = _when;
174
175         if (sscanf(buffer, "%d-%d-%d %d:%d:%d",
176                 &y, &m, &d, &hr, &min, &sec) == 6) {
177                 tm.tm_year = y;
178                 tm.tm_mon = m-1;
179                 tm.tm_mday = d;
180                 tm.tm_hour = hr;
181                 tm.tm_min = min;
182                 tm.tm_sec = sec;
183                 *when = utc_mktime(&tm);
184         }
185         free(buffer);
186 }
187
188 union int_or_float {
189         double fp;
190 };
191
192 enum number_type {
193         NEITHER,
194         FLOAT
195 };
196
197 static enum number_type integer_or_float(char *buffer, union int_or_float *res)
198 {
199         char *end;
200         long val;
201         double fp;
202
203         /* Integer or floating point? */
204         val = strtol(buffer, &end, 10);
205         if (val < 0 || end == buffer)
206                 return NEITHER;
207
208         /* Looks like it might be floating point? */
209         if (*end == '.') {
210                 errno = 0;
211                 fp = strtod(buffer, &end);
212                 if (!errno) {
213                         res->fp = fp;
214                         return FLOAT;
215                 }
216         }
217
218         res->fp = val;
219         return FLOAT;
220 }
221
222 static void pressure(char *buffer, void *_press)
223 {
224         double mbar;
225         pressure_t *pressure = _press;
226         union int_or_float val;
227
228         switch (integer_or_float(buffer, &val)) {
229         case FLOAT:
230                 /* Just ignore zero values */
231                 if (!val.fp)
232                         break;
233                 switch (units.pressure) {
234                 case BAR:
235                         /* Assume mbar, but if it's really small, it's bar */
236                         mbar = val.fp;
237                         if (mbar < 5000)
238                                 mbar = mbar * 1000;
239                         break;
240                 case PSI:
241                         mbar = val.fp * 68.95;
242                         break;
243                 }
244                 if (mbar > 5 && mbar < 500000) {
245                         pressure->mbar = mbar + 0.5;
246                         break;
247                 }
248         /* fallthrough */
249         default:
250                 printf("Strange pressure reading %s\n", buffer);
251         }
252         free(buffer);
253 }
254
255 static void depth(char *buffer, void *_depth)
256 {
257         depth_t *depth = _depth;
258         union int_or_float val;
259
260         switch (integer_or_float(buffer, &val)) {
261         case FLOAT:
262                 switch (units.length) {
263                 case METERS:
264                         depth->mm = val.fp * 1000 + 0.5;
265                         break;
266                 case FEET:
267                         depth->mm = val.fp * 304.8 + 0.5;
268                         break;
269                 }
270                 break;
271         default:
272                 printf("Strange depth reading %s\n", buffer);
273         }
274         free(buffer);
275 }
276
277 static void temperature(char *buffer, void *_temperature)
278 {
279         temperature_t *temperature = _temperature;
280         union int_or_float val;
281
282         switch (integer_or_float(buffer, &val)) {
283         case FLOAT:
284                 /* Ignore zero. It means "none" */
285                 if (!val.fp)
286                         break;
287                 /* Celsius */
288                 switch (units.temperature) {
289                 case CELSIUS:
290                         temperature->mkelvin = (val.fp + 273.15) * 1000 + 0.5;
291                         break;
292                 case FAHRENHEIT:
293                         temperature->mkelvin = (val.fp + 459.67) * 5000/9;
294                         break;
295                 }
296                 break;
297         default:
298                 printf("Strange temperature reading %s\n", buffer);
299         }
300         free(buffer);
301 }
302
303 static void sampletime(char *buffer, void *_time)
304 {
305         int i;
306         int min, sec;
307         duration_t *time = _time;
308
309         i = sscanf(buffer, "%d:%d", &min, &sec);
310         switch (i) {
311         case 1:
312                 sec = min;
313                 min = 0;
314         /* fallthrough */
315         case 2:
316                 time->seconds = sec + min*60;
317                 break;
318         default:
319                 printf("Strange sample time reading %s\n", buffer);
320         }
321         free(buffer);
322 }
323
324 static void duration(char *buffer, void *_time)
325 {
326         sampletime(buffer, _time);
327 }
328
329 static void percent(char *buffer, void *_fraction)
330 {
331         fraction_t *fraction = _fraction;
332         union int_or_float val;
333
334         switch (integer_or_float(buffer, &val)) {
335         case FLOAT:
336                 if (val.fp <= 100.0)
337                         fraction->permille = val.fp * 10 + 0.5;
338                 break;
339
340         default:
341                 printf("Strange percentage reading %s\n", buffer);
342                 break;
343         }
344         free(buffer);
345 }
346
347 static void gasmix(char *buffer, void *_fraction)
348 {
349         /* libdivecomputer does negative percentages. */
350         if (*buffer == '-')
351                 return;
352         if (gasmix_index < MAX_MIXES)
353                 percent(buffer, _fraction);
354 }
355
356 static void gasmix_nitrogen(char *buffer, void *_gasmix)
357 {
358         /* Ignore n2 percentages. There's no value in them. */
359 }
360
361 static void utf8_string(char *buffer, void *_res)
362 {
363         *(char **)_res = buffer;
364 }
365
366 /*
367  * Uemis water_pressure. In centibar. And when converting to
368  * depth, I'm just going to always use saltwater, because I
369  * think "true depth" is just stupid. From a diving standpoint,
370  * "true depth" is pretty much completely pointless, unless
371  * you're doing some kind of underwater surveying work.
372  *
373  * So I give water depths in "pressure depth", always assuming
374  * salt water. So one atmosphere per 10m.
375  */
376 static void water_pressure(char *buffer, void *_depth)
377 {
378         depth_t *depth = _depth;
379         union int_or_float val;
380         double atm, cm;
381
382         switch (integer_or_float(buffer, &val)) {
383         case FLOAT:
384                 if (!val.fp)
385                         break;
386                 /* cbar to atm */
387                 atm = (val.fp / 100) / 1.01325;
388                 /*
389                  * atm to cm. Why not mm? The precision just isn't
390                  * there.
391                  */
392                 cm = 100 * (atm - 1) + 0.5;
393                 if (cm > 0) {
394                         depth->mm = 10 * (long)cm;
395                         break;
396                 }
397         default:
398                 fprintf(stderr, "Strange water pressure '%s'\n", buffer);
399         }
400         free(buffer);
401 }
402
403 #define MATCH(pattern, fn, dest) \
404         match(pattern, strlen(pattern), name, len, fn, buf, dest)
405
406 static void get_index(char *buffer, void *_i)
407 {
408         int *i = _i;
409         *i = atoi(buffer);
410         free(buffer);
411 }
412
413 static void centibar(char *buffer, void *_pressure)
414 {
415         pressure_t *pressure = _pressure;
416         union int_or_float val;
417
418         switch (integer_or_float(buffer, &val)) {
419         case FLOAT:
420                 pressure->mbar = val.fp * 10 + 0.5;
421                 break;
422         default:
423                 fprintf(stderr, "Strange centibar pressure '%s'\n", buffer);
424         }
425         free(buffer);
426 }
427
428 static void decicelsius(char *buffer, void *_temp)
429 {
430         temperature_t *temp = _temp;
431         union int_or_float val;
432
433         switch (integer_or_float(buffer, &val)) {
434         case FLOAT:
435                 temp->mkelvin = (val.fp/10 + 273.15) * 1000 + 0.5;
436                 break;
437         default:
438                 fprintf(stderr, "Strange julian date: %s", buffer);
439         }
440         free(buffer);
441 }
442
443 static int uemis_fill_sample(struct sample *sample, const char *name, int len, char *buf)
444 {
445         return  MATCH(".reading.dive_time", sampletime, &sample->time) ||
446                 MATCH(".reading.water_pressure", water_pressure, &sample->depth) ||
447                 MATCH(".reading.active_tank", get_index, &sample->tankindex) ||
448                 MATCH(".reading.tank_pressure", centibar, &sample->tankpressure) ||
449                 MATCH(".reading.dive_temperature", decicelsius, &sample->temperature) ||
450                 0;
451 }
452
453 /* We're in samples - try to convert the random xml value to something useful */
454 static void try_to_fill_sample(struct sample *sample, const char *name, char *buf)
455 {
456         int len = strlen(name);
457
458         start_match("sample", name, buf);
459         if (MATCH(".sample.pressure", pressure, &sample->tankpressure))
460                 return;
461         if (MATCH(".sample.cylpress", pressure, &sample->tankpressure))
462                 return;
463         if (MATCH(".sample.depth", depth, &sample->depth))
464                 return;
465         if (MATCH(".sample.temp", temperature, &sample->temperature))
466                 return;
467         if (MATCH(".sample.temperature", temperature, &sample->temperature))
468                 return;
469         if (MATCH(".sample.sampletime", sampletime, &sample->time))
470                 return;
471         if (MATCH(".sample.time", sampletime, &sample->time))
472                 return;
473
474         if (uemis) {
475                 if (uemis_fill_sample(sample, name, len, buf))
476                         return;
477         }
478
479         nonmatch("sample", name, buf);
480 }
481
482 /*
483  * Crazy suunto xml. Look at how those o2/he things match up.
484  */
485 static int suunto_dive_match(struct dive *dive, const char *name, int len, char *buf)
486 {
487         return  MATCH(".o2pct", percent, &dive->gasmix[0].o2) ||
488                 MATCH(".hepct_0", percent, &dive->gasmix[0].he) ||
489                 MATCH(".o2pct_2", percent, &dive->gasmix[1].o2) ||
490                 MATCH(".hepct_1", percent, &dive->gasmix[1].he) ||
491                 MATCH(".o2pct_3", percent, &dive->gasmix[2].o2) ||
492                 MATCH(".hepct_2", percent, &dive->gasmix[2].he) ||
493                 MATCH(".o2pct_4", percent, &dive->gasmix[3].o2) ||
494                 MATCH(".hepct_3", percent, &dive->gasmix[3].he);
495 }
496
497 static int buffer_value(char *buffer)
498 {
499         int val = atoi(buffer);
500         free(buffer);
501         return val;
502 }
503
504 static void uemis_length_unit(char *buffer, void *_unused)
505 {
506         units.length = buffer_value(buffer) ? FEET : METERS;
507 }
508
509 static void uemis_volume_unit(char *buffer, void *_unused)
510 {
511         units.volume = buffer_value(buffer) ? CUFT : LITER;
512 }
513
514 static void uemis_pressure_unit(char *buffer, void *_unused)
515 {
516 #if 0
517         units.pressure = buffer_value(buffer) ? PSI : BAR;
518 #endif
519 }
520
521 static void uemis_temperature_unit(char *buffer, void *_unused)
522 {
523         units.temperature = buffer_value(buffer) ? FAHRENHEIT : CELSIUS;
524 }
525
526 static void uemis_weight_unit(char *buffer, void *_unused)
527 {
528         units.weight = buffer_value(buffer) ? LBS : KG;
529 }
530
531 static void uemis_time_unit(char *buffer, void *_unused)
532 {
533 }
534
535 static void uemis_date_unit(char *buffer, void *_unused)
536 {
537 }
538
539 /* Modified julian day, yay! */
540 static void uemis_date_time(char *buffer, void *_when)
541 {
542         time_t *when = _when;
543         union int_or_float val;
544
545         switch (integer_or_float(buffer, &val)) {
546         case FLOAT:
547                 *when = (val.fp - 40587.5) * 86400;
548                 break;
549         default:
550                 fprintf(stderr, "Strange julian date: %s", buffer);
551         }
552         free(buffer);
553 }
554
555 /*
556  * Uemis doesn't know time zones. You need to do them as
557  * minutes, not hours.
558  *
559  * But that's ok, we don't track timezones yet either. We
560  * just turn everything into "localtime expressed as UTC".
561  */
562 static void uemis_time_zone(char *buffer, void *_when)
563 {
564         time_t *when = _when;
565         signed char tz = atoi(buffer);
566
567         *when += tz * 3600;
568 }
569
570 static int uemis_dive_match(struct dive *dive, const char *name, int len, char *buf)
571 {
572         return  MATCH(".units.length", uemis_length_unit, &units) ||
573                 MATCH(".units.volume", uemis_volume_unit, &units) ||
574                 MATCH(".units.pressure", uemis_pressure_unit, &units) ||
575                 MATCH(".units.temperature", uemis_temperature_unit, &units) ||
576                 MATCH(".units.weight", uemis_weight_unit, &units) ||
577                 MATCH(".units.time", uemis_time_unit, &units) ||
578                 MATCH(".units.date", uemis_date_unit, &units) ||
579                 MATCH(".date_time", uemis_date_time, &dive->when) ||
580                 MATCH(".time_zone", uemis_time_zone, &dive->when) ||
581                 MATCH(".ambient.temperature", decicelsius, &dive->airtemp) ||
582                 0;
583 }
584
585 /* We're in the top-level dive xml. Try to convert whatever value to a dive value */
586 static void try_to_fill_dive(struct dive *dive, const char *name, char *buf)
587 {
588         int len = strlen(name);
589
590         start_match("dive", name, buf);
591         if (MATCH(".date", divedate, &dive->when))
592                 return;
593         if (MATCH(".time", divetime, &dive->when))
594                 return;
595         if (MATCH(".datetime", divedatetime, &dive->when))
596                 return;
597         if (MATCH(".maxdepth", depth, &dive->maxdepth))
598                 return;
599         if (MATCH(".meandepth", depth, &dive->meandepth))
600                 return;
601         if (MATCH(".duration", duration, &dive->duration))
602                 return;
603         if (MATCH(".divetime", duration, &dive->duration))
604                 return;
605         if (MATCH(".divetimesec", duration, &dive->duration))
606                 return;
607         if (MATCH(".surfacetime", duration, &dive->surfacetime))
608                 return;
609         if (MATCH(".airtemp", temperature, &dive->airtemp))
610                 return;
611         if (MATCH(".watertemp", temperature, &dive->watertemp))
612                 return;
613         if (MATCH(".cylinderstartpressure", pressure, &dive->beginning_pressure))
614                 return;
615         if (MATCH(".cylinderendpressure", pressure, &dive->end_pressure))
616                 return;
617         if (MATCH(".location", utf8_string, &dive->location))
618                 return;
619         if (MATCH(".notes", utf8_string, &dive->notes))
620                 return;
621
622         if (MATCH(".o2", gasmix, &dive->gasmix[gasmix_index].o2))
623                 return;
624         if (MATCH(".n2", gasmix_nitrogen, &dive->gasmix[gasmix_index]))
625                 return;
626         if (MATCH(".he", gasmix, &dive->gasmix[gasmix_index].he))
627                 return;
628
629         /* Suunto XML files are some crazy sh*t. */
630         if (suunto && suunto_dive_match(dive, name, len, buf))
631                 return;
632
633         if (uemis && uemis_dive_match(dive, name, len, buf))
634                 return;
635
636         nonmatch("dive", name, buf);
637 }
638
639 static unsigned int dive_size(int samples)
640 {
641         return sizeof(struct dive) + samples*sizeof(struct sample);
642 }
643
644 /*
645  * File boundaries are dive boundaries. But sometimes there are
646  * multiple dives per file, so there can be other events too that
647  * trigger a "new dive" marker and you may get some nesting due
648  * to that. Just ignore nesting levels.
649  */
650 static void dive_start(void)
651 {
652         unsigned int size;
653
654         if (dive)
655                 return;
656
657         alloc_samples = 5;
658         size = dive_size(alloc_samples);
659         dive = malloc(size);
660         if (!dive)
661                 exit(1);
662         memset(dive, 0, size);
663         memset(&tm, 0, sizeof(tm));
664 }
665
666 static char *generate_name(struct dive *dive)
667 {
668         int len;
669         struct tm *tm;
670         char buffer[256], *p;
671
672         tm = gmtime(&dive->when);
673
674         len = snprintf(buffer, sizeof(buffer),
675                 "%04d-%02d-%02d "
676                 "%02d:%02d:%02d "
677                 "(%d ft, %d min)",
678                 tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
679                 tm->tm_hour, tm->tm_min, tm->tm_sec,
680                 to_feet(dive->maxdepth), dive->duration.seconds / 60);
681         p = malloc(len+1);
682         if (!p)
683                 exit(1);
684         memcpy(p, buffer, len+1);
685         return p;
686 }
687
688 static void sanitize_gasmix(struct dive *dive)
689 {
690         int i;
691
692         for (i = 0; i < MAX_MIXES; i++) {
693                 gasmix_t *mix = dive->gasmix+i;
694                 unsigned int o2, he;
695
696                 o2 = mix->o2.permille;
697                 he = mix->he.permille;
698
699                 /* Regular air: leave empty */
700                 if (!he) {
701                         if (!o2)
702                                 continue;
703                         /* 20.9% or 21% O2 is just air */
704                         if (o2 >= 209 && o2 <= 210) {
705                                 mix->o2.permille = 0;
706                                 continue;
707                         }
708                 }
709
710                 /* Sane mix? */
711                 if (o2 <= 1000 && he <= 1000 && o2+he <= 1000)
712                         continue;
713                 fprintf(stderr, "Odd gasmix: %d O2 %d He\n", o2, he);
714                 memset(mix, 0, sizeof(*mix));
715         }
716 }
717
718 static void dive_end(void)
719 {
720         if (!dive)
721                 return;
722         if (!dive->name)
723                 dive->name = generate_name(dive);
724         sanitize_gasmix(dive);
725         record_dive(dive);
726         dive = NULL;
727         gasmix_index = 0;
728 }
729
730 static void suunto_start(void)
731 {
732         suunto++;
733         units = SI_units;
734 }
735
736 static void suunto_end(void)
737 {
738         suunto--;
739 }
740
741 static void uemis_start(void)
742 {
743         uemis++;
744         units = SI_units;
745 }
746
747 static void uemis_end(void)
748 {
749 }
750
751 static void event_start(void)
752 {
753 }
754
755 static void event_end(void)
756 {
757         event_index++;
758 }
759
760 static void gasmix_start(void)
761 {
762 }
763
764 static void gasmix_end(void)
765 {
766         gasmix_index++;
767 }
768
769 static void sample_start(void)
770 {
771         int nr;
772
773         if (!dive)
774                 return;
775         nr = dive->samples;
776         if (nr >= alloc_samples) {
777                 unsigned int size;
778
779                 alloc_samples = (alloc_samples * 3)/2 + 10;
780                 size = dive_size(alloc_samples);
781                 dive = realloc(dive, size);
782                 if (!dive)
783                         return;
784         }
785         sample = dive->sample + nr;
786         memset(sample, 0, sizeof(*sample));
787         event_index = 0;
788 }
789
790 static void sample_end(void)
791 {
792         if (!dive)
793                 return;
794
795         if (sample->time.seconds > dive->duration.seconds) {
796                 if (sample->depth.mm)
797                         dive->duration = sample->time;
798         }
799
800         if (sample->depth.mm > dive->maxdepth.mm)
801                 dive->maxdepth.mm = sample->depth.mm;
802
803         if (sample->temperature.mkelvin) {
804                 if (!dive->watertemp.mkelvin || dive->watertemp.mkelvin > sample->temperature.mkelvin)
805                         dive->watertemp = sample->temperature;
806         }
807
808         sample = NULL;
809         dive->samples++;
810 }
811
812 static void entry(const char *name, int size, const char *raw)
813 {
814         char *buf = malloc(size+1);
815
816         if (!buf)
817                 return;
818         memcpy(buf, raw, size);
819         buf[size] = 0;
820         if (sample) {
821                 try_to_fill_sample(sample, name, buf);
822                 return;
823         }
824         if (dive) {
825                 try_to_fill_dive(dive, name, buf);
826                 return;
827         }
828 }
829
830 static const char *nodename(xmlNode *node, char *buf, int len)
831 {
832         if (!node || !node->name)
833                 return "root";
834
835         buf += len;
836         *--buf = 0;
837         len--;
838
839         for(;;) {
840                 const char *name = node->name;
841                 int i = strlen(name);
842                 while (--i >= 0) {
843                         unsigned char c = name[i];
844                         *--buf = tolower(c);
845                         if (!--len)
846                                 return buf;
847                 }
848                 node = node->parent;
849                 if (!node || !node->name)
850                         return buf;
851                 *--buf = '.';
852                 if (!--len)
853                         return buf;
854         }
855 }
856
857 #define MAXNAME 64
858
859 static void visit_one_node(xmlNode *node)
860 {
861         int len;
862         const unsigned char *content;
863         char buffer[MAXNAME];
864         const char *name;
865
866         content = node->content;
867         if (!content)
868                 return;
869
870         /* Trim whitespace at beginning */
871         while (isspace(*content))
872                 content++;
873
874         /* Trim whitespace at end */
875         len = strlen(content);
876         while (len && isspace(content[len-1]))
877                 len--;
878
879         if (!len)
880                 return;
881
882         /* Don't print out the node name if it is "text" */
883         if (!strcmp(node->name, "text"))
884                 node = node->parent;
885
886         name = nodename(node, buffer, sizeof(buffer));
887
888         entry(name, len, content);
889 }
890
891 static void traverse(xmlNode *root);
892
893 static void traverse_properties(xmlNode *node)
894 {
895         xmlAttr *p;
896
897         for (p = node->properties; p; p = p->next)
898                 traverse(p->children);
899 }
900
901 static void visit(xmlNode *n)
902 {
903         visit_one_node(n);
904         traverse_properties(n);
905         traverse(n->children);
906 }
907
908 /*
909  * I'm sure this could be done as some fancy DTD rules.
910  * It's just not worth the headache.
911  */
912 static struct nesting {
913         const char *name;
914         void (*start)(void), (*end)(void);
915 } nesting[] = {
916         { "dive", dive_start, dive_end },
917         { "SUUNTO", suunto_start, suunto_end },
918         { "sample", sample_start, sample_end },
919         { "SAMPLE", sample_start, sample_end },
920         { "reading", sample_start, sample_end },
921         { "event", event_start, event_end },
922         { "gasmix", gasmix_start, gasmix_end },
923         { "pre_dive", uemis_start, uemis_end },
924         { NULL, }
925 };
926
927 static void traverse(xmlNode *root)
928 {
929         xmlNode *n;
930
931         for (n = root; n; n = n->next) {
932                 struct nesting *rule = nesting;
933
934                 do {
935                         if (!strcmp(rule->name, n->name))
936                                 break;
937                         rule++;
938                 } while (rule->name);
939
940                 if (rule->start)
941                         rule->start();
942                 visit(n);
943                 if (rule->end)
944                         rule->end();
945         }
946 }
947
948 /* Per-file reset */
949 static void reset_all(void)
950 {
951         /*
952          * We reset the units for each file. You'd think it was
953          * a per-dive property, but I'm not going to trust people
954          * to do per-dive setup. If the xml does have per-dive
955          * data within one file, we might have to reset it per
956          * dive for that format.
957          */
958         units = SI_units;
959         suunto = 0;
960         uemis = 0;
961 }
962
963 void parse_xml_file(const char *filename)
964 {
965         xmlDoc *doc;
966
967         doc = xmlReadFile(filename, NULL, 0);
968         if (!doc) {
969                 fprintf(stderr, "Failed to parse '%s'.\n", filename);
970                 return;
971         }
972
973         reset_all();
974         dive_start();
975         traverse(xmlDocGetRootElement(doc));
976         dive_end();
977         xmlFreeDoc(doc);
978         xmlCleanupParser();
979 }
980
981 void parse_xml_init(void)
982 {
983         LIBXML_TEST_VERSION
984 }