]> git.tdb.fi Git - ext/subsurface.git/blob - parse-xml.c
Merge branch 'more-divelist-goodness' of https://github.com/nathansamson/diveclog
[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  * 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, cylinder_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 (cylinder_index < MAX_CYLINDERS)
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 cylindersize(char *buffer, void *_volume)
362 {
363         volume_t *volume = _volume;
364         union int_or_float val;
365
366         switch (integer_or_float(buffer, &val)) {
367         case FLOAT:
368                 volume->mliter = val.fp * 1000 + 0.5;
369                 break;
370
371         default:
372                 printf("Strange volume reading %s\n", buffer);
373                 break;
374         }
375         free(buffer);
376 }
377
378 static void utf8_string(char *buffer, void *_res)
379 {
380         *(char **)_res = buffer;
381 }
382
383 /*
384  * Uemis water_pressure. In centibar. And when converting to
385  * depth, I'm just going to always use saltwater, because I
386  * think "true depth" is just stupid. From a diving standpoint,
387  * "true depth" is pretty much completely pointless, unless
388  * you're doing some kind of underwater surveying work.
389  *
390  * So I give water depths in "pressure depth", always assuming
391  * salt water. So one atmosphere per 10m.
392  */
393 static void water_pressure(char *buffer, void *_depth)
394 {
395         depth_t *depth = _depth;
396         union int_or_float val;
397         double atm, cm;
398
399         switch (integer_or_float(buffer, &val)) {
400         case FLOAT:
401                 if (!val.fp)
402                         break;
403                 /* cbar to atm */
404                 atm = (val.fp / 100) / 1.01325;
405                 /*
406                  * atm to cm. Why not mm? The precision just isn't
407                  * there.
408                  */
409                 cm = 100 * (atm - 1) + 0.5;
410                 if (cm > 0) {
411                         depth->mm = 10 * (long)cm;
412                         break;
413                 }
414         default:
415                 fprintf(stderr, "Strange water pressure '%s'\n", buffer);
416         }
417         free(buffer);
418 }
419
420 #define MATCH(pattern, fn, dest) \
421         match(pattern, strlen(pattern), name, len, fn, buf, dest)
422
423 static void get_index(char *buffer, void *_i)
424 {
425         int *i = _i;
426         *i = atoi(buffer);
427         free(buffer);
428 }
429
430 static void centibar(char *buffer, void *_pressure)
431 {
432         pressure_t *pressure = _pressure;
433         union int_or_float val;
434
435         switch (integer_or_float(buffer, &val)) {
436         case FLOAT:
437                 pressure->mbar = val.fp * 10 + 0.5;
438                 break;
439         default:
440                 fprintf(stderr, "Strange centibar pressure '%s'\n", buffer);
441         }
442         free(buffer);
443 }
444
445 static void decicelsius(char *buffer, void *_temp)
446 {
447         temperature_t *temp = _temp;
448         union int_or_float val;
449
450         switch (integer_or_float(buffer, &val)) {
451         case FLOAT:
452                 temp->mkelvin = (val.fp/10 + 273.15) * 1000 + 0.5;
453                 break;
454         default:
455                 fprintf(stderr, "Strange julian date: %s", buffer);
456         }
457         free(buffer);
458 }
459
460 static int uemis_fill_sample(struct sample *sample, const char *name, int len, char *buf)
461 {
462         return  MATCH(".reading.dive_time", sampletime, &sample->time) ||
463                 MATCH(".reading.water_pressure", water_pressure, &sample->depth) ||
464                 MATCH(".reading.active_tank", get_index, &sample->cylinderindex) ||
465                 MATCH(".reading.tank_pressure", centibar, &sample->cylinderpressure) ||
466                 MATCH(".reading.dive_temperature", decicelsius, &sample->temperature) ||
467                 0;
468 }
469
470 /* We're in samples - try to convert the random xml value to something useful */
471 static void try_to_fill_sample(struct sample *sample, const char *name, char *buf)
472 {
473         int len = strlen(name);
474
475         start_match("sample", name, buf);
476         if (MATCH(".sample.pressure", pressure, &sample->cylinderpressure))
477                 return;
478         if (MATCH(".sample.cylpress", pressure, &sample->cylinderpressure))
479                 return;
480         if (MATCH(".sample.depth", depth, &sample->depth))
481                 return;
482         if (MATCH(".sample.temp", temperature, &sample->temperature))
483                 return;
484         if (MATCH(".sample.temperature", temperature, &sample->temperature))
485                 return;
486         if (MATCH(".sample.sampletime", sampletime, &sample->time))
487                 return;
488         if (MATCH(".sample.time", sampletime, &sample->time))
489                 return;
490
491         if (uemis) {
492                 if (uemis_fill_sample(sample, name, len, buf))
493                         return;
494         }
495
496         nonmatch("sample", name, buf);
497 }
498
499 /*
500  * Crazy suunto xml. Look at how those o2/he things match up.
501  */
502 static int suunto_dive_match(struct dive *dive, const char *name, int len, char *buf)
503 {
504         return  MATCH(".o2pct", percent, &dive->cylinder[0].gasmix.o2) ||
505                 MATCH(".hepct_0", percent, &dive->cylinder[0].gasmix.he) ||
506                 MATCH(".o2pct_2", percent, &dive->cylinder[1].gasmix.o2) ||
507                 MATCH(".hepct_1", percent, &dive->cylinder[1].gasmix.he) ||
508                 MATCH(".o2pct_3", percent, &dive->cylinder[2].gasmix.o2) ||
509                 MATCH(".hepct_2", percent, &dive->cylinder[2].gasmix.he) ||
510                 MATCH(".o2pct_4", percent, &dive->cylinder[3].gasmix.o2) ||
511                 MATCH(".hepct_3", percent, &dive->cylinder[3].gasmix.he) ||
512                 MATCH(".cylindersize", cylindersize, &dive->cylinder[0].type.size) ||
513                 MATCH(".cylinderworkpressure", pressure, &dive->cylinder[0].type.workingpressure) ||
514                 0;
515 }
516
517 static int buffer_value(char *buffer)
518 {
519         int val = atoi(buffer);
520         free(buffer);
521         return val;
522 }
523
524 static void uemis_length_unit(char *buffer, void *_unused)
525 {
526         units.length = buffer_value(buffer) ? FEET : METERS;
527 }
528
529 static void uemis_volume_unit(char *buffer, void *_unused)
530 {
531         units.volume = buffer_value(buffer) ? CUFT : LITER;
532 }
533
534 static void uemis_pressure_unit(char *buffer, void *_unused)
535 {
536 #if 0
537         units.pressure = buffer_value(buffer) ? PSI : BAR;
538 #endif
539 }
540
541 static void uemis_temperature_unit(char *buffer, void *_unused)
542 {
543         units.temperature = buffer_value(buffer) ? FAHRENHEIT : CELSIUS;
544 }
545
546 static void uemis_weight_unit(char *buffer, void *_unused)
547 {
548         units.weight = buffer_value(buffer) ? LBS : KG;
549 }
550
551 static void uemis_time_unit(char *buffer, void *_unused)
552 {
553 }
554
555 static void uemis_date_unit(char *buffer, void *_unused)
556 {
557 }
558
559 /* Modified julian day, yay! */
560 static void uemis_date_time(char *buffer, void *_when)
561 {
562         time_t *when = _when;
563         union int_or_float val;
564
565         switch (integer_or_float(buffer, &val)) {
566         case FLOAT:
567                 *when = (val.fp - 40587.5) * 86400;
568                 break;
569         default:
570                 fprintf(stderr, "Strange julian date: %s", buffer);
571         }
572         free(buffer);
573 }
574
575 /*
576  * Uemis doesn't know time zones. You need to do them as
577  * minutes, not hours.
578  *
579  * But that's ok, we don't track timezones yet either. We
580  * just turn everything into "localtime expressed as UTC".
581  */
582 static void uemis_time_zone(char *buffer, void *_when)
583 {
584         time_t *when = _when;
585         signed char tz = atoi(buffer);
586
587         *when += tz * 3600;
588 }
589
590 /* Christ. Uemis tank data is a total mess. */
591 static int uemis_dive_match(struct dive *dive, const char *name, int len, char *buf)
592 {
593         return  MATCH(".units.length", uemis_length_unit, &units) ||
594                 MATCH(".units.volume", uemis_volume_unit, &units) ||
595                 MATCH(".units.pressure", uemis_pressure_unit, &units) ||
596                 MATCH(".units.temperature", uemis_temperature_unit, &units) ||
597                 MATCH(".units.weight", uemis_weight_unit, &units) ||
598                 MATCH(".units.time", uemis_time_unit, &units) ||
599                 MATCH(".units.date", uemis_date_unit, &units) ||
600                 MATCH(".date_time", uemis_date_time, &dive->when) ||
601                 MATCH(".time_zone", uemis_time_zone, &dive->when) ||
602                 MATCH(".ambient.temperature", decicelsius, &dive->airtemp) ||
603                 MATCH(".air.bottom_tank.size", cylindersize, &dive->cylinder[0].type.size) ||
604                 MATCH(".air.bottom_tank.oxygen", percent, &dive->cylinder[0].gasmix.o2) ||
605                 MATCH(".nitrox_1.bottom_tank.size", cylindersize, &dive->cylinder[1].type.size) ||
606                 MATCH(".nitrox_1.bottom_tank.oxygen", percent, &dive->cylinder[1].gasmix.o2) ||
607                 MATCH(".nitrox_2.bottom_tank.size", cylindersize, &dive->cylinder[2].type.size) ||
608                 MATCH(".nitrox_2.bottom_tank.oxygen", percent, &dive->cylinder[2].gasmix.o2) ||
609                 MATCH(".nitrox_2.deco_tank.size", cylindersize, &dive->cylinder[3].type.size) ||
610                 MATCH(".nitrox_2.deco_tank.oxygen", percent, &dive->cylinder[3].gasmix.o2) ||
611                 MATCH(".nitrox_3.bottom_tank.size", cylindersize, &dive->cylinder[4].type.size) ||
612                 MATCH(".nitrox_3.bottom_tank.oxygen", percent, &dive->cylinder[4].gasmix.o2) ||
613                 MATCH(".nitrox_3.deco_tank.size", cylindersize, &dive->cylinder[5].type.size) ||
614                 MATCH(".nitrox_3.deco_tank.oxygen", percent, &dive->cylinder[5].gasmix.o2) ||
615                 MATCH(".nitrox_3.travel_tank.size", cylindersize, &dive->cylinder[6].type.size) ||
616                 MATCH(".nitrox_3.travel_tank.oxygen", percent, &dive->cylinder[6].gasmix.o2) ||
617                 0;
618 }
619
620 /* We're in the top-level dive xml. Try to convert whatever value to a dive value */
621 static void try_to_fill_dive(struct dive *dive, const char *name, char *buf)
622 {
623         int len = strlen(name);
624
625         start_match("dive", name, buf);
626         if (MATCH(".date", divedate, &dive->when))
627                 return;
628         if (MATCH(".time", divetime, &dive->when))
629                 return;
630         if (MATCH(".datetime", divedatetime, &dive->when))
631                 return;
632         if (MATCH(".maxdepth", depth, &dive->maxdepth))
633                 return;
634         if (MATCH(".meandepth", depth, &dive->meandepth))
635                 return;
636         if (MATCH(".duration", duration, &dive->duration))
637                 return;
638         if (MATCH(".divetime", duration, &dive->duration))
639                 return;
640         if (MATCH(".divetimesec", duration, &dive->duration))
641                 return;
642         if (MATCH(".surfacetime", duration, &dive->surfacetime))
643                 return;
644         if (MATCH(".airtemp", temperature, &dive->airtemp))
645                 return;
646         if (MATCH(".watertemp", temperature, &dive->watertemp))
647                 return;
648         if (MATCH(".cylinderstartpressure", pressure, &dive->beginning_pressure))
649                 return;
650         if (MATCH(".cylinderendpressure", pressure, &dive->end_pressure))
651                 return;
652         if (MATCH(".location", utf8_string, &dive->location))
653                 return;
654         if (MATCH(".notes", utf8_string, &dive->notes))
655                 return;
656
657         if (MATCH(".cylinder.size", cylindersize, &dive->cylinder[cylinder_index].type.size))
658                 return;
659         if (MATCH(".cylinder.workpressure", pressure, &dive->cylinder[cylinder_index].type.workingpressure))
660                 return;
661         if (MATCH(".cylinder.description", utf8_string, &dive->cylinder[cylinder_index].type.description))
662                 return;
663
664         if (MATCH(".o2", gasmix, &dive->cylinder[cylinder_index].gasmix.o2))
665                 return;
666         if (MATCH(".n2", gasmix_nitrogen, &dive->cylinder[cylinder_index].gasmix))
667                 return;
668         if (MATCH(".he", gasmix, &dive->cylinder[cylinder_index].gasmix.he))
669                 return;
670
671         /* Suunto XML files are some crazy sh*t. */
672         if (suunto && suunto_dive_match(dive, name, len, buf))
673                 return;
674
675         if (uemis && uemis_dive_match(dive, name, len, buf))
676                 return;
677
678         nonmatch("dive", name, buf);
679 }
680
681 /*
682  * File boundaries are dive boundaries. But sometimes there are
683  * multiple dives per file, so there can be other events too that
684  * trigger a "new dive" marker and you may get some nesting due
685  * to that. Just ignore nesting levels.
686  */
687 static void dive_start(void)
688 {
689         unsigned int size;
690
691         if (dive)
692                 return;
693
694         alloc_samples = 5;
695         size = dive_size(alloc_samples);
696         dive = malloc(size);
697         if (!dive)
698                 exit(1);
699         memset(dive, 0, size);
700         memset(&tm, 0, sizeof(tm));
701 }
702
703 static void sanitize_gasmix(gasmix_t *mix)
704 {
705         unsigned int o2, he;
706
707         o2 = mix->o2.permille;
708         he = mix->he.permille;
709
710         /* Regular air: leave empty */
711         if (!he) {
712                 if (!o2)
713                         return;
714                 /* 20.9% or 21% O2 is just air */
715                 if (o2 >= 209 && o2 <= 210) {
716                         mix->o2.permille = 0;
717                         return;
718                 }
719         }
720
721         /* Sane mix? */
722         if (o2 <= 1000 && he <= 1000 && o2+he <= 1000)
723                 return;
724         fprintf(stderr, "Odd gasmix: %d O2 %d He\n", o2, he);
725         memset(mix, 0, sizeof(*mix));
726 }
727
728 /*
729  * See if the size/workingpressure looks like some standard cylinder
730  * size, eg "AL80".
731  */
732 static void match_standard_cylinder(cylinder_type_t *type)
733 {
734         int psi, cuft, len;
735         const char *fmt;
736         char buffer[20], *p;
737
738         /* Do we already have a cylinder description? */
739         if (type->description)
740                 return;
741
742         cuft = type->size.mliter / 1000;
743         psi = type->workingpressure.mbar / 68.95;
744
745         switch (psi) {
746         case 2300 ... 2500:     /* 2400 psi: LP tank */
747                 fmt = "LP%d";
748                 break;
749         case 2600 ... 2700:     /* 2640 psi: LP+10% */
750                 fmt = "LP%d+";
751                 break;
752         case 2900 ... 3100:     /* 3000 psi: ALx tank */
753                 fmt = "AL%d";
754                 break;
755         case 3400 ... 3500:     /* 3442 psi: HP tank */
756                 fmt = "HP%d";
757                 break;
758         case 3700 ... 3850:     /* HP+10% */
759                 fmt = "HP%d+";
760                 break;
761         default:
762                 return;
763         }
764         len = snprintf(buffer, sizeof(buffer), fmt, cuft);
765         p = malloc(len+1);
766         if (!p)
767                 return;
768         memcpy(p, buffer, len+1);
769         type->description = p;
770 }
771
772
773 /*
774  * There are two ways to give cylinder size information:
775  *  - total amount of gas in cuft (depends on working pressure and physical size)
776  *  - physical size
777  *
778  * where "physical size" is the one that actually matters and is sane.
779  *
780  * We internally use physical size only. But we save the workingpressure
781  * so that we can do the conversion if required.
782  */
783 static void sanitize_cylinder_type(cylinder_type_t *type)
784 {
785         double volume_of_air, atm, volume;
786
787         /* If we have no working pressure, it had *better* be just a physical size! */
788         if (!type->workingpressure.mbar)
789                 return;
790
791         /* No size either? Nothing to go on */
792         if (!type->size.mliter)
793                 return;
794
795         /* Ok, we have both size and pressure: try to match a description */
796         match_standard_cylinder(type);
797
798         /* .. and let's assume that the 'size' was cu ft of air */
799         volume_of_air = type->size.mliter * 28.317;     /* milli-cu ft to milliliter */
800         atm = type->workingpressure.mbar / 1013.25;     /* working pressure in atm */
801         volume = volume_of_air / atm;                   /* milliliters at 1 atm: "true size" */
802         type->size.mliter = volume + 0.5;
803 }
804
805 static void sanitize_cylinder_info(struct dive *dive)
806 {
807         int i;
808
809         for (i = 0; i < MAX_CYLINDERS; i++) {
810                 sanitize_gasmix(&dive->cylinder[i].gasmix);
811                 sanitize_cylinder_type(&dive->cylinder[i].type);
812         }
813 }
814
815 static void dive_end(void)
816 {
817         if (!dive)
818                 return;
819         sanitize_cylinder_info(dive);
820         record_dive(dive);
821         dive = NULL;
822         cylinder_index = 0;
823 }
824
825 static void suunto_start(void)
826 {
827         suunto++;
828         units = SI_units;
829 }
830
831 static void suunto_end(void)
832 {
833         suunto--;
834 }
835
836 static void uemis_start(void)
837 {
838         uemis++;
839         units = SI_units;
840 }
841
842 static void uemis_end(void)
843 {
844 }
845
846 static void event_start(void)
847 {
848 }
849
850 static void event_end(void)
851 {
852         event_index++;
853 }
854
855 static void cylinder_start(void)
856 {
857 }
858
859 static void cylinder_end(void)
860 {
861         cylinder_index++;
862 }
863
864 static void sample_start(void)
865 {
866         int nr;
867
868         if (!dive)
869                 return;
870         nr = dive->samples;
871         if (nr >= alloc_samples) {
872                 unsigned int size;
873
874                 alloc_samples = (alloc_samples * 3)/2 + 10;
875                 size = dive_size(alloc_samples);
876                 dive = realloc(dive, size);
877                 if (!dive)
878                         return;
879         }
880         sample = dive->sample + nr;
881         memset(sample, 0, sizeof(*sample));
882         event_index = 0;
883 }
884
885 static void sample_end(void)
886 {
887         if (!dive)
888                 return;
889
890         sample = NULL;
891         dive->samples++;
892 }
893
894 static void entry(const char *name, int size, const char *raw)
895 {
896         char *buf = malloc(size+1);
897
898         if (!buf)
899                 return;
900         memcpy(buf, raw, size);
901         buf[size] = 0;
902         if (sample) {
903                 try_to_fill_sample(sample, name, buf);
904                 return;
905         }
906         if (dive) {
907                 try_to_fill_dive(dive, name, buf);
908                 return;
909         }
910 }
911
912 static const char *nodename(xmlNode *node, char *buf, int len)
913 {
914         if (!node || !node->name)
915                 return "root";
916
917         buf += len;
918         *--buf = 0;
919         len--;
920
921         for(;;) {
922                 const char *name = node->name;
923                 int i = strlen(name);
924                 while (--i >= 0) {
925                         unsigned char c = name[i];
926                         *--buf = tolower(c);
927                         if (!--len)
928                                 return buf;
929                 }
930                 node = node->parent;
931                 if (!node || !node->name)
932                         return buf;
933                 *--buf = '.';
934                 if (!--len)
935                         return buf;
936         }
937 }
938
939 #define MAXNAME 64
940
941 static void visit_one_node(xmlNode *node)
942 {
943         int len;
944         const unsigned char *content;
945         char buffer[MAXNAME];
946         const char *name;
947
948         content = node->content;
949         if (!content)
950                 return;
951
952         /* Trim whitespace at beginning */
953         while (isspace(*content))
954                 content++;
955
956         /* Trim whitespace at end */
957         len = strlen(content);
958         while (len && isspace(content[len-1]))
959                 len--;
960
961         if (!len)
962                 return;
963
964         /* Don't print out the node name if it is "text" */
965         if (!strcmp(node->name, "text"))
966                 node = node->parent;
967
968         name = nodename(node, buffer, sizeof(buffer));
969
970         entry(name, len, content);
971 }
972
973 static void traverse(xmlNode *root);
974
975 static void traverse_properties(xmlNode *node)
976 {
977         xmlAttr *p;
978
979         for (p = node->properties; p; p = p->next)
980                 traverse(p->children);
981 }
982
983 static void visit(xmlNode *n)
984 {
985         visit_one_node(n);
986         traverse_properties(n);
987         traverse(n->children);
988 }
989
990 /*
991  * I'm sure this could be done as some fancy DTD rules.
992  * It's just not worth the headache.
993  */
994 static struct nesting {
995         const char *name;
996         void (*start)(void), (*end)(void);
997 } nesting[] = {
998         { "dive", dive_start, dive_end },
999         { "SUUNTO", suunto_start, suunto_end },
1000         { "sample", sample_start, sample_end },
1001         { "SAMPLE", sample_start, sample_end },
1002         { "reading", sample_start, sample_end },
1003         { "event", event_start, event_end },
1004         { "gasmix", cylinder_start, cylinder_end },
1005         { "cylinder", cylinder_start, cylinder_end },
1006         { "pre_dive", uemis_start, uemis_end },
1007         { NULL, }
1008 };
1009
1010 static void traverse(xmlNode *root)
1011 {
1012         xmlNode *n;
1013
1014         for (n = root; n; n = n->next) {
1015                 struct nesting *rule = nesting;
1016
1017                 do {
1018                         if (!strcmp(rule->name, n->name))
1019                                 break;
1020                         rule++;
1021                 } while (rule->name);
1022
1023                 if (rule->start)
1024                         rule->start();
1025                 visit(n);
1026                 if (rule->end)
1027                         rule->end();
1028         }
1029 }
1030
1031 /* Per-file reset */
1032 static void reset_all(void)
1033 {
1034         /*
1035          * We reset the units for each file. You'd think it was
1036          * a per-dive property, but I'm not going to trust people
1037          * to do per-dive setup. If the xml does have per-dive
1038          * data within one file, we might have to reset it per
1039          * dive for that format.
1040          */
1041         units = SI_units;
1042         suunto = 0;
1043         uemis = 0;
1044 }
1045
1046 void parse_xml_file(const char *filename)
1047 {
1048         xmlDoc *doc;
1049
1050         doc = xmlReadFile(filename, NULL, 0);
1051         if (!doc) {
1052                 fprintf(stderr, "Failed to parse '%s'.\n", filename);
1053                 return;
1054         }
1055
1056         reset_all();
1057         dive_start();
1058         traverse(xmlDocGetRootElement(doc));
1059         dive_end();
1060         xmlFreeDoc(doc);
1061         xmlCleanupParser();
1062 }
1063
1064 void parse_xml_init(void)
1065 {
1066         LIBXML_TEST_VERSION
1067 }