]> git.tdb.fi Git - ext/subsurface.git/blob - dive.c
Might as well free current_file
[ext/subsurface.git] / dive.c
1 /* dive.c */
2 /* maintains the internal dive list structure */
3 #include <string.h>
4 #include <stdio.h>
5
6 #include "dive.h"
7
8 void add_event(struct dive *dive, int time, int type, int flags, int value, const char *name)
9 {
10         struct event *ev, **p;
11         unsigned int size, len = strlen(name);
12
13         size = sizeof(*ev) + len + 1;
14         ev = malloc(size);
15         if (!ev)
16                 return;
17         memset(ev, 0, size);
18         memcpy(ev->name, name, len);
19         ev->time.seconds = time;
20         ev->type = type;
21         ev->flags = flags;
22         ev->value = value;
23         ev->next = NULL;
24
25         p = &dive->events;
26         while (*p)
27                 p = &(*p)->next;
28         *p = ev;
29         remember_event(name);
30 }
31
32 int get_pressure_units(unsigned int mb, const char **units)
33 {
34         int pressure;
35         const char* unit;
36
37         switch (output_units.pressure) {
38         case PASCAL:
39                 pressure = mb * 100;
40                 unit = "pascal";
41                 break;
42         case BAR:
43                 pressure = (mb + 500) / 1000;
44                 unit = "bar";
45                 break;
46         case PSI:
47                 pressure = mbar_to_PSI(mb);
48                 unit = "psi";
49                 break;
50         }
51         if (units)
52                 *units = unit;
53         return pressure;
54 }
55
56 double get_temp_units(unsigned int mk, const char **units)
57 {
58         double deg;
59         const char *unit;
60
61         if (output_units.temperature == FAHRENHEIT) {
62                 deg = mkelvin_to_F(mk);
63                 unit = UTF8_DEGREE "F";
64         } else {
65                 deg = mkelvin_to_C(mk);
66                 unit = UTF8_DEGREE "C";
67         }
68         if (units)
69                 *units = unit;
70         return deg;
71 }
72
73 double get_volume_units(unsigned int ml, int *frac, const char **units)
74 {
75         int decimals;
76         double vol;
77         const char *unit;
78
79         switch (output_units.volume) {
80         case LITER:
81                 vol = ml / 1000.0;
82                 unit = "l";
83                 decimals = 1;
84                 break;
85         case CUFT:
86                 vol = ml_to_cuft(ml);
87                 unit = "cuft";
88                 decimals = 2;
89                 break;
90         }
91         if (frac)
92                 *frac = decimals;
93         if (units)
94                 *units = unit;
95         return vol;
96 }
97
98 double get_depth_units(unsigned int mm, int *frac, const char **units)
99 {
100         int decimals;
101         double d;
102         const char *unit;
103
104         switch (output_units.length) {
105         case METERS:
106                 d = mm / 1000.0;
107                 unit = "m";
108                 decimals = d < 20;
109                 break;
110         case FEET:
111                 d = mm_to_feet(mm);
112                 unit = "ft";
113                 decimals = 0;
114                 break;
115         }
116         if (frac)
117                 *frac = decimals;
118         if (units)
119                 *units = unit;
120         return d;
121 }
122
123 double get_weight_units(unsigned int grams, int *frac, const char **units)
124 {
125         int decimals;
126         double value;
127         const char* unit;
128
129         if (output_units.weight == LBS) {
130                 value = grams_to_lbs(grams);
131                 unit = "lbs";
132                 decimals = 0;
133         } else {
134                 value = grams / 1000.0;
135                 unit = "kg";
136                 decimals = 1;
137         }
138         if (frac)
139                 *frac = decimals;
140         if (units)
141                 *units = unit;
142         return value;
143 }
144
145 struct dive *alloc_dive(void)
146 {
147         const int initial_samples = 5;
148         unsigned int size;
149         struct dive *dive;
150
151         size = dive_size(initial_samples);
152         dive = malloc(size);
153         if (!dive)
154                 exit(1);
155         memset(dive, 0, size);
156         dive->alloc_samples = initial_samples;
157         return dive;
158 }
159
160 struct sample *prepare_sample(struct dive **divep)
161 {
162         struct dive *dive = *divep;
163         if (dive) {
164                 int nr = dive->samples;
165                 int alloc_samples = dive->alloc_samples;
166                 struct sample *sample;
167                 if (nr >= alloc_samples) {
168                         unsigned int size;
169
170                         alloc_samples = (alloc_samples * 3)/2 + 10;
171                         size = dive_size(alloc_samples);
172                         dive = realloc(dive, size);
173                         if (!dive)
174                                 return NULL;
175                         dive->alloc_samples = alloc_samples;
176                         *divep = dive;
177                 }
178                 sample = dive->sample + nr;
179                 memset(sample, 0, sizeof(*sample));
180                 return sample;
181         }
182         return NULL;
183 }
184
185 void finish_sample(struct dive *dive)
186 {
187         dive->samples++;
188 }
189
190 /*
191  * So when we re-calculate maxdepth and meandepth, we will
192  * not override the old numbers if they are close to the
193  * new ones.
194  *
195  * Why? Because a dive computer may well actually track the
196  * max depth and mean depth at finer granularity than the
197  * samples it stores. So it's possible that the max and mean
198  * have been reported more correctly originally.
199  *
200  * Only if the values calculated from the samples are clearly
201  * different do we override the normal depth values.
202  *
203  * This considers 1m to be "clearly different". That's
204  * a totally random number.
205  */
206 static void update_depth(depth_t *depth, int new)
207 {
208         if (new) {
209                 int old = depth->mm;
210
211                 if (abs(old - new) > 1000)
212                         depth->mm = new;
213         }
214 }
215
216 static void update_duration(duration_t *duration, int new)
217 {
218         if (new)
219                 duration->seconds = new;
220 }
221
222 static void update_temperature(temperature_t *temperature, int new)
223 {
224         if (new) {
225                 int old = temperature->mkelvin;
226
227                 if (abs(old - new) > 1000)
228                         temperature->mkelvin = new;
229         }
230 }
231
232 static void fixup_pressure(struct dive *dive, struct sample *sample)
233 {
234         unsigned int pressure, index;
235         cylinder_t *cyl;
236
237         pressure = sample->cylinderpressure.mbar;
238         if (!pressure)
239                 return;
240         index = sample->cylinderindex;
241         if (index >= MAX_CYLINDERS)
242                 return;
243         cyl = dive->cylinder + index;
244         if (!cyl->sample_start.mbar)
245                 cyl->sample_start.mbar = pressure;
246         cyl->sample_end.mbar = pressure;
247 }
248
249 /*
250  * If the cylinder tank pressures are within half a bar
251  * (about 8 PSI) of the sample pressures, we consider it
252  * to be a rounding error, and throw them away as redundant.
253  */
254 static int same_rounded_pressure(pressure_t a, pressure_t b)
255 {
256         return abs(a.mbar - b.mbar) <= 500;
257 }
258
259 static void sanitize_gasmix(struct gasmix *mix)
260 {
261         unsigned int o2, he;
262
263         o2 = mix->o2.permille;
264         he = mix->he.permille;
265
266         /* Regular air: leave empty */
267         if (!he) {
268                 if (!o2)
269                         return;
270                 /* 20.9% or 21% O2 is just air */
271                 if (o2 >= 209 && o2 <= 210) {
272                         mix->o2.permille = 0;
273                         return;
274                 }
275         }
276
277         /* Sane mix? */
278         if (o2 <= 1000 && he <= 1000 && o2+he <= 1000)
279                 return;
280         fprintf(stderr, "Odd gasmix: %d O2 %d He\n", o2, he);
281         memset(mix, 0, sizeof(*mix));
282 }
283
284 /*
285  * See if the size/workingpressure looks like some standard cylinder
286  * size, eg "AL80".
287  */
288 static void match_standard_cylinder(cylinder_type_t *type)
289 {
290         double cuft;
291         int psi, len;
292         const char *fmt;
293         char buffer[20], *p;
294
295         /* Do we already have a cylinder description? */
296         if (type->description)
297                 return;
298
299         cuft = ml_to_cuft(type->size.mliter);
300         cuft *= to_ATM(type->workingpressure);
301         psi = to_PSI(type->workingpressure);
302
303         switch (psi) {
304         case 2300 ... 2500:     /* 2400 psi: LP tank */
305                 fmt = "LP%d";
306                 break;
307         case 2600 ... 2700:     /* 2640 psi: LP+10% */
308                 fmt = "LP%d";
309                 break;
310         case 2900 ... 3100:     /* 3000 psi: ALx tank */
311                 fmt = "AL%d";
312                 break;
313         case 3400 ... 3500:     /* 3442 psi: HP tank */
314                 fmt = "HP%d";
315                 break;
316         case 3700 ... 3850:     /* HP+10% */
317                 fmt = "HP%d+";
318                 break;
319         default:
320                 return;
321         }
322         len = snprintf(buffer, sizeof(buffer), fmt, (int) (cuft+0.5));
323         p = malloc(len+1);
324         if (!p)
325                 return;
326         memcpy(p, buffer, len+1);
327         type->description = p;
328 }
329
330
331 /*
332  * There are two ways to give cylinder size information:
333  *  - total amount of gas in cuft (depends on working pressure and physical size)
334  *  - physical size
335  *
336  * where "physical size" is the one that actually matters and is sane.
337  *
338  * We internally use physical size only. But we save the workingpressure
339  * so that we can do the conversion if required.
340  */
341 static void sanitize_cylinder_type(cylinder_type_t *type)
342 {
343         double volume_of_air, atm, volume;
344
345         /* If we have no working pressure, it had *better* be just a physical size! */
346         if (!type->workingpressure.mbar)
347                 return;
348
349         /* No size either? Nothing to go on */
350         if (!type->size.mliter)
351                 return;
352
353         if (input_units.volume == CUFT) {
354                 /* confusing - we don't really start from ml but millicuft !*/
355                 volume_of_air = cuft_to_l(type->size.mliter);
356                 atm = to_ATM(type->workingpressure);            /* working pressure in atm */
357                 volume = volume_of_air / atm;                   /* milliliters at 1 atm: "true size" */
358                 type->size.mliter = volume + 0.5;
359         }
360
361         /* Ok, we have both size and pressure: try to match a description */
362         match_standard_cylinder(type);
363 }
364
365 static void sanitize_cylinder_info(struct dive *dive)
366 {
367         int i;
368
369         for (i = 0; i < MAX_CYLINDERS; i++) {
370                 sanitize_gasmix(&dive->cylinder[i].gasmix);
371                 sanitize_cylinder_type(&dive->cylinder[i].type);
372         }
373 }
374
375 struct dive *fixup_dive(struct dive *dive)
376 {
377         int i,j;
378         double depthtime = 0;
379         int lasttime = 0;
380         int lastindex = -1;
381         int start = -1, end = -1;
382         int maxdepth = 0, mintemp = 0;
383         int lastdepth = 0;
384         int lasttemp = 0, lastpressure = 0;
385         int pressure_delta[MAX_CYLINDERS] = {INT_MAX, };
386
387         sanitize_cylinder_info(dive);
388         for (i = 0; i < dive->samples; i++) {
389                 struct sample *sample = dive->sample + i;
390                 int time = sample->time.seconds;
391                 int depth = sample->depth.mm;
392                 int temp = sample->temperature.mkelvin;
393                 int pressure = sample->cylinderpressure.mbar;
394                 int index = sample->cylinderindex;
395
396                 if (index == lastindex) {
397                         /* Remove duplicate redundant pressure information */
398                         if (pressure == lastpressure)
399                                 sample->cylinderpressure.mbar = 0;
400                         /* check for simply linear data in the samples
401                            +INT_MAX means uninitialized, -INT_MAX means not linear */
402                         if (pressure_delta[index] != -INT_MAX && lastpressure) {
403                                 if (pressure_delta[index] == INT_MAX) {
404                                         pressure_delta[index] = abs(pressure - lastpressure);
405                                 } else {
406                                         int cur_delta = abs(pressure - lastpressure);
407                                         if (cur_delta && abs(cur_delta - pressure_delta[index]) > 150) {
408                                                 /* ok the samples aren't just a linearisation
409                                                  * between start and end */
410                                                 pressure_delta[index] = -INT_MAX;
411                                         }
412                                 }
413                         }
414                 }
415                 lastindex = index;
416                 lastpressure = pressure;
417
418                 if (lastdepth)
419                         end = time;
420
421                 if (depth) {
422                         if (start < 0)
423                                 start = lasttime;
424                         if (depth > maxdepth)
425                                 maxdepth = depth;
426                 }
427
428                 fixup_pressure(dive, sample);
429
430                 if (temp) {
431                         /*
432                          * If we have consecutive identical
433                          * temperature readings, throw away
434                          * the redundant ones.
435                          */
436                         if (lasttemp == temp)
437                                 sample->temperature.mkelvin = 0;
438                         else
439                                 lasttemp = temp;
440
441                         if (!mintemp || temp < mintemp)
442                                 mintemp = temp;
443                 }
444                 depthtime += (time - lasttime) * (lastdepth + depth) / 2;
445                 lastdepth = depth;
446                 lasttime = time;
447         }
448         /* if all the samples for a cylinder have pressure data that
449          * is basically equidistant throw out the sample cylinder pressure
450          * information but make sure we still have a valid start and end
451          * pressure
452          * this happens when DivingLog decides to linearalize the
453          * pressure between beginning and end and for strange reasons
454          * decides to put that in the sample data as if it came from
455          * the dive computer; we don't want that (we'll visualize with
456          * constant SAC rate instead)
457          * WARNING WARNING - I have only seen this in single tank dives
458          * --- maybe I should try to create a multi tank dive and see what
459          * --- divinglog does there - but the code right now is only tested
460          * --- for the single tank case */
461         for (j = 0; j < MAX_CYLINDERS; j++) {
462                 if (abs(pressure_delta[j]) != INT_MAX) {
463                         cylinder_t *cyl = dive->cylinder + j;
464                         for (i = 0; i < dive->samples; i++)
465                                 if (dive->sample[i].cylinderindex == j)
466                                         dive->sample[i].cylinderpressure.mbar = 0;
467                         if (! cyl->start.mbar)
468                                 cyl->start.mbar = cyl->sample_start.mbar;
469                         if (! cyl->end.mbar)
470                                 cyl->end.mbar = cyl->sample_end.mbar;
471                         cyl->sample_start.mbar = 0;
472                         cyl->sample_end.mbar = 0;
473                 }
474         }
475         if (end < 0) {
476                 /* Assume an ascent/descent rate of 9 m/min */
477                 int depth = dive->maxdepth.mm;
478                 int asc_desc_time = depth*60/9000;
479                 int duration = dive->duration.seconds;
480
481                 /* Protect against insane dives - make mean be half of max */
482                 if (duration <= asc_desc_time) {
483                         duration = 2;
484                         asc_desc_time = 1;
485                 }
486                 dive->meandepth.mm = depth*(duration-asc_desc_time)/duration;
487                 return dive;
488         }
489
490         update_duration(&dive->duration, end - start);
491         if (start != end)
492                 depthtime /= (end - start);
493
494         update_depth(&dive->meandepth, depthtime);
495         update_temperature(&dive->watertemp, mintemp);
496         update_depth(&dive->maxdepth, maxdepth);
497
498         add_people(dive->buddy);
499         add_people(dive->divemaster);
500         add_location(dive->location);
501         add_suit(dive->suit);
502         for (i = 0; i < MAX_CYLINDERS; i++) {
503                 cylinder_t *cyl = dive->cylinder + i;
504                 add_cylinder_description(&cyl->type);
505                 if (same_rounded_pressure(cyl->sample_start, cyl->start))
506                         cyl->start.mbar = 0;
507                 if (same_rounded_pressure(cyl->sample_end, cyl->end))
508                         cyl->end.mbar = 0;
509         }
510         for (i = 0; i < MAX_WEIGHTSYSTEMS; i++) {
511                 weightsystem_t *ws = dive->weightsystem + i;
512                 add_weightsystem_description(ws);
513         }
514
515         return dive;
516 }
517
518 /* Don't pick a zero for MERGE_MIN() */
519 #define MERGE_MAX(res, a, b, n) res->n = MAX(a->n, b->n)
520 #define MERGE_MIN(res, a, b, n) res->n = (a->n)?(b->n)?MIN(a->n, b->n):(a->n):(b->n)
521 #define MERGE_TXT(res, a, b, n) res->n = merge_text(a->n, b->n)
522 #define MERGE_NONZERO(res, a, b, n) res->n = a->n ? a->n : b->n
523
524 static struct dive *add_sample(struct sample *sample, int time, struct dive *dive)
525 {
526         struct sample *p = prepare_sample(&dive);
527
528         if (!p)
529                 return NULL;
530         *p = *sample;
531         p->time.seconds = time;
532         finish_sample(dive);
533         return dive;
534 }
535
536 /*
537  * Merge samples. Dive 'a' is "offset" seconds before Dive 'b'
538  */
539 static struct dive *merge_samples(struct dive *res, struct dive *a, struct dive *b, int offset)
540 {
541         int asamples = a->samples;
542         int bsamples = b->samples;
543         struct sample *as = a->sample;
544         struct sample *bs = b->sample;
545
546         for (;;) {
547                 int at, bt;
548                 struct sample sample;
549
550                 if (!res)
551                         return NULL;
552
553                 at = asamples ? as->time.seconds : -1;
554                 bt = bsamples ? bs->time.seconds + offset : -1;
555
556                 /* No samples? All done! */
557                 if (at < 0 && bt < 0)
558                         return fixup_dive(res);
559
560                 /* Only samples from a? */
561                 if (bt < 0) {
562 add_sample_a:
563                         res = add_sample(as, at, res);
564                         as++;
565                         asamples--;
566                         continue;
567                 }
568
569                 /* Only samples from b? */
570                 if (at < 0) {
571 add_sample_b:
572                         res = add_sample(bs, bt, res);
573                         bs++;
574                         bsamples--;
575                         continue;
576                 }
577
578                 if (at < bt)
579                         goto add_sample_a;
580                 if (at > bt)
581                         goto add_sample_b;
582
583                 /* same-time sample: add a merged sample. Take the non-zero ones */
584                 sample = *bs;
585                 if (as->depth.mm)
586                         sample.depth = as->depth;
587                 if (as->temperature.mkelvin)
588                         sample.temperature = as->temperature;
589                 if (as->cylinderpressure.mbar)
590                         sample.cylinderpressure = as->cylinderpressure;
591                 if (as->cylinderindex)
592                         sample.cylinderindex = as->cylinderindex;
593
594                 res = add_sample(&sample, at, res);
595
596                 as++;
597                 bs++;
598                 asamples--;
599                 bsamples--;
600         }
601 }
602
603 static char *merge_text(const char *a, const char *b)
604 {
605         char *res;
606
607         if (!a || !*a)
608                 return (char *)b;
609         if (!b || !*b)
610                 return (char *)a;
611         if (!strcmp(a,b))
612                 return (char *)a;
613         res = malloc(strlen(a) + strlen(b) + 9);
614         if (!res)
615                 return (char *)a;
616         sprintf(res, "(%s) or (%s)", a, b);
617         return res;
618 }
619
620 #define SORT(a,b,field) \
621         if (a->field != b->field) return a->field < b->field ? -1 : 1
622
623 static int sort_event(struct event *a, struct event *b)
624 {
625         SORT(a,b,time.seconds);
626         SORT(a,b,type);
627         SORT(a,b,flags);
628         SORT(a,b,value);
629         return strcmp(a->name, b->name);
630 }
631
632 static void merge_events(struct dive *res, struct dive *src1, struct dive *src2, int offset)
633 {
634         struct event *a, *b;
635         struct event **p = &res->events;
636
637         a = src1->events;
638         b = src2->events;
639         while (b) {
640                 b->time.seconds += offset;
641                 b = b->next;
642         }
643         b = src2->events;
644
645         while (a || b) {
646                 int s;
647                 if (!b) {
648                         *p = a;
649                         break;
650                 }
651                 if (!a) {
652                         *p = b;
653                         break;
654                 }
655                 s = sort_event(a, b);
656                 /* Pick b */
657                 if (s > 0) {
658                         *p = b;
659                         p = &b->next;
660                         b = b->next;
661                         continue;
662                 }
663                 /* Pick 'a' or neither */
664                 if (s < 0) {
665                         *p = a;
666                         p = &a->next;
667                 }
668                 a = a->next;
669                 continue;
670         }
671 }
672
673 /* Pick whichever has any info (if either). Prefer 'a' */
674 static void merge_cylinder_type(cylinder_type_t *res, cylinder_type_t *a, cylinder_type_t *b)
675 {
676         if (a->size.mliter)
677                 b = a;
678         *res = *b;
679 }
680
681 static void merge_cylinder_mix(struct gasmix *res, struct gasmix *a, struct gasmix *b)
682 {
683         if (a->o2.permille)
684                 b = a;
685         *res = *b;
686 }
687
688 static void merge_cylinder_info(cylinder_t *res, cylinder_t *a, cylinder_t *b)
689 {
690         merge_cylinder_type(&res->type, &a->type, &b->type);
691         merge_cylinder_mix(&res->gasmix, &a->gasmix, &b->gasmix);
692         MERGE_MAX(res, a, b, start.mbar);
693         MERGE_MIN(res, a, b, end.mbar);
694 }
695
696 /*
697  * This could do a lot more merging. Right now it really only
698  * merges almost exact duplicates - something that happens easily
699  * with overlapping dive downloads.
700  */
701 struct dive *try_to_merge(struct dive *a, struct dive *b)
702 {
703         int i;
704         struct dive *res;
705
706         if ((a->when >= b->when + 60) || (a->when <= b->when - 60))
707                 return NULL;
708
709         res = alloc_dive();
710
711         res->when = a->when;
712         MERGE_NONZERO(res, a, b, latitude);
713         MERGE_NONZERO(res, a, b, longitude);
714         MERGE_TXT(res, a, b, location);
715         MERGE_TXT(res, a, b, notes);
716         MERGE_TXT(res, a, b, buddy);
717         MERGE_TXT(res, a, b, divemaster);
718         MERGE_MAX(res, a, b, rating);
719         MERGE_TXT(res, a, b, suit);
720         MERGE_MAX(res, a, b, number);
721         MERGE_MAX(res, a, b, maxdepth.mm);
722         res->meandepth.mm = 0;
723         MERGE_MAX(res, a, b, duration.seconds);
724         MERGE_MAX(res, a, b, surfacetime.seconds);
725         MERGE_MAX(res, a, b, airtemp.mkelvin);
726         MERGE_MIN(res, a, b, watertemp.mkelvin);
727         for (i = 0; i < MAX_CYLINDERS; i++)
728                 merge_cylinder_info(res->cylinder+i, a->cylinder + i, b->cylinder + i);
729         merge_events(res, a, b, 0);
730         return merge_samples(res, a, b, 0);
731 }