File: gtk-sat-map.c

package info (click to toggle)
gpredict 1.1-7
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 8,280 kB
  • ctags: 2,873
  • sloc: ansic: 34,903; sh: 10,151; makefile: 417
file content (2240 lines) | stat: -rw-r--r-- 78,754 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/*
  Gpredict: Real-time satellite tracking and orbit prediction program

  Copyright (C)  2001-2009  Alexandru Csete, OZ9AEC.
  Copyright (C)  2006-2007  William J Beksi, KC2EXL.

  Authors: Alexandru Csete <oz9aec@gmail.com>
  William J Beksi <wjbeksi@users.sourceforge.net>

  Comments, questions and bugreports should be submitted via
  http://sourceforge.net/projects/gpredict/
  More details can be found at the project home page:

  http://gpredict.oz9aec.net/
 
  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.
  
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with this program; if not, visit http://www.fsf.org/
*/

/** \brief Satellite Map Widget.
 *
 * The satellite map widget is responsible for plotting and updating information
 * relevent to each satellite. This information includes the satellite position,
 * label, and footprint. Satellites are stored in a hash table by their catalog 
 * number. The satellite map widget is also responsible for loading and resizing
 * the map.
 *
 */
#include <gtk/gtk.h>
#include <glib/gi18n.h>
#include <math.h>
#include "sgpsdp/sgp4sdp4.h"
#include "sat-log.h"
#include "config-keys.h"
#include "sat-cfg.h"
#include "mod-cfg-get-param.h"
#include "gtk-sat-data.h"
#include "gpredict-utils.h"
#include "compat.h"
#include "gtk-sat-map-popup.h"
#include "gtk-sat-map-ground-track.h"
#include "gtk-sat-map.h"
#include "locator.h"
#include "sat-debugger.h"
#ifdef HAVE_CONFIG_H
#  include <build-config.h>
#endif
#include <goocanvas.h>

#define MARKER_SIZE_HALF    1

static void gtk_sat_map_class_init (GtkSatMapClass *class);
static void gtk_sat_map_init       (GtkSatMap *polview);
static void gtk_sat_map_destroy    (GtkObject *object);
static void size_allocate_cb       (GtkWidget *widget, GtkAllocation *allocation, gpointer data);
static void update_map_size        (GtkSatMap *satmap);
static void update_sat             (gpointer key, gpointer value, gpointer data);
static void plot_sat               (gpointer key, gpointer value, gpointer data);
static void lonlat_to_xy           (GtkSatMap *m, gdouble lon, gdouble lat, gfloat *x, gfloat *y);
static void xy_to_lonlat           (GtkSatMap *m, gfloat x, gfloat y, gfloat *lon, gfloat *lat);
static gboolean on_motion_notify   (GooCanvasItem *item,
                                    GooCanvasItem *target,
                                    GdkEventMotion *event,
                                    gpointer data);
static void on_item_created        (GooCanvas *canvas,
                                    GooCanvasItem *item,
                                    GooCanvasItemModel *model,
                                    gpointer data);
static void on_canvas_realized     (GtkWidget *canvas, gpointer data);
static gboolean on_button_press    (GooCanvasItem *item,
                                    GooCanvasItem *target,
                                    GdkEventButton *event,
                                    gpointer data);
static gboolean on_button_release  (GooCanvasItem *item,
                                    GooCanvasItem *target,
                                    GdkEventButton *event,
                                    gpointer data);
static void clear_selection        (gpointer key, gpointer val, gpointer data);
static void load_map_file          (GtkSatMap *satmap);
static GooCanvasItemModel*         create_canvas_model (GtkSatMap *satmap);
static gdouble arccos              (gdouble, gdouble);
static gboolean pole_is_covered    (sat_t *sat);
static gboolean mirror_lon         (sat_t *sat, gdouble rangelon, gdouble *mlon);
static guint calculate_footprint   (GtkSatMap *satmap, sat_t *sat);
static void  split_points          (GtkSatMap *satmap, sat_t *sat, gdouble sspx);
static void sort_points_x          (GtkSatMap *satmap, sat_t *sat, GooCanvasPoints *points, gint num);
static void sort_points_y          (GtkSatMap *satmap, sat_t *sat, GooCanvasPoints *points, gint num);
static gint compare_coordinates_x  (gconstpointer a, gconstpointer b, gpointer data);
static gint compare_coordinates_y  (gconstpointer a, gconstpointer b, gpointer data);
static void update_selected        (GtkSatMap *satmap, sat_t *sat);
static void draw_grid_lines        (GtkSatMap *satmap, GooCanvasItemModel *root);
static void redraw_grid_lines      (GtkSatMap *satmap);

static GtkVBoxClass *parent_class = NULL;
static GooCanvasPoints *points1;
static GooCanvasPoints *points2;


/** \brief Register the satellite map widget. */
GtkType
gtk_sat_map_get_type ()
{
    static GType gtk_sat_map_type = 0;

    if (!gtk_sat_map_type) {
        static const GTypeInfo gtk_sat_map_info = {
            sizeof (GtkSatMapClass),
            NULL, /* base init */
            NULL, /* base finalize */
            (GClassInitFunc) gtk_sat_map_class_init,
            NULL, /* class finalize */
            NULL, /* class data */
            sizeof (GtkSatMap),
            5,    /* n_preallocs */
            (GInstanceInitFunc) gtk_sat_map_init,
        };

        gtk_sat_map_type = g_type_register_static (GTK_TYPE_VBOX,
                                                   "GtkSatMap",
                                                   &gtk_sat_map_info,
                                                   0);
    }

    return gtk_sat_map_type;
}


/** \brief Initialize a GtkSatMapClass object. */
static void
gtk_sat_map_class_init (GtkSatMapClass *class)
{
    GObjectClass      *gobject_class;
    GtkObjectClass    *object_class;
    GtkWidgetClass    *widget_class;
    GtkContainerClass *container_class;

    gobject_class   = G_OBJECT_CLASS (class);
    object_class    = (GtkObjectClass*) class;
    widget_class    = (GtkWidgetClass*) class;
    container_class = (GtkContainerClass*) class;

    parent_class = g_type_class_peek_parent (class);

    object_class->destroy = gtk_sat_map_destroy;
    /* widget_class->size_allocate = gtk_sat_map_size_allocate; */
}


/** \brief Initialize a newly created GtkSatMap widget. */
static void
gtk_sat_map_init (GtkSatMap *satmap)
{
    satmap->sats      = NULL;
    satmap->qth       = NULL;
    satmap->obj       = NULL;
    satmap->naos      = 2458849.5;
    satmap->ncat      = 0;
    satmap->tstamp    = 2458849.5;
    satmap->x0        = 0;
    satmap->y0        = 0;
    satmap->width     = 0;
    satmap->height    = 0;
    satmap->refresh   = 0;
    satmap->counter   = 0;
    satmap->qthinfo   = FALSE;
    satmap->eventinfo = FALSE;
    satmap->cursinfo  = FALSE;
    satmap->showgrid  = FALSE;
    satmap->keepratio = FALSE;
    satmap->resize    = FALSE;
}


/** \brief Destroy a GtkSatMap widget. */
static void
gtk_sat_map_destroy (GtkObject *object)
{
    (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
}


/** \brief Initialize and plot each satellite on a canvas model. 
 *  
 *  This function creates a canvas model and loads the background map
 *  onto the canvas. Each satellite is then plotted on the map.
 *
 */
GtkWidget*
gtk_sat_map_new (GKeyFile *cfgdata, GHashTable *sats, qth_t *qth)
{
    GtkWidget *satmap;
    GooCanvasItemModel *root;
    guint32 col;

    satmap = g_object_new (GTK_TYPE_SAT_MAP, NULL);

    GTK_SAT_MAP (satmap)->cfgdata = cfgdata;
    GTK_SAT_MAP (satmap)->sats = sats;
    GTK_SAT_MAP (satmap)->qth  = qth;

    GTK_SAT_MAP (satmap)->obj  = g_hash_table_new_full (g_int_hash, g_int_equal, g_free, NULL);

    /* get settings */
    GTK_SAT_MAP (satmap)->refresh = mod_cfg_get_int (cfgdata,
                                                     MOD_CFG_MAP_SECTION,
                                                     MOD_CFG_MAP_REFRESH,
                                                     SAT_CFG_INT_MAP_REFRESH);
    GTK_SAT_MAP (satmap)->counter = 1;

    GTK_SAT_MAP (satmap)->qthinfo = mod_cfg_get_bool (cfgdata,
                                                      MOD_CFG_MAP_SECTION,
                                                      MOD_CFG_MAP_SHOW_QTH_INFO,
                                                      SAT_CFG_BOOL_MAP_SHOW_QTH_INFO);

    GTK_SAT_MAP (satmap)->eventinfo = mod_cfg_get_bool (cfgdata,
                                                        MOD_CFG_MAP_SECTION,
                                                        MOD_CFG_MAP_SHOW_NEXT_EVENT,
                                                        SAT_CFG_BOOL_MAP_SHOW_NEXT_EV);

    GTK_SAT_MAP (satmap)->cursinfo = mod_cfg_get_bool (cfgdata,
                                                       MOD_CFG_MAP_SECTION,
                                                       MOD_CFG_MAP_SHOW_CURS_TRACK,
                                                       SAT_CFG_BOOL_MAP_SHOW_CURS_TRACK);

    GTK_SAT_MAP (satmap)->showgrid = mod_cfg_get_bool (cfgdata,
                                                       MOD_CFG_MAP_SECTION,
                                                       MOD_CFG_MAP_SHOW_GRID,
                                                       SAT_CFG_BOOL_MAP_SHOW_GRID);

    GTK_SAT_MAP (satmap)->keepratio = mod_cfg_get_bool (cfgdata,
                                                        MOD_CFG_MAP_SECTION,
                                                        MOD_CFG_MAP_KEEP_RATIO,
                                                        SAT_CFG_BOOL_MAP_KEEP_RATIO);
    col = mod_cfg_get_int (cfgdata,
                           MOD_CFG_MAP_SECTION,
                           MOD_CFG_MAP_INFO_BGD_COL,
                           SAT_CFG_INT_MAP_INFO_BGD_COL);

    GTK_SAT_MAP (satmap)->infobgd = rgba2html (col);

    /* create the canvas */
    GTK_SAT_MAP (satmap)->canvas = goo_canvas_new ();

    /* safely load a background map */
    load_map_file (GTK_SAT_MAP (satmap));

    /* Initial size request should be based on map size
       but if we do this we can not shrink the canvas below this size
       even though the map shrinks => better to set default size of
       main container window.
    */
    /*  gtk_widget_set_size_request (GTK_SAT_MAP (satmap)->canvas, */
    /*  gdk_pixbuf_get_width (GTK_SAT_MAP (satmap)->origmap), */
    /*  gdk_pixbuf_get_height (GTK_SAT_MAP (satmap)->origmap)); */

    goo_canvas_set_bounds (GOO_CANVAS (GTK_SAT_MAP (satmap)->canvas), 0, 0,
                           gdk_pixbuf_get_width (GTK_SAT_MAP (satmap)->origmap),
                           gdk_pixbuf_get_height (GTK_SAT_MAP (satmap)->origmap));
    
                           
    /* connect size-request signal */
    g_signal_connect (GTK_SAT_MAP (satmap)->canvas, "size-allocate",
                      G_CALLBACK (size_allocate_cb), satmap);
    g_signal_connect (GTK_SAT_MAP (satmap)->canvas, "item_created",
                      (GtkSignalFunc) on_item_created, satmap);
    g_signal_connect_after (GTK_SAT_MAP (satmap)->canvas, "realize",
                            (GtkSignalFunc) on_canvas_realized, satmap);

    gtk_widget_show (GTK_SAT_MAP (satmap)->canvas);

    /* create the canvas model */
    root = create_canvas_model (GTK_SAT_MAP (satmap));
    goo_canvas_set_root_item_model (GOO_CANVAS (GTK_SAT_MAP (satmap)->canvas), root);

    g_object_unref (root);

    /* plot each sat on the canvas */
    g_hash_table_foreach (GTK_SAT_MAP (satmap)->sats, plot_sat, GTK_SAT_MAP (satmap));

    /* gtk_box_pack_start (GTK_BOX (satmap), GTK_SAT_MAP (satmap)->swin, TRUE, TRUE, 0); */
    gtk_container_add (GTK_CONTAINER (satmap), GTK_SAT_MAP (satmap)->canvas);

    return satmap;
}


/** \brief Create the map items on the canvas. 
 *  
 *  This function intializes the map dimensions and sets up the cursor track. 
 *  It creates and sets all of the static map items (QTH, grid lines, etc.)
 *  on the canvas.
 *
 */
static GooCanvasItemModel *
create_canvas_model (GtkSatMap *satmap)
{
    GooCanvasItemModel *root;
    gchar *buff;
    gfloat x,y;
    guint32 col;

    root = goo_canvas_group_model_new (NULL, NULL);

    /* map dimensions */
    satmap->width = gdk_pixbuf_get_width (satmap->origmap);
    satmap->height = gdk_pixbuf_get_height (satmap->origmap);
    satmap->x0 = 0;
    satmap->y0 = 0;

    /* background map */
    satmap->map = goo_canvas_image_model_new (root,
                                              satmap->origmap,
                                              satmap->x0,
                                              satmap->y0,
                                              NULL);

    goo_canvas_item_model_lower (satmap->map, NULL);

    /* grid lines */
    draw_grid_lines (satmap, root);

    /* QTH mark */
    col = mod_cfg_get_int (satmap->cfgdata,
                           MOD_CFG_MAP_SECTION,
                           MOD_CFG_MAP_QTH_COL,
                           SAT_CFG_INT_MAP_QTH_COL);

    lonlat_to_xy (satmap, satmap->qth->lon, satmap->qth->lat, &x, &y);
    
    satmap->qthmark = goo_canvas_rect_model_new (root,
                                                 x - MARKER_SIZE_HALF,
                                                 y - MARKER_SIZE_HALF,
                                                 2 * MARKER_SIZE_HALF,
                                                 2 * MARKER_SIZE_HALF,
                                                 "fill-color-rgba", col,
                                                 "stroke-color-rgba", col,
                                                 NULL);

    satmap->qthlabel = goo_canvas_text_model_new (root, satmap->qth->name,
                                                  x, y+2, -1,
                                                  GTK_ANCHOR_NORTH,
                                                  "font", "Sans 8",
                                                  "fill-color-rgba", col,
                                                  NULL);

    /* QTH info */
    col = mod_cfg_get_int (satmap->cfgdata,
                           MOD_CFG_MAP_SECTION,
                           MOD_CFG_MAP_INFO_COL,
                           SAT_CFG_INT_MAP_INFO_COL);

    satmap->locnam = goo_canvas_text_model_new (root, "",
                                                satmap->x0 + 2, satmap->y0 + 1, -1,
                                                GTK_ANCHOR_NORTH_WEST,
                                                "font", "Sans 8",
                                                "fill-color-rgba", col,
                                                "use-markup", TRUE,
                                                NULL);

    /* set text only if QTH info is enabled */
    if (satmap->qthinfo) {
        /* For now only QTH name and location.
           It would be nice with coordinates (remember NWSE setting)
           and Maidenhead locator, when using hamlib.
         
           Note: I used pango markup to set the background color, I didn't find any
           other obvious ways to get the text height in pixels to draw rectangle.
        */
        buff = g_strdup_printf ("<span background=\"#%s\"> %s \302\267 %s </span>",
                                satmap->infobgd,
                                satmap->qth->name,
                                satmap->qth->loc);
        g_object_set (satmap->locnam, "text", buff, NULL);
        g_free (buff);
    }

    /* next event */
    satmap->next = goo_canvas_text_model_new (root, "",
                                              satmap->x0+satmap->width - 2,
                                              satmap->y0 + 1, -1,
                                              GTK_ANCHOR_NORTH_EAST,
                                              "font", "Sans 8",
                                              "fill-color-rgba", col,
                                              "use-markup", TRUE,
                                              NULL);

    /* set text only if QTH info is enabled */
    if (satmap->eventinfo) {
        buff = g_strdup_printf ("<span background=\"#%s\"> ... </span>",
                                satmap->infobgd);
        g_object_set (satmap->next, "text", buff, NULL);
        g_free (buff);
    }

    /* cursor track */
    satmap->curs = goo_canvas_text_model_new (root, "",
                                              satmap->x0 + 2,
                                              satmap->y0 + satmap->height - 1,
                                              -1,
                                              GTK_ANCHOR_SOUTH_WEST,
                                              "font", "Sans 8",
                                              "fill-color-rgba", col,
                                              "use-markup", TRUE,
                                              NULL);

    /* info about a selected satellite */
    satmap->sel = goo_canvas_text_model_new (root, "",
                                             satmap->x0 + satmap->width - 2,
                                             satmap->y0 + satmap->height - 1,
                                             -1,
                                             GTK_ANCHOR_SOUTH_EAST,
                                             "font", "Sans 8",
                                             "fill-color-rgba", col,
                                             "use-markup", TRUE,
                                             NULL);

    return root;
}


/** \brief Manage new size allocation.
 *
 * This function is called when the canvas receives a new size allocation,
 * e.g. when the container is re-sized. The function sets the resize flag of
 * the GtkSatMap widget to TRUE to indicate that the map sizes should be
 * recalculated during the next timeout cycle.
 *
 * \note We could also do the calculation here, but that can be very CPU
 *       intensive because repetitive size allocation will also occur while
 *       the user resizes the window or the GtkPaned layout containers.
 */
static void
size_allocate_cb (GtkWidget *widget, GtkAllocation *allocation, gpointer data)
{
    GTK_SAT_MAP (data)->resize = TRUE;
}


/** \brief Update map size.
 *  \param widget Pointer to a GtkSatMap widget.
 *
 * This function is used to recalculate the GtkSatMap dimensions based on
 * its size allocations. It is normally called by the cyclic timeout handler
 * when the satmap->resize flag is set to TRUE.
 *
 * If the aspect ratio of the map is to be kept, we must use the following
 * algorithm to calculate the map dimensions:
 *
 *   ratio = origmap.w / origmap.h
 *   size = min (alloc.w, ratio*alloc.h)
 *   map.w = size
 *   map.h = size / ratio
 *
 * otherwise we can simply calculate using allocation->width and height.
 *
 */
static void
update_map_size (GtkSatMap *satmap)
{
    GtkAllocation allocation;
    GdkPixbuf *pbuf;
    gfloat x, y;
    gfloat ratio;   /* ratio between map width and height */
    gfloat size;    /* size = min (alloc.w, ratio*alloc.h) */

    if (GTK_WIDGET_REALIZED (satmap)) {
        /* get graph dimensions */
        allocation.width = GTK_WIDGET (satmap)->allocation.width;
        allocation.height = GTK_WIDGET (satmap)->allocation.height;

        if (satmap->keepratio) {
            /* Use allocation->width and allocation->height to calculate
             *  new X0 Y0 width and height. Map proportions must be kept.
             */
            ratio = gdk_pixbuf_get_width (satmap->origmap) /
                gdk_pixbuf_get_height (satmap->origmap);

            size = MIN(allocation.width, ratio*allocation.height);

            satmap->width = (guint) size;
            satmap->height = (guint) (size / ratio);
            
            satmap->x0 = (allocation.width - satmap->width) / 2;
            satmap->y0 = (allocation.height - satmap->height) / 2;

            /* rescale pixbuf */
            pbuf = gdk_pixbuf_scale_simple (satmap->origmap,
                                            satmap->width,
                                            satmap->height,
                                            GDK_INTERP_BILINEAR);
        }
        else {
            satmap->x0 = 0;
            satmap->y0 = 0;
            satmap->width = allocation.width;
            satmap->height =allocation.height;

            /* rescale pixbuf */
            pbuf = gdk_pixbuf_scale_simple (satmap->origmap,
                                            satmap->width,
                                            satmap->height,
                                            GDK_INTERP_BILINEAR);
        }

        /* set canvas bounds to match new size */
        goo_canvas_set_bounds (GOO_CANVAS (GTK_SAT_MAP (satmap)->canvas), 0, 0,
                                           satmap->width, satmap->height);


        /* redraw static elements */
        g_object_set (satmap->map,
                      "pixbuf", pbuf,
                      "x", (gdouble) satmap->x0,
                      "y", (gdouble) satmap->y0,
                      NULL);
        g_object_unref (pbuf);

        /* grid lines */
        redraw_grid_lines (satmap);
        
        /* QTH */
        lonlat_to_xy (satmap,  satmap->qth->lon, satmap->qth->lat, &x, &y);
        g_object_set (satmap->qthmark,
                      "x", x - MARKER_SIZE_HALF,
                      "y", y - MARKER_SIZE_HALF,
                      NULL);
        g_object_set (satmap->qthlabel,
                      "x", x,
                      "y", y+2,
                      NULL);

        /* QTH info */
        g_object_set (satmap->locnam,
                      "x", (gdouble) satmap->x0 + 2,
                      "y", (gdouble) satmap->y0 + 1,
                      NULL);

        /* next event */
        g_object_set (satmap->next,
                      "x", (gdouble) satmap->x0 + satmap->width - 2,
                      "y", (gdouble) satmap->y0 + 1,
                      NULL);

        /* cursor info */
        g_object_set (satmap->curs,
                      "x", (gdouble) satmap->x0 + 2,
                      "y", (gdouble) satmap->y0 + satmap->height - 1,
                      NULL);

        /* selected sat info */
        g_object_set (satmap->sel,
                      "x", (gdouble) satmap->x0 + satmap->width - 2,
                      "y", (gdouble) satmap->y0 + satmap->height - 1,
                      NULL);


        /* update satellites */
        g_hash_table_foreach (satmap->sats, update_sat, satmap);

        satmap->resize = FALSE;
    }
}


/** \brief Manage canvas realize signals.
 *
 * The function is used to re-order the canvas items (they can not be
 * re-ordered at creation, since the canvas is not visible).
 */
static void
on_canvas_realized (GtkWidget *canvas, gpointer data)
{
    GtkSatMap *satmap = GTK_SAT_MAP(data);

    /* raise info items */
    goo_canvas_item_model_raise (satmap->sel, NULL);
    goo_canvas_item_model_raise (satmap->locnam, NULL);
    goo_canvas_item_model_raise (satmap->next, NULL);
    goo_canvas_item_model_raise (satmap->curs, NULL);
}


/** \brief Update the GtkSatMap widget
 *
 * Called periodically from GtkSatModule.
 */
void
gtk_sat_map_update (GtkWidget  *widget)
{
    GtkSatMap *satmap = GTK_SAT_MAP (widget);
    sat_t *sat = NULL;
    gdouble number, now;
    gchar *buff;
    gint *catnr;
    guint h, m, s;
    gchar *ch, *cm, *cs;

    /* check whether there are any pending resize requests */
    if (satmap->resize) 
        update_map_size (satmap);

    /* check refresh rate and refresh sats if time */
    if (satmap->counter < satmap->refresh) {
        satmap->counter++;
    }
    else {
        /* reset data */
        satmap->counter = 1;
        satmap->naos = 2458849.5;

        /* update sats */
        g_hash_table_foreach (satmap->sats, update_sat, satmap);

        /* update countdown to NEXT AOS label */
        if (satmap->eventinfo) {

            if (satmap->ncat > 0) {

                catnr = g_try_new0 (gint, 1);
                *catnr = satmap->ncat;
                sat = SAT(g_hash_table_lookup (satmap->sats, catnr));
                g_free (catnr);

                /* last desperate sanity check */
                if (sat != NULL) {

                    now = satmap->tstamp;//get_current_daynum ();
                    number = satmap->naos - now;

                    /* convert julian date to seconds */
                    s = (guint) (number * 86400);

                    /* extract hours */
                    h = (guint) floor (s/3600);
                    s -= 3600*h;

                    /* leading zero */
                    if ((h > 0) && (h < 10))
                        ch = g_strdup ("0");
                    else
                        ch = g_strdup ("");

                    /* extract minutes */
                    m = (guint) floor (s/60);
                    s -= 60*m;

                    /* leading zero */
                    if (m < 10)
                        cm = g_strdup ("0");
                    else
                        cm = g_strdup ("");

                    /* leading zero */
                    if (s < 10)
                        cs = g_strdup (":0");
                    else
                        cs = g_strdup (":");

                    if (h > 0) 
                        buff = g_strdup_printf (_("<span background=\"#%s\"> "\
                                                "Next: %s in %s%d:%s%d%s%d </span>"),
                                                satmap->infobgd,
                                                sat->nickname,
                                                ch, h, cm, m, cs, s);
                    else 
                        buff = g_strdup_printf (_("<span background=\"#%s\"> " \
                                                "Next: %s in %s%d%s%d </span>"),
                                                satmap->infobgd,
                                                sat->nickname,
                                                cm, m, cs, s);

                    g_object_set (satmap->next,
                                  "text", buff,
                                  NULL);

                    g_free (buff);
                    g_free (ch);
                    g_free (cm);
                    g_free (cs);
                }
                else {
                    sat_log_log (SAT_LOG_LEVEL_BUG,
                                 _("%s: Can not find NEXT satellite."),
                                 __FUNCTION__);
                    g_object_set (satmap->next,
                                  "text", _("Next: ERR"),
                                  NULL);
                }
            }
            else {
                g_object_set (satmap->next,
                              "text", _("Next: N/A"),
                              NULL);
            }
        }
        else {
            g_object_set (satmap->next,
                          "text", "",
                          NULL);
        }
    }
}


/** \brief Convert latitude and longitude to screen coordinates.
 *  \param m The GtkSatMap widget on which the conversion should be done.
 *  \param lat The latitude in decimal degrees North.
 *  \param lon The longitude in decimal degrees East.
 *  \param x The X coordinate on the screen (left to right)
 *  \param y The Y coordinate on the screen (top to bottom)
 *
 */
static void
lonlat_to_xy (GtkSatMap *p, gdouble lon, gdouble lat, gfloat *x, gfloat *y)
{
    *x = p->x0 + (180.0 - lon) * p->width / 360.0;
    if (*x < 0.0) /* west longitude */
        *x *= -1;
    else  /* east longitude */
        *x = p->x0 + (180.0 + lon) * p->width / 360.0;

    *y = p->y0 + (90.0 - lat) * p->height / 180.0;;
}


/** \brief Convert screen coordinates to latitude and longitude.
 *  \param m The GtkSatMap widget on which the conversion should be done.
 *  \param x The X coordinate on the screen (left to right)
 *  \param y The Y coordinate on the screen (top to bottom)
 *  \param lat The latitude in decimal degrees North.
 *  \param lon The longitude in decimal degrees East.
 *
 * The function will return nonsense when the cursor is off the map
 * so it is the responsibility of the consumer to check whether returned
 * values are in between valid ranges.
 */
static void
xy_to_lonlat (GtkSatMap *p, gfloat x, gfloat y, gfloat *lon, gfloat *lat)
{
    *lat = 90.0 - (180.0 / p->height) * (y - p->y0);
    *lon = (360.0 / p->width) * (x - p->x0) - 180.0;
}


/** \brief Manage map motion events.
 *
 * This function is called every time the mouse is moving on the map. Its purpose
 * is to update the cursor text with lat and lon coordinates.
 */
static gboolean
on_motion_notify (GooCanvasItem *item,
                  GooCanvasItem *target,
                  GdkEventMotion *event,
                  gpointer data)
{
    GtkSatMap *satmap = GTK_SAT_MAP (data);
    gfloat lat,lon;
    gchar *text;

    /* set text only if QTH info is enabled */
    if (satmap->cursinfo) {

        xy_to_lonlat (satmap, event->x, event->y, &lon, &lat);

        /*** FIXME:
             - Add QRA?
        */
        /* cursor track */
        text = g_strdup_printf ("<span background=\"#%s\"> "\
                                "LON:%.0f\302\260 LAT:%.0f\302\260 </span>",
                                satmap->infobgd, lon, lat);

        g_object_set (satmap->curs, "text", text, NULL);
        g_free (text);
    }

    return TRUE;
}


/** \brief Finish canvas item setup.
 *  \param canvas 
 *  \param item
 *  \param model 
 *  \param data Pointer to the GtkSatMap object.
 *
 * This function is called when a canvas item is created. Its purpose is to connect
 * the corresponding signals to the created items.
 *
 * The root item, ie the background is connected to motion notify event, while other
 * items (sats) are connected to mouse click events.
 *
 * \bug Should filter out QTH or do we want to click on the QTH?
 */
static void
on_item_created (GooCanvas *canvas,
                 GooCanvasItem *item,
                 GooCanvasItemModel *model,
                 gpointer data)
{
    if (!goo_canvas_item_model_get_parent (model)) {
        /* root item / canvas */
        g_signal_connect (item, "motion_notify_event",
                          (GtkSignalFunc) on_motion_notify, data);
    }

    else if (!g_object_get_data (G_OBJECT (item), "skip-signal-connection")) {
        g_signal_connect (item, "button_press_event",
                          (GtkSignalFunc) on_button_press, data);
        g_signal_connect (item, "button_release_event",
                          (GtkSignalFunc) on_button_release, data);
    }
}


/** \brief Manage button press events
 *
 * This function is called when a mouse button is pressed on a satellite object.
 * If the pressed button is #3 (right button) the satellite popup menu will be
 * created and executed.
 */
static gboolean
on_button_press (GooCanvasItem *item,
                 GooCanvasItem *target,
                 GdkEventButton *event,
                 gpointer data)
{
    GooCanvasItemModel *model = goo_canvas_item_get_model (item);
    GtkSatMap *satmap = GTK_SAT_MAP (data);
    gint catnum = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (model), "catnum"));
    gint *catpoint = NULL;
    sat_t *sat = NULL;

    switch (event->button) {

        /* pop-up menu */
    case 3:
        catpoint = g_try_new0 (gint, 1);
        *catpoint = catnum;

        sat = SAT (g_hash_table_lookup (satmap->sats, catpoint));

        if (sat != NULL) {
            gtk_sat_map_popup_exec (sat, satmap->qth, satmap, event,
                                    gtk_widget_get_toplevel (GTK_WIDGET (satmap)));
        }
        else {
            /* clicked on map -> map pop-up in the future */
        }

        g_free (catpoint);

        break;

    default:
        break;
    }

    return TRUE;
}


/** \brief Manage button release events.
 *
 * This function is called when the mouse button is released above
 * a satellite object. It will act as a button click and if the relesed
 * button is the left one, the clock will correspond to selecting or
 * deselecting a satellite
 */
static gboolean
on_button_release (GooCanvasItem *item,
                   GooCanvasItem *target,
                   GdkEventButton *event,
                   gpointer data)
{
    GooCanvasItemModel *model = goo_canvas_item_get_model (item);
    GtkSatMap *satmap = GTK_SAT_MAP (data);
    gint catnum = GPOINTER_TO_INT (g_object_get_data (G_OBJECT (model), "catnum"));
    gint *catpoint = NULL;
    sat_map_obj_t *obj = NULL;
    guint32  col;

    catpoint = g_try_new0 (gint, 1);
    *catpoint = catnum;

    switch (event->button) {
        /* Select / de-select satellite */
    case 1:
        obj = SAT_MAP_OBJ (g_hash_table_lookup (satmap->obj, catpoint));
        if (obj == NULL) {
            sat_log_log (SAT_LOG_LEVEL_BUG,
                         _("%s:%d: Can not find clicked object (%d) in hash table"),
                         __FILE__, __LINE__, catnum);
        }
        else {
            obj->selected = !obj->selected;

            if (obj->selected) {
                col = mod_cfg_get_int (satmap->cfgdata,
                                       MOD_CFG_MAP_SECTION,
                                       MOD_CFG_MAP_SAT_SEL_COL,
                                       SAT_CFG_INT_MAP_SAT_SEL_COL);
            }
            else {
                col = mod_cfg_get_int (satmap->cfgdata,
                                       MOD_CFG_MAP_SECTION,
                                       MOD_CFG_MAP_SAT_COL,
                                       SAT_CFG_INT_MAP_SAT_COL);
                *catpoint = 0;

                g_object_set (satmap->sel, "text", "", NULL);
            }

            g_object_set (obj->marker,
                          "fill-color-rgba", col,
                          "stroke-color-rgba", col,
                          NULL);
            g_object_set (obj->label,
                          "fill-color-rgba", col,
                          "stroke-color-rgba", col,
                          NULL);
            g_object_set (obj->range1,
                          "stroke-color-rgba", col,
                          NULL);

            if (obj->oldrcnum == 2)
                g_object_set (obj->range2,
                              "stroke-color-rgba", col,
                              NULL);

            /* clear other selections */
            g_hash_table_foreach (satmap->obj, clear_selection, catpoint);
        }
        break;
    default:
        break;
    }

    g_free (catpoint);
    
    return TRUE;
}


/** \brief Clear selection.
 *
 * This function is used to clear the old selection when a new satellite
 * is selected.
 */
static void
clear_selection (gpointer key, gpointer val, gpointer data)
{
    gint *old = key;
    gint *new = data;
    sat_map_obj_t *obj = SAT_MAP_OBJ (val);
    guint32 col;

    if ((*old != *new) && (obj->selected)) {
        obj->selected = FALSE;

        /** FIXME: this is only global default; need the satmap here! */
        col = sat_cfg_get_int (SAT_CFG_INT_MAP_SAT_COL);

        g_object_set (obj->marker,
                      "fill-color-rgba", col,
                      "stroke-color-rgba", col,
                      NULL);
        g_object_set (obj->label,
                      "fill-color-rgba", col,
                      "stroke-color-rgba", col,
                      NULL);
        g_object_set (obj->range1,
                      "stroke-color-rgba", col,
                      NULL);

        if (obj->oldrcnum == 2)
            g_object_set (obj->range2,
                          "stroke-color-rgba", col,
                          NULL);
    }
}


/** \brief Reconfigure map.
 *
 * This function should eventually reload all configuration for the GtkSatMap.
 * Currently this function is not implemented for any of the views. Reconfiguration
 * is done by recreating the whole module.
 */
void
gtk_sat_map_reconf (GtkWidget  *widget, GKeyFile *cfgdat)
{
}


/** \brief Safely load a map file.
 *  \param satmap The GtkSatMap widget
 *
 * This function is called shortly after the canvas has been created. Its purpose
 * is to load a mapfile into satmap->origmap.
 *
 * The function ensures that satmap->origmap will contain a valid GdkPixpuf, by
 * using the following logic:
 *
 *   - Get either module specific or global map file using mod_cfg_get_str
 *   - If the returned file does not exist try sat_cfg_get_str_def
 *   - If loading of default map does not succeed, create a dummy GdkPixbuf
 *     (and raise all possible alarms)
 *
 * \note satmap->cfgdata cshould contain a valid GKeyFile.
 *
 */
static void
load_map_file (GtkSatMap *satmap)
{
    gchar *buff;
    gchar *mapfile;
    GError *error = NULL;

    /* get local, global or default map file */
    buff = mod_cfg_get_str (satmap->cfgdata,
                            MOD_CFG_MAP_SECTION,
                            MOD_CFG_MAP_FILE,
                            SAT_CFG_STR_MAP_FILE);

    if (g_path_is_absolute (buff)) {
        /* map is user specific, ie. in $HOME/.gpredict2/maps/ */
        mapfile = g_strdup (buff);
    }
    else {
        /* build complete path */
        mapfile = map_file_name (buff);
    }
    g_free (buff);

    sat_log_log (SAT_LOG_LEVEL_DEBUG,
                 _("%s:%d: Loading map file %s"),
                 __FILE__, __LINE__, mapfile);

    /* check that file exists, if not get the default */
    if (g_file_test (mapfile, G_FILE_TEST_EXISTS)) {
        sat_log_log (SAT_LOG_LEVEL_DEBUG,
                     _("%s:%d: Map file found"),
                     __FILE__, __LINE__);
    }
    else {
        sat_log_log (SAT_LOG_LEVEL_ERROR,
                     _("%s:%d: Could not find map file %s"),
                     __FILE__, __LINE__, mapfile);

        /* get default map file */
        g_free (mapfile);
        mapfile = sat_cfg_get_str_def (SAT_CFG_STR_MAP_FILE);

        sat_log_log (SAT_LOG_LEVEL_ERROR,
                     _("%s:%d: Using default map: %s"),
                     __FILE__, __LINE__, mapfile);
    }

    /* try to load the map file */
    satmap->origmap = gdk_pixbuf_new_from_file (mapfile, &error);

    if (error != NULL) {
        sat_log_log (SAT_LOG_LEVEL_ERROR,
                     _("%s:%d: Error loading map file (%s)"),
                     __FILE__, __LINE__, error->message);
        g_clear_error (&error);

        /* create a dummy GdkPixbuf to avoid crash */
        satmap->origmap = gdk_pixbuf_new (GDK_COLORSPACE_RGB,
                                          FALSE,
                                          8, 400, 200);
        gdk_pixbuf_fill (satmap->origmap, 0x0F0F0F0F);
    }
                
    g_free (mapfile);
}


/** \brief Arccosine implementation. 
 *
 * Returns a value between zero and two pi.
 * Borrowed from gsat 0.9 by Xavier Crehueras, EB3CZS.
 * Optimized by Alexandru Csete.
 */
static gdouble
arccos (gdouble x, gdouble y)
{
    if (x && y) {
        if (y > 0.0)
            return acos (x/y);
        else if (y < 0.0)
            return pi + acos (x/y);
    }

    return 0.0;
}


/** \brief Check whether the footprint covers the North or South pole. */
static gboolean
pole_is_covered   (sat_t *sat)
{
    int ret1,ret2;
    gdouble qrb1, qrb2, az1, az2;

    ret1 = qrb (sat->ssplon, sat->ssplat, 0.0, 90.0, &qrb1, &az1);
    ret2 = qrb (sat->ssplon, sat->ssplat, 0.0, -90.0, &qrb2, &az2);

    if ((qrb1 <= 0.5*sat->footprint) || (qrb2 <= 0.5*sat->footprint))
        return TRUE;
    
    return FALSE;
}


/** \brief Mirror the footprint longitude. */
static gboolean
mirror_lon (sat_t *sat, gdouble rangelon, gdouble *mlon)
{
    gdouble diff;
    gboolean warped = FALSE;

    if (sat->ssplon < 0.0) {
        /* western longitude */
        if (rangelon < 0.0) {
            /* rangelon has not been warped over */
            *mlon = sat->ssplon + fabs (rangelon - sat->ssplon);
        }
        else {
            /* rangelon has been warped over */
            diff = 360.0 + sat->ssplon - rangelon;
            *mlon = sat->ssplon + diff;
            warped = TRUE;
        }
    }
    else {
        /* eastern longitude */
        *mlon = sat->ssplon + fabs (rangelon - sat->ssplon);
        
        if (*mlon > 180.0) {
            *mlon -= 360;
            warped = TRUE;
        }
    }

    return warped;
}


/** \brief Calculate satellite footprint and coverage area.
 *  \param satmap TheGtkSatMap widget.
 *  \param sat The satellite.
 *  \param points1 Initialised GooCanvasPoints structure with 360 points.
 *  \param points2 Initialised GooCanvasPoints structure with 360 points.
 *  \return The number of range circle parts.
 *
 * This function calculates the "left" side of the range circle and mirrors
 * the points in longitude to create the "right side of the range circle, too.
 * In order to be able to use the footprint points to create a set of subsequent
 * lines conencted to each other (poly-lines) the function may have to perform
 * one of the following three actions:
 *
 * 1. If the footprint covers the North or South pole, we need to sort the points
 *    and add two extra points: One to begin the range circle (e.g. -180,90) and
 *    one to end the range circle (e.g. 180,90). This is necessary to create a
 *    complete and consistent set of points suitable for a polyline. The addition
 *    of the extra points is done by the sort_points function.
 *
 * 2. Else if parts of the range circle is on one side of the map, while parts of
 *    it is on the right side of the map, i.e. the range circle runs off the border
 *    of the map, it calls the split_points function to split the points into two
 *    complete and consistent sets of points that are suitable to create two 
 *    poly-lines.
 *
 * 3. Else nothing needs to be done since the points are already suitable for
 *    a polyline.
 *
 * The function will re-initialise points1 and points2 according to its needs. The
 * total number of points will always be 360, even with the addition of the two
 * extra points. 
 */
static guint
calculate_footprint (GtkSatMap *satmap, sat_t *sat)
{
    guint azi;
    gfloat sx, sy, msx, msy, ssx, ssy;
    gdouble ssplat, ssplon, beta, azimuth, num, dem;
    gdouble rangelon, rangelat, mlon;
    gboolean warped = FALSE;
    guint numrc = 1;

    /* Range circle calculations.
     * Borrowed from gsat 0.9.0 by Xavier Crehueras, EB3CZS
     * who borrowed from John Magliacane, KD2BD.
     * Optimized by Alexandru Csete and William J Beksi.
     */
    ssplat = sat->ssplat * de2ra;
    ssplon = sat->ssplon * de2ra;
    beta = (0.5 * sat->footprint) / xkmper;

    for (azi = 0; azi < 180; azi++)    {
        azimuth = de2ra * (double)azi;
        rangelat = asin (sin (ssplat) * cos (beta) + cos (azimuth) *
                         sin (beta) * cos (ssplat));
        num = cos (beta) - (sin (ssplat) * sin (rangelat));
        dem = cos (ssplat) * cos (rangelat);
            
        if (azi == 0 && (beta > pio2 - ssplat))
            rangelon = ssplon + pi;
            
        else if (azi == 180 && (beta > pio2 + ssplat))
            rangelon = ssplon + pi;
                
        else if (fabs (num / dem) > 1.0)
            rangelon = ssplon;
                
        else {
            if ((180 - azi) >= 0)
                rangelon = ssplon - arccos (num, dem);
            else
                rangelon = ssplon + arccos (num, dem);
        }
                
        while (rangelon < -pi)
            rangelon += twopi;
        
        while (rangelon > (pi))
            rangelon -= twopi;
                
        rangelat = rangelat / de2ra;
        rangelon = rangelon / de2ra;

        /* mirror longitude */
        if (mirror_lon (sat, rangelon, &mlon))
            warped = TRUE;

        lonlat_to_xy (satmap, rangelon, rangelat, &sx, &sy);
        lonlat_to_xy (satmap, mlon, rangelat, &msx, &msy);

        points1->coords[2*azi] = sx;
        points1->coords[2*azi+1] = sy;
    
        /* Add mirrored point */
        points1->coords[718-2*azi] = msx;
        points1->coords[719-2*azi] = msy;
    }

    /* points1 ow contains 360 pairs of map-based XY coordinates.
       Check whether actions 1, 2 or 3 have to be performed.
    */

    /* pole is covered => sort points1 and add additional points */
    if (pole_is_covered (sat)) {

        sort_points_x (satmap, sat, points1, 360);
        numrc = 1;

    }

    /* pole not covered but range circle has been warped
       => split points */
    else if (warped == TRUE) {

        lonlat_to_xy (satmap, sat->ssplon, sat->ssplat, &ssx, &ssy);
        split_points (satmap, sat, ssx);
        numrc = 2;

    }

    /* the nominal condition => points1 is adequate */
    else {

        numrc = 1;

    }

    return numrc;
}


/** \brief Split and sort polyline points.
 *  \param satmap The GtkSatMap structure.
 *  \param points1 GooCanvasPoints containing the footprint points.
 *  \param points2 A GooCanvasPoints structure containing the second set of points.
 *  \param sspx Canvas based x-coordinate of SSP.
 *  \bug We should ensure that the endpoints in points1 have x=x0, while in
 *       the endpoints in points2 should have x=x0+width (TBC).
 *
 * \note This function works on canvas-based coordinates rather than lat/lon
 * \note DO NOT USE this function when the footprint covers one of the poles
 *       (the end result may freeze the X-server requiring a hard-reset!)
 */
static void
split_points (GtkSatMap *satmap, sat_t *sat, gdouble sspx)
{
    GooCanvasPoints *tps1,*tps2;
    gint n,n1,n2,ns,i,j,k;

    /* initialize parameters */
    n = points1->num_points;
    n1 = 0;
    n2 = 0;
    i = 0;
    j = 0;
    k = 0;
    ns = 0;
    tps1 = goo_canvas_points_new (n);
    tps2 = goo_canvas_points_new (n);

    //if ((sspx >= (satmap->x0 + satmap->width - 0.6)) ||
    //    (sspx >= (satmap->x0 - 0.6))) {
    //if ((sspx == (satmap->x0 + satmap->width)) ||
    //    (sspx == (satmap->x0))) {
    if ((sat->ssplon >= 179.4) || (sat->ssplon <= -179.4)) {
        /* sslon = +/-180 deg.
           - copy points with (x > satmap->x0+satmap->width/2) to tps1
           - copy points with (x < satmap->x0+satmap->width/2) to tps2
           - sort tps1 and tps2
        */
        for (i = 0; i < n; i++) {
            
            if (points1->coords[2*i] > (satmap->x0 + satmap->width/2)) {
                tps1->coords[2*n1] = points1->coords[2*i];
                tps1->coords[2*n1+1] = points1->coords[2*i+1];
                n1++;
            }
            else {
                tps2->coords[2*n2] = points1->coords[2*i];
                tps2->coords[2*n2+1] = points1->coords[2*i+1];
                n2++;
            }
        }

        sort_points_y (satmap, sat, tps1, n1);
        sort_points_y (satmap, sat, tps2, n2);
    }

    else if (sspx < (satmap->x0 + satmap->width / 2)) {
        /* We are on the left side of the map.
           Scan through points1 until we get to x > sspx (i=ns):

           - copy the points forwards until x < (x0+w/2) => tps2
           - continue to copy until the end => tps1
           - copy the points from i=0 to i=ns => tps1.

           Copy tps1 => points1 and tps2 => points2
        */
        while (points1->coords[2*i] <= sspx) {
            i++;
        }
        ns = i-1;

        while (points1->coords[2*i] > (satmap->x0 + satmap->width/2)) {
            tps2->coords[2*j] = points1->coords[2*i];
            tps2->coords[2*j+1] = points1->coords[2*i+1];
            i++;
            j++;
            n2++;
        }

        while (i < n) {
            tps1->coords[2*k] = points1->coords[2*i];
            tps1->coords[2*k+1] = points1->coords[2*i+1];
            i++;
            k++;
            n1++;
        }

        for (i = 0; i <= ns; i++) {
            tps1->coords[2*k] = points1->coords[2*i];
            tps1->coords[2*k+1] = points1->coords[2*i+1];
            k++;
            n1++;
        }
    }
    else {
        /* We are on the right side of the map.
           Scan backwards through points1 until x < sspx (i=ns):

           - copy the points i=ns,i-- until x >= x0+w/2  => tps2
           - copy the points until we reach i=0          => tps1
           - copy the points from i=n to i=ns            => tps1

        */
        i = n-1;
        while (points1->coords[2*i] >= sspx) {
            i--;
        }
        ns = i+1;

        while (points1->coords[2*i] < (satmap->x0 + satmap->width/2)) {
            tps2->coords[2*j] = points1->coords[2*i];
            tps2->coords[2*j+1] = points1->coords[2*i+1];
            i--;
            j++;
            n2++;
        }

        while (i >= 0) {
            tps1->coords[2*k] = points1->coords[2*i];
            tps1->coords[2*k+1] = points1->coords[2*i+1];
            i--;
            k++;
            n1++;
        }

        for (i = n-1; i >= ns; i--) {
            tps1->coords[2*k] = points1->coords[2*i];
            tps1->coords[2*k+1] = points1->coords[2*i+1];
            k++;
            n1++;
        }
    }

    //g_print ("NS:%d  N1:%d  N2:%d\n", ns, n1, n2);

    /* free points and copy new contents */
    goo_canvas_points_unref (points1);
    goo_canvas_points_unref (points2);

    points1 = goo_canvas_points_new (n1);
    for (i = 0; i < n1; i++) {
        points1->coords[2*i] = tps1->coords[2*i];
        points1->coords[2*i+1] = tps1->coords[2*i+1];
    }
    goo_canvas_points_unref (tps1);
    
    points2 = goo_canvas_points_new (n2);
    for (i = 0; i < n2; i++) {
        points2->coords[2*i] = tps2->coords[2*i];
        points2->coords[2*i+1] = tps2->coords[2*i+1];
    }
    goo_canvas_points_unref (tps2);

    /* stretch end points to map borders */
    if (points1->coords[0] > (satmap->x0+satmap->width/2)) {
        points1->coords[0] = satmap->x0+satmap->width;
        points1->coords[2*(n1-1)] = satmap->x0+satmap->width;
        points2->coords[0] = satmap->x0;
        points2->coords[2*(n2-1)] = satmap->x0;
    }
    else {
        points2->coords[0] = satmap->x0+satmap->width;
        points2->coords[2*(n2-1)] = satmap->x0+satmap->width;
        points1->coords[0] = satmap->x0;
        points1->coords[2*(n1-1)] = satmap->x0;
    }
}


/** \brief Sort points according to X coordinates.
 *  \param satmap The GtkSatMap structure.
 *  \param sat The satellite data structure.
 *  \param points The points to sort.
 *  \param num The number of points. By specifying it as parameter we can
 *             sort incomplete arrays.
 *
 * This function sorts the points in ascending order with respect
 * to their x value. After sorting the function adds two extra points
 * to the array using the following algorithms:
 *
 *   move point at position 0 to position 1
 *   move point at position N to position N-1
 *   if (ssplat > 0)
 *         insert (x0,y0) into position 0
 *         insert (x0+width,y0) into position N
 *   else
 *         insert (x0,y0+height) into position 0
 *         insert (x0+width,y0+height) into position N
 *
 * This way we loose the points at position 1 and N-1, but that does not
 * make any big difference anyway, since we have 360 points in total.
 *
 */
static void
sort_points_x (GtkSatMap *satmap, sat_t *sat, GooCanvasPoints *points, gint num)
{
    gsize size = 2*sizeof(double);

    /* call g_qsort_with_data, which warps the qsort function
       from stdlib */
    g_qsort_with_data (points->coords, num, size,
                       compare_coordinates_x, NULL);

    /* move point at position 0 to position 1 */
    points->coords[2] = satmap->x0;
    points->coords[3] = points->coords[1];

    /* move point at position N to position N-1 */
    points->coords[716] = satmap->x0+satmap->width;//points->coords[718];
    points->coords[717] = points->coords[719];

    if (sat->ssplat > 0.0) {
        /* insert (x0-1,y0) into position 0 */
        points->coords[0] = satmap->x0;
        points->coords[1] = satmap->y0;
        
        /* insert (x0+width,y0) into position N */
        points->coords[718] = satmap->x0 + satmap->width;
        points->coords[719] = satmap->y0;
    }
    else {
        /* insert (x0,y0+height) into position 0 */
        points->coords[0] = satmap->x0;
        points->coords[1] = satmap->y0 + satmap->height;

        /* insert (x0+width,y0+height) into position N */
        points->coords[718] = satmap->x0 + satmap->width;
        points->coords[719] = satmap->y0 + satmap->height;
    }
}


/** \brief Sort points according to Y coordinates.
 *  \param satmap The GtkSatMap structure.
 *  \param sat The satellite data structure.
 *  \param points The points to sort.
 *  \param num The number of points. By specifying it as parameter we can
 *             sort incomplete arrays.
 *
 * This function sorts the points in ascending order with respect
 * to their y value.
 *
 */
static void
sort_points_y (GtkSatMap *satmap, sat_t *sat, GooCanvasPoints *points, gint num)
{
    gsize size;

    size = 2*sizeof(double);

    /* call g_qsort_with_data, which warps the qsort function
       from stdlib */
    g_qsort_with_data (points->coords, num, size,
                       compare_coordinates_y, NULL);
}


/** \brief Compare two X coordinates.
 *  \param a Pointer to one coordinate (x,y) both double.
 *  \param b Pointer to the second coordinate (x,y) both double.
 *  \param data User data; always NULL.
 *  \return Negative value if a < b; zero if a = b; positive value if a > b. 
 *
 * This function is used by the g_qsort_with_data function to compare two
 * elements in the coordinate array of the GooCanvasPoints structure. We have
 * to remember that GooCanvasPoints->coords is an array of XY values, i.e.
 * [X0,Y0,X1,Y1,...,Xn,Yn], but we only want to sort according to the X
 * coordinate. Therefore, we let the g_qsort_with_data believe that the whole
 * pair is one element (which is OK even according to the API docs) but we
 * cast the pointers to an array with two elements and compare only the first
 * one (x).
 *
 */
static gint
compare_coordinates_x (gconstpointer a, gconstpointer b, gpointer data)
{
    double *ea = (double *)a;
    double *eb = (double *)b;
    
    if (ea[0] < eb[0]) {
        return -1;
    }

    else if (ea[0] > eb[0]) {
        return 1;
    }

    return 0;
}


/** \brief Compare two Y coordinates.
 *  \param a Pointer to one coordinate (x,y) both double.
 *  \param b Pointer to the second coordinate (x,y) both double.
 *  \param data User data; always NULL.
 *  \return Negative value if a < b; zero if a = b; positive value if a > b. 
 *
 * This function is used by the g_qsort_with_data function to compare two
 * elements in the coordinate array of the GooCanvasPoints structure. We have
 * to remember that GooCanvasPoints->coords is an array of XY values, i.e.
 * [X0,Y0,X1,Y1,...,Xn,Yn], but we only want to sort according to the Y
 * coordinate. Therefore, we let the g_qsort_with_data believe that the whole
 * pair is one element (which is OK even according to the API docs) but we
 * cast the pointers to an array with two elements and compare only the second
 * one (y).
 *
 */
static gint
compare_coordinates_y (gconstpointer a, gconstpointer b, gpointer data)
{
    double *ea = (double *)a;
    double *eb = (double *)b;
    
    if (ea[1] < eb[1]) {
        return -1;
    }

    else if (ea[1] > eb[1]) {
        return 1;
    }

    return 0;
}


/** \brief Plot a satellite.
 *  \param key The hash table key.
 *  \param value Pointer to the satellite.
 *  \param data Pointer to the GtkSatMap widget.
 *
 * This function creates and initializes the canvas objects (rectangle, label,
 * footprint) for a satellite. The function is called as a g_hash_table_foreach
 * callback.
 */
static void
plot_sat (gpointer key, gpointer value, gpointer data)
{
    GtkSatMap *satmap = GTK_SAT_MAP (data);
    sat_map_obj_t *obj = NULL;
    sat_t *sat = SAT(value);
    GooCanvasItemModel *root;
    gint *catnum;
    guint32 col,covcol;
    gfloat x,y;

    /* get satellite and SSP */
    catnum = g_new0 (gint, 1);
    *catnum = sat->tle.catnr;

    lonlat_to_xy (satmap, sat->ssplon, sat->ssplat, &x, &y);
    
    /* create and initialize a sat object */
    obj = g_try_new (sat_map_obj_t, 1);

    obj->selected = FALSE;
    obj->showtrack = FALSE;
    obj->showcov = TRUE;
    obj->istarget = FALSE;
    obj->oldrcnum = 0;
    obj->newrcnum = 0;
    obj->track_data.latlon = NULL;
    obj->track_data.lines = NULL;
    obj->track_orbit = 0;

    root = goo_canvas_get_root_item_model (GOO_CANVAS (satmap->canvas));

    /* satellite color */
    col = mod_cfg_get_int (satmap->cfgdata,
                           MOD_CFG_MAP_SECTION,
                           MOD_CFG_MAP_SAT_COL,
                           SAT_CFG_INT_MAP_SAT_COL);

    /* area coverage colour */
    /*     if ((obj->showcov) && (sat->otype != ORBIT_TYPE_DECAYED)) { */
    covcol = mod_cfg_get_int (satmap->cfgdata,
                              MOD_CFG_MAP_SECTION,
                              MOD_CFG_MAP_SAT_COV_COL,
                              SAT_CFG_INT_MAP_SAT_COV_COL);
    /*     } */
    /*     else { */
    /*         covcol = 0x00000000; */
    /*     } */

    obj->marker = goo_canvas_rect_model_new (root,
                                             x - MARKER_SIZE_HALF,
                                             y - MARKER_SIZE_HALF,
                                             2 * MARKER_SIZE_HALF,
                                             2 * MARKER_SIZE_HALF,
                                             "fill-color-rgba", col,
                                             "stroke-color-rgba", col,
                                             NULL);

    obj->label = goo_canvas_text_model_new (root, sat->nickname,
                                            x, 
                                            y+2,
                                            -1,
                                            GTK_ANCHOR_NORTH,
                                            "font", "Sans 8",
                                            "fill-color-rgba", col,
                                            NULL);

    g_object_set_data (G_OBJECT (obj->marker), "catnum", GINT_TO_POINTER (*catnum));
    g_object_set_data (G_OBJECT (obj->label), "catnum", GINT_TO_POINTER (*catnum));

    /* initialize points for footprint */
    points1 = goo_canvas_points_new (360);
    points2 = goo_canvas_points_new (360);

    /* calculate footprint */
    obj->newrcnum = calculate_footprint (satmap, sat);
    obj->oldrcnum = obj->newrcnum;

    /* invisible footprint for decayed sats (STS fix) */
    /*     if (sat->otype == ORBIT_TYPE_DECAYED) { */
    /*         col = 0x00000000; */
    /*     } */

    /* always create first part of range circle */
    obj->range1 = goo_canvas_polyline_model_new (root, FALSE, 0,
                                                 "points", points1,
                                                 "line-width", 1.0,
                                                 "fill-color-rgba", covcol,
                                                 "stroke-color-rgba", col,
                                                 "line-cap", CAIRO_LINE_CAP_SQUARE,
                                                 "line-join", CAIRO_LINE_JOIN_MITER,
                                                 NULL);
    g_object_set_data (G_OBJECT (obj->range1), "catnum", GINT_TO_POINTER (*catnum));
    
    /* create second part if available */
    if (obj->newrcnum == 2) {
        //g_print ("N1:%d  N2:%d\n", points1->num_points, points2->num_points);

        obj->range2 = goo_canvas_polyline_model_new (root, FALSE, 0,
                                                     "points", points2,
                                                     "line-width", 1.0,
                                                     "fill-color-rgba", covcol,
                                                     "stroke-color-rgba", col,
                                                     "line-cap", CAIRO_LINE_CAP_SQUARE,
                                                     "line-join", CAIRO_LINE_JOIN_MITER,
                                                     NULL);
        g_object_set_data (G_OBJECT (obj->range2), "catnum", GINT_TO_POINTER (*catnum));

    }

    goo_canvas_points_unref (points1);
    goo_canvas_points_unref (points2);

    /* add sat to hash table */
    g_hash_table_insert (satmap->obj, catnum, obj);
}


/** \brief Update a given satellite.
 */
static void
update_sat (gpointer key, gpointer value, gpointer data)
{
    gint               *catnum;
    GtkSatMap          *satmap = GTK_SAT_MAP (data);
    sat_map_obj_t      *obj = NULL;
    sat_t              *sat = SAT(value);
    gfloat             x, y;
    gdouble            oldx, oldy; 
    gdouble            now;  // = get_current_daynum ();
    GooCanvasItemModel *root;
    gint               idx;
    guint32            col,covcol;

    //gdouble sspla,ssplo;

    root = goo_canvas_get_root_item_model (GOO_CANVAS (satmap->canvas));

    catnum = g_new0 (gint, 1);
    *catnum = sat->tle.catnr;

    now = satmap->tstamp;

    /* update next AOS */
    if ((sat->aos > now) && (sat->aos < satmap->naos)) {
        satmap->naos = sat->aos;
        satmap->ncat = sat->tle.catnr;
    }

    obj = SAT_MAP_OBJ (g_hash_table_lookup (satmap->obj, catnum));

    if (obj->selected) {
        /* update satmap->sel */
        update_selected (satmap, sat);
    }

    //sat_debugger_get_ssp (&ssplo,&sspla);
    //sat->ssplon = ssplo;
    //sat->ssplat = sspla;

    lonlat_to_xy (satmap, sat->ssplon, sat->ssplat, &x, &y);

    /* update only if satellite has moved at least
       2 * MARKER_SIZE_HALF (no need to drain CPU all the time)
    */
    g_object_get (obj->marker,
                  "x", &oldx,
                  "y", &oldy,
                  NULL);

    if ((fabs (oldx-x) >= 2*MARKER_SIZE_HALF) ||
        (fabs (oldy-y) >= 2*MARKER_SIZE_HALF)) {

        /* update sat mark */
        g_object_set (obj->marker,
                      "x", (gdouble) (x - MARKER_SIZE_HALF),
                      "y", (gdouble) (y - MARKER_SIZE_HALF),
                      NULL);

        /* update sat label */
        if (x < 50) {
            g_object_set (obj->label,
                          "x", (gdouble) (x+3),
                          "y", (gdouble) (y),
                          "anchor", GTK_ANCHOR_WEST,
                          NULL);
        } else if ((satmap->width - x ) < 50) {
            g_object_set (obj->label,
                          "x", (gdouble) (x),
                          "y", (gdouble) (y),
                          "anchor", GTK_ANCHOR_EAST,
                          NULL);
        } else if ((satmap->height - y) < 25) {
            g_object_set (obj->label,
                          "x", (gdouble) (x),
                          "y", (gdouble) (y-2),
                          "anchor", GTK_ANCHOR_SOUTH,
                          NULL);
        } else {
            g_object_set (obj->label,
                          "x", (gdouble) (x),
                          "y", (gdouble) (y+2),
                          "anchor", GTK_ANCHOR_NORTH,
                          NULL);
        }

        /* initialize points for footprint */
        points1 = goo_canvas_points_new (360);
        points2 = goo_canvas_points_new (360);

        /* calculate footprint */
        obj->newrcnum = calculate_footprint (satmap, sat);

        /* always update first part */
        g_object_set (obj->range1,
                      "points", points1,
                      NULL);

        if (obj->newrcnum == 2) {
            if (obj->oldrcnum == 1) {
                /* we need to create the second part */
                if (obj->selected) {
                    col = mod_cfg_get_int (satmap->cfgdata,
                                           MOD_CFG_MAP_SECTION,
                                           MOD_CFG_MAP_SAT_SEL_COL,
                                           SAT_CFG_INT_MAP_SAT_SEL_COL);
                }
                else {
                    col = mod_cfg_get_int (satmap->cfgdata,
                                           MOD_CFG_MAP_SECTION,
                                           MOD_CFG_MAP_SAT_COL,
                                           SAT_CFG_INT_MAP_SAT_COL);
                }
                /* coverage color */
                if (obj->showcov) {
                    covcol = mod_cfg_get_int (satmap->cfgdata,
                                              MOD_CFG_MAP_SECTION,
                                              MOD_CFG_MAP_SAT_COV_COL,
                                              SAT_CFG_INT_MAP_SAT_COV_COL);
                }
                else {
                    covcol = 0x00000000;
                }
                obj->range2 = goo_canvas_polyline_model_new (root, FALSE, 0,
                                                             "points", points2,
                                                             "line-width", 1.0,
                                                             "fill-color-rgba", covcol,
                                                             "stroke-color-rgba", col,
                                                             "line-cap", CAIRO_LINE_CAP_SQUARE,
                                                             "line-join", CAIRO_LINE_JOIN_MITER,
                                                             NULL);
                g_object_set_data (G_OBJECT (obj->range2), "catnum",
                                   GINT_TO_POINTER (*catnum));
            }
            else {
                /* just update the second part */
                g_object_set (obj->range2,
                              "points", points2,
                              NULL);
            }
        }
        else {
            if (obj->oldrcnum == 2) {
                /* remove second part */
                idx = goo_canvas_item_model_find_child (root, obj->range2);
                if (idx != -1) {
                    goo_canvas_item_model_remove_child (root, idx);
                }
            }
        }

        /* update rc-number */
        obj->oldrcnum = obj->newrcnum;

        goo_canvas_points_unref (points1);
        goo_canvas_points_unref (points2);
    }

    /* if ground track is visible check whether we have passed into a
       new orbit, in which case we need to recalculate the ground track
    */
    if (obj->showtrack) {
        if (obj->track_orbit != sat->orbit) {
            ground_track_update (satmap, sat, satmap->qth, obj, TRUE);
        }
        /* otherwise we may be in a map rescale process */
        else if (satmap->resize) {
            ground_track_update (satmap, sat, satmap->qth, obj, FALSE);
        }
    }

    g_free (catnum);
}


/** \brief Update information about the selected satellite.
 *  \param satmap Pointer to the GtkSatMap widget.
 *  \param sat Pointer to the selected satellite
 *
 * 
 */
static void
update_selected (GtkSatMap *satmap, sat_t *sat)
{
    guint         h,m,s;
    gchar        *ch,*cm,*cs;
    gchar        *alsstr,*text;
    gdouble       number, now;
    gboolean      isgeo = FALSE;  /* set to TRUE if satellite appears to be GEO */

    now = satmap->tstamp;//get_current_daynum ();

    if (sat->el > 0.0) {
        if (sat->los > 0.0) {
            number = sat->los - now;
            alsstr = g_strdup ("LOS");
        }
        else {
            isgeo = TRUE;
        }
    }
    else {
        if (sat->aos > 0.0) {
            number = sat->aos - now;
            alsstr = g_strdup ("AOS");
        }
        else {
            isgeo = TRUE;
        }
    }

    /* if satellite appears to be GEO don't attempt to show AOS/LOS */
    if (isgeo) {
        if (sat->el > 0.0) {
            text = g_strdup_printf ("<span background=\"#%s\"> %s: Always in range </span>",
                                    satmap->infobgd, sat->nickname);
        }
        else {
            text = g_strdup_printf ("<span background=\"#%s\"> %s: Always out of range </span>",
                                    satmap->infobgd, sat->nickname);
        }
    }
    else {
        /* convert julian date to seconds */
        s = (guint) (number * 86400);

        /* extract hours */
        h = (guint) floor (s/3600);
        s -= 3600*h;

        /* leading zero */
        if ((h > 0) && (h < 10))
            ch = g_strdup ("0");
        else
            ch = g_strdup ("");

        /* extract minutes */
        m = (guint) floor (s/60);
        s -= 60*m;

        /* leading zero */
        if (m < 10)
            cm = g_strdup ("0");
        else
            cm = g_strdup ("");

        /* leading zero */
        if (s < 10)
            cs = g_strdup (":0");
        else
            cs = g_strdup (":");

        if (h > 0) {
            text = g_strdup_printf ("<span background=\"#%s\"> "\
                                    "%s %s in %s%d:%s%d%s%d </span>",
                                    satmap->infobgd, sat->nickname,
                                    alsstr, ch, h, cm, m, cs, s);
        }
        else {
            text = g_strdup_printf ("<span background=\"#%s\"> "\
                                    "%s %s in %s%d%s%d </span>",
                                    satmap->infobgd, sat->nickname,
                                    alsstr, cm, m, cs, s);
        }

        g_free (ch);
        g_free (cm);
        g_free (cs);
        g_free (alsstr);
    }

    /* update info text */
    g_object_set (satmap->sel, "text", text, NULL);
    g_free (text);
}


/** \brief Add grid lines and labels to the map. */
static void
draw_grid_lines (GtkSatMap *satmap, GooCanvasItemModel *root)
{
    gdouble        xstep, ystep;
    gfloat        lon, lat;
    guint32        col;
    guint        i;
    gchar        *buf, hmf = ' ';

    /* initialize algo parameters */
    col = mod_cfg_get_int (satmap->cfgdata,
                           MOD_CFG_MAP_SECTION,
                           MOD_CFG_MAP_GRID_COL,
                           SAT_CFG_INT_MAP_GRID_COL);

    xstep = (gdouble) (30.0 * satmap->width / 360.0);
    ystep = (gdouble) (30.0 * satmap->height / 180.0);

    /* horizontal grid */
    for (i = 0; i < 5; i++) {
        /* line */
        satmap->gridh[i] = goo_canvas_polyline_model_new_line (root,
                                                               (gdouble) satmap->x0,
                                                               (gdouble) (satmap->y0 + (i+1)*ystep),
                                                               (gdouble) (satmap->x0 + satmap->width),
                                                               (gdouble) (satmap->y0 + (i+1)*ystep),
                                                               "stroke-color-rgba", col,
                                                               "line-cap", CAIRO_LINE_CAP_SQUARE,
                                                               "line-join", CAIRO_LINE_JOIN_MITER,
                                                               "line-width", 0.5,
                                                               NULL);

        /* FIXME: Use dotted line pattern? */

        /* label */
        xy_to_lonlat (satmap, satmap->x0, satmap->y0 + (i+1)*ystep, &lon, &lat);
        if (sat_cfg_get_bool (SAT_CFG_BOOL_USE_NSEW)) {
            if (lat < 0.00) {
                lat = -lat;
                hmf = 'S';
            }
            else {
                hmf = 'N';
            }
        }
        buf = g_strdup_printf ("%.0f\302\260%c", lat, hmf);
        satmap->gridhlab[i] = goo_canvas_text_model_new (root, 
                                                         buf,
                                                         (gdouble) (satmap->x0 + 15),
                                                         (gdouble) (satmap->y0 + (i+1)*ystep),
                                                         -1, GTK_ANCHOR_NORTH,
                                                         "font", "Sans 8", "fill-color-rgba", col,
                                                         NULL);
        g_free (buf);

        /* lower items to be just above the background map
           or below it if lines are invisible
        */
        if (satmap->showgrid) {
            goo_canvas_item_model_raise (satmap->gridh[i], satmap->map);
            goo_canvas_item_model_raise (satmap->gridhlab[i], satmap->map);
        }
        else {
            goo_canvas_item_model_lower (satmap->gridh[i], satmap->map);
            goo_canvas_item_model_lower (satmap->gridhlab[i], satmap->map);
        }
    }

    /* vertical grid */
    for (i = 0; i < 11; i++) {
        /* line */
        satmap->gridv[i] = goo_canvas_polyline_model_new_line (root,
                                                               (gdouble) (satmap->x0 + (i+1)*xstep),
                                                               (gdouble) satmap->y0,
                                                               (gdouble) (satmap->x0 + (i+1)*xstep),
                                                               (gdouble) (satmap->y0 + satmap->height),
                                                               "stroke-color-rgba", col,
                                                               "line-cap", CAIRO_LINE_CAP_SQUARE,
                                                               "line-join", CAIRO_LINE_JOIN_MITER,
                                                               "line-width", 0.5,
                                                               NULL);

        /* label */
        xy_to_lonlat (satmap, satmap->x0 + (i+1)*xstep, satmap->y0, &lon, &lat);
        if (sat_cfg_get_bool (SAT_CFG_BOOL_USE_NSEW)) {
            if (lon < 0.00) {
                lon = -lon;
                hmf = 'W';
            }
            else {
                hmf = 'E';
            }
        }
        buf = g_strdup_printf ("%.0f\302\260%c", lon, hmf);
        satmap->gridvlab[i] = goo_canvas_text_model_new (root, 
                                                         buf,
                                                         (gdouble) (satmap->x0 + (i+1)*xstep),
                                                         (gdouble) (satmap->y0 + satmap->height - 5),
                                                         -1, GTK_ANCHOR_EAST,
                                                         "font", "Sans 8", "fill-color-rgba", col,
                                                         NULL);
        g_free (buf);

        /* lower items to be just above the background map
           or below it if lines are invisible
        */
        if (satmap->showgrid) {
            goo_canvas_item_model_raise (satmap->gridv[i], satmap->map);
            goo_canvas_item_model_raise (satmap->gridvlab[i], satmap->map);
        }
        else {
            goo_canvas_item_model_lower (satmap->gridv[i], satmap->map);
            goo_canvas_item_model_lower (satmap->gridvlab[i], satmap->map);
        }
    }
}


/** \brief Redraw grid lines and labels. */
static void redraw_grid_lines (GtkSatMap *satmap)
{
    GooCanvasPoints *line;
    gdouble xstep, ystep;
    guint i;

    xstep = (gdouble) 30.0 * ((gdouble) satmap->width) / 360.0;
    ystep = (gdouble) 30.0 * ((gdouble) satmap->height) / 180.0;

    /* horizontal grid */
    for (i = 0; i < 5; i++) {

        /* update line */
        line = goo_canvas_points_new (2);
        line->coords[0] = (gdouble) satmap->x0;
        line->coords[1] = (gdouble) (satmap->y0 + (i+1)*ystep);
        line->coords[2] = (gdouble) (satmap->x0 + satmap->width);
        line->coords[3] = (gdouble) (satmap->y0 + (i+1)*ystep);
        g_object_set (satmap->gridh[i], "points", line, NULL);
        goo_canvas_points_unref (line);

        /* update label */
        g_object_set (satmap->gridhlab[i],
                      "x", (gdouble) (satmap->x0 + 15),
                      "y", (gdouble) (satmap->y0 + (i+1)*ystep),
                      NULL);

        /* lower items to be just above the background map
           or below it if lines are invisible
        */
        if (satmap->showgrid) {
            goo_canvas_item_model_raise (satmap->gridh[i], satmap->map);
            goo_canvas_item_model_raise (satmap->gridhlab[i], satmap->map);
        }
        else
            goo_canvas_item_model_lower (satmap->gridh[i], satmap->map);
    }

    /* vertical grid */
    for (i = 0; i < 11; i++) {
        /* update line */
        line = goo_canvas_points_new (2);
        line->coords[0] = (gdouble) (satmap->x0 + (i+1)*xstep);
        line->coords[1] = (gdouble) satmap->y0;
        line->coords[2] = (gdouble) (satmap->x0 + (i+1)*xstep);
        line->coords[3] = (gdouble) (satmap->y0 + satmap->height);
        g_object_set (satmap->gridv[i], "points", line, NULL);
        goo_canvas_points_unref (line);

        /* update label */
        g_object_set (satmap->gridvlab[i],
                      "x", (gdouble) (satmap->x0 + (i+1)*xstep),
                      "y", (gdouble) (satmap->y0 + satmap->height - 5),
                      NULL);

        /* lower items to be just above the background map
           or below it if lines are invisible
        */
        if (satmap->showgrid) {
            goo_canvas_item_model_raise (satmap->gridv[i], satmap->map);
            goo_canvas_item_model_raise (satmap->gridvlab[i], satmap->map);
        }
        else {
            goo_canvas_item_model_lower (satmap->gridv[i], satmap->map);
            goo_canvas_item_model_lower (satmap->gridvlab[i], satmap->map);
        }
    }
}


/** \brief  Public wrapper for private conversion function. */
void gtk_sat_map_lonlat_to_xy (GtkSatMap *m,
                               gdouble lon, gdouble lat,
                               gdouble *x, gdouble *y)
{
    gfloat fx,fy;

    fx = (gfloat) *x;
    fy = (gfloat) *y;

    lonlat_to_xy (m, lon, lat, &fx, &fy);

    *x = (gdouble) fx;
    *y = (gdouble) fy;
}


/** \brief Reload reference to satellites (e.g. after TLE update). */
void
gtk_sat_map_reload_sats (GtkWidget *satmap, GHashTable *sats)
{
    GTK_SAT_MAP (satmap)->sats = sats;
    GTK_SAT_MAP (satmap)->naos = 0.0;
    GTK_SAT_MAP (satmap)->ncat = 0;
}