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