]> git.tdb.fi Git - ext/subsurface.git/blob - profile.c
Fix profile and average depth for freedives
[ext/subsurface.git] / profile.c
1 /* profile.c */
2 /* creates all the necessary data for drawing the dive profile
3  * uses cairo to draw it
4  */
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdarg.h>
8 #include <string.h>
9 #include <time.h>
10
11 #include "dive.h"
12 #include "display.h"
13 #include "divelist.h"
14 #include "color.h"
15
16 int selected_dive = 0;
17 char zoomed_plot = 0;
18
19 typedef enum { STABLE, SLOW, MODERATE, FAST, CRAZY } velocity_t;
20
21 /* Plot info with smoothing, velocity indication
22  * and one-, two- and three-minute minimums and maximums */
23 struct plot_info {
24         int nr;
25         int maxtime;
26         int meandepth, maxdepth;
27         int maxpressure;
28         int mintemp, maxtemp;
29         struct plot_data {
30                 unsigned int same_cylinder:1;
31                 unsigned int cylinderindex;
32                 int sec;
33                 /* pressure[0] is sensor pressure
34                  * pressure[1] is interpolated pressure */
35                 int pressure[2];
36                 int temperature;
37                 /* Depth info */
38                 int depth;
39                 int smoothed;
40                 velocity_t velocity;
41                 struct plot_data *min[3];
42                 struct plot_data *max[3];
43                 int avg[3];
44         } entry[];
45 };
46
47 #define SENSOR_PR 0
48 #define INTERPOLATED_PR 1
49 #define SENSOR_PRESSURE(_entry) (_entry)->pressure[SENSOR_PR]
50 #define INTERPOLATED_PRESSURE(_entry) (_entry)->pressure[INTERPOLATED_PR]
51 #define GET_PRESSURE(_entry) (SENSOR_PRESSURE(_entry) ? : INTERPOLATED_PRESSURE(_entry))
52
53 #define SAC_COLORS_START_IDX SAC_1
54 #define SAC_COLORS 9
55 #define VELOCITY_COLORS_START_IDX VELO_STABLE
56 #define VELOCITY_COLORS 5
57
58 typedef enum {
59         /* SAC colors. Order is important, the SAC_COLORS_START_IDX define above. */
60         SAC_1, SAC_2, SAC_3, SAC_4, SAC_5, SAC_6, SAC_7, SAC_8, SAC_9,
61
62         /* Velocity colors.  Order is still important, ref VELOCITY_COLORS_START_IDX. */
63         VELO_STABLE, VELO_SLOW, VELO_MODERATE, VELO_FAST, VELO_CRAZY,
64
65         /* Other colors */
66         TEXT_BACKGROUND, ALERT_BG, ALERT_FG, EVENTS, SAMPLE_DEEP, SAMPLE_SHALLOW,
67         SMOOTHED, MINUTE, TIME_GRID, TIME_TEXT, DEPTH_GRID, MEAN_DEPTH, DEPTH_TOP,
68         DEPTH_BOTTOM, TEMP_TEXT, TEMP_PLOT, SAC_DEFAULT, BOUNDING_BOX, PRESSURE_TEXT, BACKGROUND
69 } color_indice_t;
70
71 typedef struct {
72         /* media[0] is screen, and media[1] is printer */
73         struct rgba {
74                 double r,g,b,a;
75         } media[2];
76 } color_t;
77
78 /* [color indice] = {{screen color, printer color}} */
79 static const color_t profile_color[] = {
80         [SAC_1]           = {{FUNGREEN1, BLACK1_LOW_TRANS}},
81         [SAC_2]           = {{APPLE1, BLACK1_LOW_TRANS}},
82         [SAC_3]           = {{ATLANTIS1, BLACK1_LOW_TRANS}},
83         [SAC_4]           = {{ATLANTIS2, BLACK1_LOW_TRANS}},
84         [SAC_5]           = {{EARLSGREEN1, BLACK1_LOW_TRANS}},
85         [SAC_6]           = {{HOKEYPOKEY1, BLACK1_LOW_TRANS}},
86         [SAC_7]           = {{TUSCANY1, BLACK1_LOW_TRANS}},
87         [SAC_8]           = {{CINNABAR1, BLACK1_LOW_TRANS}},
88         [SAC_9]           = {{REDORANGE1, BLACK1_LOW_TRANS}},
89
90         [VELO_STABLE]     = {{CAMARONE1, BLACK1_LOW_TRANS}},
91         [VELO_SLOW]       = {{LIMENADE1, BLACK1_LOW_TRANS}},
92         [VELO_MODERATE]   = {{RIOGRANDE1, BLACK1_LOW_TRANS}},
93         [VELO_FAST]       = {{PIRATEGOLD1, BLACK1_LOW_TRANS}},
94         [VELO_CRAZY]      = {{RED1, BLACK1_LOW_TRANS}},
95
96         [TEXT_BACKGROUND] = {{CONCRETE1_LOWER_TRANS, WHITE1}},
97         [ALERT_BG]        = {{BROOM1_LOWER_TRANS, BLACK1_LOW_TRANS}},
98         [ALERT_FG]        = {{BLACK1_LOW_TRANS, BLACK1_LOW_TRANS}},
99         [EVENTS]          = {{REDORANGE1, BLACK1_LOW_TRANS}},
100         [SAMPLE_DEEP]     = {{PERSIANRED1, BLACK1_LOW_TRANS}},
101         [SAMPLE_SHALLOW]  = {{PERSIANRED1, BLACK1_LOW_TRANS}},
102         [SMOOTHED]        = {{REDORANGE1_HIGH_TRANS, BLACK1_LOW_TRANS}},
103         [MINUTE]          = {{MEDIUMREDVIOLET1_HIGHER_TRANS, BLACK1_LOW_TRANS}},
104         [TIME_GRID]       = {{WHITE1, TUNDORA1_MED_TRANS}},
105         [TIME_TEXT]       = {{FORESTGREEN1, BLACK1_LOW_TRANS}},
106         [DEPTH_GRID]      = {{WHITE1, TUNDORA1_MED_TRANS}},
107         [MEAN_DEPTH]      = {{REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS}},
108         [DEPTH_BOTTOM]    = {{GOVERNORBAY1_MED_TRANS, TUNDORA1_MED_TRANS}},
109         [DEPTH_TOP]       = {{MERCURY1_MED_TRANS, WHITE1_MED_TRANS}},
110         [TEMP_TEXT]       = {{GOVERNORBAY2, BLACK1_LOW_TRANS}},
111         [TEMP_PLOT]       = {{ROYALBLUE2_LOW_TRANS, BLACK1_LOW_TRANS}},
112         [SAC_DEFAULT]     = {{WHITE1, BLACK1_LOW_TRANS}},
113         [BOUNDING_BOX]    = {{WHITE1, BLACK1_LOW_TRANS}},
114         [PRESSURE_TEXT]   = {{KILLARNEY1, BLACK1_LOW_TRANS}},
115         [BACKGROUND]      = {{SPRINGWOOD1, BLACK1_LOW_TRANS}},
116 };
117
118 #define plot_info_size(nr) (sizeof(struct plot_info) + (nr)*sizeof(struct plot_data))
119
120 /* Scale to 0,0 -> maxx,maxy */
121 #define SCALEX(gc,x)  (((x)-gc->leftx)/(gc->rightx-gc->leftx)*gc->maxx)
122 #define SCALEY(gc,y)  (((y)-gc->topy)/(gc->bottomy-gc->topy)*gc->maxy)
123 #define SCALE(gc,x,y) SCALEX(gc,x),SCALEY(gc,y)
124
125 static void move_to(struct graphics_context *gc, double x, double y)
126 {
127         cairo_move_to(gc->cr, SCALE(gc, x, y));
128 }
129
130 static void line_to(struct graphics_context *gc, double x, double y)
131 {
132         cairo_line_to(gc->cr, SCALE(gc, x, y));
133 }
134
135 static void set_source_rgba(struct graphics_context *gc, color_indice_t c)
136 {
137         const color_t *col = &profile_color[c];
138         struct rgba rgb = col->media[gc->printer];
139         double r = rgb.r;
140         double g = rgb.g;
141         double b = rgb.b;
142         double a = rgb.a;
143
144         cairo_set_source_rgba(gc->cr, r, g, b, a);
145 }
146
147 void init_profile_background(struct graphics_context *gc)
148 {
149         set_source_rgba(gc, BACKGROUND);
150 }
151
152 void pattern_add_color_stop_rgba(struct graphics_context *gc, cairo_pattern_t *pat, double o, color_indice_t c)
153 {
154         const color_t *col = &profile_color[c];
155         struct rgba rgb = col->media[gc->printer];
156         cairo_pattern_add_color_stop_rgba(pat, o, rgb.r, rgb.g, rgb.b, rgb.a);
157 }
158
159 #define ROUND_UP(x,y) ((((x)+(y)-1)/(y))*(y))
160
161 /* debugging tool - not normally used */
162 static void dump_pi (struct plot_info *pi)
163 {
164         int i;
165
166         printf("pi:{nr:%d maxtime:%d meandepth:%d maxdepth:%d \n"
167                 "    maxpressure:%d mintemp:%d maxtemp:%d\n",
168                 pi->nr, pi->maxtime, pi->meandepth, pi->maxdepth,
169                 pi->maxpressure, pi->mintemp, pi->maxtemp);
170         for (i = 0; i < pi->nr; i++)
171                 printf("    entry[%d]:{same_cylinder:%d cylinderindex:%d sec:%d pressure:{%d,%d}\n"
172                         "                time:%d:%02d temperature:%d depth:%d smoothed:%d}\n",
173                         i, pi->entry[i].same_cylinder, pi->entry[i].cylinderindex, pi->entry[i].sec,
174                         pi->entry[i].pressure[0], pi->entry[i].pressure[1],
175                         pi->entry[i].sec / 60, pi->entry[i].sec % 60,
176                         pi->entry[i].temperature, pi->entry[i].depth, pi->entry[i].smoothed);
177         printf("   }\n");
178 }
179
180 /*
181  * When showing dive profiles, we scale things to the
182  * current dive. However, we don't scale past less than
183  * 30 minutes or 90 ft, just so that small dives show
184  * up as such unless zoom is enabled.
185  * We also need to add 180 seconds at the end so the min/max
186  * plots correctly
187  */
188 static int get_maxtime(struct plot_info *pi)
189 {
190         int seconds = pi->maxtime;
191         if (zoomed_plot) {
192                 /* Rounded up to one minute, with at least 2.5 minutes to
193                  * spare.
194                  * For dive times shorter than 10 minutes, we use seconds/4 to
195                  * calculate the space dynamically.
196                  * This is seamless since 600/4 = 150.
197                  */
198                 if ( seconds < 600 )
199                         return ROUND_UP(seconds+seconds/4, 60);
200                 else
201                         return ROUND_UP(seconds+150, 60);
202         } else {
203                 /* min 30 minutes, rounded up to 5 minutes, with at least 2.5 minutes to spare */
204                 return MAX(30*60, ROUND_UP(seconds+150, 60*5));
205         }
206 }
207
208 static int get_maxdepth(struct plot_info *pi)
209 {
210         unsigned mm = pi->maxdepth;
211         if (zoomed_plot) {
212                 /* Rounded up to 10m, with at least 3m to spare */
213                 return ROUND_UP(mm+3000, 10000);
214         } else {
215                 /* Minimum 30m, rounded up to 10m, with at least 3m to spare */
216                 return MAX(30000, ROUND_UP(mm+3000, 10000));
217         }
218 }
219
220 typedef struct {
221         int size;
222         color_indice_t color;
223         double hpos, vpos;
224 } text_render_options_t;
225
226 #define RIGHT (-1.0)
227 #define CENTER (-0.5)
228 #define LEFT (0.0)
229
230 #define TOP (1)
231 #define MIDDLE (0)
232 #define BOTTOM (-1)
233
234 static void plot_text(struct graphics_context *gc, const text_render_options_t *tro,
235                       double x, double y, const char *fmt, ...)
236 {
237         cairo_t *cr = gc->cr;
238         cairo_font_extents_t fe;
239         cairo_text_extents_t extents;
240         double dx, dy;
241         char buffer[80];
242         va_list args;
243
244         va_start(args, fmt);
245         vsnprintf(buffer, sizeof(buffer), fmt, args);
246         va_end(args);
247
248         cairo_set_font_size(cr, tro->size);
249         cairo_font_extents(cr, &fe);
250         cairo_text_extents(cr, buffer, &extents);
251         dx = tro->hpos * extents.width + extents.x_bearing;
252         dy = tro->vpos * extents.height + fe.descent;
253
254         move_to(gc, x, y);
255         cairo_rel_move_to(cr, dx, dy);
256
257         cairo_text_path(cr, buffer);
258         set_source_rgba(gc, TEXT_BACKGROUND);
259         cairo_stroke(cr);
260
261         move_to(gc, x, y);
262         cairo_rel_move_to(cr, dx, dy);
263
264         set_source_rgba(gc, tro->color);
265         cairo_show_text(cr, buffer);
266 }
267
268 struct ev_select {
269         char *ev_name;
270         gboolean plot_ev;
271 };
272 static struct ev_select *ev_namelist;
273 static int evn_allocated;
274 static int evn_used;
275
276 void evn_foreach(void (*callback)(const char *, int *, void *), void *data)
277 {
278         int i;
279
280         for (i = 0; i < evn_used; i++) {
281                 callback(ev_namelist[i].ev_name, &ev_namelist[i].plot_ev, data);
282         }
283 }
284
285 void remember_event(const char *eventname)
286 {
287         int i=0, len;
288
289         if (!eventname || (len = strlen(eventname)) == 0)
290                 return;
291         while (i < evn_used) {
292                 if (!strncmp(eventname,ev_namelist[i].ev_name,len))
293                         return;
294                 i++;
295         }
296         if (evn_used == evn_allocated) {
297                 evn_allocated += 10;
298                 ev_namelist = realloc(ev_namelist, evn_allocated * sizeof(struct ev_select));
299                 if (! ev_namelist)
300                         /* we are screwed, but let's just bail out */
301                         return;
302         }
303         ev_namelist[evn_used].ev_name = strdup(eventname);
304         ev_namelist[evn_used].plot_ev = TRUE;
305         evn_used++;
306 }
307
308 static void plot_one_event(struct graphics_context *gc, struct plot_info *pi, struct event *event, const text_render_options_t *tro)
309 {
310         int i, depth = 0;
311         int x,y;
312
313         /* is plotting this event disabled? */
314         if (event->name) {
315                 for (i = 0; i < evn_used; i++) {
316                         if (! strcmp(event->name, ev_namelist[i].ev_name)) {
317                                 if (ev_namelist[i].plot_ev)
318                                         break;
319                                 else
320                                         return;
321                         }
322                 }
323         }
324         for (i = 0; i < pi->nr; i++) {
325                 struct plot_data *data = pi->entry + i;
326                 if (event->time.seconds < data->sec)
327                         break;
328                 depth = data->depth;
329         }
330         /* draw a little tirangular marker and attach tooltip */
331         x = SCALEX(gc, event->time.seconds);
332         y = SCALEY(gc, depth);
333         set_source_rgba(gc, ALERT_BG);
334         cairo_move_to(gc->cr, x-15, y+6);
335         cairo_line_to(gc->cr, x-3  , y+6);
336         cairo_line_to(gc->cr, x-9, y-6);
337         cairo_line_to(gc->cr, x-15, y+6);
338         cairo_stroke_preserve(gc->cr);
339         cairo_fill(gc->cr);
340         set_source_rgba(gc, ALERT_FG);
341         cairo_move_to(gc->cr, x-9, y-3);
342         cairo_line_to(gc->cr, x-9, y+1);
343         cairo_move_to(gc->cr, x-9, y+4);
344         cairo_line_to(gc->cr, x-9, y+4);
345         cairo_stroke(gc->cr);
346         attach_tooltip(x-15, y-6, 12, 12, event->name);
347 }
348
349 static void plot_events(struct graphics_context *gc, struct plot_info *pi, struct dive *dive)
350 {
351         static const text_render_options_t tro = {14, EVENTS, CENTER, TOP};
352         struct event *event = dive->events;
353
354         if (gc->printer)
355                 return;
356
357         while (event) {
358                 plot_one_event(gc, pi, event, &tro);
359                 event = event->next;
360         }
361 }
362
363 static void render_depth_sample(struct graphics_context *gc, struct plot_data *entry, const text_render_options_t *tro)
364 {
365         int sec = entry->sec, decimals;
366         double d;
367
368         d = get_depth_units(entry->depth, &decimals, NULL);
369
370         plot_text(gc, tro, sec, entry->depth, "%.*f", decimals, d);
371 }
372
373 static void plot_text_samples(struct graphics_context *gc, struct plot_info *pi)
374 {
375         static const text_render_options_t deep = {14, SAMPLE_DEEP, CENTER, TOP};
376         static const text_render_options_t shallow = {14, SAMPLE_SHALLOW, CENTER, BOTTOM};
377         int i;
378         int last = -1;
379
380         for (i = 0; i < pi->nr; i++) {
381                 struct plot_data *entry = pi->entry + i;
382
383                 if (entry->depth < 2000)
384                         continue;
385
386                 if ((entry == entry->max[2]) && entry->depth != last) {
387                         render_depth_sample(gc, entry, &deep);
388                         last = entry->depth;
389                 }
390
391                 if ((entry == entry->min[2]) && entry->depth != last) {
392                         render_depth_sample(gc, entry, &shallow);
393                         last = entry->depth;
394                 }
395
396                 if (entry->depth != last)
397                         last = -1;
398         }
399 }
400
401 static void plot_depth_text(struct graphics_context *gc, struct plot_info *pi)
402 {
403         int maxtime, maxdepth;
404
405         /* Get plot scaling limits */
406         maxtime = get_maxtime(pi);
407         maxdepth = get_maxdepth(pi);
408
409         gc->leftx = 0; gc->rightx = maxtime;
410         gc->topy = 0; gc->bottomy = maxdepth;
411
412         plot_text_samples(gc, pi);
413 }
414
415 static void plot_smoothed_profile(struct graphics_context *gc, struct plot_info *pi)
416 {
417         int i;
418         struct plot_data *entry = pi->entry;
419
420         set_source_rgba(gc, SMOOTHED);
421         move_to(gc, entry->sec, entry->smoothed);
422         for (i = 1; i < pi->nr; i++) {
423                 entry++;
424                 line_to(gc, entry->sec, entry->smoothed);
425         }
426         cairo_stroke(gc->cr);
427 }
428
429 static void plot_minmax_profile_minute(struct graphics_context *gc, struct plot_info *pi,
430                                 int index)
431 {
432         int i;
433         struct plot_data *entry = pi->entry;
434
435         set_source_rgba(gc, MINUTE);
436         move_to(gc, entry->sec, entry->min[index]->depth);
437         for (i = 1; i < pi->nr; i++) {
438                 entry++;
439                 line_to(gc, entry->sec, entry->min[index]->depth);
440         }
441         for (i = 1; i < pi->nr; i++) {
442                 line_to(gc, entry->sec, entry->max[index]->depth);
443                 entry--;
444         }
445         cairo_close_path(gc->cr);
446         cairo_fill(gc->cr);
447 }
448
449 static void plot_minmax_profile(struct graphics_context *gc, struct plot_info *pi)
450 {
451         if (gc->printer)
452                 return;
453         plot_minmax_profile_minute(gc, pi, 2);
454         plot_minmax_profile_minute(gc, pi, 1);
455         plot_minmax_profile_minute(gc, pi, 0);
456 }
457
458 static void plot_depth_profile(struct graphics_context *gc, struct plot_info *pi)
459 {
460         int i, incr;
461         cairo_t *cr = gc->cr;
462         int sec, depth;
463         struct plot_data *entry;
464         int maxtime, maxdepth, marker;
465         int increments[8] = { 10, 20, 30, 60, 5*60, 10*60, 15*60, 30*60 };
466
467         /* Get plot scaling limits */
468         maxtime = get_maxtime(pi);
469         maxdepth = get_maxdepth(pi);
470
471         /* Time markers: at most every 10 seconds, but no more than 12 markers.
472          * We start out with 10 seconds and increment up to 30 minutes,
473          * depending on the dive time.
474          * This allows for 6h dives - enough (I hope) for even the craziest
475          * divers - but just in case, for those 8h depth-record-breaking dives,
476          * we double the interval if this still doesn't get us to 12 or fewer
477          * time markers */
478         i = 0;
479         while (maxtime / increments[i] > 12 && i < 8)
480                 i++;
481         incr = increments[i];
482         while (maxtime / incr > 12)
483                 incr *= 2;
484
485         gc->leftx = 0; gc->rightx = maxtime;
486         gc->topy = 0; gc->bottomy = 1.0;
487         set_source_rgba(gc, TIME_GRID);
488         cairo_set_line_width(gc->cr, 2);
489
490         for (i = incr; i < maxtime; i += incr) {
491                 move_to(gc, i, 0);
492                 line_to(gc, i, 1);
493         }
494         cairo_stroke(cr);
495
496         /* now the text on the time markers */
497         text_render_options_t tro = {10, TIME_TEXT, CENTER, TOP};
498         if (maxtime < 600) {
499                 /* Be a bit more verbose with shorter dives */
500                 for (i = incr; i < maxtime; i += incr)
501                         plot_text(gc, &tro, i, 1, "%02d:%02d", i/60, i%60);
502         } else {
503                 /* Only render the time on every second marker for normal dives */
504                 for (i = incr; i < maxtime; i += 2 * incr)
505                         plot_text(gc, &tro, i, 1, "%d", i/60);
506         }
507         /* Depth markers: every 30 ft or 10 m*/
508         gc->leftx = 0; gc->rightx = 1.0;
509         gc->topy = 0; gc->bottomy = maxdepth;
510         switch (output_units.length) {
511         case METERS: marker = 10000; break;
512         case FEET: marker = 9144; break;        /* 30 ft */
513         }
514
515         set_source_rgba(gc, DEPTH_GRID);
516         for (i = marker; i < maxdepth; i += marker) {
517                 move_to(gc, 0, i);
518                 line_to(gc, 1, i);
519         }
520         cairo_stroke(cr);
521
522         /* Show mean depth */
523         if (! gc->printer) {
524                 set_source_rgba(gc, MEAN_DEPTH);
525                 move_to(gc, 0, pi->meandepth);
526                 line_to(gc, 1, pi->meandepth);
527                 cairo_stroke(cr);
528         }
529
530         gc->leftx = 0; gc->rightx = maxtime;
531
532         /*
533          * These are good for debugging text placement etc,
534          * but not for actual display..
535          */
536         if (0) {
537                 plot_smoothed_profile(gc, pi);
538                 plot_minmax_profile(gc, pi);
539         }
540
541         /* Do the depth profile for the neat fill */
542         gc->topy = 0; gc->bottomy = maxdepth;
543
544         cairo_pattern_t *pat;
545         pat = cairo_pattern_create_linear (0.0, 0.0,  0.0, 256.0);
546         pattern_add_color_stop_rgba (gc, pat, 1, DEPTH_BOTTOM);
547         pattern_add_color_stop_rgba (gc, pat, 0, DEPTH_TOP);
548
549         cairo_set_source(gc->cr, pat);
550         cairo_pattern_destroy(pat);
551         cairo_set_line_width(gc->cr, 2);
552
553         entry = pi->entry;
554         move_to(gc, 0, 0);
555         for (i = 0; i < pi->nr; i++, entry++)
556                 line_to(gc, entry->sec, entry->depth);
557         cairo_close_path(gc->cr);
558
559         cairo_fill(gc->cr);
560
561         /* Now do it again for the velocity colors */
562         entry = pi->entry;
563         for (i = 1; i < pi->nr; i++) {
564                 entry++;
565                 sec = entry->sec;
566                 /* we want to draw the segments in different colors
567                  * representing the vertical velocity, so we need to
568                  * chop this into short segments */
569                 depth = entry->depth;
570                 set_source_rgba(gc, VELOCITY_COLORS_START_IDX + entry->velocity);
571                 move_to(gc, entry[-1].sec, entry[-1].depth);
572                 line_to(gc, sec, depth);
573                 cairo_stroke(cr);
574         }
575 }
576
577 static int setup_temperature_limits(struct graphics_context *gc, struct plot_info *pi)
578 {
579         int maxtime, mintemp, maxtemp, delta;
580
581         /* Get plot scaling limits */
582         maxtime = get_maxtime(pi);
583         mintemp = pi->mintemp;
584         maxtemp = pi->maxtemp;
585
586         gc->leftx = 0; gc->rightx = maxtime;
587         /* Show temperatures in roughly the lower third, but make sure the scale
588            is at least somewhat reasonable */
589         delta = maxtemp - mintemp;
590         if (delta > 3000) { /* more than 3K in fluctuation */
591                 gc->topy = maxtemp + delta*2;
592                 gc->bottomy = mintemp - delta/2;
593         } else {
594                 gc->topy = maxtemp + 1500 + delta*2;
595                 gc->bottomy = mintemp - delta/2;
596         }
597
598         return maxtemp > mintemp;
599 }
600
601 static void plot_single_temp_text(struct graphics_context *gc, int sec, int mkelvin)
602 {
603         double deg;
604         const char *unit;
605         static const text_render_options_t tro = {12, TEMP_TEXT, LEFT, TOP};
606
607         deg = get_temp_units(mkelvin, &unit);
608
609         plot_text(gc, &tro, sec, mkelvin, "%d%s", (int)(deg + 0.5), unit);
610 }
611
612 static void plot_temperature_text(struct graphics_context *gc, struct plot_info *pi)
613 {
614         int i;
615         int last = -300, sec = 0;
616         int last_temperature = 0, last_printed_temp = 0;
617
618         if (!setup_temperature_limits(gc, pi))
619                 return;
620
621         for (i = 0; i < pi->nr; i++) {
622                 struct plot_data *entry = pi->entry+i;
623                 int mkelvin = entry->temperature;
624
625                 if (!mkelvin)
626                         continue;
627                 last_temperature = mkelvin;
628                 sec = entry->sec;
629                 /* don't print a temperature
630                  * if it's been less than 5min and less than a 2K change OR
631                  * if it's been less than 2min OR if the change from the
632                  * last print is less than .4K (and therefore less than 1F */
633                 if (((sec < last + 300) && (abs(mkelvin - last_printed_temp) < 2000)) ||
634                         (sec < last + 120) ||
635                         (abs(mkelvin - last_printed_temp) < 400))
636                         continue;
637                 last = sec;
638                 plot_single_temp_text(gc,sec,mkelvin);
639                 last_printed_temp = mkelvin;
640         }
641         /* it would be nice to print the end temperature, if it's
642          * different or if the last temperature print has been more
643          * than a quarter of the dive back */
644         if ((abs(last_temperature - last_printed_temp) > 500) ||
645                 ((double)last / (double)sec < 0.75))
646                 plot_single_temp_text(gc, sec, last_temperature);
647 }
648
649 static void plot_temperature_profile(struct graphics_context *gc, struct plot_info *pi)
650 {
651         int i;
652         cairo_t *cr = gc->cr;
653         int last = 0;
654
655         if (!setup_temperature_limits(gc, pi))
656                 return;
657
658         cairo_set_line_width(gc->cr, 2);
659         set_source_rgba(gc, TEMP_PLOT);
660         for (i = 0; i < pi->nr; i++) {
661                 struct plot_data *entry = pi->entry + i;
662                 int mkelvin = entry->temperature;
663                 int sec = entry->sec;
664                 if (!mkelvin) {
665                         if (!last)
666                                 continue;
667                         mkelvin = last;
668                 }
669                 if (last)
670                         line_to(gc, sec, mkelvin);
671                 else
672                         move_to(gc, sec, mkelvin);
673                 last = mkelvin;
674         }
675         cairo_stroke(cr);
676 }
677
678 /* gets both the actual start and end pressure as well as the scaling factors */
679 static int get_cylinder_pressure_range(struct graphics_context *gc, struct plot_info *pi)
680 {
681         gc->leftx = 0;
682         gc->rightx = get_maxtime(pi);
683
684         gc->bottomy = 0; gc->topy = pi->maxpressure * 1.5;
685         return pi->maxpressure != 0;
686 }
687
688 /* set the color for the pressure plot according to temporary sac rate
689  * as compared to avg_sac; the calculation simply maps the delta between
690  * sac and avg_sac to indexes 0 .. (SAC_COLORS - 1) with everything
691  * more than 6000 ml/min below avg_sac mapped to 0 */
692
693 static void set_sac_color(struct graphics_context *gc, int sac, int avg_sac)
694 {
695         int sac_index = 0;
696         int delta = sac - avg_sac + 7000;
697
698         if (!gc->printer) {
699                 sac_index = delta / 2000;
700                 if (sac_index < 0)
701                         sac_index = 0;
702                 if (sac_index > SAC_COLORS - 1)
703                         sac_index = SAC_COLORS - 1;
704                 set_source_rgba(gc, SAC_COLORS_START_IDX + sac_index);
705         } else {
706                 set_source_rgba(gc, SAC_DEFAULT);
707         }
708 }
709
710 /* calculate the current SAC in ml/min and convert to int */
711 #define GET_LOCAL_SAC(_entry1, _entry2, _dive)  (int)                           \
712         ((GET_PRESSURE((_entry1)) - GET_PRESSURE((_entry2))) *                  \
713                 (_dive)->cylinder[(_entry1)->cylinderindex].type.size.mliter /  \
714                 (((_entry2)->sec - (_entry1)->sec) / 60.0) /                    \
715                 (1 + ((_entry1)->depth + (_entry2)->depth) / 20000.0) /         \
716                 1000.0)
717
718 #define SAC_WINDOW 45   /* sliding window in seconds for current SAC calculation */
719
720 static void plot_cylinder_pressure(struct graphics_context *gc, struct plot_info *pi,
721                                 struct dive *dive)
722 {
723         int i;
724         int last = -1;
725         int lift_pen = FALSE;
726         int first_plot = TRUE;
727         int sac = 0;
728         struct plot_data *last_entry = NULL;
729
730         if (!get_cylinder_pressure_range(gc, pi))
731                 return;
732
733         cairo_set_line_width(gc->cr, 2);
734
735         for (i = 0; i < pi->nr; i++) {
736                 int mbar;
737                 struct plot_data *entry = pi->entry + i;
738
739                 mbar = GET_PRESSURE(entry);
740                 if (!entry->same_cylinder) {
741                         lift_pen = TRUE;
742                         last_entry = NULL;
743                 }
744                 if (!mbar) {
745                         lift_pen = TRUE;
746                         continue;
747                 }
748                 if (!last_entry) {
749                         last = i;
750                         last_entry = entry;
751                         sac = GET_LOCAL_SAC(entry, pi->entry + i + 1, dive);
752                 } else {
753                         int j;
754                         sac = 0;
755                         for (j = last; j < i; j++)
756                                 sac += GET_LOCAL_SAC(pi->entry + j, pi->entry + j + 1, dive);
757                         sac /= (i - last);
758                         if (entry->sec - last_entry->sec >= SAC_WINDOW) {
759                                 last++;
760                                 last_entry = pi->entry + last;
761                         }
762                 }
763                 set_sac_color(gc, sac, dive->sac);
764                 if (lift_pen) {
765                         if (!first_plot && entry->same_cylinder) {
766                                 /* if we have a previous event from the same tank,
767                                  * draw at least a short line */
768                                 int prev_pr;
769                                 prev_pr = GET_PRESSURE(entry - 1);
770                                 move_to(gc, (entry-1)->sec, prev_pr);
771                                 line_to(gc, entry->sec, mbar);
772                         } else {
773                                 first_plot = FALSE;
774                                 move_to(gc, entry->sec, mbar);
775                         }
776                         lift_pen = FALSE;
777                 } else {
778                         line_to(gc, entry->sec, mbar);
779                 }
780                 cairo_stroke(gc->cr);
781                 move_to(gc, entry->sec, mbar);
782         }
783 }
784
785 static void plot_pressure_value(struct graphics_context *gc, int mbar, int sec,
786                                 int xalign, int yalign)
787 {
788         int pressure;
789         const char *unit;
790
791         pressure = get_pressure_units(mbar, &unit);
792         text_render_options_t tro = {10, PRESSURE_TEXT, xalign, yalign};
793         plot_text(gc, &tro, sec, mbar, "%d %s", pressure, unit);
794 }
795
796 static void plot_cylinder_pressure_text(struct graphics_context *gc, struct plot_info *pi)
797 {
798         int i;
799         int mbar, cyl;
800         int seen_cyl[MAX_CYLINDERS] = { FALSE, };
801         int last_pressure[MAX_CYLINDERS] = { 0, };
802         int last_time[MAX_CYLINDERS] = { 0, };
803         struct plot_data *entry;
804
805         if (!get_cylinder_pressure_range(gc, pi))
806                 return;
807
808         /* only loop over the actual events from the dive computer
809          * plus the second synthetic event at the start (to make sure
810          * we get "time=0" right)
811          * sadly with a recent change that first entry may no longer
812          * have any pressure reading - in that case just grab the
813          * pressure from the second entry */
814         if (GET_PRESSURE(pi->entry + 1) == 0 && GET_PRESSURE(pi->entry + 2) !=0)
815                 INTERPOLATED_PRESSURE(pi->entry + 1) = GET_PRESSURE(pi->entry + 2);
816         for (i = 1; i < pi->nr; i++) {
817                 entry = pi->entry + i;
818
819                 if (!entry->same_cylinder) {
820                         cyl = entry->cylinderindex;
821                         if (!seen_cyl[cyl]) {
822                                 mbar = GET_PRESSURE(entry);
823                                 plot_pressure_value(gc, mbar, entry->sec, LEFT, BOTTOM);
824                                 seen_cyl[cyl] = TRUE;
825                         }
826                         if (i > 2) {
827                                 /* remember the last pressure and time of
828                                  * the previous cylinder */
829                                 cyl = (entry - 1)->cylinderindex;
830                                 last_pressure[cyl] = GET_PRESSURE(entry - 1);
831                                 last_time[cyl] = (entry - 1)->sec;
832                         }
833                 }
834         }
835         cyl = entry->cylinderindex;
836         if (GET_PRESSURE(entry))
837                 last_pressure[cyl] = GET_PRESSURE(entry);
838         last_time[cyl] = entry->sec;
839
840         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) {
841                 if (last_time[cyl]) {
842                         plot_pressure_value(gc, last_pressure[cyl], last_time[cyl], CENTER, TOP);
843                 }
844         }
845 }
846
847 static void analyze_plot_info_minmax_minute(struct plot_data *entry, struct plot_data *first, struct plot_data *last, int index)
848 {
849         struct plot_data *p = entry;
850         int time = entry->sec;
851         int seconds = 90*(index+1);
852         struct plot_data *min, *max;
853         int avg, nr;
854
855         /* Go back 'seconds' in time */
856         while (p > first) {
857                 if (p[-1].sec < time - seconds)
858                         break;
859                 p--;
860         }
861
862         /* Then go forward until we hit an entry past the time */
863         min = max = p;
864         avg = p->depth;
865         nr = 1;
866         while (++p < last) {
867                 int depth = p->depth;
868                 if (p->sec > time + seconds)
869                         break;
870                 avg += depth;
871                 nr ++;
872                 if (depth < min->depth)
873                         min = p;
874                 if (depth > max->depth)
875                         max = p;
876         }
877         entry->min[index] = min;
878         entry->max[index] = max;
879         entry->avg[index] = (avg + nr/2) / nr;
880 }
881
882 static void analyze_plot_info_minmax(struct plot_data *entry, struct plot_data *first, struct plot_data *last)
883 {
884         analyze_plot_info_minmax_minute(entry, first, last, 0);
885         analyze_plot_info_minmax_minute(entry, first, last, 1);
886         analyze_plot_info_minmax_minute(entry, first, last, 2);
887 }
888
889 static velocity_t velocity(int speed)
890 {
891         velocity_t v;
892
893         if (speed < -304) /* ascent faster than -60ft/min */
894                 v = CRAZY;
895         else if (speed < -152) /* above -30ft/min */
896                 v = FAST;
897         else if (speed < -76) /* -15ft/min */
898                 v = MODERATE;
899         else if (speed < -25) /* -5ft/min */
900                 v = SLOW;
901         else if (speed < 25) /* very hard to find data, but it appears that the recommendations
902                                 for descent are usually about 2x ascent rate; still, we want
903                                 stable to mean stable */
904                 v = STABLE;
905         else if (speed < 152) /* between 5 and 30ft/min is considered slow */
906                 v = SLOW;
907         else if (speed < 304) /* up to 60ft/min is moderate */
908                 v = MODERATE;
909         else if (speed < 507) /* up to 100ft/min is fast */
910                 v = FAST;
911         else /* more than that is just crazy - you'll blow your ears out */
912                 v = CRAZY;
913
914         return v;
915 }
916 static struct plot_info *analyze_plot_info(struct plot_info *pi)
917 {
918         int i;
919         int nr = pi->nr;
920
921         /* Do pressure min/max based on the non-surface data */
922         for (i = 0; i < nr; i++) {
923                 struct plot_data *entry = pi->entry+i;
924                 int pressure = GET_PRESSURE(entry);
925                 int temperature = entry->temperature;
926
927                 if (pressure) {
928                         if (pressure > pi->maxpressure)
929                                 pi->maxpressure = pressure;
930                 }
931
932                 if (temperature) {
933                         if (!pi->mintemp || temperature < pi->mintemp)
934                                 pi->mintemp = temperature;
935                         if (temperature > pi->maxtemp)
936                                 pi->maxtemp = temperature;
937                 }
938         }
939
940         /* Smoothing function: 5-point triangular smooth */
941         for (i = 2; i < nr; i++) {
942                 struct plot_data *entry = pi->entry+i;
943                 int depth;
944
945                 if (i < nr-2) {
946                         depth = entry[-2].depth + 2*entry[-1].depth + 3*entry[0].depth + 2*entry[1].depth + entry[2].depth;
947                         entry->smoothed = (depth+4) / 9;
948                 }
949                 /* vertical velocity in mm/sec */
950                 /* Linus wants to smooth this - let's at least look at the samples that aren't FAST or CRAZY */
951                 if (entry[0].sec - entry[-1].sec) {
952                         entry->velocity = velocity((entry[0].depth - entry[-1].depth) / (entry[0].sec - entry[-1].sec));
953                         /* if our samples are short and we aren't too FAST*/
954                         if (entry[0].sec - entry[-1].sec < 15 && entry->velocity < FAST) {
955                                 int past = -2;
956                                 while (i+past > 0 && entry[0].sec - entry[past].sec < 15)
957                                         past--;
958                                 entry->velocity = velocity((entry[0].depth - entry[past].depth) /
959                                                         (entry[0].sec - entry[past].sec));
960                         }
961                 } else
962                         entry->velocity = STABLE;
963         }
964
965         /* One-, two- and three-minute minmax data */
966         for (i = 0; i < nr; i++) {
967                 struct plot_data *entry = pi->entry +i;
968                 analyze_plot_info_minmax(entry, pi->entry, pi->entry+nr);
969         }
970
971         return pi;
972 }
973
974 /*
975  * simple structure to track the beginning and end tank pressure as
976  * well as the integral of depth over time spent while we have no
977  * pressure reading from the tank */
978 typedef struct pr_track_struct pr_track_t;
979 struct pr_track_struct {
980         int start;
981         int end;
982         int t_start;
983         int t_end;
984         double pressure_time;
985         pr_track_t *next;
986 };
987
988 static pr_track_t *pr_track_alloc(int start, int t_start) {
989         pr_track_t *pt = malloc(sizeof(pr_track_t));
990         pt->start = start;
991         pt->t_start = t_start;
992         pt->end = 0;
993         pt->t_end = 0;
994         pt->pressure_time = 0.0;
995         pt->next = NULL;
996         return pt;
997 }
998
999 /* poor man's linked list */
1000 static pr_track_t *list_last(pr_track_t *list)
1001 {
1002         pr_track_t *tail = list;
1003         if (!tail)
1004                 return NULL;
1005         while (tail->next) {
1006                 tail = tail->next;
1007         }
1008         return tail;
1009 }
1010
1011 static pr_track_t *list_add(pr_track_t *list, pr_track_t *element)
1012 {
1013         pr_track_t *tail = list_last(list);
1014         if (!tail)
1015                 return element;
1016         tail->next = element;
1017         return list;
1018 }
1019
1020 static void list_free(pr_track_t *list)
1021 {
1022         if (!list)
1023                 return;
1024         list_free(list->next);
1025         free(list);
1026 }
1027
1028 static void dump_pr_track(pr_track_t **track_pr)
1029 {
1030         int cyl;
1031         pr_track_t *list;
1032
1033         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) {
1034                 list = track_pr[cyl];
1035                 while (list) {
1036                         printf("cyl%d: start %d end %d t_start %d t_end %d pt %6.3f\n", cyl,
1037                                 list->start, list->end, list->t_start, list->t_end, list->pressure_time);
1038                         list = list->next;
1039                 }
1040         }
1041 }
1042
1043 static void fill_missing_tank_pressures(struct plot_info *pi, pr_track_t **track_pr)
1044 {
1045         pr_track_t *list = NULL;
1046         pr_track_t *nlist = NULL;
1047         double pt, magic;
1048         int cyl, i;
1049         struct plot_data *entry;
1050         int cur_pr[MAX_CYLINDERS];
1051
1052         if (0) {
1053                 /* another great debugging tool */
1054                 dump_pr_track(track_pr);
1055         }
1056         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) {
1057                 cur_pr[cyl] = track_pr[cyl]->start;
1058         }
1059
1060         /* The first two are "fillers", but in case we don't have a sample
1061          * at time 0 we need to process the second of them here */
1062         for (i = 1; i < pi->nr; i++) {
1063                 entry = pi->entry + i;
1064                 if (SENSOR_PRESSURE(entry)) {
1065                         cur_pr[entry->cylinderindex] = SENSOR_PRESSURE(entry);
1066                 } else {
1067                         if(!list || list->t_end < entry->sec) {
1068                                 nlist = track_pr[entry->cylinderindex];
1069                                 list = NULL;
1070                                 while (nlist && nlist->t_start <= entry->sec) {
1071                                         list = nlist;
1072                                         nlist = list->next;
1073                                 }
1074                                 /* there may be multiple segments - so
1075                                  * let's assemble the length */
1076                                 nlist = list;
1077                                 if (list) {
1078                                         pt = list->pressure_time;
1079                                         while (!nlist->end) {
1080                                                 nlist = nlist->next;
1081                                                 if (!nlist) {
1082                                                         /* oops - we have no end pressure,
1083                                                          * so this means this is a tank without
1084                                                          * gas consumption information */
1085                                                         break;
1086                                                 }
1087                                                 pt += nlist->pressure_time;
1088                                         }
1089                                 }
1090                                 if (!nlist) {
1091                                         /* just continue without calculating
1092                                          * interpolated values */
1093                                         INTERPOLATED_PRESSURE(entry) = cur_pr[entry->cylinderindex];
1094                                         list = NULL;
1095                                         continue;
1096                                 }
1097                                 magic = (nlist->end - cur_pr[entry->cylinderindex]) / pt;
1098                         }
1099                         if (pt != 0.0) {
1100                                 double cur_pt = (entry->sec - (entry-1)->sec) *
1101                                         (1 + (entry->depth + (entry-1)->depth) / 20000.0);
1102                                 INTERPOLATED_PRESSURE(entry) =
1103                                         cur_pr[entry->cylinderindex] + cur_pt * magic + 0.5;
1104                                 cur_pr[entry->cylinderindex] = INTERPOLATED_PRESSURE(entry);
1105                         } else
1106                                 INTERPOLATED_PRESSURE(entry) = cur_pr[entry->cylinderindex];
1107                 }
1108         }
1109 }
1110
1111 static int get_cylinder_index(struct dive *dive, struct event *ev)
1112 {
1113         int i;
1114
1115         /*
1116          * Try to find a cylinder that matches the O2 percentage
1117          * in the gas change event 'value' field.
1118          *
1119          * Crazy suunto gas change events. We really should do
1120          * this in libdivecomputer or something.
1121          */
1122         for (i = 0; i < MAX_CYLINDERS; i++) {
1123                 cylinder_t *cyl = dive->cylinder+i;
1124                 int o2 = (cyl->gasmix.o2.permille + 5) / 10;
1125                 if (o2 == ev->value)
1126                         return i;
1127         }
1128
1129         return 0;
1130 }
1131
1132 static struct event *get_next_gaschange(struct event *event)
1133 {
1134         while (event) {
1135                 if (!strcmp(event->name, "gaschange"))
1136                         return event;
1137                 event = event->next;
1138         }
1139         return event;
1140 }
1141
1142 static int set_cylinder_index(struct plot_info *pi, int i, int cylinderindex, unsigned int end)
1143 {
1144         while (i < pi->nr) {
1145                 struct plot_data *entry = pi->entry+i;
1146                 if (entry->sec > end)
1147                         break;
1148                 if (entry->cylinderindex != cylinderindex) {
1149                         entry->cylinderindex = cylinderindex;
1150                         entry->pressure[0] = 0;
1151                 }
1152                 i++;
1153         }
1154         return i;
1155 }
1156
1157 static void check_gas_change_events(struct dive *dive, struct plot_info *pi)
1158 {
1159         int i = 0, cylinderindex = 0;
1160         struct event *ev = get_next_gaschange(dive->events);
1161
1162         if (!ev)
1163                 return;
1164
1165         do {
1166                 i = set_cylinder_index(pi, i, cylinderindex, ev->time.seconds);
1167                 cylinderindex = get_cylinder_index(dive, ev);
1168                 ev = get_next_gaschange(ev->next);
1169         } while (ev);
1170         set_cylinder_index(pi, i, cylinderindex, ~0u);
1171 }
1172
1173 /* for computers that track gas changes through events */
1174 static int count_gas_change_events(struct dive *dive)
1175 {
1176         int count = 0;
1177         struct event *ev = get_next_gaschange(dive->events);
1178
1179         while (ev) {
1180                 count++;
1181                 ev = get_next_gaschange(ev->next);
1182         }
1183         return count;
1184 }
1185
1186 /*
1187  * Create a plot-info with smoothing and ranged min/max
1188  *
1189  * This also makes sure that we have extra empty events on both
1190  * sides, so that you can do end-points without having to worry
1191  * about it.
1192  */
1193 static struct plot_info *create_plot_info(struct dive *dive, int nr_samples, struct sample *dive_sample)
1194 {
1195         int cylinderindex = -1;
1196         int lastdepth, lastindex;
1197         int i, pi_idx, nr, sec, cyl;
1198         size_t alloc_size;
1199         struct plot_info *pi;
1200         pr_track_t *track_pr[MAX_CYLINDERS] = {NULL, };
1201         pr_track_t *pr_track, *current;
1202         gboolean missing_pr = FALSE;
1203         struct plot_data *entry = NULL;
1204         struct event *ev;
1205
1206         /* we want to potentially add synthetic plot_info elements for the gas changes */
1207         nr = nr_samples + 4 + 2 * count_gas_change_events(dive);
1208         alloc_size = plot_info_size(nr);
1209         pi = malloc(alloc_size);
1210         if (!pi)
1211                 return pi;
1212         memset(pi, 0, alloc_size);
1213         pi->nr = nr;
1214         pi_idx = 2; /* the two extra events at the start */
1215         /* check for gas changes before the samples start */
1216         ev = get_next_gaschange(dive->events);
1217         while (ev && ev->time.seconds < dive_sample->time.seconds) {
1218                 entry = pi->entry + pi_idx;
1219                 entry->sec = ev->time.seconds;
1220                 entry->depth = 0; /* is that always correct ? */
1221                 pi_idx++;
1222                 ev = get_next_gaschange(ev->next);
1223         }
1224         if (ev && ev->time.seconds == dive_sample->time.seconds) {
1225                 /* we already have a sample at the time of the event */
1226                 ev = get_next_gaschange(ev->next);
1227         }
1228         sec = 0;
1229         lastindex = 0;
1230         lastdepth = -1;
1231         for (i = 0; i < nr_samples; i++) {
1232                 int depth;
1233                 int delay = 0;
1234                 struct sample *sample = dive_sample+i;
1235
1236                 entry = pi->entry + i + pi_idx;
1237                 while (ev && ev->time.seconds < sample->time.seconds) {
1238                         /* insert two fake plot info structures for the end of
1239                          * the old tank and the start of the new tank */
1240                         if (ev->time.seconds == sample->time.seconds - 1) {
1241                                 entry->sec = ev->time.seconds - 1;
1242                                 (entry+1)->sec = ev->time.seconds;
1243                         } else {
1244                                 entry->sec = ev->time.seconds;
1245                                 (entry+1)->sec = ev->time.seconds + 1;
1246                         }
1247                         /* we need a fake depth - let's interpolate */
1248                         if (i) {
1249                                 entry->depth = sample->depth.mm -
1250                                         (sample->depth.mm - (sample-1)->depth.mm) / 2;
1251                         } else
1252                                 entry->depth = sample->depth.mm;
1253                         (entry+1)->depth = entry->depth;
1254                         pi_idx += 2;
1255                         entry = pi->entry + i + pi_idx;
1256                         ev = get_next_gaschange(ev->next);
1257                 }
1258                 if (ev && ev->time.seconds == sample->time.seconds) {
1259                         /* we already have a sample at the time of the event
1260                          * just add a new one for the old tank and delay the
1261                          * real even by one second (to keep time monotonous) */
1262                         entry->sec = ev->time.seconds;
1263                         entry->depth = sample->depth.mm;
1264                         pi_idx++;
1265                         entry = pi->entry + i + pi_idx;
1266                         ev = get_next_gaschange(ev->next);
1267                         delay = 1;
1268                 }
1269                 sec = entry->sec = sample->time.seconds + delay;
1270                 depth = entry->depth = sample->depth.mm;
1271                 entry->cylinderindex = sample->cylinderindex;
1272                 SENSOR_PRESSURE(entry) = sample->cylinderpressure.mbar;
1273                 entry->temperature = sample->temperature.mkelvin;
1274
1275                 if (depth || lastdepth)
1276                         lastindex = i + pi_idx;
1277
1278                 lastdepth = depth;
1279                 if (depth > pi->maxdepth)
1280                         pi->maxdepth = depth;
1281         }
1282         entry = pi->entry + i + pi_idx;
1283         /* are there still unprocessed gas changes? that would be very strange */
1284         while (ev) {
1285                 entry->sec = ev->time.seconds;
1286                 entry->depth = 0; /* why are there gas changes after the dive is over? */
1287                 pi_idx++;
1288                 entry = pi->entry + i + pi_idx;
1289                 ev = get_next_gaschange(ev->next);
1290         }
1291         nr = nr_samples + pi_idx - 2;
1292         check_gas_change_events(dive, pi);
1293
1294         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) /* initialize the start pressures */
1295                 track_pr[cyl] = pr_track_alloc(dive->cylinder[cyl].start.mbar, -1);
1296         current = track_pr[pi->entry[2].cylinderindex];
1297         for (i = 0; i < nr + 1; i++) {
1298                 entry = pi->entry + i + 1;
1299
1300                 entry->same_cylinder = entry->cylinderindex == cylinderindex;
1301                 cylinderindex = entry->cylinderindex;
1302
1303                 /* track the segments per cylinder and their pressure/time integral */
1304                 if (!entry->same_cylinder) {
1305                         current->end = SENSOR_PRESSURE(entry-1);
1306                         current->t_end = (entry-1)->sec;
1307                         current = pr_track_alloc(SENSOR_PRESSURE(entry), entry->sec);
1308                         track_pr[cylinderindex] = list_add(track_pr[cylinderindex], current);
1309                 } else { /* same cylinder */
1310                         if ((!SENSOR_PRESSURE(entry) && SENSOR_PRESSURE(entry-1)) ||
1311                                 (SENSOR_PRESSURE(entry) && !SENSOR_PRESSURE(entry-1))) {
1312                                 /* transmitter changed its working status */
1313                                 current->end = SENSOR_PRESSURE(entry-1);
1314                                 current->t_end = (entry-1)->sec;
1315                                 current = pr_track_alloc(SENSOR_PRESSURE(entry), entry->sec);
1316                                 track_pr[cylinderindex] =
1317                                         list_add(track_pr[cylinderindex], current);
1318                         }
1319                 }
1320                 /* finally, do the discrete integration to get the SAC rate equivalent */
1321                 current->pressure_time += (entry->sec - (entry-1)->sec) *
1322                         (1 + (entry->depth + (entry-1)->depth) / 20000.0);
1323                 missing_pr |= !SENSOR_PRESSURE(entry);
1324         }
1325
1326         if (entry)
1327                 current->t_end = entry->sec;
1328
1329         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) { /* initialize the end pressures */
1330                 int pr = dive->cylinder[cyl].end.mbar;
1331                 if (pr && track_pr[cyl]) {
1332                         pr_track = list_last(track_pr[cyl]);
1333                         pr_track->end = pr;
1334                 }
1335         }
1336         /* Fill in the last two entries with empty values but valid times
1337          * without creating a false cylinder change event */
1338         i = nr + 2;
1339         pi->entry[i].sec = sec + 20;
1340         pi->entry[i].same_cylinder = 1;
1341         pi->entry[i].cylinderindex = pi->entry[i-1].cylinderindex;
1342         INTERPOLATED_PRESSURE(pi->entry + i) = GET_PRESSURE(pi->entry + i - 1);
1343         pi->entry[i+1].sec = sec + 40;
1344         pi->entry[i+1].same_cylinder = 1;
1345         pi->entry[i+1].cylinderindex = pi->entry[i-1].cylinderindex;
1346         INTERPOLATED_PRESSURE(pi->entry + i + 1) = GET_PRESSURE(pi->entry + i - 1);
1347         /* the number of actual entries - some computers have lots of
1348          * depth 0 samples at the end of a dive, we want to make sure
1349          * we have exactly one of them at the end */
1350         pi->nr = lastindex+1;
1351         while (pi->nr <= i+2 && pi->entry[pi->nr-1].depth > 0)
1352                 pi->nr++;
1353         pi->maxtime = pi->entry[lastindex].sec;
1354
1355         /* Analyze_plot_info() will do the sample max pressures,
1356          * this handles the manual pressures
1357          */
1358         pi->maxpressure = 0;
1359         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) {
1360                 unsigned int mbar = dive->cylinder[cyl].start.mbar;
1361                 if (mbar > pi->maxpressure)
1362                         pi->maxpressure = mbar;
1363         }
1364
1365         pi->meandepth = dive->meandepth.mm;
1366
1367         if (missing_pr) {
1368                 fill_missing_tank_pressures(pi, track_pr);
1369         }
1370         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++)
1371                 list_free(track_pr[cyl]);
1372         if (0) /* awesome for debugging - not useful otherwise */
1373                 dump_pi(pi);
1374         return analyze_plot_info(pi);
1375 }
1376
1377 void plot(struct graphics_context *gc, cairo_rectangle_int_t *drawing_area, struct dive *dive)
1378 {
1379         struct plot_info *pi;
1380         static struct sample fake[4];
1381         struct sample *sample = dive->sample;
1382         int nr = dive->samples;
1383
1384         if (!nr) {
1385                 /* The dive has no samples, so create a few fake ones.  This assumes an
1386                 ascent/descent rate of 9 m/min, which is just below the limit for FAST. */
1387                 int duration = dive->duration.seconds;
1388                 int maxdepth = dive->maxdepth.mm;
1389                 int asc_desc_time = dive->maxdepth.mm*60/9000;
1390                 if (asc_desc_time * 2 >= duration)
1391                         asc_desc_time = duration / 2;
1392                 sample = fake;
1393                 fake[1].time.seconds = asc_desc_time;
1394                 fake[1].depth.mm = maxdepth;
1395                 fake[2].time.seconds = duration - asc_desc_time;
1396                 fake[2].depth.mm = maxdepth;
1397                 fake[3].time.seconds = duration * 1.00;
1398                 nr = 4;
1399         }
1400
1401         pi = create_plot_info(dive, nr, sample);
1402
1403         cairo_translate(gc->cr, drawing_area->x, drawing_area->y);
1404         cairo_set_line_width(gc->cr, 1);
1405         cairo_set_line_cap(gc->cr, CAIRO_LINE_CAP_ROUND);
1406         cairo_set_line_join(gc->cr, CAIRO_LINE_JOIN_ROUND);
1407
1408         /*
1409          * We can use "cairo_translate()" because that doesn't
1410          * scale line width etc. But the actual scaling we need
1411          * do set up ourselves..
1412          *
1413          * Snif. What a pity.
1414          */
1415         gc->maxx = (drawing_area->width - 2*drawing_area->x);
1416         gc->maxy = (drawing_area->height - 2*drawing_area->y);
1417
1418         /* Depth profile */
1419         plot_depth_profile(gc, pi);
1420         plot_events(gc, pi, dive);
1421
1422         /* Temperature profile */
1423         plot_temperature_profile(gc, pi);
1424
1425         /* Cylinder pressure plot */
1426         plot_cylinder_pressure(gc, pi, dive);
1427
1428         /* Text on top of all graphs.. */
1429         plot_temperature_text(gc, pi);
1430         plot_depth_text(gc, pi);
1431         plot_cylinder_pressure_text(gc, pi);
1432
1433         /* Bounding box last */
1434         gc->leftx = 0; gc->rightx = 1.0;
1435         gc->topy = 0; gc->bottomy = 1.0;
1436
1437         set_source_rgba(gc, BOUNDING_BOX);
1438         cairo_set_line_width(gc->cr, 1);
1439         move_to(gc, 0, 0);
1440         line_to(gc, 0, 1);
1441         line_to(gc, 1, 1);
1442         line_to(gc, 1, 0);
1443         cairo_close_path(gc->cr);
1444         cairo_stroke(gc->cr);
1445
1446         free(pi);
1447 }