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