]> git.street.me.uk Git - andy/viking.git/blob - src/viktrwlayer_propwin.c
Fix printing of DEBUG message since glib 2.32
[andy/viking.git] / src / viktrwlayer_propwin.c
1 /*
2  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
3  *
4  * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
5  * Copyright (C) 2005-2007, Alex Foobarian <foobarian@gmail.com>
6  * Copyright (C) 2007-2008, Quy Tonthat <qtonthat@gmail.com>
7  * Copyright (C) 2011, Rob Norris <rw_norris@hotmail.com>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
28
29 #ifdef HAVE_MATH_H
30 #include <math.h>
31 #endif
32
33 #include <gtk/gtk.h>
34 #include <glib/gi18n.h>
35 #include <time.h>
36 #ifdef HAVE_STRING_H
37 #include <string.h>
38 #endif
39 #include "coords.h"
40 #include "vikcoord.h"
41 #include "viktrack.h"
42 #include "viktrwlayer.h"
43 #include "viktrwlayer_propwin.h"
44 #include "vikwaypoint.h"
45 #include "dialog.h"
46 #include "globals.h"
47 #include "dems.h"
48
49 #include "vikviewport.h" /* ugh */
50 #include "viktreeview.h" /* ugh */
51 #include <gdk-pixbuf/gdk-pixdata.h>
52 #include "viklayer.h" /* ugh */
53 #include "vikaggregatelayer.h"
54 #include "viklayerspanel.h" /* ugh */
55
56 #define PROPWIN_PROFILE_WIDTH 600
57 #define PROPWIN_PROFILE_HEIGHT 300
58
59 #define PROPWIN_LABEL_FONT "Sans 7"
60
61 typedef enum {
62   PROPWIN_GRAPH_TYPE_ELEVATION_DISTANCE,
63   PROPWIN_GRAPH_TYPE_SPEED_TIME,
64   PROPWIN_GRAPH_TYPE_DISTANCE_TIME,
65   PROPWIN_GRAPH_TYPE_ELEVATION_TIME,
66   PROPWIN_GRAPH_TYPE_SPEED_DISTANCE,
67   PROPWIN_GRAPH_TYPE_END,
68 } VikPropWinGraphType_t;
69
70 /* (Hopefully!) Human friendly altitude grid sizes - note no fixed 'ratio' just numbers that look nice...*/
71 static const gdouble chunksa[] = {2.0, 5.0, 10.0, 15.0, 20.0,
72                                   25.0, 40.0, 50.0, 75.0, 100.0,
73                                   150.0, 200.0, 250.0, 375.0, 500.0,
74                                   750.0, 1000.0, 2000.0, 5000.0, 10000.0, 100000.0};
75
76 /* (Hopefully!) Human friendly grid sizes - note no fixed 'ratio' just numbers that look nice...*/
77 /* As need to cover walking speeds - have many low numbers (but also may go up to airplane speeds!) */
78 static const gdouble chunkss[] = {1.0, 2.0, 3.0, 4.0, 5.0, 8.0, 10.0,
79                                   15.0, 20.0, 25.0, 40.0, 50.0, 75.0,
80                                   100.0, 150.0, 200.0, 250.0, 375.0, 500.0,
81                                   750.0, 1000.0, 10000.0};
82
83 /* (Hopefully!) Human friendly distance grid sizes - note no fixed 'ratio' just numbers that look nice...*/
84 static const gdouble chunksd[] = {0.1, 0.5, 1.0, 2.0, 3.0, 4.0, 5.0, 8.0, 10.0,
85                                   15.0, 20.0, 25.0, 40.0, 50.0, 75.0,
86                                   100.0, 150.0, 200.0, 250.0, 375.0, 500.0,
87                                   750.0, 1000.0, 10000.0};
88
89 typedef struct _propsaved {
90   gboolean saved;
91   GdkImage *img;
92 } PropSaved;
93
94 typedef struct _propwidgets {
95   gboolean  configure_dialog;
96   VikTrwLayer *vtl;
97   VikTrack *tr;
98   gchar *track_name;
99   gint      profile_width;
100   gint      profile_height;
101   gint      profile_width_old;
102   gint      profile_height_old;
103   gint      profile_width_offset;
104   gint      profile_height_offset;
105   GtkWidget *dialog;
106   GtkWidget *w_comment;
107   GtkWidget *w_track_length;
108   GtkWidget *w_tp_count;
109   GtkWidget *w_segment_count;
110   GtkWidget *w_duptp_count;
111   GtkWidget *w_max_speed;
112   GtkWidget *w_avg_speed;
113   GtkWidget *w_mvg_speed;
114   GtkWidget *w_avg_dist;
115   GtkWidget *w_elev_range;
116   GtkWidget *w_elev_gain;
117   GtkWidget *w_time_start;
118   GtkWidget *w_time_end;
119   GtkWidget *w_time_dur;
120   GtkWidget *w_cur_dist; /*< Current distance */
121   GtkWidget *w_cur_elevation;
122   GtkWidget *w_cur_time; /*< Current time */
123   GtkWidget *w_cur_speed;
124   GtkWidget *w_cur_dist_dist; /*< Current distance on distance graph */
125   GtkWidget *w_cur_dist_time; /*< Current time on distance graph */
126   GtkWidget *w_cur_elev_elev;
127   GtkWidget *w_cur_elev_time;
128   GtkWidget *w_cur_speed_dist;
129   GtkWidget *w_cur_speed_speed;
130   GtkWidget *w_show_dem;
131   GtkWidget *w_show_alt_gps_speed;
132   GtkWidget *w_show_gps_speed;
133   GtkWidget *w_show_dist_speed;
134   GtkWidget *w_show_elev_speed;
135   GtkWidget *w_show_sd_gps_speed;
136   gdouble   track_length;
137   gdouble   track_length_inc_gaps;
138   PropSaved elev_graph_saved_img;
139   PropSaved speed_graph_saved_img;
140   PropSaved dist_graph_saved_img;
141   PropSaved elev_time_graph_saved_img;
142   PropSaved speed_dist_graph_saved_img;
143   GtkWidget *elev_box;
144   GtkWidget *speed_box;
145   GtkWidget *dist_box;
146   GtkWidget *elev_time_box;
147   GtkWidget *speed_dist_box;
148   gdouble   *altitudes;
149   gdouble   *ats; // altitudes in time
150   gdouble   min_altitude;
151   gdouble   max_altitude;
152   gdouble   draw_min_altitude;
153   gdouble   draw_min_altitude_time;
154   gint      cia; // Chunk size Index into Altitudes
155   gint      ciat; // Chunk size Index into Altitudes / Time
156   // NB cia & ciat are normally same value but sometimes not due to differing methods of altitude array creation
157   //    thus also have draw_min_altitude for each altitude graph type
158   gdouble   *speeds;
159   gdouble   *speeds_dist;
160   gdouble   min_speed;
161   gdouble   max_speed;
162   gdouble   draw_min_speed;
163   gdouble   max_speed_dist;
164   gint      cis; // Chunk size Index into Speeds
165   gint      cisd; // Chunk size Index into Speed/Distance
166   gdouble   *distances;
167   gint      cid; // Chunk size Index into Distance
168   VikTrackpoint *marker_tp;
169   gboolean  is_marker_drawn;
170   VikTrackpoint *blob_tp;
171   gboolean  is_blob_drawn;
172 } PropWidgets;
173
174 static PropWidgets *prop_widgets_new()
175 {
176   PropWidgets *widgets = g_malloc0(sizeof(PropWidgets));
177
178   return widgets;
179 }
180
181 static void prop_widgets_free(PropWidgets *widgets)
182 {
183   if (widgets->elev_graph_saved_img.img)
184     g_object_unref(widgets->elev_graph_saved_img.img);
185   if (widgets->speed_graph_saved_img.img)
186     g_object_unref(widgets->speed_graph_saved_img.img);
187   if (widgets->dist_graph_saved_img.img)
188     g_object_unref(widgets->dist_graph_saved_img.img);
189   if (widgets->elev_time_graph_saved_img.img)
190     g_object_unref(widgets->elev_time_graph_saved_img.img);
191   if (widgets->speed_dist_graph_saved_img.img)
192     g_object_unref(widgets->speed_dist_graph_saved_img.img);
193   if (widgets->altitudes)
194     g_free(widgets->altitudes);
195   if (widgets->speeds)
196     g_free(widgets->speeds);
197   if (widgets->distances)
198     g_free(widgets->distances);
199   if (widgets->ats)
200     g_free(widgets->ats);
201   if (widgets->speeds_dist)
202     g_free(widgets->speeds_dist);
203   g_free(widgets);
204 }
205
206 static void minmax_array(const gdouble *array, gdouble *min, gdouble *max, gboolean NO_ALT_TEST, gint PROFILE_WIDTH)
207 {
208   *max = -1000;
209   *min = 20000;
210   guint i;
211   for ( i=0; i < PROFILE_WIDTH; i++ ) {
212     if ( NO_ALT_TEST || (array[i] != VIK_DEFAULT_ALTITUDE) ) {
213       if ( array[i] > *max )
214         *max = array[i];
215       if ( array[i] < *min )
216         *min = array[i];
217     }
218   }
219 }
220
221 #define MARGIN 70
222 #define LINES 5
223 /**
224  * Returns via pointers:
225  *   the new minimum value to be used for the altitude graph
226  *   the index in to the altitudes chunk sizes array (ci = Chunk Index)
227  */
228 static void get_new_min_and_chunk_index_altitude (gdouble mina, gdouble maxa, gdouble *new_min, gint *ci)
229 {
230   /* Get unitized chunk */
231   /* Find suitable chunk index */
232   *ci = 0;
233   gdouble diffa_chunk = (maxa - mina)/LINES;
234
235   /* Loop through to find best match */
236   while (diffa_chunk > chunksa[*ci]) {
237     (*ci)++;
238     /* Last Resort Check */
239     if ( *ci == sizeof(chunksa)/sizeof(chunksa[0]) )
240       break;
241   }
242
243   /* Ensure adjusted minimum .. maximum covers mina->maxa */
244
245   // Now work out adjusted minimum point to the nearest lowest chunk divisor value
246   // When negative ensure logic uses lowest value
247   if ( mina < 0 )
248     *new_min = (gdouble) ( ( (gint)(mina - chunksa[*ci]) / (gint)chunksa[*ci] ) * (gint)chunksa[*ci] );
249   else
250     *new_min = (gdouble) ( ( (gint)mina / (gint)chunksa[*ci] ) * (gint)chunksa[*ci] );
251
252   // Range not big enough - as new minimum has lowered
253   if ((*new_min + (chunksa[*ci] * LINES) < maxa)) {
254     // Next chunk should cover it
255     if ( *ci < sizeof(chunksa)/sizeof(chunksa[0]) ) {
256       (*ci)++;
257       // Remember to adjust the minimum too...
258       if ( mina < 0 )
259         *new_min = (gdouble) ( ( (gint)(mina - chunksa[*ci]) / (gint)chunksa[*ci] ) * (gint)chunksa[*ci] );
260       else
261         *new_min = (gdouble) ( ( (gint)mina / (gint)chunksa[*ci] ) * (gint)chunksa[*ci] );
262     }
263   }
264 }
265
266 /**
267  * Returns via pointers:
268  *   the new minimum value to be used for the appropriate graph
269  *   the index in to that array (ci = Chunk Index)
270  */
271 static void get_new_min_and_chunk_index (gdouble mins, gdouble maxs, const gdouble *chunks, size_t chunky, gdouble *new_min, gint *ci)
272 {
273   *ci = 0;
274   gdouble diff_chunk = (maxs - mins)/LINES;
275
276   /* Loop through to find best match */
277   while (diff_chunk > chunks[*ci]) {
278     (*ci)++;
279     /* Last Resort Check */
280     if ( *ci == chunky )
281       break;
282   }
283   *new_min = (gdouble) ( (gint)((mins / chunks[*ci] ) * chunks[*ci]) );
284
285   // Speeds are never negative so don't need to worry about a negative new minimum
286 }
287
288 static VikTrackpoint *set_center_at_graph_position(gdouble event_x,
289                                                    gint img_width,
290                                                    VikTrwLayer *vtl,
291                                                    VikLayersPanel *vlp,
292                                                    VikViewport *vvp,
293                                                    VikTrack *tr,
294                                                    gboolean time_base,
295                                                    gint PROFILE_WIDTH)
296 {
297   VikTrackpoint *trackpoint;
298   gdouble x = event_x - img_width / 2 + PROFILE_WIDTH / 2 - MARGIN / 2;
299   if (x < 0)
300     x = 0;
301   if (x > PROFILE_WIDTH)
302     x = PROFILE_WIDTH;
303
304   if (time_base)
305     trackpoint = vik_track_get_closest_tp_by_percentage_time ( tr, (gdouble) x / PROFILE_WIDTH, NULL );
306   else
307     trackpoint = vik_track_get_closest_tp_by_percentage_dist ( tr, (gdouble) x / PROFILE_WIDTH, NULL );
308
309   if ( trackpoint ) {
310     VikCoord coord = trackpoint->coord;
311     if ( vlp ) {
312       vik_viewport_set_center_coord ( vik_layers_panel_get_viewport(vlp), &coord );
313       vik_layers_panel_emit_update ( vlp );
314     }
315     else {
316       /* since vlp not set, vvp should be valid instead! */
317       if ( vvp )
318         vik_viewport_set_center_coord ( vvp, &coord );
319       vik_layer_emit_update ( VIK_LAYER(vtl), FALSE );
320     }
321   }
322   return trackpoint;
323 }
324
325 /**
326  * Returns whether the marker was drawn or not and whether the blob was drawn or not
327  */
328 static void save_image_and_draw_graph_marks (GtkWidget *image,
329                                              gdouble marker_x,
330                                              GdkGC *gc,
331                                              gint blob_x,
332                                              gint blob_y,
333                                              PropSaved *saved_img,
334                                              gint PROFILE_WIDTH,
335                                              gint PROFILE_HEIGHT,
336                                              gboolean *marker_drawn,
337                                              gboolean *blob_drawn)
338 {
339   GdkPixmap *pix = NULL;
340   /* the pixmap = margin + graph area */
341   gtk_image_get_pixmap(GTK_IMAGE(image), &pix, NULL);
342
343   /* Restore previously saved image */
344   if (saved_img->saved) {
345     gdk_draw_image(GDK_DRAWABLE(pix), gc, saved_img->img, 0, 0, 0, 0, MARGIN+PROFILE_WIDTH, PROFILE_HEIGHT);
346     saved_img->saved = FALSE;
347   }
348
349   // ATM always save whole image - as anywhere could have changed
350   if (saved_img->img)
351     gdk_drawable_copy_to_image(GDK_DRAWABLE(pix), saved_img->img, 0, 0, 0, 0, MARGIN+PROFILE_WIDTH, PROFILE_HEIGHT);
352   else
353     saved_img->img = gdk_drawable_copy_to_image(GDK_DRAWABLE(pix), saved_img->img, 0, 0, 0, 0, MARGIN+PROFILE_WIDTH, PROFILE_HEIGHT);
354   saved_img->saved = TRUE;
355
356   if ((marker_x >= MARGIN) && (marker_x < (PROFILE_WIDTH + MARGIN))) {
357     gdk_draw_line (GDK_DRAWABLE(pix), gc, marker_x, 0, marker_x, image->allocation.height);
358     *marker_drawn = TRUE;
359   }
360   else
361     *marker_drawn = FALSE;
362
363   // Draw a square blob to indicate where we are on track for this graph
364   if ( (blob_x >= MARGIN) && (blob_x < (PROFILE_WIDTH + MARGIN)) && (blob_y < PROFILE_HEIGHT) ) {
365     gdk_draw_rectangle (GDK_DRAWABLE(pix), gc, TRUE, blob_x-3, blob_y-3, 6, 6);
366     *blob_drawn = TRUE;
367   }
368   else
369     *blob_drawn = FALSE;
370   
371   // Anywhere on image could have changed
372   if (*marker_drawn || *blob_drawn)
373     gtk_widget_queue_draw(image);
374 }
375
376 /**
377  * Return the percentage of how far a trackpoint is a long a track via the time method
378  */
379 static gdouble tp_percentage_by_time ( VikTrack *tr, VikTrackpoint *trackpoint )
380 {
381   gdouble pc = NAN;
382   if (trackpoint == NULL)
383     return pc;
384   time_t t_start, t_end, t_total;
385   t_start = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
386   t_end = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
387   t_total = t_end - t_start;
388   pc = (gdouble)(trackpoint->timestamp - t_start)/t_total;
389   return pc;
390 }
391
392 /**
393  * Return the percentage of how far a trackpoint is a long a track via the distance method
394  */
395 static gdouble tp_percentage_by_distance ( VikTrack *tr, VikTrackpoint *trackpoint, gdouble track_length )
396 {
397   gdouble pc = NAN;
398   if (trackpoint == NULL)
399     return pc;
400   gdouble dist = 0.0;
401   GList *iter;
402   for (iter = tr->trackpoints->next; iter != NULL; iter = iter->next) {
403     dist += vik_coord_diff(&(VIK_TRACKPOINT(iter->data)->coord),
404                            &(VIK_TRACKPOINT(iter->prev->data)->coord));
405     /* Assuming trackpoint is not a copy */
406     if (trackpoint == VIK_TRACKPOINT(iter->data))
407       break;
408   }
409   if (iter != NULL)
410     pc = dist/track_length;
411   return pc;
412 }
413
414 static void track_graph_click( GtkWidget *event_box, GdkEventButton *event, gpointer *pass_along, VikPropWinGraphType_t graph_type )
415 {
416   VikTrack *tr = pass_along[0];
417   VikLayersPanel *vlp = pass_along[1];
418   VikViewport *vvp = pass_along[2];
419   PropWidgets *widgets = pass_along[3];
420
421   gboolean is_time_graph =
422     ( graph_type == PROPWIN_GRAPH_TYPE_SPEED_TIME ||
423       graph_type == PROPWIN_GRAPH_TYPE_DISTANCE_TIME ||
424       graph_type == PROPWIN_GRAPH_TYPE_ELEVATION_TIME );
425
426   VikTrackpoint *trackpoint = set_center_at_graph_position(event->x, event_box->allocation.width, widgets->vtl, vlp, vvp, tr, is_time_graph, widgets->profile_width);
427   // Unable to get the point so give up
428   if ( trackpoint == NULL ) {
429     gtk_dialog_set_response_sensitive(GTK_DIALOG(widgets->dialog), VIK_TRW_LAYER_PROPWIN_SPLIT_MARKER, FALSE);
430     return;
431   }
432
433   widgets->marker_tp = trackpoint;
434
435   GList *child;
436   GtkWidget *image;
437   GtkWidget *window = gtk_widget_get_toplevel(GTK_WIDGET(event_box));
438   GtkWidget *graph_box;
439   PropSaved *graph_saved_img;
440   gdouble pc = NAN;
441
442   // Attempt to redraw marker on all graph types
443   gint graphite;
444   for ( graphite = PROPWIN_GRAPH_TYPE_ELEVATION_DISTANCE;
445         graphite < PROPWIN_GRAPH_TYPE_END;
446         graphite++ ) {
447
448     // Switch commonal variables to particular graph type
449     switch (graphite) {
450     default:
451     case PROPWIN_GRAPH_TYPE_ELEVATION_DISTANCE:
452       graph_box       = widgets->elev_box;
453       graph_saved_img = &widgets->elev_graph_saved_img;
454       is_time_graph   = FALSE;
455       break;
456     case PROPWIN_GRAPH_TYPE_SPEED_TIME:
457       graph_box       = widgets->speed_box;
458       graph_saved_img = &widgets->speed_graph_saved_img;
459       is_time_graph   = TRUE;
460       break;
461     case PROPWIN_GRAPH_TYPE_DISTANCE_TIME:
462       graph_box       = widgets->dist_box;
463       graph_saved_img = &widgets->dist_graph_saved_img;
464       is_time_graph   = TRUE;
465       break;
466     case PROPWIN_GRAPH_TYPE_ELEVATION_TIME:
467       graph_box       = widgets->elev_time_box;
468       graph_saved_img = &widgets->elev_time_graph_saved_img;
469       is_time_graph   = TRUE;
470       break;
471     case PROPWIN_GRAPH_TYPE_SPEED_DISTANCE:
472       graph_box       = widgets->speed_dist_box;
473       graph_saved_img = &widgets->speed_dist_graph_saved_img;
474       is_time_graph   = FALSE;
475       break;
476     }
477
478     // Commonal method of redrawing marker
479     if ( graph_box ) {
480
481       child = gtk_container_get_children(GTK_CONTAINER(graph_box));
482       image = GTK_WIDGET(child->data);
483
484       if (is_time_graph)
485         pc = tp_percentage_by_time ( tr, trackpoint );
486       else
487         pc = tp_percentage_by_distance ( tr, trackpoint, widgets->track_length_inc_gaps );
488
489       if (!isnan(pc)) {
490         gdouble marker_x = (pc * widgets->profile_width) + MARGIN;
491         save_image_and_draw_graph_marks(image,
492                                         marker_x,
493                                         window->style->black_gc,
494                                         -1, // Don't draw blob on clicks
495                                         0,
496                                         graph_saved_img,
497                                         widgets->profile_width,
498                                         widgets->profile_height,
499                                         &widgets->is_marker_drawn,
500                                         &widgets->is_blob_drawn);
501       }
502       g_list_free(child);
503     }
504   }
505
506   gtk_dialog_set_response_sensitive(GTK_DIALOG(widgets->dialog), VIK_TRW_LAYER_PROPWIN_SPLIT_MARKER, widgets->is_marker_drawn);
507 }
508
509 static gboolean track_profile_click( GtkWidget *event_box, GdkEventButton *event, gpointer *pass_along )
510 {
511   track_graph_click(event_box, event, pass_along, PROPWIN_GRAPH_TYPE_ELEVATION_DISTANCE);
512   return TRUE;  /* don't call other (further) callbacks */
513 }
514
515 static gboolean track_vt_click( GtkWidget *event_box, GdkEventButton *event, gpointer *pass_along )
516 {
517   track_graph_click(event_box, event, pass_along, PROPWIN_GRAPH_TYPE_SPEED_TIME);
518   return TRUE;  /* don't call other (further) callbacks */
519 }
520
521 static gboolean track_dt_click( GtkWidget *event_box, GdkEventButton *event, gpointer *pass_along )
522 {
523   track_graph_click(event_box, event, pass_along, PROPWIN_GRAPH_TYPE_DISTANCE_TIME);
524   return TRUE;  /* don't call other (further) callbacks */
525 }
526
527 static gboolean track_et_click( GtkWidget *event_box, GdkEventButton *event, gpointer *pass_along )
528 {
529   track_graph_click(event_box, event, pass_along, PROPWIN_GRAPH_TYPE_ELEVATION_TIME);
530   return TRUE;  /* don't call other (further) callbacks */
531 }
532
533 static gboolean track_sd_click( GtkWidget *event_box, GdkEventButton *event, gpointer *pass_along )
534 {
535   track_graph_click(event_box, event, pass_along, PROPWIN_GRAPH_TYPE_SPEED_DISTANCE);
536   return TRUE;  /* don't call other (further) callbacks */
537 }
538
539 /**
540  * Calculate y position for blob on elevation graph
541  */
542 static gint blobby_altitude ( gdouble x_blob, PropWidgets *widgets )
543 {
544   gint ix = (gint)x_blob;
545   // Ensure ix is inbounds
546   if (ix == widgets->profile_width)
547     ix--;
548
549   gint y_blob = widgets->profile_height-widgets->profile_height*(widgets->altitudes[ix]-widgets->draw_min_altitude)/(chunksa[widgets->cia]*LINES);
550
551   return y_blob;
552 }
553
554 /**
555  * Calculate y position for blob on speed graph
556  */
557 static gint blobby_speed ( gdouble x_blob, PropWidgets *widgets )
558 {
559   gint ix = (gint)x_blob;
560   // Ensure ix is inbounds
561   if (ix == widgets->profile_width)
562     ix--;
563
564   gint y_blob = widgets->profile_height-widgets->profile_height*(widgets->speeds[ix]-widgets->draw_min_speed)/(chunkss[widgets->cis]*LINES);
565
566   return y_blob;
567 }
568
569 /**
570  * Calculate y position for blob on distance graph
571  */
572 static gint blobby_distance ( gdouble x_blob, PropWidgets *widgets )
573 {
574   gint ix = (gint)x_blob;
575   // Ensure ix is inbounds
576   if (ix == widgets->profile_width)
577     ix--;
578
579   gint y_blob = widgets->profile_height-widgets->profile_height*(widgets->distances[ix])/(chunksd[widgets->cid]*LINES);
580   //NB min distance is always 0, so no need to subtract that from this  ______/
581
582   return y_blob;
583 }
584
585 /**
586  * Calculate y position for blob on elevation/time graph
587  */
588 static gint blobby_altitude_time ( gdouble x_blob, PropWidgets *widgets )
589 {
590   gint ix = (gint)x_blob;
591   // Ensure ix is inbounds
592   if (ix == widgets->profile_width)
593     ix--;
594
595   gint y_blob = widgets->profile_height-widgets->profile_height*(widgets->ats[ix]-widgets->draw_min_altitude_time)/(chunksa[widgets->ciat]*LINES);
596   return y_blob;
597 }
598
599 /**
600  * Calculate y position for blob on speed/dist graph
601  */
602 static gint blobby_speed_dist ( gdouble x_blob, PropWidgets *widgets )
603 {
604   gint ix = (gint)x_blob;
605   // Ensure ix is inbounds
606   if (ix == widgets->profile_width)
607     ix--;
608
609   gint y_blob = widgets->profile_height-widgets->profile_height*(widgets->speeds_dist[ix]-widgets->draw_min_speed)/(chunkss[widgets->cisd]*LINES);
610
611   return y_blob;
612 }
613
614
615 void track_profile_move( GtkWidget *event_box, GdkEventMotion *event, gpointer *pass_along )
616 {
617   VikTrack *tr = pass_along[0];
618   PropWidgets *widgets = pass_along[3];
619   int mouse_x, mouse_y;
620   GdkModifierType state;
621
622   if (event->is_hint)
623     gdk_window_get_pointer (event->window, &mouse_x, &mouse_y, &state);
624   else
625     mouse_x = event->x;
626
627   gdouble x = mouse_x - event_box->allocation.width / 2 + widgets->profile_width / 2 - MARGIN / 2;
628   if (x < 0)
629     x = 0;
630   if (x > widgets->profile_width)
631     x = widgets->profile_width;
632
633   gdouble meters_from_start;
634   VikTrackpoint *trackpoint = vik_track_get_closest_tp_by_percentage_dist ( tr, (gdouble) x / widgets->profile_width, &meters_from_start );
635   if (trackpoint && widgets->w_cur_dist) {
636     static gchar tmp_buf[20];
637     vik_units_distance_t dist_units = a_vik_get_units_distance ();
638     switch (dist_units) {
639     case VIK_UNITS_DISTANCE_KILOMETRES:
640       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km", meters_from_start/1000.0);
641       break;
642     case VIK_UNITS_DISTANCE_MILES:
643       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f miles", VIK_METERS_TO_MILES(meters_from_start) );
644       break;
645     default:
646       g_critical("Houston, we've had a problem. distance=%d", dist_units);
647     }
648     gtk_label_set_text(GTK_LABEL(widgets->w_cur_dist), tmp_buf);
649   }
650
651   // Show track elevation for this position - to the nearest whole number
652   if (trackpoint && widgets->w_cur_elevation) {
653     static gchar tmp_buf[20];
654     if (a_vik_get_units_height () == VIK_UNITS_HEIGHT_FEET)
655       g_snprintf(tmp_buf, sizeof(tmp_buf), "%d ft", (int)VIK_METERS_TO_FEET(trackpoint->altitude));
656     else
657       g_snprintf(tmp_buf, sizeof(tmp_buf), "%d m", (int)trackpoint->altitude);
658     gtk_label_set_text(GTK_LABEL(widgets->w_cur_elevation), tmp_buf);
659   }
660
661   widgets->blob_tp = trackpoint;
662
663   if ( widgets->altitudes == NULL )
664     return;
665
666   GtkWidget *window = gtk_widget_get_toplevel (event_box);
667   GList *child = gtk_container_get_children(GTK_CONTAINER(event_box));
668   GtkWidget *image = GTK_WIDGET(child->data);
669
670   gint y_blob = blobby_altitude (x, widgets);
671
672   gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
673   if (widgets->is_marker_drawn) {
674     gdouble pc = tp_percentage_by_distance ( tr, widgets->marker_tp, widgets->track_length_inc_gaps );
675     if (!isnan(pc)) {
676       marker_x = (pc * widgets->profile_width) + MARGIN;
677     }
678   }
679
680   save_image_and_draw_graph_marks (image,
681                                    marker_x,
682                                    window->style->black_gc,
683                                    MARGIN+x,
684                                    y_blob,
685                                    &widgets->elev_graph_saved_img,
686                                    widgets->profile_width,
687                                    widgets->profile_height,
688                                    &widgets->is_marker_drawn,
689                                    &widgets->is_blob_drawn);
690
691   g_list_free(child);
692 }
693
694 void track_vt_move( GtkWidget *event_box, GdkEventMotion *event, gpointer *pass_along )
695 {
696   VikTrack *tr = pass_along[0];
697   PropWidgets *widgets = pass_along[3];
698   int mouse_x, mouse_y;
699   GdkModifierType state;
700
701   if (event->is_hint)
702     gdk_window_get_pointer (event->window, &mouse_x, &mouse_y, &state);
703   else
704     mouse_x = event->x;
705
706   gdouble x = mouse_x - event_box->allocation.width / 2 + widgets->profile_width / 2 - MARGIN / 2;
707   if (x < 0)
708     x = 0;
709   if (x > widgets->profile_width)
710     x = widgets->profile_width;
711
712   time_t seconds_from_start;
713   VikTrackpoint *trackpoint = vik_track_get_closest_tp_by_percentage_time ( tr, (gdouble) x / widgets->profile_width, &seconds_from_start );
714   if (trackpoint && widgets->w_cur_time) {
715     static gchar tmp_buf[20];
716     guint h, m, s;
717     h = seconds_from_start/3600;
718     m = (seconds_from_start - h*3600)/60;
719     s = seconds_from_start - (3600*h) - (60*m);
720     g_snprintf(tmp_buf, sizeof(tmp_buf), "%02d:%02d:%02d", h, m, s);
721
722     gtk_label_set_text(GTK_LABEL(widgets->w_cur_time), tmp_buf);
723   }
724
725   gint ix = (gint)x;
726   // Ensure ix is inbounds
727   if (ix == widgets->profile_width)
728     ix--;
729
730   // Show track speed for this position
731   if (trackpoint && widgets->w_cur_speed) {
732     static gchar tmp_buf[20];
733     // Even if GPS speed available (trackpoint->speed), the text will correspond to the speed map shown
734     // No conversions needed as already in appropriate units
735     vik_units_speed_t speed_units = a_vik_get_units_speed ();
736     switch (speed_units) {
737     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
738       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f kph"), widgets->speeds[ix]);
739       break;
740     case VIK_UNITS_SPEED_MILES_PER_HOUR:
741       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f mph"), widgets->speeds[ix]);
742       break;
743     case VIK_UNITS_SPEED_KNOTS:
744       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f knots"), widgets->speeds[ix]);
745       break;
746     default:
747       // VIK_UNITS_SPEED_METRES_PER_SECOND:
748       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f m/s"), widgets->speeds[ix]);
749       break;
750     }
751     gtk_label_set_text(GTK_LABEL(widgets->w_cur_speed), tmp_buf);
752   }
753
754   widgets->blob_tp = trackpoint;
755
756   if ( widgets->speeds == NULL )
757     return;
758
759   GtkWidget *window = gtk_widget_get_toplevel (event_box);
760   GList *child = gtk_container_get_children(GTK_CONTAINER(event_box));
761   GtkWidget *image = GTK_WIDGET(child->data);
762
763   gint y_blob = blobby_speed (x, widgets);
764
765   gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
766   if (widgets->is_marker_drawn) {
767     gdouble pc = tp_percentage_by_time ( tr, widgets->marker_tp );
768     if (!isnan(pc)) {
769       marker_x = (pc * widgets->profile_width) + MARGIN;
770     }
771   }
772
773   save_image_and_draw_graph_marks (image,
774                                    marker_x,
775                                    window->style->black_gc,
776                                    MARGIN+x,
777                                    y_blob,
778                                    &widgets->speed_graph_saved_img,
779                                    widgets->profile_width,
780                                    widgets->profile_height,
781                                    &widgets->is_marker_drawn,
782                                    &widgets->is_blob_drawn);
783
784   g_list_free(child);
785 }
786
787 /**
788  * Update labels and blob marker on mouse moves in the distance/time graph
789  */
790 void track_dt_move( GtkWidget *event_box, GdkEventMotion *event, gpointer *pass_along )
791 {
792   VikTrack *tr = pass_along[0];
793   PropWidgets *widgets = pass_along[3];
794   int mouse_x, mouse_y;
795   GdkModifierType state;
796
797   if (event->is_hint)
798     gdk_window_get_pointer (event->window, &mouse_x, &mouse_y, &state);
799   else
800     mouse_x = event->x;
801
802   gdouble x = mouse_x - event_box->allocation.width / 2 + widgets->profile_width / 2 - MARGIN / 2;
803   if (x < 0)
804     x = 0;
805   if (x > widgets->profile_width)
806     x = widgets->profile_width;
807
808   time_t seconds_from_start;
809   VikTrackpoint *trackpoint = vik_track_get_closest_tp_by_percentage_time ( tr, (gdouble) x / widgets->profile_width, &seconds_from_start );
810   if (trackpoint && widgets->w_cur_dist_time) {
811     static gchar tmp_buf[20];
812     guint h, m, s;
813     h = seconds_from_start/3600;
814     m = (seconds_from_start - h*3600)/60;
815     s = seconds_from_start - (3600*h) - (60*m);
816     g_snprintf(tmp_buf, sizeof(tmp_buf), "%02d:%02d:%02d", h, m, s);
817
818     gtk_label_set_text(GTK_LABEL(widgets->w_cur_dist_time), tmp_buf);
819   }
820
821   gint ix = (gint)x;
822   // Ensure ix is inbounds
823   if (ix == widgets->profile_width)
824     ix--;
825
826   if (trackpoint && widgets->w_cur_dist_dist) {
827     static gchar tmp_buf[20];
828     if ( a_vik_get_units_distance () == VIK_UNITS_DISTANCE_MILES )
829       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f miles", widgets->distances[ix]);
830     else
831       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km", widgets->distances[ix]);
832     gtk_label_set_text(GTK_LABEL(widgets->w_cur_dist_dist), tmp_buf);
833   }
834
835   widgets->blob_tp = trackpoint;
836
837   if ( widgets->distances == NULL )
838     return;
839
840   GtkWidget *window = gtk_widget_get_toplevel (event_box);
841   GList *child = gtk_container_get_children(GTK_CONTAINER(event_box));
842   GtkWidget *image = GTK_WIDGET(child->data);
843
844   gint y_blob = blobby_distance (x, widgets);
845
846   gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
847   if (widgets->is_marker_drawn) {
848     gdouble pc = tp_percentage_by_time ( tr, widgets->marker_tp );
849     if (!isnan(pc)) {
850       marker_x = (pc * widgets->profile_width) + MARGIN;
851     }
852   }
853
854   save_image_and_draw_graph_marks (image,
855                                    marker_x,
856                                    window->style->black_gc,
857                                    MARGIN+x,
858                                    y_blob,
859                                    &widgets->dist_graph_saved_img,
860                                    widgets->profile_width,
861                                    widgets->profile_height,
862                                    &widgets->is_marker_drawn,
863                                    &widgets->is_blob_drawn);
864
865   g_list_free(child);
866 }
867
868 /**
869  * Update labels and blob marker on mouse moves in the elevation/time graph
870  */
871 void track_et_move( GtkWidget *event_box, GdkEventMotion *event, gpointer *pass_along )
872 {
873   VikTrack *tr = pass_along[0];
874   PropWidgets *widgets = pass_along[3];
875   int mouse_x, mouse_y;
876   GdkModifierType state;
877
878   if (event->is_hint)
879     gdk_window_get_pointer (event->window, &mouse_x, &mouse_y, &state);
880   else
881     mouse_x = event->x;
882
883   gdouble x = mouse_x - event_box->allocation.width / 2 + widgets->profile_width / 2 - MARGIN / 2;
884   if (x < 0)
885     x = 0;
886   if (x > widgets->profile_width)
887     x = widgets->profile_width;
888
889   time_t seconds_from_start;
890   VikTrackpoint *trackpoint = vik_track_get_closest_tp_by_percentage_time ( tr, (gdouble) x / widgets->profile_width, &seconds_from_start );
891   if (trackpoint && widgets->w_cur_elev_time) {
892     static gchar tmp_buf[20];
893     guint h, m, s;
894     h = seconds_from_start/3600;
895     m = (seconds_from_start - h*3600)/60;
896     s = seconds_from_start - (3600*h) - (60*m);
897     g_snprintf(tmp_buf, sizeof(tmp_buf), "%02d:%02d:%02d", h, m, s);
898
899     gtk_label_set_text(GTK_LABEL(widgets->w_cur_elev_time), tmp_buf);
900   }
901
902   gint ix = (gint)x;
903   // Ensure ix is inbounds
904   if (ix == widgets->profile_width)
905     ix--;
906
907   if (trackpoint && widgets->w_cur_elev_elev) {
908     static gchar tmp_buf[20];
909     if (a_vik_get_units_height () == VIK_UNITS_HEIGHT_FEET)
910       g_snprintf(tmp_buf, sizeof(tmp_buf), "%d ft", (int)VIK_METERS_TO_FEET(trackpoint->altitude));
911     else
912       g_snprintf(tmp_buf, sizeof(tmp_buf), "%d m", (int)trackpoint->altitude);
913     gtk_label_set_text(GTK_LABEL(widgets->w_cur_elev_elev), tmp_buf);
914   }
915
916   widgets->blob_tp = trackpoint;
917
918   if ( widgets->ats == NULL )
919     return;
920
921   GtkWidget *window = gtk_widget_get_toplevel (event_box);
922   GList *child = gtk_container_get_children(GTK_CONTAINER(event_box));
923   GtkWidget *image = GTK_WIDGET(child->data);
924
925   gint y_blob = blobby_altitude_time (x, widgets);
926
927   gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
928   if (widgets->is_marker_drawn) {
929     gdouble pc = tp_percentage_by_time ( tr, widgets->marker_tp );
930     if (!isnan(pc)) {
931       marker_x = (pc * widgets->profile_width) + MARGIN;
932     }
933   }
934
935   save_image_and_draw_graph_marks (image,
936                                    marker_x,
937                                    window->style->black_gc,
938                                    MARGIN+x,
939                                    y_blob,
940                                    &widgets->elev_time_graph_saved_img,
941                                    widgets->profile_width,
942                                    widgets->profile_height,
943                                    &widgets->is_marker_drawn,
944                                    &widgets->is_blob_drawn);
945
946   g_list_free(child);
947 }
948
949 void track_sd_move( GtkWidget *event_box, GdkEventMotion *event, gpointer *pass_along )
950 {
951   VikTrack *tr = pass_along[0];
952   PropWidgets *widgets = pass_along[3];
953   int mouse_x, mouse_y;
954   GdkModifierType state;
955
956   if (event->is_hint)
957     gdk_window_get_pointer (event->window, &mouse_x, &mouse_y, &state);
958   else
959     mouse_x = event->x;
960
961   gdouble x = mouse_x - event_box->allocation.width / 2 + widgets->profile_width / 2 - MARGIN / 2;
962   if (x < 0)
963     x = 0;
964   if (x > widgets->profile_width)
965     x = widgets->profile_width;
966
967   gdouble meters_from_start;
968   VikTrackpoint *trackpoint = vik_track_get_closest_tp_by_percentage_dist ( tr, (gdouble) x / widgets->profile_width, &meters_from_start );
969   if (trackpoint && widgets->w_cur_speed_dist) {
970     static gchar tmp_buf[20];
971     vik_units_distance_t dist_units = a_vik_get_units_distance ();
972     switch (dist_units) {
973     case VIK_UNITS_DISTANCE_KILOMETRES:
974       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km", meters_from_start/1000.0);
975       break;
976     case VIK_UNITS_DISTANCE_MILES:
977       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f miles", VIK_METERS_TO_MILES(meters_from_start) );
978       break;
979     default:
980       g_critical("Houston, we've had a problem. distance=%d", dist_units);
981     }
982     gtk_label_set_text(GTK_LABEL(widgets->w_cur_speed_dist), tmp_buf);
983   }
984
985   gint ix = (gint)x;
986   // Ensure ix is inbounds
987   if (ix == widgets->profile_width)
988     ix--;
989
990   if ( widgets->speeds_dist == NULL )
991     return;
992
993   // Show track speed for this position
994   if (widgets->w_cur_speed_speed) {
995     static gchar tmp_buf[20];
996     // Even if GPS speed available (trackpoint->speed), the text will correspond to the speed map shown
997     // No conversions needed as already in appropriate units
998     vik_units_speed_t speed_units = a_vik_get_units_speed ();
999     switch (speed_units) {
1000     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
1001       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f kph"), widgets->speeds_dist[ix]);
1002       break;
1003     case VIK_UNITS_SPEED_MILES_PER_HOUR:
1004       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f mph"), widgets->speeds_dist[ix]);
1005       break;
1006     case VIK_UNITS_SPEED_KNOTS:
1007       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f knots"), widgets->speeds_dist[ix]);
1008       break;
1009     default:
1010       // VIK_UNITS_SPEED_METRES_PER_SECOND:
1011       g_snprintf(tmp_buf, sizeof(tmp_buf), _("%.1f m/s"), widgets->speeds_dist[ix]);
1012       break;
1013     }
1014     gtk_label_set_text(GTK_LABEL(widgets->w_cur_speed_speed), tmp_buf);
1015   }
1016
1017   widgets->blob_tp = trackpoint;
1018
1019   GtkWidget *window = gtk_widget_get_toplevel (event_box);
1020   GList *child = gtk_container_get_children(GTK_CONTAINER(event_box));
1021   GtkWidget *image = GTK_WIDGET(child->data);
1022
1023   gint y_blob = blobby_speed_dist (x, widgets);
1024
1025   gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
1026   if (widgets->is_marker_drawn) {
1027     gdouble pc = tp_percentage_by_distance ( tr, widgets->marker_tp, widgets->track_length_inc_gaps );
1028     if (!isnan(pc)) {
1029       marker_x = (pc * widgets->profile_width) + MARGIN;
1030     }
1031   }
1032
1033   save_image_and_draw_graph_marks (image,
1034                                    marker_x,
1035                                    window->style->black_gc,
1036                                    MARGIN+x,
1037                                    y_blob,
1038                                    &widgets->speed_dist_graph_saved_img,
1039                                    widgets->profile_width,
1040                                    widgets->profile_height,
1041                                    &widgets->is_marker_drawn,
1042                                    &widgets->is_blob_drawn);
1043
1044   g_list_free(child);
1045 }
1046
1047 /**
1048  * Draws DEM points and a respresentative speed on the supplied pixmap
1049  *   (which is the elevations graph)
1050  */
1051 static void draw_dem_alt_speed_dist(VikTrack *tr,
1052                                     GdkDrawable *pix,
1053                                     GdkGC *alt_gc,
1054                                     GdkGC *speed_gc,
1055                                     gdouble alt_offset,
1056                                     gdouble alt_diff,
1057                                     gdouble max_speed_in,
1058                                     gint cia,
1059                                     gint width,
1060                                     gint height,
1061                                     gint margin,
1062                                     gboolean do_dem,
1063                                     gboolean do_speed)
1064 {
1065   GList *iter;
1066   gdouble max_speed = 0;
1067   gdouble total_length = vik_track_get_length_including_gaps(tr);
1068
1069   // Calculate the max speed factor
1070   if (do_speed)
1071     max_speed = max_speed_in * 110 / 100;
1072
1073   gdouble dist = 0;
1074   for (iter = tr->trackpoints->next; iter; iter = iter->next) {
1075     int x;
1076     dist += vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord),
1077                              &(VIK_TRACKPOINT(iter->prev->data)->coord) );
1078     x = (width * dist)/total_length + margin;
1079     if (do_dem) {
1080       gint16 elev = a_dems_get_elev_by_coord(&(VIK_TRACKPOINT(iter->data)->coord), VIK_DEM_INTERPOL_BEST);
1081       elev -= alt_offset;
1082       if ( elev != VIK_DEM_INVALID_ELEVATION ) {
1083         // Convert into height units
1084         if (a_vik_get_units_height () == VIK_UNITS_HEIGHT_FEET)
1085           elev =  VIK_METERS_TO_FEET(elev);
1086         // No conversion needed if already in metres
1087
1088         // consider chunk size
1089         int y_alt = height - ((height * elev)/(chunksa[cia]*LINES) );
1090         gdk_draw_rectangle(GDK_DRAWABLE(pix), alt_gc, TRUE, x-2, y_alt-2, 4, 4);
1091       }
1092     }
1093     if (do_speed) {
1094       // This is just a speed indicator - no actual values can be inferred by user
1095       if (!isnan(VIK_TRACKPOINT(iter->data)->speed)) {
1096         int y_speed = height - (height * VIK_TRACKPOINT(iter->data)->speed)/max_speed;
1097         gdk_draw_rectangle(GDK_DRAWABLE(pix), speed_gc, TRUE, x-2, y_speed-2, 4, 4);
1098       }
1099     }
1100   }
1101 }
1102
1103 /**
1104  * Draw just the height profile image
1105  */
1106 static void draw_elevations (GtkWidget *image, VikTrack *tr, PropWidgets *widgets )
1107 {
1108   GtkWidget *window;
1109   GdkPixmap *pix;
1110   gdouble mina, maxa;
1111   guint i;
1112
1113   GdkGC *no_alt_info;
1114   GdkColor color;
1115
1116   // Free previous allocation
1117   if ( widgets->altitudes )
1118     g_free ( widgets->altitudes );
1119
1120   widgets->altitudes = vik_track_make_elevation_map ( tr, widgets->profile_width );
1121
1122   if ( widgets->altitudes == NULL )
1123     return;
1124
1125   // Convert into appropriate units
1126   vik_units_height_t height_units = a_vik_get_units_height ();
1127   if ( height_units == VIK_UNITS_HEIGHT_FEET ) {
1128     // Convert altitudes into feet units
1129     for ( i = 0; i < widgets->profile_width; i++ ) {
1130       widgets->altitudes[i] = VIK_METERS_TO_FEET(widgets->altitudes[i]);
1131     }
1132   }
1133   // Otherwise leave in metres
1134
1135   minmax_array(widgets->altitudes, &widgets->min_altitude, &widgets->max_altitude, TRUE, widgets->profile_width);
1136
1137   get_new_min_and_chunk_index_altitude (widgets->min_altitude, widgets->max_altitude, &widgets->draw_min_altitude, &widgets->cia);
1138
1139   // Assign locally
1140   mina = widgets->draw_min_altitude;
1141   maxa = widgets->max_altitude;
1142
1143   window = gtk_widget_get_toplevel (widgets->elev_box);
1144
1145   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
1146
1147   gtk_image_set_from_pixmap ( GTK_IMAGE(image), pix, NULL );
1148
1149   no_alt_info = gdk_gc_new ( window->window );
1150   gdk_color_parse ( "yellow", &color );
1151   gdk_gc_set_rgb_fg_color ( no_alt_info, &color);
1152
1153   /* clear the image */
1154   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->bg_gc[0], 
1155                      TRUE, 0, 0, MARGIN, widgets->profile_height);
1156   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->mid_gc[0], 
1157                      TRUE, MARGIN, 0, widgets->profile_width, widgets->profile_height);
1158   
1159   /* draw grid */
1160   for (i=0; i<=LINES; i++) {
1161     PangoFontDescription *pfd;
1162     PangoLayout *pl = gtk_widget_create_pango_layout (GTK_WIDGET(image), NULL);
1163     gchar s[32];
1164     int w, h;
1165
1166     pango_layout_set_alignment (pl, PANGO_ALIGN_RIGHT);
1167     pfd = pango_font_description_from_string (PROPWIN_LABEL_FONT);
1168     pango_layout_set_font_description (pl, pfd);
1169     pango_font_description_free (pfd);
1170     switch (height_units) {
1171     case VIK_UNITS_HEIGHT_METRES:
1172       sprintf(s, "%8dm", (int)(mina + (LINES-i)*chunksa[widgets->cia]));
1173       break;
1174     case VIK_UNITS_HEIGHT_FEET:
1175       // NB values already converted into feet
1176       sprintf(s, "%8dft", (int)(mina + (LINES-i)*chunksa[widgets->cia]));
1177       break;
1178     default:
1179       sprintf(s, "--");
1180       g_critical("Houston, we've had a problem. height=%d", height_units);
1181     }
1182     pango_layout_set_text(pl, s, -1);
1183     pango_layout_get_pixel_size (pl, &w, &h);
1184     gdk_draw_layout(GDK_DRAWABLE(pix), window->style->fg_gc[0], MARGIN-w-3, 
1185                     CLAMP((int)i*widgets->profile_height/LINES - h/2, 0, widgets->profile_height-h), pl);
1186
1187     gdk_draw_line (GDK_DRAWABLE(pix), window->style->dark_gc[0], 
1188                    MARGIN, widgets->profile_height/LINES * i, MARGIN + widgets->profile_width, widgets->profile_height/LINES * i);
1189     g_object_unref ( G_OBJECT ( pl ) );
1190     pl = NULL;
1191   }
1192
1193   /* draw elevations */
1194   for ( i = 0; i < widgets->profile_width; i++ )
1195     if ( widgets->altitudes[i] == VIK_DEFAULT_ALTITUDE )
1196       gdk_draw_line ( GDK_DRAWABLE(pix), no_alt_info, 
1197                       i + MARGIN, 0, i + MARGIN, widgets->profile_height );
1198     else 
1199       gdk_draw_line ( GDK_DRAWABLE(pix), window->style->dark_gc[3], 
1200                       i + MARGIN, widgets->profile_height, i + MARGIN, widgets->profile_height-widgets->profile_height*(widgets->altitudes[i]-mina)/(chunksa[widgets->cia]*LINES) );
1201
1202   if ( gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(widgets->w_show_dem)) ||
1203        gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(widgets->w_show_alt_gps_speed)) ) {
1204
1205     GdkGC *dem_alt_gc = gdk_gc_new ( window->window );
1206     GdkGC *gps_speed_gc = gdk_gc_new ( window->window );
1207
1208     gdk_color_parse ( "green", &color );
1209     gdk_gc_set_rgb_fg_color ( dem_alt_gc, &color);
1210
1211     gdk_color_parse ( "red", &color );
1212     gdk_gc_set_rgb_fg_color ( gps_speed_gc, &color);
1213
1214     // Ensure somekind of max speed when not set
1215     if ( widgets->max_speed < 0.01 )
1216       widgets->max_speed = vik_track_get_max_speed(tr);
1217
1218     draw_dem_alt_speed_dist(tr,
1219                             GDK_DRAWABLE(pix),
1220                             dem_alt_gc,
1221                             gps_speed_gc,
1222                             mina,
1223                             maxa - mina,
1224                             widgets->max_speed,
1225                             widgets->cia,
1226                             widgets->profile_width,
1227                             widgets->profile_height,
1228                             MARGIN,
1229                             gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(widgets->w_show_dem)),
1230                             gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(widgets->w_show_alt_gps_speed)));
1231     
1232     g_object_unref ( G_OBJECT(dem_alt_gc) );
1233     g_object_unref ( G_OBJECT(gps_speed_gc) );
1234   }
1235
1236   /* draw border */
1237   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->black_gc, FALSE, MARGIN, 0, widgets->profile_width-1, widgets->profile_height-1);
1238
1239   g_object_unref ( G_OBJECT(pix) );
1240   g_object_unref ( G_OBJECT(no_alt_info) );
1241 }
1242
1243 /**
1244  * Draw just the speed (velocity)/time image
1245  */
1246 static void draw_vt ( GtkWidget *image, VikTrack *tr, PropWidgets *widgets)
1247 {
1248   GtkWidget *window;
1249   GdkPixmap *pix;
1250   gdouble mins;
1251   guint i;
1252
1253   // Free previous allocation
1254   if ( widgets->speeds )
1255     g_free ( widgets->speeds );
1256
1257   widgets->speeds = vik_track_make_speed_map ( tr, widgets->profile_width );
1258   if ( widgets->speeds == NULL )
1259     return;
1260
1261   // Convert into appropriate units
1262   vik_units_speed_t speed_units = a_vik_get_units_speed ();
1263   switch (speed_units) {
1264   case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
1265     for ( i = 0; i < widgets->profile_width; i++ ) {
1266       widgets->speeds[i] = VIK_MPS_TO_KPH(widgets->speeds[i]);
1267     }
1268     break;
1269   case VIK_UNITS_SPEED_MILES_PER_HOUR:
1270     for ( i = 0; i < widgets->profile_width; i++ ) {
1271       widgets->speeds[i] = VIK_MPS_TO_MPH(widgets->speeds[i]);
1272     }
1273     break;
1274   case VIK_UNITS_SPEED_KNOTS:
1275     for ( i = 0; i < widgets->profile_width; i++ ) {
1276       widgets->speeds[i] = VIK_MPS_TO_KNOTS(widgets->speeds[i]);
1277     }
1278     break;
1279   default:
1280     // VIK_UNITS_SPEED_METRES_PER_SECOND:
1281     // No need to convert as already in m/s
1282     break;
1283   }
1284
1285   window = gtk_widget_get_toplevel (widgets->speed_box);
1286
1287   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
1288
1289   gtk_image_set_from_pixmap ( GTK_IMAGE(image), pix, NULL );
1290
1291   minmax_array(widgets->speeds, &widgets->min_speed, &widgets->max_speed, FALSE, widgets->profile_width);
1292   if (widgets->min_speed < 0.0)
1293     widgets->min_speed = 0; /* splines sometimes give negative speeds */
1294
1295   /* Find suitable chunk index */
1296   get_new_min_and_chunk_index (widgets->min_speed, widgets->max_speed, chunkss, sizeof(chunkss)/sizeof(chunkss[0]), &widgets->draw_min_speed, &widgets->cis);
1297
1298   // Assign locally
1299   mins = widgets->draw_min_speed;
1300   
1301   /* clear the image */
1302   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->bg_gc[0], 
1303                      TRUE, 0, 0, MARGIN, widgets->profile_height);
1304   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->mid_gc[0], 
1305                      TRUE, MARGIN, 0, widgets->profile_width, widgets->profile_height);
1306
1307   /* draw grid */
1308   for (i=0; i<=LINES; i++) {
1309     PangoFontDescription *pfd;
1310     PangoLayout *pl = gtk_widget_create_pango_layout (GTK_WIDGET(image), NULL);
1311     gchar s[32];
1312     int w, h;
1313
1314     pango_layout_set_alignment (pl, PANGO_ALIGN_RIGHT);
1315     pfd = pango_font_description_from_string (PROPWIN_LABEL_FONT);
1316     pango_layout_set_font_description (pl, pfd);
1317     pango_font_description_free (pfd);
1318     // NB: No need to convert here anymore as numbers are in the appropriate units
1319     switch (speed_units) {
1320     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
1321       sprintf(s, "%8dkm/h", (int)(mins + (LINES-i)*chunkss[widgets->cis]));
1322       break;
1323     case VIK_UNITS_SPEED_MILES_PER_HOUR:
1324       sprintf(s, "%8dmph", (int)(mins + (LINES-i)*chunkss[widgets->cis]));
1325       break;
1326     case VIK_UNITS_SPEED_METRES_PER_SECOND:
1327       sprintf(s, "%8dm/s", (int)(mins + (LINES-i)*chunkss[widgets->cis]));
1328       break;
1329     case VIK_UNITS_SPEED_KNOTS:
1330       sprintf(s, "%8dknots", (int)(mins + (LINES-i)*chunkss[widgets->cis]));
1331       break;
1332     default:
1333       sprintf(s, "--");
1334       g_critical("Houston, we've had a problem. speed=%d", speed_units);
1335     }
1336
1337     pango_layout_set_text(pl, s, -1);
1338     pango_layout_get_pixel_size (pl, &w, &h);
1339     gdk_draw_layout(GDK_DRAWABLE(pix), window->style->fg_gc[0], MARGIN-w-3, 
1340                     CLAMP((int)i*widgets->profile_height/LINES - h/2, 0, widgets->profile_height-h), pl);
1341
1342     gdk_draw_line (GDK_DRAWABLE(pix), window->style->dark_gc[0], 
1343                    MARGIN, widgets->profile_height/LINES * i, MARGIN + widgets->profile_width, widgets->profile_height/LINES * i);
1344     g_object_unref ( G_OBJECT ( pl ) );
1345     pl = NULL;
1346   }
1347   
1348
1349   /* draw speeds */
1350   for ( i = 0; i < widgets->profile_width; i++ )
1351       gdk_draw_line ( GDK_DRAWABLE(pix), window->style->dark_gc[3], 
1352                       i + MARGIN, widgets->profile_height, i + MARGIN, widgets->profile_height-widgets->profile_height*(widgets->speeds[i]-mins)/(chunkss[widgets->cis]*LINES) );
1353
1354
1355   if ( gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widgets->w_show_gps_speed)) ) {
1356
1357     GdkGC *gps_speed_gc = gdk_gc_new ( window->window );
1358     GdkColor color;
1359     gdk_color_parse ( "red", &color );
1360     gdk_gc_set_rgb_fg_color ( gps_speed_gc, &color);
1361
1362     time_t beg_time = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
1363     time_t dur =  VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp - beg_time;
1364
1365     GList *iter;
1366     for (iter = tr->trackpoints; iter; iter = iter->next) {
1367       gdouble gps_speed = VIK_TRACKPOINT(iter->data)->speed;
1368       if (isnan(gps_speed))
1369         continue;
1370       switch (speed_units) {
1371       case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
1372         gps_speed = VIK_MPS_TO_KPH(gps_speed);
1373         break;
1374       case VIK_UNITS_SPEED_MILES_PER_HOUR:
1375         gps_speed = VIK_MPS_TO_MPH(gps_speed);
1376         break;
1377       case VIK_UNITS_SPEED_KNOTS:
1378         gps_speed = VIK_MPS_TO_KNOTS(gps_speed);
1379         break;
1380       default:
1381         // VIK_UNITS_SPEED_METRES_PER_SECOND:
1382         // No need to convert as already in m/s
1383         break;
1384       }
1385       int x = MARGIN + widgets->profile_width * (VIK_TRACKPOINT(iter->data)->timestamp - beg_time) / dur;
1386       int y = widgets->profile_height - widgets->profile_height*(gps_speed - mins)/(chunkss[widgets->cis]*LINES);
1387       gdk_draw_rectangle(GDK_DRAWABLE(pix), gps_speed_gc, TRUE, x-2, y-2, 4, 4);
1388     }
1389     g_object_unref ( G_OBJECT(gps_speed_gc) );
1390   }
1391
1392   /* draw border */
1393   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->black_gc, FALSE, MARGIN, 0, widgets->profile_width-1, widgets->profile_height-1);
1394
1395   g_object_unref ( G_OBJECT(pix) );
1396 }
1397
1398 /**
1399  * Draw just the distance/time image
1400  */
1401 static void draw_dt ( GtkWidget *image, VikTrack *tr, PropWidgets *widgets )
1402 {
1403   GtkWidget *window;
1404   GdkPixmap *pix;
1405   gdouble maxd;
1406   guint i;
1407
1408   // Free previous allocation
1409   if ( widgets->distances )
1410     g_free ( widgets->distances );
1411
1412   widgets->distances = vik_track_make_distance_map ( tr, widgets->profile_width );
1413   if ( widgets->distances == NULL )
1414     return;
1415
1416   // Convert into appropriate units
1417   vik_units_distance_t dist_units = a_vik_get_units_distance ();
1418   if ( dist_units == VIK_UNITS_DISTANCE_MILES ) {
1419     for ( i = 0; i < widgets->profile_width; i++ ) {
1420       widgets->distances[i] = VIK_METERS_TO_MILES(widgets->distances[i]);
1421     }
1422   }
1423   else {
1424     // Metres - but want in kms
1425     for ( i = 0; i < widgets->profile_width; i++ ) {
1426       widgets->distances[i] = widgets->distances[i]/1000.0;
1427     }
1428   }
1429
1430   window = gtk_widget_get_toplevel (widgets->dist_box);
1431
1432   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
1433
1434   gtk_image_set_from_pixmap ( GTK_IMAGE(image), pix, NULL );
1435
1436   // easy to work out min / max of distance!
1437   // Assign locally
1438   // mind = 0.0; - Thus not used
1439   if ( dist_units == VIK_UNITS_DISTANCE_MILES )
1440     maxd = VIK_METERS_TO_MILES(vik_track_get_length_including_gaps (tr));
1441   else
1442     maxd = vik_track_get_length_including_gaps (tr) / 1000.0;
1443
1444   /* Find suitable chunk index */
1445   gdouble dummy = 0.0; // expect this to remain the same! (not that it's used)
1446   get_new_min_and_chunk_index (0, maxd, chunksd, sizeof(chunksd)/sizeof(chunksd[0]), &dummy, &widgets->cid);
1447
1448   /* clear the image */
1449   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->bg_gc[0],
1450                      TRUE, 0, 0, MARGIN, widgets->profile_height);
1451   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->mid_gc[0],
1452                      TRUE, MARGIN, 0, widgets->profile_width, widgets->profile_height);
1453
1454   /* draw grid */
1455   for (i=0; i<=LINES; i++) {
1456     PangoFontDescription *pfd;
1457     PangoLayout *pl = gtk_widget_create_pango_layout (GTK_WIDGET(image), NULL);
1458     gchar s[32];
1459     int w, h;
1460
1461     pango_layout_set_alignment (pl, PANGO_ALIGN_RIGHT);
1462     pfd = pango_font_description_from_string (PROPWIN_LABEL_FONT);
1463     pango_layout_set_font_description (pl, pfd);
1464     pango_font_description_free (pfd);
1465     if ( dist_units == VIK_UNITS_DISTANCE_MILES )
1466       sprintf(s, _("%.1f miles"), ((LINES-i)*chunksd[widgets->cid]));
1467     else
1468       sprintf(s, _("%.1f km"), ((LINES-i)*chunksd[widgets->cid]));
1469
1470     pango_layout_set_text(pl, s, -1);
1471     pango_layout_get_pixel_size (pl, &w, &h);
1472     gdk_draw_layout(GDK_DRAWABLE(pix), window->style->fg_gc[0], MARGIN-w-3,
1473                     CLAMP((int)i*widgets->profile_height/LINES - h/2, 0, widgets->profile_height-h), pl);
1474
1475     gdk_draw_line (GDK_DRAWABLE(pix), window->style->dark_gc[0],
1476                    MARGIN, widgets->profile_height/LINES * i, MARGIN + widgets->profile_width, widgets->profile_height/LINES * i);
1477     g_object_unref ( G_OBJECT ( pl ) );
1478     pl = NULL;
1479   }
1480   
1481   /* draw distance */
1482   for ( i = 0; i < widgets->profile_width; i++ )
1483       gdk_draw_line ( GDK_DRAWABLE(pix), window->style->dark_gc[3],
1484                       i + MARGIN, widgets->profile_height, i + MARGIN, widgets->profile_height-widgets->profile_height*(widgets->distances[i])/(chunksd[widgets->cid]*LINES) );
1485
1486   // Show speed indicator
1487   if ( gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widgets->w_show_dist_speed)) ) {
1488     GdkGC *dist_speed_gc = gdk_gc_new ( window->window );
1489     GdkColor color;
1490     gdk_color_parse ( "red", &color );
1491     gdk_gc_set_rgb_fg_color ( dist_speed_gc, &color);
1492
1493     gdouble max_speed = 0;
1494     max_speed = widgets->max_speed * 110 / 100;
1495
1496     // This is just an indicator - no actual values can be inferred by user
1497     gint i;
1498     for ( i = 0; i < widgets->profile_width; i++ ) {
1499       int y_speed = widgets->profile_height - (widgets->profile_height * widgets->speeds[i])/max_speed;
1500       gdk_draw_rectangle(GDK_DRAWABLE(pix), dist_speed_gc, TRUE, i+MARGIN-2, y_speed-2, 4, 4);
1501     }
1502     g_object_unref ( G_OBJECT(dist_speed_gc) );
1503   }
1504
1505   /* draw border */
1506   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->black_gc, FALSE, MARGIN, 0, widgets->profile_width-1, widgets->profile_height-1);
1507
1508   g_object_unref ( G_OBJECT(pix) );
1509
1510 }
1511
1512 /**
1513  * Draw just the elevation/time image
1514  */
1515 static void draw_et ( GtkWidget *image, VikTrack *tr, PropWidgets *widgets )
1516 {
1517   GtkWidget *window;
1518   GdkPixmap *pix;
1519   gdouble mina;
1520   guint i;
1521
1522   // Free previous allocation
1523   if ( widgets->ats )
1524     g_free ( widgets->ats );
1525
1526   widgets->ats = vik_track_make_elevation_time_map ( tr, widgets->profile_width );
1527
1528   if ( widgets->ats == NULL )
1529     return;
1530
1531   // Convert into appropriate units
1532   vik_units_height_t height_units = a_vik_get_units_height ();
1533   if ( height_units == VIK_UNITS_HEIGHT_FEET ) {
1534     // Convert altitudes into feet units
1535     for ( i = 0; i < widgets->profile_width; i++ ) {
1536       widgets->ats[i] = VIK_METERS_TO_FEET(widgets->ats[i]);
1537     }
1538   }
1539   // Otherwise leave in metres
1540
1541   minmax_array(widgets->ats, &widgets->min_altitude, &widgets->max_altitude, TRUE, widgets->profile_width);
1542
1543   get_new_min_and_chunk_index_altitude (widgets->min_altitude, widgets->max_altitude, &widgets->draw_min_altitude_time, &widgets->ciat);
1544
1545   // Assign locally
1546   mina = widgets->draw_min_altitude_time;
1547
1548   window = gtk_widget_get_toplevel (widgets->elev_time_box);
1549
1550   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
1551
1552   gtk_image_set_from_pixmap ( GTK_IMAGE(image), pix, NULL );
1553
1554   /* clear the image */
1555   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->bg_gc[0],
1556                      TRUE, 0, 0, MARGIN, widgets->profile_height);
1557   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->mid_gc[0],
1558                      TRUE, MARGIN, 0, widgets->profile_width, widgets->profile_height);
1559
1560   /* draw grid */
1561   for (i=0; i<=LINES; i++) {
1562     PangoFontDescription *pfd;
1563     PangoLayout *pl = gtk_widget_create_pango_layout (GTK_WIDGET(image), NULL);
1564     gchar s[32];
1565     int w, h;
1566
1567     pango_layout_set_alignment (pl, PANGO_ALIGN_RIGHT);
1568     pfd = pango_font_description_from_string (PROPWIN_LABEL_FONT);
1569     pango_layout_set_font_description (pl, pfd);
1570     pango_font_description_free (pfd);
1571     switch (height_units) {
1572     case VIK_UNITS_HEIGHT_METRES:
1573       sprintf(s, "%8dm", (int)(mina + (LINES-i)*chunksa[widgets->ciat]));
1574       break;
1575     case VIK_UNITS_HEIGHT_FEET:
1576       // NB values already converted into feet
1577       sprintf(s, "%8dft", (int)(mina + (LINES-i)*chunksa[widgets->ciat]));
1578       break;
1579     default:
1580       sprintf(s, "--");
1581       g_critical("Houston, we've had a problem. height=%d", height_units);
1582     }
1583     pango_layout_set_text(pl, s, -1);
1584     pango_layout_get_pixel_size (pl, &w, &h);
1585     gdk_draw_layout(GDK_DRAWABLE(pix), window->style->fg_gc[0], MARGIN-w-3,
1586                     CLAMP((int)i*widgets->profile_height/LINES - h/2, 0, widgets->profile_height-h), pl);
1587
1588     gdk_draw_line (GDK_DRAWABLE(pix), window->style->dark_gc[0],
1589                    MARGIN, widgets->profile_height/LINES * i, MARGIN + widgets->profile_width, widgets->profile_height/LINES * i);
1590     g_object_unref ( G_OBJECT ( pl ) );
1591     pl = NULL;
1592   }
1593
1594   /* draw elevations */
1595   for ( i = 0; i < widgets->profile_width; i++ )
1596       gdk_draw_line ( GDK_DRAWABLE(pix), window->style->dark_gc[3],
1597                       i + MARGIN, widgets->profile_height, i + MARGIN, widgets->profile_height-widgets->profile_height*(widgets->ats[i]-mina)/(chunksa[widgets->ciat]*LINES) );
1598
1599   // Show speed indicator
1600   if ( gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widgets->w_show_elev_speed)) ) {
1601     GdkGC *elev_speed_gc = gdk_gc_new ( window->window );
1602     GdkColor color;
1603     gdk_color_parse ( "red", &color );
1604     gdk_gc_set_rgb_fg_color ( elev_speed_gc, &color);
1605
1606     gdouble max_speed = 0;
1607     max_speed = widgets->max_speed * 110 / 100;
1608
1609     // This is just an indicator - no actual values can be inferred by user
1610     gint i;
1611     for ( i = 0; i < widgets->profile_width; i++ ) {
1612       int y_speed = widgets->profile_height - (widgets->profile_height * widgets->speeds[i])/max_speed;
1613       gdk_draw_rectangle(GDK_DRAWABLE(pix), elev_speed_gc, TRUE, i+MARGIN-2, y_speed-2, 4, 4);
1614     }
1615     g_object_unref ( G_OBJECT(elev_speed_gc) );
1616   }
1617
1618   /* draw border */
1619   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->black_gc, FALSE, MARGIN, 0, widgets->profile_width-1, widgets->profile_height-1);
1620
1621   g_object_unref ( G_OBJECT(pix) );
1622
1623 }
1624
1625 /**
1626  * Draw just the speed/distance image
1627  */
1628 static void draw_sd ( GtkWidget *image, VikTrack *tr, PropWidgets *widgets)
1629 {
1630   GtkWidget *window;
1631   GdkPixmap *pix;
1632   gdouble mins;
1633   guint i;
1634
1635   // Free previous allocation
1636   if ( widgets->speeds_dist )
1637     g_free ( widgets->speeds_dist );
1638
1639   widgets->speeds_dist = vik_track_make_speed_dist_map ( tr, widgets->profile_width );
1640   if ( widgets->speeds_dist == NULL )
1641     return;
1642
1643   // Convert into appropriate units
1644   vik_units_speed_t speed_units = a_vik_get_units_speed ();
1645   switch (speed_units) {
1646   case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
1647     for ( i = 0; i < widgets->profile_width; i++ ) {
1648       widgets->speeds_dist[i] = VIK_MPS_TO_KPH(widgets->speeds_dist[i]);
1649     }
1650     break;
1651   case VIK_UNITS_SPEED_MILES_PER_HOUR:
1652     for ( i = 0; i < widgets->profile_width; i++ ) {
1653       widgets->speeds_dist[i] = VIK_MPS_TO_MPH(widgets->speeds_dist[i]);
1654     }
1655     break;
1656   case VIK_UNITS_SPEED_KNOTS:
1657     for ( i = 0; i < widgets->profile_width; i++ ) {
1658       widgets->speeds_dist[i] = VIK_MPS_TO_KNOTS(widgets->speeds_dist[i]);
1659     }
1660     break;
1661   default:
1662     // VIK_UNITS_SPEED_METRES_PER_SECOND:
1663     // No need to convert as already in m/s
1664     break;
1665   }
1666
1667   window = gtk_widget_get_toplevel (widgets->speed_dist_box);
1668
1669   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
1670
1671   gtk_image_set_from_pixmap ( GTK_IMAGE(image), pix, NULL );
1672
1673   // OK to resuse min_speed here
1674   minmax_array(widgets->speeds_dist, &widgets->min_speed, &widgets->max_speed_dist, FALSE, widgets->profile_width);
1675   if (widgets->min_speed < 0.0)
1676     widgets->min_speed = 0; /* splines sometimes give negative speeds */
1677
1678   /* Find suitable chunk index */
1679   get_new_min_and_chunk_index (widgets->min_speed, widgets->max_speed_dist, chunkss, sizeof(chunkss)/sizeof(chunkss[0]), &widgets->draw_min_speed, &widgets->cisd);
1680
1681   // Assign locally
1682   mins = widgets->draw_min_speed;
1683   
1684   /* clear the image */
1685   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->bg_gc[0],
1686                      TRUE, 0, 0, MARGIN, widgets->profile_height);
1687   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->mid_gc[0],
1688                      TRUE, MARGIN, 0, widgets->profile_width, widgets->profile_height);
1689
1690   /* draw grid */
1691   for (i=0; i<=LINES; i++) {
1692     PangoFontDescription *pfd;
1693     PangoLayout *pl = gtk_widget_create_pango_layout (GTK_WIDGET(image), NULL);
1694     gchar s[32];
1695     int w, h;
1696
1697     pango_layout_set_alignment (pl, PANGO_ALIGN_RIGHT);
1698     pfd = pango_font_description_from_string (PROPWIN_LABEL_FONT);
1699     pango_layout_set_font_description (pl, pfd);
1700     pango_font_description_free (pfd);
1701     // NB: No need to convert here anymore as numbers are in the appropriate units
1702     switch (speed_units) {
1703     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
1704       sprintf(s, "%8dkm/h", (int)(mins + (LINES-i)*chunkss[widgets->cisd]));
1705       break;
1706     case VIK_UNITS_SPEED_MILES_PER_HOUR:
1707       sprintf(s, "%8dmph", (int)(mins + (LINES-i)*chunkss[widgets->cisd]));
1708       break;
1709     case VIK_UNITS_SPEED_METRES_PER_SECOND:
1710       sprintf(s, "%8dm/s", (int)(mins + (LINES-i)*chunkss[widgets->cisd]));
1711       break;
1712     case VIK_UNITS_SPEED_KNOTS:
1713       sprintf(s, "%8dknots", (int)(mins + (LINES-i)*chunkss[widgets->cisd]));
1714       break;
1715     default:
1716       sprintf(s, "--");
1717       g_critical("Houston, we've had a problem. speed=%d", speed_units);
1718     }
1719
1720     pango_layout_set_text(pl, s, -1);
1721     pango_layout_get_pixel_size (pl, &w, &h);
1722     gdk_draw_layout(GDK_DRAWABLE(pix), window->style->fg_gc[0], MARGIN-w-3,
1723                     CLAMP((int)i*widgets->profile_height/LINES - h/2, 0, widgets->profile_height-h), pl);
1724
1725     gdk_draw_line (GDK_DRAWABLE(pix), window->style->dark_gc[0],
1726                    MARGIN, widgets->profile_height/LINES * i, MARGIN + widgets->profile_width, widgets->profile_height/LINES * i);
1727     g_object_unref ( G_OBJECT ( pl ) );
1728     pl = NULL;
1729   }
1730   
1731
1732   /* draw speeds */
1733   for ( i = 0; i < widgets->profile_width; i++ )
1734       gdk_draw_line ( GDK_DRAWABLE(pix), window->style->dark_gc[3],
1735                       i + MARGIN, widgets->profile_height, i + MARGIN, widgets->profile_height-widgets->profile_height*(widgets->speeds_dist[i]-mins)/(chunkss[widgets->cisd]*LINES) );
1736
1737
1738   if ( gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widgets->w_show_sd_gps_speed)) ) {
1739
1740     GdkGC *gps_speed_gc = gdk_gc_new ( window->window );
1741     GdkColor color;
1742     gdk_color_parse ( "red", &color );
1743     gdk_gc_set_rgb_fg_color ( gps_speed_gc, &color);
1744
1745     gdouble dist = vik_track_get_length_including_gaps(tr);
1746     gdouble dist_tp = 0.0;
1747
1748     GList *iter = tr->trackpoints;
1749     for (iter = iter->next; iter; iter = iter->next) {
1750       gdouble gps_speed = VIK_TRACKPOINT(iter->data)->speed;
1751       if (isnan(gps_speed))
1752         continue;
1753       switch (speed_units) {
1754       case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
1755         gps_speed = VIK_MPS_TO_KPH(gps_speed);
1756         break;
1757       case VIK_UNITS_SPEED_MILES_PER_HOUR:
1758         gps_speed = VIK_MPS_TO_MPH(gps_speed);
1759         break;
1760       case VIK_UNITS_SPEED_KNOTS:
1761         gps_speed = VIK_MPS_TO_KNOTS(gps_speed);
1762         break;
1763       default:
1764         // VIK_UNITS_SPEED_METRES_PER_SECOND:
1765         // No need to convert as already in m/s
1766         break;
1767       }
1768       dist_tp += vik_coord_diff ( &(VIK_TRACKPOINT(iter->data)->coord), &(VIK_TRACKPOINT(iter->prev->data)->coord) );
1769       int x = MARGIN + (widgets->profile_width * dist_tp / dist);
1770       int y = widgets->profile_height - widgets->profile_height*(gps_speed - mins)/(chunkss[widgets->cisd]*LINES);
1771       gdk_draw_rectangle(GDK_DRAWABLE(pix), gps_speed_gc, TRUE, x-2, y-2, 4, 4);
1772     }
1773     g_object_unref ( G_OBJECT(gps_speed_gc) );
1774   }
1775
1776   /* draw border */
1777   gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->black_gc, FALSE, MARGIN, 0, widgets->profile_width-1, widgets->profile_height-1);
1778
1779   g_object_unref ( G_OBJECT(pix) );
1780 }
1781 #undef LINES
1782
1783 /**
1784  * Draw all graphs
1785  */
1786 static void draw_all_graphs ( GtkWidget *widget, gpointer *pass_along, gboolean resized )
1787 {
1788   VikTrack *tr = pass_along[0];
1789   PropWidgets *widgets = pass_along[3];
1790
1791   // Draw graphs even if they are not visible
1792
1793   GList *child = NULL;
1794   GtkWidget *image = NULL;
1795   GtkWidget *window = gtk_widget_get_toplevel(widget);
1796   gdouble pc = NAN;
1797   gdouble pc_blob = NAN;
1798
1799   // Draw elevations
1800   if (widgets->elev_box != NULL) {
1801
1802     // Saved image no longer any good as we've resized, so we remove it here
1803     if (resized && widgets->elev_graph_saved_img.img) {
1804       g_object_unref(widgets->elev_graph_saved_img.img);
1805       widgets->elev_graph_saved_img.img = NULL;
1806       widgets->elev_graph_saved_img.saved = FALSE;
1807     }
1808
1809     child = gtk_container_get_children(GTK_CONTAINER(widgets->elev_box));
1810     draw_elevations (GTK_WIDGET(child->data), tr, widgets );
1811
1812     image = GTK_WIDGET(child->data);
1813     g_list_free(child);
1814
1815     // Ensure marker or blob are redrawn if necessary
1816     if (widgets->is_marker_drawn || widgets->is_blob_drawn) {
1817
1818       pc = tp_percentage_by_distance ( tr, widgets->marker_tp, widgets->track_length_inc_gaps );
1819       gdouble x_blob = -MARGIN - 1.0; // i.e. Don't draw unless we get a valid value
1820       gint y_blob = 0;
1821       if (widgets->is_blob_drawn) {
1822         pc_blob = tp_percentage_by_distance ( tr, widgets->blob_tp, widgets->track_length_inc_gaps );
1823         if (!isnan(pc_blob)) {
1824           x_blob = (pc_blob * widgets->profile_width);
1825         }
1826         y_blob = blobby_altitude (x_blob, widgets);
1827       }
1828
1829       gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
1830       if (!isnan(pc)) {
1831         marker_x = (pc * widgets->profile_width) + MARGIN;
1832       }
1833
1834       save_image_and_draw_graph_marks (image,
1835                                        marker_x,
1836                                        window->style->black_gc,
1837                                        x_blob+MARGIN,
1838                                        y_blob,
1839                                        &widgets->elev_graph_saved_img,
1840                                        widgets->profile_width,
1841                                        widgets->profile_height,
1842                                        &widgets->is_marker_drawn,
1843                                        &widgets->is_blob_drawn);
1844     }
1845   }
1846
1847   // Draw speeds
1848   if (widgets->speed_box != NULL) {
1849
1850     // Saved image no longer any good as we've resized
1851     if (resized && widgets->speed_graph_saved_img.img) {
1852       g_object_unref(widgets->speed_graph_saved_img.img);
1853       widgets->speed_graph_saved_img.img = NULL;
1854       widgets->speed_graph_saved_img.saved = FALSE;
1855     }
1856
1857     child = gtk_container_get_children(GTK_CONTAINER(widgets->speed_box));
1858     draw_vt (GTK_WIDGET(child->data), tr, widgets );
1859
1860     image = GTK_WIDGET(child->data);
1861     g_list_free(child);
1862
1863     // Ensure marker or blob are redrawn if necessary
1864     if (widgets->is_marker_drawn || widgets->is_blob_drawn) {
1865
1866       pc = tp_percentage_by_time ( tr, widgets->marker_tp );
1867
1868       gdouble x_blob = -MARGIN - 1.0; // i.e. Don't draw unless we get a valid value
1869       gint    y_blob = 0;
1870       if (widgets->is_blob_drawn) {
1871         pc_blob = tp_percentage_by_time ( tr, widgets->blob_tp );
1872         if (!isnan(pc_blob)) {
1873           x_blob = (pc_blob * widgets->profile_width);
1874         }
1875          
1876         y_blob = blobby_speed (x_blob, widgets);
1877       }
1878
1879       gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
1880       if (!isnan(pc)) {
1881         marker_x = (pc * widgets->profile_width) + MARGIN;
1882       }
1883
1884       save_image_and_draw_graph_marks (image,
1885                                        marker_x,
1886                                        window->style->black_gc,
1887                                        x_blob+MARGIN,
1888                                        y_blob,
1889                                        &widgets->speed_graph_saved_img,
1890                                        widgets->profile_width,
1891                                        widgets->profile_height,
1892                                        &widgets->is_marker_drawn,
1893                                        &widgets->is_blob_drawn);
1894     }
1895   }
1896
1897   // Draw Distances
1898   if (widgets->dist_box != NULL) {
1899
1900     // Saved image no longer any good as we've resized
1901     if (resized && widgets->dist_graph_saved_img.img) {
1902       g_object_unref(widgets->dist_graph_saved_img.img);
1903       widgets->dist_graph_saved_img.img = NULL;
1904       widgets->dist_graph_saved_img.saved = FALSE;
1905     }
1906
1907     child = gtk_container_get_children(GTK_CONTAINER(widgets->dist_box));
1908     draw_dt (GTK_WIDGET(child->data), tr, widgets );
1909
1910     image = GTK_WIDGET(child->data);
1911     g_list_free(child);
1912
1913     // Ensure marker or blob are redrawn if necessary
1914     if (widgets->is_marker_drawn || widgets->is_blob_drawn) {
1915
1916       pc = tp_percentage_by_time ( tr, widgets->marker_tp );
1917
1918       gdouble x_blob = -MARGIN - 1.0; // i.e. Don't draw unless we get a valid value
1919       gint    y_blob = 0;
1920       if (widgets->is_blob_drawn) {
1921         pc_blob = tp_percentage_by_time ( tr, widgets->blob_tp );
1922         if (!isnan(pc_blob)) {
1923           x_blob = (pc_blob * widgets->profile_width);
1924         }
1925          
1926         y_blob = blobby_distance (x_blob, widgets);
1927       }
1928
1929       gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
1930       if (!isnan(pc)) {
1931         marker_x = (pc * widgets->profile_width) + MARGIN;
1932       }
1933
1934       save_image_and_draw_graph_marks (image,
1935                                        marker_x,
1936                                        window->style->black_gc,
1937                                        x_blob+MARGIN,
1938                                        y_blob,
1939                                        &widgets->dist_graph_saved_img,
1940                                        widgets->profile_width,
1941                                        widgets->profile_height,
1942                                        &widgets->is_marker_drawn,
1943                                        &widgets->is_blob_drawn);
1944     }
1945   }
1946
1947   // Draw Elevations in timely manner
1948   if (widgets->elev_time_box != NULL) {
1949
1950     // Saved image no longer any good as we've resized
1951     if (resized && widgets->elev_time_graph_saved_img.img) {
1952       g_object_unref(widgets->elev_time_graph_saved_img.img);
1953       widgets->elev_time_graph_saved_img.img = NULL;
1954       widgets->elev_time_graph_saved_img.saved = FALSE;
1955     }
1956
1957     child = gtk_container_get_children(GTK_CONTAINER(widgets->elev_time_box));
1958     draw_et (GTK_WIDGET(child->data), tr, widgets );
1959
1960     image = GTK_WIDGET(child->data);
1961     g_list_free(child);
1962
1963     // Ensure marker or blob are redrawn if necessary
1964     if (widgets->is_marker_drawn || widgets->is_blob_drawn) {
1965
1966       pc = tp_percentage_by_time ( tr, widgets->marker_tp );
1967
1968       gdouble x_blob = -MARGIN - 1.0; // i.e. Don't draw unless we get a valid value
1969       gint    y_blob = 0;
1970       if (widgets->is_blob_drawn) {
1971         pc_blob = tp_percentage_by_time ( tr, widgets->blob_tp );
1972         if (!isnan(pc_blob)) {
1973           x_blob = (pc_blob * widgets->profile_width);
1974         }
1975         y_blob = blobby_altitude_time (x_blob, widgets);
1976       }
1977
1978       gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
1979       if (!isnan(pc)) {
1980         marker_x = (pc * widgets->profile_width) + MARGIN;
1981       }
1982
1983       save_image_and_draw_graph_marks (image,
1984                                        marker_x,
1985                                        window->style->black_gc,
1986                                        x_blob+MARGIN,
1987                                        y_blob,
1988                                        &widgets->elev_time_graph_saved_img,
1989                                        widgets->profile_width,
1990                                        widgets->profile_height,
1991                                        &widgets->is_marker_drawn,
1992                                        &widgets->is_blob_drawn);
1993     }
1994   }
1995
1996   // Draw speed distances
1997   if (widgets->speed_dist_box != NULL) {
1998
1999     // Saved image no longer any good as we've resized, so we remove it here
2000     if (resized && widgets->speed_dist_graph_saved_img.img) {
2001       g_object_unref(widgets->speed_dist_graph_saved_img.img);
2002       widgets->speed_dist_graph_saved_img.img = NULL;
2003       widgets->speed_dist_graph_saved_img.saved = FALSE;
2004     }
2005
2006     child = gtk_container_get_children(GTK_CONTAINER(widgets->speed_dist_box));
2007     draw_sd (GTK_WIDGET(child->data), tr, widgets );
2008
2009     image = GTK_WIDGET(child->data);
2010     g_list_free(child);
2011
2012     // Ensure marker or blob are redrawn if necessary
2013     if (widgets->is_marker_drawn || widgets->is_blob_drawn) {
2014
2015       pc = tp_percentage_by_distance ( tr, widgets->marker_tp, widgets->track_length_inc_gaps );
2016       gdouble x_blob = -MARGIN - 1.0; // i.e. Don't draw unless we get a valid value
2017       gint y_blob = 0;
2018       if (widgets->is_blob_drawn) {
2019         pc_blob = tp_percentage_by_distance ( tr, widgets->blob_tp, widgets->track_length_inc_gaps );
2020         if (!isnan(pc_blob)) {
2021           x_blob = (pc_blob * widgets->profile_width);
2022         }
2023         y_blob = blobby_speed_dist (x_blob, widgets);
2024       }
2025
2026       gdouble marker_x = -1.0; // i.e. Don't draw unless we get a valid value
2027       if (!isnan(pc)) {
2028         marker_x = (pc * widgets->profile_width) + MARGIN;
2029       }
2030
2031       save_image_and_draw_graph_marks (image,
2032                                        marker_x,
2033                                        window->style->black_gc,
2034                                        x_blob+MARGIN,
2035                                        y_blob,
2036                                        &widgets->speed_dist_graph_saved_img,
2037                                        widgets->profile_width,
2038                                        widgets->profile_height,
2039                                        &widgets->is_marker_drawn,
2040                                        &widgets->is_blob_drawn);
2041     }
2042   }
2043
2044 }
2045
2046 /**
2047  * Configure/Resize the profile & speed/time images
2048  */
2049 static gboolean configure_event ( GtkWidget *widget, GdkEventConfigure *event, gpointer *pass_along )
2050 {
2051   PropWidgets *widgets = pass_along[3];
2052
2053   if (widgets->configure_dialog) {
2054     // Determine size offsets between dialog size and size for images
2055     // Only on the initialisation of the dialog
2056     widgets->profile_width_offset = event->width - widgets->profile_width;
2057     widgets->profile_height_offset = event->height - widgets->profile_height;
2058     widgets->configure_dialog = FALSE;
2059
2060     // Without this the settting, the dialog will only grow in vertical size - one can not then make it smaller!
2061     gtk_widget_set_size_request ( widget, widgets->profile_width+widgets->profile_width_offset, widgets->profile_height );
2062     // In fact this allows one to compress it a bit more vertically as I don't add on the height offset
2063   }
2064   else {
2065     widgets->profile_width_old = widgets->profile_width;
2066     widgets->profile_height_old = widgets->profile_height;
2067   }
2068
2069   // Now adjust From Dialog size to get image size
2070   widgets->profile_width = event->width - widgets->profile_width_offset;
2071   widgets->profile_height = event->height - widgets->profile_height_offset;
2072
2073   // ATM we receive configure_events when the dialog is moved and so no further action is necessary
2074   if ( !widgets->configure_dialog &&
2075        (widgets->profile_width_old == widgets->profile_width) && (widgets->profile_height_old == widgets->profile_height) )
2076     return FALSE;
2077
2078   // Draw stuff
2079   draw_all_graphs ( widget, pass_along, TRUE );
2080
2081   return FALSE;
2082 }
2083
2084 /**
2085  * Create height profile widgets including the image and callbacks
2086  */
2087 GtkWidget *vik_trw_layer_create_profile ( GtkWidget *window, VikTrack *tr, gpointer vlp, VikViewport *vvp, PropWidgets *widgets, gdouble *min_alt, gdouble *max_alt)
2088 {
2089   GdkPixmap *pix;
2090   GtkWidget *image;
2091   GtkWidget *eventbox;
2092   gpointer *pass_along;
2093
2094   // First allocation
2095   widgets->altitudes = vik_track_make_elevation_map ( tr, widgets->profile_width );
2096
2097   if ( widgets->altitudes == NULL ) {
2098     *min_alt = *max_alt = VIK_DEFAULT_ALTITUDE;
2099     return NULL;
2100   }
2101
2102   minmax_array(widgets->altitudes, min_alt, max_alt, TRUE, widgets->profile_width);
2103   
2104   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
2105   image = gtk_image_new_from_pixmap ( pix, NULL );
2106
2107   g_object_unref ( G_OBJECT(pix) );
2108
2109   pass_along = g_malloc ( sizeof(gpointer) * 4 ); /* FIXME: mem leak -- never be freed */
2110   pass_along[0] = tr;
2111   pass_along[1] = vlp;
2112   pass_along[2] = vvp;
2113   pass_along[3] = widgets;
2114
2115   eventbox = gtk_event_box_new ();
2116   g_signal_connect ( G_OBJECT(eventbox), "button_press_event", G_CALLBACK(track_profile_click), pass_along );
2117   g_signal_connect ( G_OBJECT(eventbox), "motion_notify_event", G_CALLBACK(track_profile_move), pass_along );
2118   g_signal_connect_swapped ( G_OBJECT(eventbox), "destroy", G_CALLBACK(g_free), pass_along );
2119   gtk_container_add ( GTK_CONTAINER(eventbox), image );
2120   gtk_widget_set_events (eventbox, GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_STRUCTURE_MASK);
2121
2122   return eventbox;
2123 }
2124
2125 /**
2126  * Create speed/time widgets including the image and callbacks
2127  */
2128 GtkWidget *vik_trw_layer_create_vtdiag ( GtkWidget *window, VikTrack *tr, gpointer vlp, VikViewport *vvp, PropWidgets *widgets)
2129 {
2130   GdkPixmap *pix;
2131   GtkWidget *image;
2132   GtkWidget *eventbox;
2133   gpointer *pass_along;
2134
2135   // First allocation
2136   widgets->speeds = vik_track_make_speed_map ( tr, widgets->profile_width );
2137   if ( widgets->speeds == NULL )
2138     return NULL;
2139
2140   pass_along = g_malloc ( sizeof(gpointer) * 4 ); /* FIXME: mem leak -- never be freed */
2141   pass_along[0] = tr;
2142   pass_along[1] = vlp;
2143   pass_along[2] = vvp;
2144   pass_along[3] = widgets;
2145
2146   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
2147   image = gtk_image_new_from_pixmap ( pix, NULL );
2148
2149 #if 0
2150   /* XXX this can go out, it's just a helpful dev tool */
2151   {
2152     int j;
2153     GdkGC **colors[8] = { window->style->bg_gc,
2154                           window->style->fg_gc,
2155                           window->style->light_gc,
2156                           window->style->dark_gc,
2157                           window->style->mid_gc,
2158                           window->style->text_gc,
2159                           window->style->base_gc,
2160                           window->style->text_aa_gc };
2161     for (i=0; i<5; i++) {
2162       for (j=0; j<8; j++) {
2163         gdk_draw_rectangle(GDK_DRAWABLE(pix), colors[j][i],
2164                            TRUE, i*20, j*20, 20, 20);
2165         gdk_draw_rectangle(GDK_DRAWABLE(pix), window->style->black_gc,
2166                            FALSE, i*20, j*20, 20, 20);
2167       }
2168     }
2169   }
2170 #endif
2171
2172   g_object_unref ( G_OBJECT(pix) );
2173
2174   eventbox = gtk_event_box_new ();
2175   g_signal_connect ( G_OBJECT(eventbox), "button_press_event", G_CALLBACK(track_vt_click), pass_along );
2176   g_signal_connect ( G_OBJECT(eventbox), "motion_notify_event", G_CALLBACK(track_vt_move), pass_along );
2177   g_signal_connect_swapped ( G_OBJECT(eventbox), "destroy", G_CALLBACK(g_free), pass_along );
2178   gtk_container_add ( GTK_CONTAINER(eventbox), image );
2179   gtk_widget_set_events (eventbox, GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK);
2180
2181   return eventbox;
2182 }
2183
2184 /**
2185  * Create distance / time widgets including the image and callbacks
2186  */
2187 GtkWidget *vik_trw_layer_create_dtdiag ( GtkWidget *window, VikTrack *tr, gpointer vlp, VikViewport *vvp, PropWidgets *widgets)
2188 {
2189   GdkPixmap *pix;
2190   GtkWidget *image;
2191   GtkWidget *eventbox;
2192   gpointer *pass_along;
2193
2194   // First allocation
2195   widgets->distances = vik_track_make_distance_map ( tr, widgets->profile_width );
2196   if ( widgets->distances == NULL )
2197     return NULL;
2198
2199   pass_along = g_malloc ( sizeof(gpointer) * 4 ); /* FIXME: mem leak -- never be freed */
2200   pass_along[0] = tr;
2201   pass_along[1] = vlp;
2202   pass_along[2] = vvp;
2203   pass_along[3] = widgets;
2204
2205   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
2206   image = gtk_image_new_from_pixmap ( pix, NULL );
2207
2208   g_object_unref ( G_OBJECT(pix) );
2209
2210   eventbox = gtk_event_box_new ();
2211   g_signal_connect ( G_OBJECT(eventbox), "button_press_event", G_CALLBACK(track_dt_click), pass_along );
2212   g_signal_connect ( G_OBJECT(eventbox), "motion_notify_event", G_CALLBACK(track_dt_move), pass_along );
2213   g_signal_connect_swapped ( G_OBJECT(eventbox), "destroy", G_CALLBACK(g_free), pass_along );
2214   gtk_container_add ( GTK_CONTAINER(eventbox), image );
2215   gtk_widget_set_events (eventbox, GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK);
2216
2217   return eventbox;
2218 }
2219
2220 /**
2221  * Create elevation / time widgets including the image and callbacks
2222  */
2223 GtkWidget *vik_trw_layer_create_etdiag ( GtkWidget *window, VikTrack *tr, gpointer vlp, VikViewport *vvp, PropWidgets *widgets)
2224 {
2225   GdkPixmap *pix;
2226   GtkWidget *image;
2227   GtkWidget *eventbox;
2228   gpointer *pass_along;
2229
2230   // First allocation
2231   widgets->ats = vik_track_make_elevation_time_map ( tr, widgets->profile_width );
2232   if ( widgets->ats == NULL )
2233     return NULL;
2234
2235   pass_along = g_malloc ( sizeof(gpointer) * 4 ); /* FIXME: mem leak -- never be freed */
2236   pass_along[0] = tr;
2237   pass_along[1] = vlp;
2238   pass_along[2] = vvp;
2239   pass_along[3] = widgets;
2240
2241   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
2242   image = gtk_image_new_from_pixmap ( pix, NULL );
2243
2244   g_object_unref ( G_OBJECT(pix) );
2245
2246   eventbox = gtk_event_box_new ();
2247   g_signal_connect ( G_OBJECT(eventbox), "button_press_event", G_CALLBACK(track_et_click), pass_along );
2248   g_signal_connect ( G_OBJECT(eventbox), "motion_notify_event", G_CALLBACK(track_et_move), pass_along );
2249   g_signal_connect_swapped ( G_OBJECT(eventbox), "destroy", G_CALLBACK(g_free), pass_along );
2250   gtk_container_add ( GTK_CONTAINER(eventbox), image );
2251   gtk_widget_set_events (eventbox, GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK);
2252
2253   return eventbox;
2254 }
2255
2256 /**
2257  * Create speed/distance widgets including the image and callbacks
2258  */
2259 GtkWidget *vik_trw_layer_create_sddiag ( GtkWidget *window, VikTrack *tr, gpointer vlp, VikViewport *vvp, PropWidgets *widgets)
2260 {
2261   GdkPixmap *pix;
2262   GtkWidget *image;
2263   GtkWidget *eventbox;
2264   gpointer *pass_along;
2265
2266   // First allocation
2267   widgets->speeds_dist = vik_track_make_speed_dist_map ( tr, widgets->profile_width );
2268   if ( widgets->speeds_dist == NULL )
2269     return NULL;
2270
2271   pass_along = g_malloc ( sizeof(gpointer) * 4 ); /* FIXME: mem leak -- never be freed */
2272   pass_along[0] = tr;
2273   pass_along[1] = vlp;
2274   pass_along[2] = vvp;
2275   pass_along[3] = widgets;
2276
2277   pix = gdk_pixmap_new( window->window, widgets->profile_width + MARGIN, widgets->profile_height, -1 );
2278   image = gtk_image_new_from_pixmap ( pix, NULL );
2279
2280   g_object_unref ( G_OBJECT(pix) );
2281
2282   eventbox = gtk_event_box_new ();
2283   g_signal_connect ( G_OBJECT(eventbox), "button_press_event", G_CALLBACK(track_sd_click), pass_along );
2284   g_signal_connect ( G_OBJECT(eventbox), "motion_notify_event", G_CALLBACK(track_sd_move), pass_along );
2285   g_signal_connect_swapped ( G_OBJECT(eventbox), "destroy", G_CALLBACK(g_free), pass_along );
2286   gtk_container_add ( GTK_CONTAINER(eventbox), image );
2287   gtk_widget_set_events (eventbox, GDK_BUTTON_PRESS_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK);
2288
2289   return eventbox;
2290 }
2291 #undef MARGIN
2292
2293 static void propwin_response_cb( GtkDialog *dialog, gint resp, PropWidgets *widgets)
2294 {
2295   VikTrack *tr = widgets->tr;
2296   VikTrwLayer *vtl = widgets->vtl;
2297   gboolean keep_dialog = FALSE;
2298
2299   /* FIXME: check and make sure the track still exists before doing anything to it */
2300   /* Note: destroying diaglog (eg, parent window exit) won't give "response" */
2301   switch (resp) {
2302     case GTK_RESPONSE_DELETE_EVENT: /* received delete event (not from buttons) */
2303     case GTK_RESPONSE_REJECT:
2304       break;
2305     case GTK_RESPONSE_ACCEPT:
2306       vik_track_set_comment(tr, gtk_entry_get_text(GTK_ENTRY(widgets->w_comment)));
2307       break;
2308     case VIK_TRW_LAYER_PROPWIN_REVERSE:
2309       vik_track_reverse(tr);
2310       vik_layer_emit_update ( VIK_LAYER(vtl), FALSE );
2311       break;
2312     case VIK_TRW_LAYER_PROPWIN_DEL_DUP:
2313       vik_track_remove_dup_points(tr);
2314       /* above operation could have deleted current_tp or last_tp */
2315       trw_layer_cancel_tps_of_track ( vtl, widgets->track_name );
2316       vik_layer_emit_update ( VIK_LAYER(vtl), FALSE );
2317       break;
2318     case VIK_TRW_LAYER_PROPWIN_SPLIT:
2319       {
2320         /* get new tracks, add them, resolve naming conflicts (free if cancel), and delete old. old can still exist on clipboard. */
2321         guint ntracks;
2322         VikTrack **tracks = vik_track_split_into_segments(tr, &ntracks);
2323         gchar *new_tr_name;
2324         guint i;
2325         for ( i = 0; i < ntracks; i++ )
2326         {
2327           g_assert ( tracks[i] );
2328           new_tr_name = g_strdup_printf("%s #%d", widgets->track_name, i+1);
2329           /* if ( (wp_exists) && (! overwrite) ) */
2330           /* don't need to upper case new_tr_name because old tr name was uppercase */
2331           if ( vik_trw_layer_get_track(vtl, new_tr_name ) && 
2332              ( ! a_dialog_yes_or_no ( VIK_GTK_WINDOW_FROM_LAYER(vtl), "The track \"%s\" exists, do you wish to overwrite it?", new_tr_name ) ) )
2333           {
2334             gchar *new_new_tr_name = a_dialog_new_track ( VIK_GTK_WINDOW_FROM_LAYER(vtl), vik_trw_layer_get_tracks(vtl), NULL );
2335             g_free ( new_tr_name );
2336             if (new_new_tr_name)
2337               new_tr_name = new_new_tr_name;
2338             else
2339             {
2340               new_tr_name = NULL;
2341               vik_track_free ( tracks[i] );
2342             }
2343           }
2344           if ( new_tr_name )
2345             vik_trw_layer_add_track ( vtl, new_tr_name, tracks[i] );
2346         }
2347         if ( tracks )
2348         {
2349           g_free ( tracks );
2350           /* Don't let track destroy this dialog */
2351           vik_track_clear_property_dialog(tr);
2352           vik_trw_layer_delete_track ( vtl, widgets->track_name );
2353           vik_layer_emit_update ( VIK_LAYER(vtl), FALSE ); /* chase thru the hoops */
2354         }
2355       }
2356       break;
2357     case VIK_TRW_LAYER_PROPWIN_SPLIT_MARKER:
2358       {
2359         GList *iter = tr->trackpoints;
2360         while ((iter = iter->next)) {
2361           if (widgets->marker_tp == VIK_TRACKPOINT(iter->data))
2362             break;
2363         }
2364         if (iter == NULL) {
2365           a_dialog_msg(VIK_GTK_WINDOW_FROM_LAYER(vtl), GTK_MESSAGE_ERROR,
2366                   _("Failed spliting track. Track unchanged"), NULL);
2367           keep_dialog = TRUE;
2368           break;
2369         }
2370
2371         gchar *r_name = g_strdup_printf("%s #2", widgets->track_name);
2372         if (vik_trw_layer_get_track(vtl, r_name ) && 
2373              ( ! a_dialog_yes_or_no( VIK_GTK_WINDOW_FROM_LAYER(vtl),
2374               "The track \"%s\" exists, do you wish to overwrite it?", r_name)))
2375         {
2376           gchar *new_r_name = a_dialog_new_track( VIK_GTK_WINDOW_FROM_LAYER(vtl), vik_trw_layer_get_tracks(vtl), NULL );
2377             if (new_r_name) {
2378               g_free( r_name );
2379               r_name = new_r_name;
2380             }
2381             else {
2382               a_dialog_msg(VIK_GTK_WINDOW_FROM_LAYER(vtl), GTK_MESSAGE_WARNING,
2383                   _("Operation Aborted. Track unchanged"), NULL);
2384               keep_dialog = TRUE;
2385               break;
2386             }
2387         }
2388         iter->prev->next = NULL;
2389         iter->prev = NULL;
2390         VikTrack *tr_right = vik_track_new();
2391         if ( tr->comment )
2392           vik_track_set_comment ( tr_right, tr->comment );
2393         tr_right->visible = tr->visible;
2394         tr_right->trackpoints = iter;
2395
2396         vik_trw_layer_add_track(vtl, r_name, tr_right);
2397         vik_layer_emit_update ( VIK_LAYER(vtl), FALSE );
2398       }
2399       break;
2400     default:
2401       fprintf(stderr, "DEBUG: unknown response\n");
2402       return;
2403   }
2404
2405   /* Keep same behaviour for now: destroy dialog if click on any button */
2406   if (!keep_dialog) {
2407     prop_widgets_free(widgets);
2408     vik_track_clear_property_dialog(tr);
2409     gtk_widget_destroy ( GTK_WIDGET(dialog) );
2410   }
2411 }
2412
2413 /**
2414  * Force a redraw when checkbutton has been toggled to show/hide that information
2415  */
2416 static void checkbutton_toggle_cb ( GtkToggleButton *togglebutton, gpointer *pass_along, gpointer dummy)
2417 {
2418   PropWidgets *widgets = pass_along[3];
2419   // Even though not resized, we'll pretend it is -
2420   //  as this invalidates the saved images (since the image may have changed)
2421   draw_all_graphs ( widgets->dialog, pass_along, TRUE);
2422 }
2423
2424 /**
2425  *  Create the widgets for the given graph tab
2426  */
2427 static GtkWidget *create_graph_page ( GtkWidget *graph,
2428                                       const gchar *markup,
2429                                       GtkWidget *value,
2430                                       const gchar *markup2,
2431                                       GtkWidget *value2,
2432                                       GtkWidget *checkbutton1,
2433                                       gboolean checkbutton1_default,
2434                                       GtkWidget *checkbutton2,
2435                                       gboolean checkbutton2_default )
2436 {
2437   GtkWidget *hbox = gtk_hbox_new ( FALSE, 10 );
2438   GtkWidget *vbox = gtk_vbox_new ( FALSE, 10 );
2439   GtkWidget *label = gtk_label_new (NULL);
2440   GtkWidget *label2 = gtk_label_new (NULL);
2441   gtk_box_pack_start (GTK_BOX(vbox), graph, FALSE, FALSE, 0);
2442   gtk_label_set_markup ( GTK_LABEL(label), markup );
2443   gtk_label_set_markup ( GTK_LABEL(label2), markup2 );
2444   gtk_box_pack_start (GTK_BOX(hbox), label, FALSE, FALSE, 0);
2445   gtk_box_pack_start (GTK_BOX(hbox), value, FALSE, FALSE, 0);
2446   gtk_box_pack_start (GTK_BOX(hbox), label2, FALSE, FALSE, 0);
2447   gtk_box_pack_start (GTK_BOX(hbox), value2, FALSE, FALSE, 0);
2448   if (checkbutton2) {
2449     gtk_box_pack_end (GTK_BOX(hbox), checkbutton2, FALSE, FALSE, 0);
2450     gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON(checkbutton2), checkbutton2_default);
2451   }
2452   if (checkbutton1) {
2453     gtk_box_pack_end (GTK_BOX(hbox), checkbutton1, FALSE, FALSE, 0);
2454     gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON(checkbutton1), checkbutton1_default);
2455   }
2456   gtk_box_pack_start (GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
2457
2458   return vbox;
2459 }
2460
2461 void vik_trw_layer_propwin_run ( GtkWindow *parent, VikTrwLayer *vtl, VikTrack *tr, gpointer vlp, gchar *track_name, VikViewport *vvp )
2462 {
2463   /* FIXME: free widgets when destroy signal received */
2464   PropWidgets *widgets = prop_widgets_new();
2465   widgets->vtl = vtl;
2466   widgets->tr = tr;
2467   widgets->profile_width  = PROPWIN_PROFILE_WIDTH;
2468   widgets->profile_height = PROPWIN_PROFILE_HEIGHT;
2469   widgets->track_name = track_name;
2470   gchar *title = g_strdup_printf(_("%s - Track Properties"), track_name);
2471   GtkWidget *dialog = gtk_dialog_new_with_buttons (title,
2472                          parent,
2473                          GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_NO_SEPARATOR,
2474                          GTK_STOCK_CANCEL, GTK_RESPONSE_REJECT,
2475                          _("Split at _Marker"), VIK_TRW_LAYER_PROPWIN_SPLIT_MARKER,
2476                          _("Split _Segments"), VIK_TRW_LAYER_PROPWIN_SPLIT,
2477                          _("_Reverse"),        VIK_TRW_LAYER_PROPWIN_REVERSE,
2478                          _("_Delete Dupl."),   VIK_TRW_LAYER_PROPWIN_DEL_DUP,
2479                          GTK_STOCK_OK,     GTK_RESPONSE_ACCEPT,
2480                          NULL);
2481   widgets->dialog = dialog;
2482   g_free(title);
2483   g_signal_connect(dialog, "response", G_CALLBACK(propwin_response_cb), widgets);
2484   GtkTable *table;
2485   gdouble tr_len;
2486   guint32 tp_count, seg_count;
2487
2488   gdouble min_alt, max_alt;
2489   widgets->elev_box = vik_trw_layer_create_profile(GTK_WIDGET(parent), tr, vlp, vvp, widgets, &min_alt, &max_alt);
2490   widgets->speed_box = vik_trw_layer_create_vtdiag(GTK_WIDGET(parent), tr, vlp, vvp, widgets);
2491   widgets->dist_box = vik_trw_layer_create_dtdiag(GTK_WIDGET(parent), tr, vlp, vvp, widgets);
2492   widgets->elev_time_box = vik_trw_layer_create_etdiag(GTK_WIDGET(parent), tr, vlp, vvp, widgets);
2493   widgets->speed_dist_box = vik_trw_layer_create_sddiag(GTK_WIDGET(parent), tr, vlp, vvp, widgets);
2494   GtkWidget *graphs = gtk_notebook_new();
2495
2496   GtkWidget *content[20];
2497   int cnt;
2498   int i;
2499
2500   static gchar *label_texts[] = { N_("<b>Comment:</b>"), N_("<b>Track Length:</b>"), N_("<b>Trackpoints:</b>"), N_("<b>Segments:</b>"), N_("<b>Duplicate Points:</b>"), N_("<b>Max Speed:</b>"), N_("<b>Avg. Speed:</b>"), N_("<b>Moving Avg. Speed:</b>"), N_("<b>Avg. Dist. Between TPs:</b>"), N_("<b>Elevation Range:</b>"), N_("<b>Total Elevation Gain/Loss:</b>"), N_("<b>Start:</b>"), N_("<b>End:</b>"), N_("<b>Duration:</b>") };
2501   static gchar tmp_buf[50];
2502   gdouble tmp_speed;
2503
2504   cnt = 0;
2505   widgets->w_comment = gtk_entry_new ();
2506   if ( tr->comment )
2507     gtk_entry_set_text ( GTK_ENTRY(widgets->w_comment), tr->comment );
2508   g_signal_connect_swapped ( widgets->w_comment, "activate", G_CALLBACK(a_dialog_response_accept), GTK_DIALOG(dialog) );
2509   content[cnt++] = widgets->w_comment;
2510
2511   vik_units_distance_t dist_units = a_vik_get_units_distance ();
2512
2513   // NB This value not shown yet - but is used by internal calculations
2514   widgets->track_length_inc_gaps = vik_track_get_length_including_gaps(tr);
2515
2516   tr_len = widgets->track_length = vik_track_get_length(tr);
2517   switch (dist_units) {
2518   case VIK_UNITS_DISTANCE_KILOMETRES:
2519     g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km", tr_len/1000.0 );
2520     break;
2521   case VIK_UNITS_DISTANCE_MILES:
2522     g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f miles", VIK_METERS_TO_MILES(tr_len) );
2523     break;
2524   default:
2525     g_critical("Houston, we've had a problem. distance=%d", dist_units);
2526   }
2527   widgets->w_track_length = content[cnt++] = gtk_label_new ( tmp_buf );
2528
2529   tp_count = vik_track_get_tp_count(tr);
2530   g_snprintf(tmp_buf, sizeof(tmp_buf), "%u", tp_count );
2531   widgets->w_tp_count = content[cnt++] = gtk_label_new ( tmp_buf );
2532
2533   seg_count = vik_track_get_segment_count(tr) ;
2534   g_snprintf(tmp_buf, sizeof(tmp_buf), "%u", seg_count );
2535   widgets->w_segment_count = content[cnt++] = gtk_label_new ( tmp_buf );
2536
2537   g_snprintf(tmp_buf, sizeof(tmp_buf), "%lu", vik_track_get_dup_point_count(tr) );
2538   widgets->w_duptp_count = content[cnt++] = gtk_label_new ( tmp_buf );
2539
2540   vik_units_speed_t speed_units = a_vik_get_units_speed ();
2541   tmp_speed = vik_track_get_max_speed(tr);
2542   if ( tmp_speed == 0 )
2543     g_snprintf(tmp_buf, sizeof(tmp_buf), _("No Data"));
2544   else {
2545     switch (speed_units) {
2546     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
2547       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km/h", VIK_MPS_TO_KPH(tmp_speed));
2548       break;
2549     case VIK_UNITS_SPEED_MILES_PER_HOUR:
2550       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f mph", VIK_MPS_TO_MPH(tmp_speed));
2551       break;
2552     case VIK_UNITS_SPEED_METRES_PER_SECOND:
2553       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f m/s", tmp_speed );
2554       break;
2555     case VIK_UNITS_SPEED_KNOTS:
2556       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f knots", VIK_MPS_TO_KNOTS(tmp_speed));
2557       break;
2558     default:
2559       g_snprintf (tmp_buf, sizeof(tmp_buf), "--" );
2560       g_critical("Houston, we've had a problem. speed=%d", speed_units);
2561     }
2562   }
2563   widgets->w_max_speed = content[cnt++] = gtk_label_new ( tmp_buf );
2564
2565   tmp_speed = vik_track_get_average_speed(tr);
2566   if ( tmp_speed == 0 )
2567     g_snprintf(tmp_buf, sizeof(tmp_buf), _("No Data"));
2568   else {
2569     switch (speed_units) {
2570     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
2571       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km/h", VIK_MPS_TO_KPH(tmp_speed));
2572       break;
2573     case VIK_UNITS_SPEED_MILES_PER_HOUR:
2574       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f mph", VIK_MPS_TO_MPH(tmp_speed));
2575       break;
2576     case VIK_UNITS_SPEED_METRES_PER_SECOND:
2577       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f m/s", tmp_speed );
2578       break;
2579     case VIK_UNITS_SPEED_KNOTS:
2580       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f knots", VIK_MPS_TO_KNOTS(tmp_speed));
2581       break;
2582     default:
2583       g_snprintf (tmp_buf, sizeof(tmp_buf), "--" );
2584       g_critical("Houston, we've had a problem. speed=%d", speed_units);
2585     }
2586   }
2587   widgets->w_avg_speed = content[cnt++] = gtk_label_new ( tmp_buf );
2588
2589   // Use 60sec as the default period to be considered stopped
2590   //  this is the TrackWaypoint draw stops default value 'vtl->stop_length'
2591   //  however this variable is not directly accessible - and I don't expect it's often changed from the default
2592   //  so ATM just put in the number
2593   tmp_speed = vik_track_get_average_speed_moving(tr, 60);
2594   if ( tmp_speed == 0 )
2595     g_snprintf(tmp_buf, sizeof(tmp_buf), _("No Data"));
2596   else {
2597     switch (speed_units) {
2598     case VIK_UNITS_SPEED_KILOMETRES_PER_HOUR:
2599       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f km/h", VIK_MPS_TO_KPH(tmp_speed));
2600       break;
2601     case VIK_UNITS_SPEED_MILES_PER_HOUR:
2602       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f mph", VIK_MPS_TO_MPH(tmp_speed));
2603       break;
2604     case VIK_UNITS_SPEED_METRES_PER_SECOND:
2605       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f m/s", tmp_speed );
2606       break;
2607     case VIK_UNITS_SPEED_KNOTS:
2608       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f knots", VIK_MPS_TO_KNOTS(tmp_speed));
2609       break;
2610     default:
2611       g_snprintf (tmp_buf, sizeof(tmp_buf), "--" );
2612       g_critical("Houston, we've had a problem. speed=%d", speed_units);
2613     }
2614   }
2615   widgets->w_mvg_speed = content[cnt++] = gtk_label_new ( tmp_buf );
2616
2617   switch (dist_units) {
2618   case VIK_UNITS_DISTANCE_KILOMETRES:
2619     // Even though kilometres, the average distance between points is going to be quite small so keep in metres
2620     g_snprintf(tmp_buf, sizeof(tmp_buf), "%.2f m", (tp_count - seg_count) == 0 ? 0 : tr_len / ( tp_count - seg_count ) );
2621     break;
2622   case VIK_UNITS_DISTANCE_MILES:
2623     g_snprintf(tmp_buf, sizeof(tmp_buf), "%.3f miles", (tp_count - seg_count) == 0 ? 0 : VIK_METERS_TO_MILES(tr_len / ( tp_count - seg_count )) );
2624     break;
2625   default:
2626     g_critical("Houston, we've had a problem. distance=%d", dist_units);
2627   }
2628   widgets->w_avg_dist = content[cnt++] = gtk_label_new ( tmp_buf );
2629
2630   vik_units_height_t height_units = a_vik_get_units_height ();
2631   if ( min_alt == VIK_DEFAULT_ALTITUDE )
2632     g_snprintf(tmp_buf, sizeof(tmp_buf), _("No Data"));
2633   else {
2634     switch (height_units) {
2635     case VIK_UNITS_HEIGHT_METRES:
2636       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.0f m - %.0f m", min_alt, max_alt );
2637       break;
2638     case VIK_UNITS_HEIGHT_FEET:
2639       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.0f feet - %.0f feet", VIK_METERS_TO_FEET(min_alt), VIK_METERS_TO_FEET(max_alt) );
2640       break;
2641     default:
2642       g_snprintf(tmp_buf, sizeof(tmp_buf), "--" );
2643       g_critical("Houston, we've had a problem. height=%d", height_units);
2644     }
2645   }
2646   widgets->w_elev_range = content[cnt++] = gtk_label_new ( tmp_buf );
2647
2648   vik_track_get_total_elevation_gain(tr, &max_alt, &min_alt );
2649   if ( min_alt == VIK_DEFAULT_ALTITUDE )
2650     g_snprintf(tmp_buf, sizeof(tmp_buf), _("No Data"));
2651   else {
2652     switch (height_units) {
2653     case VIK_UNITS_HEIGHT_METRES:
2654       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.0f m / %.0f m", max_alt, min_alt );
2655       break;
2656     case VIK_UNITS_HEIGHT_FEET:
2657       g_snprintf(tmp_buf, sizeof(tmp_buf), "%.0f feet / %.0f feet", VIK_METERS_TO_FEET(max_alt), VIK_METERS_TO_FEET(min_alt) );
2658       break;
2659     default:
2660       g_snprintf(tmp_buf, sizeof(tmp_buf), "--" );
2661       g_critical("Houston, we've had a problem. height=%d", height_units);
2662     }
2663   }
2664   widgets->w_elev_gain = content[cnt++] = gtk_label_new ( tmp_buf );
2665
2666 #if 0
2667 #define PACK(w) gtk_box_pack_start (GTK_BOX(right_vbox), w, FALSE, FALSE, 0);
2668   gtk_box_pack_start (GTK_BOX(right_vbox), e_cmt, FALSE, FALSE, 0); 
2669   PACK(l_len);
2670   PACK(l_tps);
2671   PACK(l_segs);
2672   PACK(l_dups);
2673   PACK(l_maxs);
2674   PACK(l_avgs);
2675   PACK(l_avgd);
2676   PACK(l_elev);
2677   PACK(l_galo);
2678 #undef PACK;
2679 #endif
2680
2681   if ( tr->trackpoints && VIK_TRACKPOINT(tr->trackpoints->data)->timestamp )
2682   {
2683     time_t t1, t2;
2684     t1 = VIK_TRACKPOINT(tr->trackpoints->data)->timestamp;
2685     t2 = VIK_TRACKPOINT(g_list_last(tr->trackpoints)->data)->timestamp;
2686
2687     strncpy(tmp_buf, ctime(&t1), sizeof(tmp_buf));
2688     tmp_buf[sizeof(tmp_buf)-1] = 0;
2689     g_strchomp(tmp_buf);
2690     widgets->w_time_start = content[cnt++] = gtk_label_new(tmp_buf);
2691
2692     strncpy(tmp_buf, ctime(&t2), sizeof(tmp_buf));
2693     tmp_buf[sizeof(tmp_buf)-1] = 0;
2694     g_strchomp(tmp_buf);
2695     widgets->w_time_end = content[cnt++] = gtk_label_new(tmp_buf);
2696
2697     g_snprintf(tmp_buf, sizeof(tmp_buf), _("%d minutes"), (int)(t2-t1)/60);
2698     widgets->w_time_dur = content[cnt++] = gtk_label_new(tmp_buf);
2699   } else {
2700     widgets->w_time_start = content[cnt++] = gtk_label_new(_("No Data"));
2701     widgets->w_time_end = content[cnt++] = gtk_label_new(_("No Data"));
2702     widgets->w_time_dur = content[cnt++] = gtk_label_new(_("No Data"));
2703   }
2704
2705   table = GTK_TABLE(gtk_table_new (cnt, 2, FALSE));
2706   gtk_table_set_col_spacing (table, 0, 10);
2707   for (i=0; i<cnt; i++) {
2708     GtkWidget *label;
2709
2710     // Settings so the text positioning only moves around vertically when the dialog is resized
2711     // This also gives more room to see the track comment
2712     label = gtk_label_new(NULL);
2713     gtk_misc_set_alignment ( GTK_MISC(label), 1, 0.5 ); // Position text centrally in vertical plane
2714     gtk_label_set_markup ( GTK_LABEL(label), _(label_texts[i]) );
2715     gtk_table_attach ( table, label, 0, 1, i, i+1, GTK_FILL, GTK_SHRINK, 0, 0 );
2716     if (GTK_IS_MISC(content[i])) {
2717       gtk_misc_set_alignment ( GTK_MISC(content[i]), 0, 0.5 );
2718     }
2719     gtk_table_attach_defaults ( table, content[i], 1, 2, i, i+1 );
2720   }
2721
2722   gtk_notebook_append_page(GTK_NOTEBOOK(graphs), GTK_WIDGET(table), gtk_label_new(_("Statistics")));
2723
2724   gpointer *pass_along;
2725   pass_along = g_malloc ( sizeof(gpointer) * 4 ); /* FIXME: mem leak -- never be freed */
2726   pass_along[0] = tr;
2727   pass_along[1] = vlp;
2728   pass_along[2] = vvp;
2729   pass_along[3] = widgets;
2730
2731   if ( widgets->elev_box ) {
2732     GtkWidget *page = NULL;
2733     widgets->w_cur_dist = gtk_label_new(_("No Data"));
2734     widgets->w_cur_elevation = gtk_label_new(_("No Data"));
2735     widgets->w_show_dem = gtk_check_button_new_with_mnemonic(_("Show D_EM"));
2736     widgets->w_show_alt_gps_speed = gtk_check_button_new_with_mnemonic(_("Show _GPS Speed"));
2737     page = create_graph_page (widgets->elev_box,
2738                               _("<b>Track Distance:</b>"), widgets->w_cur_dist,
2739                               _("<b>Track Height:</b>"), widgets->w_cur_elevation,
2740                               widgets->w_show_dem, TRUE,
2741                               widgets->w_show_alt_gps_speed, TRUE);
2742     g_signal_connect (widgets->w_show_dem, "toggled", G_CALLBACK (checkbutton_toggle_cb), pass_along);
2743     g_signal_connect (widgets->w_show_alt_gps_speed, "toggled", G_CALLBACK (checkbutton_toggle_cb), pass_along);
2744     gtk_notebook_append_page(GTK_NOTEBOOK(graphs), page, gtk_label_new(_("Elevation-distance")));
2745   }
2746
2747   if ( widgets->speed_box ) {
2748     GtkWidget *page = NULL;
2749     widgets->w_cur_time = gtk_label_new(_("No Data"));
2750     widgets->w_cur_speed = gtk_label_new(_("No Data"));
2751     widgets->w_show_gps_speed = gtk_check_button_new_with_mnemonic(_("Show _GPS Speed"));
2752     page = create_graph_page (widgets->speed_box,
2753                               _("<b>Track Time:</b>"), widgets->w_cur_time,
2754                               _("<b>Track Speed:</b>"), widgets->w_cur_speed,
2755                               widgets->w_show_gps_speed, TRUE,
2756                               NULL, FALSE);
2757     g_signal_connect (widgets->w_show_gps_speed, "toggled", G_CALLBACK (checkbutton_toggle_cb), pass_along);
2758     gtk_notebook_append_page(GTK_NOTEBOOK(graphs), page, gtk_label_new(_("Speed-time")));
2759   }
2760
2761   if ( widgets->dist_box ) {
2762     GtkWidget *page = NULL;
2763     widgets->w_cur_dist_time = gtk_label_new(_("No Data"));
2764     widgets->w_cur_dist_dist = gtk_label_new(_("No Data"));
2765     widgets->w_show_dist_speed = gtk_check_button_new_with_mnemonic(_("Show S_peed"));
2766     page = create_graph_page (widgets->dist_box,
2767                               _("<b>Track Distance:</b>"), widgets->w_cur_dist_dist,
2768                               _("<b>Track Time:</b>"), widgets->w_cur_dist_time,
2769                               widgets->w_show_dist_speed, FALSE,
2770                               NULL, FALSE);
2771     g_signal_connect (widgets->w_show_dist_speed, "toggled", G_CALLBACK (checkbutton_toggle_cb), pass_along);
2772     gtk_notebook_append_page(GTK_NOTEBOOK(graphs), page, gtk_label_new(_("Distance-time")));
2773   }
2774
2775   if ( widgets->elev_time_box ) {
2776     GtkWidget *page = NULL;
2777     widgets->w_cur_elev_time = gtk_label_new(_("No Data"));
2778     widgets->w_cur_elev_elev = gtk_label_new(_("No Data"));
2779     widgets->w_show_elev_speed = gtk_check_button_new_with_mnemonic(_("Show S_peed"));
2780     page = create_graph_page (widgets->elev_time_box,
2781                               _("<b>Track Time:</b>"), widgets->w_cur_elev_time,
2782                               _("<b>Track Height:</b>"), widgets->w_cur_elev_elev,
2783                               widgets->w_show_elev_speed, FALSE,
2784                               NULL, FALSE);
2785     g_signal_connect (widgets->w_show_elev_speed, "toggled", G_CALLBACK (checkbutton_toggle_cb), pass_along);
2786     gtk_notebook_append_page(GTK_NOTEBOOK(graphs), page, gtk_label_new(_("Elevation-time")));
2787   }
2788
2789   if ( widgets->speed_dist_box ) {
2790     GtkWidget *page = NULL;
2791     widgets->w_cur_speed_dist = gtk_label_new(_("No Data"));
2792     widgets->w_cur_speed_speed = gtk_label_new(_("No Data"));
2793     widgets->w_show_sd_gps_speed = gtk_check_button_new_with_mnemonic(_("Show _GPS Speed"));
2794     page = create_graph_page (widgets->speed_dist_box,
2795                               _("<b>Track Distance:</b>"), widgets->w_cur_speed_dist,
2796                               _("<b>Track Speed:</b>"), widgets->w_cur_speed_speed,
2797                               widgets->w_show_sd_gps_speed, TRUE,
2798                               NULL, FALSE);
2799     g_signal_connect (widgets->w_show_sd_gps_speed, "toggled", G_CALLBACK (checkbutton_toggle_cb), pass_along);
2800     gtk_notebook_append_page(GTK_NOTEBOOK(graphs), page, gtk_label_new(_("Speed-distance")));
2801   }
2802
2803   gtk_box_pack_start (GTK_BOX(GTK_DIALOG(dialog)->vbox), graphs, FALSE, FALSE, 0);
2804
2805   gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog), VIK_TRW_LAYER_PROPWIN_SPLIT_MARKER, FALSE);
2806   if (seg_count <= 1)
2807     gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog), VIK_TRW_LAYER_PROPWIN_SPLIT, FALSE);
2808   if (vik_track_get_dup_point_count(tr) <= 0)
2809     gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog), VIK_TRW_LAYER_PROPWIN_DEL_DUP, FALSE);
2810
2811   // On dialog realization configure_event casues the graphs to be initially drawn
2812   widgets->configure_dialog = TRUE;
2813   g_signal_connect ( G_OBJECT(dialog), "configure-event", G_CALLBACK (configure_event), pass_along);
2814
2815   vik_track_set_property_dialog(tr, dialog);
2816   gtk_dialog_set_default_response ( GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT );
2817   gtk_widget_show_all ( dialog );
2818 }