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