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