File: mapsource.c

package info (click to toggle)
gpsbabel 1.2.4-2
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 5,660 kB
  • ctags: 3,780
  • sloc: ansic: 38,884; makefile: 333; pascal: 302; perl: 212; xml: 84; tcl: 74; sh: 20; objc: 7
file content (2174 lines) | stat: -rw-r--r-- 61,651 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
/*
    Access to Garmin MapSource files.
    Based on information provided by Ian Cowley & Mark Bradley

    Copyright (C) 2002 Robert Lipe, robertlipe@usa.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, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111 USA
 */

/* #define	MPS_DEBUG	0 */

#include <stdio.h>
#include <string.h>

#include "defs.h"
#include "garmin_tables.h"
#include <ctype.h>

static	FILE	*mps_file_in;
static	FILE	*mps_file_out;
static	FILE	*mps_file_temp;
static	void	*mkshort_handle;

static	int		mps_ver_in = 0;
static	int		mps_ver_out = 0;
static	int		mps_ver_temp = 0;

/* Temporary pathname used when merging gpsbabel output with an existing file */
static	char	tempname[256];
static	char	origname[256];

static	const waypoint	*prevRouteWpt;
/* Private queues of written out waypoints */
static queue written_wpt_head;
static queue written_route_wpt_head;
static void *written_wpt_mkshort_handle;

/* Private queue of read in waypoints assumed to be used only for routes */
static queue read_route_wpt_head;
static void *read_route_wpt_mkshort_handle;

#define MPSDEFAULTWPTCLASS		0
#define MPSHIDDENROUTEWPTCLASS	8

#define MYNAME "MAPSOURCE" 
#define ISME 0
#define NOTME 1

#define DEFAULTICONDESCR		"Waypoint"
#define DEFAULTICONVALUE		18

#define MPSNAMEBUFFERLEN	1024
#define MPSNOTESBUFFERLEN	4096
#define MPSDESCBUFFERLEN	4096

char *snlen = NULL;
char *snwhiteopt = NULL;
char *mpsverout = NULL;
char *mpsmergeout = NULL;
char *mpsusedepth = NULL;
char *mpsuseprox = NULL;

static
arglist_t mps_args[] = {
	{"snlen", &snlen, "Length of generated shortnames", NULL, ARGTYPE_INT },
	{ "snwhite", &snwhiteopt, "(0/1) Allow whitespace synth. shortnames",
		NULL, ARGTYPE_BOOL},
	{"mpsverout", &mpsverout, 
		"Version of mapsource file to generate (3,4,5)", NULL,
		ARGTYPE_INT },
	{"mpsmergeout", &mpsmergeout, "Merge output with existing file", 
		NULL, ARGTYPE_BOOL },
	{"mpsusedepth", &mpsusedepth, 
		"Use depth values on output (default is ignore)", NULL,
		ARGTYPE_BOOL },
	{"mpsuseprox", &mpsuseprox, 
		"Use proximity values on output (default is ignore)", 
		NULL, ARGTYPE_BOOL },
	{0, 0, 0, 0, 0}
};

/*
 * A wrapper to ensure the doubles we fwrite are in correct endianness.
 */

le_fwrite64(void *ptr, int sz, int ct, FILE *stream)
{
	unsigned char cbuf[8];

	if ((sz != 8) || (ct != 1)) {
		fatal(MYNAME ": Bad internal arguments to le_fwrite64");
	}

	le_read64(cbuf, ptr);
	fwrite(cbuf, 8, 1, stream);
}

le_fread64(void *ptr, int sz, int ct, FILE *stream)
{
	unsigned char cbuf[8];

	fread(cbuf, 8, 1, stream);
	le_read64(ptr, cbuf);
}

static void 
mps_noop(const route_head *wp)
{
	/* no-op */
}

void
mps_wpt_q_init(queue *whichQueue)
{
	QUEUE_INIT(whichQueue);
}

void
mps_wpt_q_deinit(queue *whichQueue)
{
	queue *elem, *tmp;

	QUEUE_FOR_EACH(whichQueue, elem, tmp) {
		waypoint *q = (waypoint *) dequeue(elem);
		waypt_free(q);
	}
}

/*
 * Find a waypoint that we've already written out
 *
 */
waypoint *
mps_find_wpt_q_by_name(const queue *whichQueue, const char *name)
{
	queue *elem, *tmp;
	waypoint *waypointp;

	QUEUE_FOR_EACH(whichQueue, elem, tmp) {
		waypointp = (waypoint *) elem;
		if (0 == strcmp(waypointp->shortname, name)) {
			return waypointp;
		}
	}
	return NULL;
}

/*
 * Add a waypoint that we've already written out to our list
 *
 */
void
mps_wpt_q_add(const queue *whichQueue, const waypoint *wpt)
{
	waypoint *written_wpt = waypt_dupe(wpt);
	ENQUEUE_TAIL(whichQueue, &written_wpt->Q);
}

const char *
mps_find_desc_from_icon_number(const int icon, garmin_formats_e garmin_format)
{
	icon_mapping_t *i;

	for (i = garmin_icon_table; i->icon; i++) {
		switch (garmin_format) {
			case MAPSOURCE:
				if (icon == i->mpssymnum)
					return i->icon;
				break;
			case PCX:
			case GARMIN_SERIAL:
				if (icon == i->pcxsymnum)
					return i->icon;
				break;
			default:
				fatal(MYNAME ": unknown garmin format");
		}
	}
	return DEFAULTICONDESCR;
}

int
mps_find_icon_number_from_desc(const char *desc, garmin_formats_e garmin_format)
{
	icon_mapping_t *i;
	int def_icon = DEFAULTICONVALUE;
	int n;

	if (!desc)
		return def_icon;

	/*
	 * If we were given a numeric icon number as a description 
	 * (i.e. 8255), just return that.
	 */
	n = atoi(desc);
	if (n)  {
		return n;
	}

	for (i = garmin_icon_table; i->icon; i++) {
		if (case_ignore_strcmp(desc,i->icon) == 0) {
			switch (garmin_format) {
			case MAPSOURCE:
				return i->mpssymnum;
			case PCX:
			case GARMIN_SERIAL:
				return i->pcxsymnum;
			default:
				fatal(MYNAME ": unknown garmin format");
			}
		}
	}
	return def_icon;
}

int mps_converted_icon_number(const int icon_num, const int mpsver, garmin_formats_e garmin_format)
{
	int def_icon = DEFAULTICONVALUE;

	switch (garmin_format) {
	case MAPSOURCE:
		if (mpsver == 5) return icon_num;
		if (mpsver == 4) {
			/* Water hydrant */
			if (icon_num == 139) return def_icon;
			else return icon_num;
		}
		else {
			/* the Contact icons - V3 doesn't have anything like this */
			if ((icon_num >= 119) && (icon_num <= 138)) return def_icon;
			/* the Geocache icons - V3 use the Circle with X */
			if ((icon_num >= 117) && (icon_num <= 118)) return 65;
			/* Water hydrant */
			if (icon_num == 139) return def_icon;
			return icon_num;
		}

	case PCX:
	case GARMIN_SERIAL:
		if (mpsver == 5) return icon_num;
		if (mpsver == 4) {
			/* Water hydrant */
			if (icon_num == 8282) return def_icon;
			else return icon_num;
		}
		/* the Contact icons - V3 doesn't have anything like this */
		if ((icon_num >= 8257) && (icon_num <= 8276)) return def_icon;
		/* the Geocache icons - V3 use the Circle with X */
		if ((icon_num >= 8255) && (icon_num <= 8256)) return 179;
		/* Water hydrant */
		if (icon_num == 8282) return def_icon;
		return icon_num;

	default:
		fatal(MYNAME ": unknown garmin format");
	}
	return def_icon;
}

static void
mps_rd_init(const char *fname)
{
	mps_file_in = xfopen(fname, "rb", MYNAME);

	read_route_wpt_mkshort_handle = mkshort_new_handle();
	/* initialise the "private" queue of waypoints read for routes */
	mps_wpt_q_init(&read_route_wpt_head);
}

static void
mps_rd_deinit(void)
{
	fclose(mps_file_in);
	if ( read_route_wpt_mkshort_handle ) {
		mkshort_del_handle( read_route_wpt_mkshort_handle );
	}
	/* flush the "private" queue of waypoints read for routes */
	mps_wpt_q_deinit(&read_route_wpt_head);
}

static void
mps_wr_init(const char *fname)
{
	if (mpsmergeout) {
		mps_file_out = xfopen(fname, "rb", MYNAME);
		if (mps_file_out == NULL) {
			mpsmergeout = NULL;
		}
		else {
			fclose(mps_file_out);
			srand((unsigned) current_time());

			for (;;) {
				/* create a temporary name  based on a random char and the existing name */
				/* then test if it already exists, if so try again with another rand num */
				/* yeah, yeah, so there's probably a library function for this           */
				sprintf(tempname, "%s.%08x", fname, rand());
				mps_file_temp = fopen(tempname, "rb");
				if (mps_file_temp == NULL) break;
				fclose(mps_file_temp);
			}
			rename(fname, tempname);
			mps_file_temp = xfopen(tempname, "rb", MYNAME);
			strcpy(origname, fname);	/* save in case we need to revert the renamed file */
		}
	}

	mps_file_out = xfopen(fname, "wb", MYNAME);

	written_wpt_mkshort_handle = mkshort_new_handle();
	/* initialise the "private" queue of waypoints written */
	mps_wpt_q_init(&written_wpt_head);
	mps_wpt_q_init(&written_route_wpt_head);
}

static void
mps_wr_deinit(void)
{
	fclose(mps_file_out);

	if (mpsmergeout) {
		fclose(mps_file_temp);
		remove(tempname);
	}

	if ( written_wpt_mkshort_handle ) {
		mkshort_del_handle( written_wpt_mkshort_handle );
	}
	/* flush the "private" queue of waypoints written */
	mps_wpt_q_deinit(&written_wpt_head);
	mps_wpt_q_deinit(&written_route_wpt_head);
}

/*
 * get characters until and including terminating NULL from mps_file_in 
 * and write into buf.
 */
static void
mps_readstr(FILE *mps_file, char *buf, size_t sz)
{
	int c;
	while (sz-- && (c = fgetc (mps_file)) != EOF) {
		*buf++ = c;
		if (c == 0)  {
			return;
		}
	}
}

/*
 * read in from file to check a) valid format b) version of data formating
 * MRCB
 */
static void
mps_fileHeader_r(FILE *mps_file, int *mps_ver)
{
	char hdr[100];
	int reclen;

	mps_readstr(mps_file, hdr, sizeof(hdr));
	if ( strcmp( hdr, "MsRcd" )) {
		fatal(MYNAME ": This doesn't look like a mapsource file.\n");
	}
	/* Read record length of "format details" section */
	fread(&reclen, 4, 1, mps_file);
	reclen = le_read32(&reclen);
	/* Read the "format details" in plus the trailing null */
	fread( hdr, 3, 1, mps_file);
	if (hdr[0] != 'D')  {
		/* No flag for the "data" section */
		fatal(MYNAME ": This doesn't look like a mapsource file.\n");
	}
	if (hdr[1] == 'd')  {
		*mps_ver = 3;
	}
	else if ((hdr[1] > 'd') && (hdr[1] <= 'h')) {
		*mps_ver = 4;
	}
	else if ((hdr[1] > 'h') && (hdr[1] <= 'i')) {
		*mps_ver = 5;
	}
	else {
		fatal(MYNAME ": Unsuppported version of mapsource file.\n");
	}
	/* Skip reliably over the "format details" section */
	fseek( mps_file, reclen+1-3, SEEK_CUR); 
	/* Read record length of "program signature" section */
	fread(&reclen, 4, 1, mps_file);
	reclen = le_read32(&reclen);
	/* Skip reliably over the "program signature" section */
	if (reclen >= 0) fseek(mps_file, reclen+1, SEEK_CUR); 
}

/*
 * write out to file 
 * MRCB
 */
static void
mps_fileHeader_w(FILE *mps_file, int mps_ver)
{
	char hdr[100];
	int reclen;

	strcpy (hdr, "MsRc");
	fwrite(hdr, 4, 1, mps_file);

	/* Between versions 3 & 5 this value is 'd', but might change in the future */
	strcpy(hdr, "d");
	fwrite(hdr, 2, 1, mps_file);	/* include trailing NULL char */

	/* Start of a "Data" section */
	hdr[0] = 'D';
	/* if (mps_ver == 3) */
	hdr[1] = 'd';						/* equates to V3.02 */
	if (mps_ver == 4) hdr[1] = 'g';		/* equates to V4.06 */
	if (mps_ver == 5) hdr[1] = 'i';		/* equates to V5.0 */
	hdr[2] = 0;

	reclen = 2;							/* this is 3 byte record */
	le_write32(&reclen, reclen);
	fwrite(&reclen, 4, 1, mps_file);
	fwrite(hdr, 3, 1, mps_file);		/* reclen + 1 */

	hdr[0] = 'A';
	/* if (mps_ver == 3) */
	hdr[1] = 0x2E; hdr[2] = 0x01;		/* equates to V3.02 */
	hdr[3] = 'S'; 
	hdr[4] = 'Q'; 
	hdr[5] = 'A';
	hdr[6] = 0;
	strcpy(hdr+7,"Oct 20 1999");
	strcpy(hdr+19,"12:50:33");
	if (mps_ver == 4) {
		hdr[1] = 0x96;					/* equates to V4.06 */
		strcpy(hdr+7,"Oct 22 2001");
		strcpy(hdr+19,"15:45:33");
	}
	if (mps_ver == 5) {
		hdr[1] = 0xF4;					/* equates to V5.0 */
		strcpy(hdr+7,"Jul  3 2003");
		strcpy(hdr+19,"08:35:33");
	}

	reclen = 27;						/* pre measured! */
	le_write32(&reclen, reclen);
	fwrite(&reclen, 4, 1, mps_file);
	fwrite(hdr, 28, 1, mps_file);		/* reclen + 1  - can't use this as reclen may be wrongendian now */
}

/*
 * read in from file a map segment record
 * MRCB
 */
static void
mps_mapsegment_r(FILE *mps_file, int mps_ver)
{
	char hdr[100];
	int reclen;

	/* At the moment we're not doing anything with map segments, but here's the template code as if we were
	fread(&CDid, 4, 1, mps_file);
	reclen = le_read32(&CDid);

	fread(&CDSegmentid, 4, 1, mps_file);
	reclen = le_read32(&CDSegmentid);

	mps_readstr(mps_file, CDName, sizeof(CDName));
	mps_readstr(mps_file, CDSegmentName, sizeof(CDSegmentName));
	mps_readstr(mps_file, CDAreaName, sizeof(CDAreaName));

	fread(hdr, 4, 1, mps_file); /* trailing long value */
	
	fseek(mps_file, -5, SEEK_CUR);
	fread(&reclen, 4, 1, mps_file);
	reclen = le_read32(&reclen);
	if (reclen >= 0) fseek( mps_file, reclen+1, SEEK_CUR); 
	return;
}


/*
 * read in from file a mapsetname record
 * there should always be one of these at the end of the file
 * MRCB
 */
static void
mps_mapsetname_r(FILE *mps_file, int mps_ver)
{
	char hdr[100];
	int reclen;

	/* At the moment we're not doing anything with mapsetnames, but here's the template code as if we were
	mps_readstr(mps_file, hdr, sizeof(hdr));
	char mapsetnamename[very large number?];
	strcpy(mapsetnamename,hdr);
	char mapsetnameAutonameFlag;
	fread(&mapsetnameAutonameFlag, 1, 1, mps_file); */

	fseek(mps_file, -5, SEEK_CUR);
	fread(&reclen, 4, 1, mps_file);
	reclen = le_read32(&reclen);
	fseek( mps_file, reclen+1, SEEK_CUR); 
	return;
}


/*
 * write out to file a mapsetname record
 * there should always be one of these at the end of the file
 * MRCB
 */
static void
mps_mapsetname_w(FILE *mps_file, int mps_ver)
{
	char hdr[100];
	int reclen;

	hdr[0] = 'V';	/* mapsetname start of record indicator			*/
	hdr[1] = 0;		/* zero length null terminated string			*/
	hdr[2] = 1;		/* mapsetname autoname flag set to DO autoname	*/
	reclen = 2;		/* three bytes of the V record					*/
	le_write32(&reclen, reclen);
	fwrite(&reclen, 4, 1, mps_file);
	fwrite(hdr, 3, 1, mps_file);		/* reclen + 1 */
}


/*
 * read in from file a waypoint record
 * MRCB
 */
static void
mps_waypoint_r(FILE *mps_file, int mps_ver, waypoint **wpt, unsigned int *mpsclass)
{
	char tbuf[100];
	char wptname[MPSNAMEBUFFERLEN];
	char wptdesc[MPSDESCBUFFERLEN];
	char wptnotes[MPSNOTESBUFFERLEN];
	int lat;
	int lon;
	int	icon;

 	waypoint	*thisWaypoint = NULL;
	double	mps_altitude = unknown_alt;
	double	mps_proximity = unknown_alt;
	double	mps_depth = unknown_alt;

	thisWaypoint = waypt_new();
	*wpt = thisWaypoint;

	mps_readstr(mps_file, wptname, sizeof(wptname));

	fread(mpsclass, 4, 1, mps_file);			/* class */
	(*mpsclass) = le_read32(mpsclass);
	mps_readstr(mps_file, tbuf, sizeof(tbuf));	/* country */

	fread(tbuf,17, 1, mps_file);				/* subclass data (17) */

	if ((mps_ver == 4) || (mps_ver == 5)) {
		fread(tbuf, 5, 1, mps_file);			/* additional subclass data (1) & terminator? (4) */
	}

	fread(&lat, 4, 1, mps_file); 
	fread(&lon, 4, 1, mps_file); 
	lat = le_read32(&lat);
	lon = le_read32(&lon);
	
	fread(tbuf, 1, 1, mps_file);				/* altitude validity */
	if (tbuf[0] == 1) {
		le_fread64(&mps_altitude,sizeof(mps_altitude),1,mps_file);
	}
	else {
		mps_altitude = unknown_alt;
		le_fread64(tbuf,sizeof(mps_altitude),1, mps_file);
	}

	mps_readstr(mps_file, wptdesc, sizeof(wptdesc));

	fread(tbuf, 1, 1, mps_file);				/* proximity validity */
	if (tbuf[0] == 1) {
		le_fread64(&mps_proximity,sizeof(mps_proximity),1,mps_file);
	}
	else {
		mps_proximity = unknown_alt;
		le_fread64(tbuf,sizeof(mps_proximity),1, mps_file);
	}

	fread(tbuf, 4, 1, mps_file);					/* display flag */
	fread(tbuf, 4, 1, mps_file);					/* colour */
	fread(&icon, 4, 1, mps_file);					/* display symbol */
	icon = le_read32(&icon);

	mps_readstr(mps_file, tbuf, sizeof(tbuf));		/* city */
	mps_readstr(mps_file, tbuf, sizeof(tbuf));		/* state */
	mps_readstr(mps_file, tbuf, sizeof(tbuf));		/*facility */

	fread(tbuf, 1, 1, mps_file);					/* unknown */

	fread(tbuf, 1, 1, mps_file);					/* depth validity */
	if (tbuf[0] == 1) {
		le_fread64(&mps_depth,sizeof(mps_depth),1,mps_file);
	}
	else {
		mps_depth = unknown_alt;
		le_fread64(tbuf,sizeof(mps_depth),1, mps_file);
	}

	if ((mps_ver == 4) || (mps_ver == 5)) {
		fread(tbuf, 6, 1, mps_file);				/* unknown */
		mps_readstr(mps_file, wptnotes, sizeof(wptnotes));
	}
	else {
		fread(tbuf, 2, 1, mps_file);				/* unknown */
	}

	thisWaypoint->shortname = xstrdup(wptname);
	thisWaypoint->description = xstrdup(wptdesc);
	thisWaypoint->notes = xstrdup(wptnotes);
	thisWaypoint->latitude = lat / 2147483648.0 * 180.0;
	thisWaypoint->longitude = lon / 2147483648.0 * 180.0;
	thisWaypoint->altitude = mps_altitude;
	thisWaypoint->proximity = mps_proximity;
	thisWaypoint->depth = mps_depth;

	/* might need to change this to handle version dependent icon handling */
	thisWaypoint->icon_descr = mps_find_desc_from_icon_number(icon, MAPSOURCE);

	/* The following Now done elsewhere since it can be useful to read in and 
	  perhaps not add to the list */
	/* waypt_add(thisWaypoint); */
	
	return;
}

/*
 * write out to file a waypoint record
 * MRCB
 */
static void
mps_waypoint_w(FILE *mps_file, int mps_ver, const waypoint *wpt, const int isRouteWpt)
{
	unsigned char hdr[100];
	int reclen;
	int lat = wpt->latitude  / 180.0 * 2147483648.0;
	int lon = wpt->longitude  / 180.0 * 2147483648.0;
	int	icon;
	char *src;
	char *ident;
	char *ascii_description;
	char zbuf[25];
	char ffbuf[25];
	int display = 1;
	int colour = 0;			/*  (unknown colour) black is 1, white is 16 */

	double	mps_altitude = wpt->altitude;
	double	mps_proximity = (mpsuseprox ? wpt->proximity : unknown_alt);
	double	mps_depth = (mpsusedepth ? wpt->depth : unknown_alt);
	
	if(wpt->description) src = wpt->description;
	if(wpt->notes) src = wpt->notes;
	ident = global_opts.synthesize_shortnames ?
				mkshort(mkshort_handle, src) :
				wpt->shortname;

	memset(zbuf, 0, sizeof(zbuf));
	memset(ffbuf, 0xff, sizeof(ffbuf));

	/* might need to change this to handle version dependent icon handling */
	icon = mps_find_icon_number_from_desc(wpt->icon_descr, MAPSOURCE);

	if (get_cache_icon(wpt) /* && wpt->icon_descr && (strcmp(wpt->icon_descr, "Geocache Found") != 0)*/) {
		icon = mps_find_icon_number_from_desc(get_cache_icon(wpt), MAPSOURCE);
	}

	icon = mps_converted_icon_number(icon, mps_ver, MAPSOURCE);

	/* two NULL (0x0) bytes at end of each string */
	ascii_description = wpt->description ? str_utf8_to_ascii(wpt->description) : xstrdup("");
	reclen = strlen(ident) + strlen(ascii_description) + 2;	
	if ((mps_ver == 4) || (mps_ver == 5)) {
		/* v4.06 & V5.0*/
		reclen += 85;				/* "W" (1) + strlen(name) + NULL (1) + class(4) + country(sz) +  
										subclass(18) + unknown(4) + lat(4) + lon(4) + alt(9) + strlen(desc)
										+ NULL (1) + prox(9) + display(4) + colour(4) + symbol(4) + city(sz) + 
										state(sz) + facility(sz) + unknown2(1) + depth(9) + unknown3(7) */
									/* -1 as reclen is interpreted from zero meaning a reclength of one */
		if (wpt->notes) reclen += strlen(wpt->notes);
	}
	else {
		/* v3.02 */
		reclen += 75;				/* "W" (1) + strlen(name) + NULL (1) + + class(4) + country(sz) +  
										subclass(17) + lat(4) +  lon(4) + alt(9) + strlen(desc) + 
										NULL (1) + prox(9) + display(4) + 
										colour(4) + symbol(4) + city(sz) + state(sz) + facility(sz) + 
										unknown2(1) + depth(9) + unknown3(2) */
									/* -1 as reclen is interpreted from zero meaning a reclength of one */
	}

	le_write32(&reclen, reclen);
	fwrite(&reclen, 4, 1, mps_file);
	fwrite("W", 1, 1, mps_file);
	fputs(ident, mps_file);
	fwrite(zbuf, 1, 1, mps_file);		/* NULL termination to ident */

	if (isRouteWpt)	zbuf[0] = (char)MPSHIDDENROUTEWPTCLASS;
	else			zbuf[0] = (char)MPSDEFAULTWPTCLASS;
	fwrite(zbuf, 4, 1, mps_file);		/* class */

	zbuf[0]=0;
	fwrite(zbuf, 1, 1, mps_file);		/* country empty string */

	if ((mps_ver == 4) || (mps_ver == 5)) {
		fwrite(zbuf, 4, 1, mps_file);	/* subclass part 1 */
		fwrite(ffbuf, 12, 1, mps_file);	/* subclass part 2 */
		fwrite(zbuf, 2, 1, mps_file);	/* subclass part 3 */
		fwrite(ffbuf, 4, 1, mps_file);	/* unknown */
	}
	else {
		fwrite(zbuf, 8, 1, mps_file);
		fwrite(ffbuf, 8, 1, mps_file);
		fwrite(zbuf, 1, 1, mps_file);
	}

	le_write32(&lat, lat);
	le_write32(&lon, lon);
	fwrite(&lat, 4, 1, mps_file);
	fwrite(&lon, 4, 1, mps_file);

	if (mps_altitude == unknown_alt) {
		fwrite(zbuf, 9, 1, mps_file);
	}
	else {
		hdr[0] = 1;
		fwrite(hdr, 1 , 1, mps_file);
		le_fwrite64(&mps_altitude, 8 , 1, mps_file);
	}
	if (wpt->description) fputs(ascii_description, mps_file);
	fwrite(zbuf, 1, 1, mps_file);	/* NULL termination */
	xfree(ascii_description);
	ascii_description = NULL;

	if (mps_proximity == unknown_alt) {
		fwrite(zbuf, 9, 1, mps_file);
	}
	else {
		hdr[0] = 1;
		fwrite(hdr, 1 , 1, mps_file);
		le_fwrite64(&mps_proximity, 8 , 1, mps_file);
	}

	le_write32(&display, display);
	fwrite(&display, 4, 1, mps_file);	/* Show waypoint w/ name */

	le_write32(&colour, colour);
	fwrite(&colour, 4, 1, mps_file);

	le_write32(&icon, icon);
	fwrite(&icon, 4, 1, mps_file);

	fwrite(zbuf, 3, 1, mps_file);		/* city, state, facility */

	fwrite(zbuf, 1, 1, mps_file);		/* unknown */

	if (mps_depth == unknown_alt) {
		fwrite(zbuf, 9, 1, mps_file);
	}
	else {
		hdr[0] = 1;
		fwrite(hdr, 1 , 1, mps_file);
		le_fwrite64(&mps_depth, 8 , 1, mps_file);
	}

	fwrite(zbuf, 2, 1, mps_file);		/* unknown */
	if ((mps_ver == 4) || (mps_ver == 5)) {
		fwrite(zbuf, 4, 1, mps_file);	/* unknown */
		if (wpt->notes) fputs(wpt->notes, mps_file);
		fwrite(zbuf, 1, 1, mps_file);	/* string termination */
	}
}

/*
 * wrapper to include the mps_ver_out information
 * A waypoint is only written if it hasn't been written before
 * based on it shortname alone
 *
 */
static void
mps_waypoint_w_unique_wrapper(const waypoint *wpt)
{
	waypoint *wptfound = NULL;

	/* Search for this waypoint in the ones already written */
	wptfound = mps_find_wpt_q_by_name(&written_wpt_head, wpt->shortname);
	/* is the next line necessary? Assumes we know who's called us and in what order */
	if (wptfound == NULL) 
		wptfound = mps_find_wpt_q_by_name(&written_route_wpt_head, wpt->shortname);

	/* if this waypoint hasn't been written then it is okay to do so */
	if (wptfound == NULL) {
		mps_waypoint_w(mps_file_out, mps_ver_out, wpt, (1==0));

		/* ensure we record in our "private" queue what has been 
		written so that we don't write it again */
		mps_wpt_q_add(&written_wpt_head, wpt);
	}
}

/*
 * wrapper to include the mps_ver_out information
 * A waypoint is only written if it hasn't been written before
 * based on it shortname alone
 * Provided as a separate function from above in case we find
 * have to do other things
 *
 */
static void
mps_route_wpt_w_unique_wrapper(const waypoint *wpt)
{
	waypoint *wptfound = NULL;

	/* Search for this waypoint in the ones already written */
	wptfound = mps_find_wpt_q_by_name(&written_wpt_head, wpt->shortname);
	if (wptfound == NULL) 
		/* so, not a real wpt, so must check route wpts already written as reals */
		wptfound = mps_find_wpt_q_by_name(&written_route_wpt_head, wpt->shortname);

	/* if this waypoint hasn't been written then it is okay to do so
	   but assume it is only required for the route
    */
	if (wptfound == NULL) {
		/* Although we haven't written one out, this might still be a "real" waypoint
		   If so, we need to write it out now accordingly */
		wptfound = find_waypt_by_name (wpt->shortname);

		if (wptfound == NULL) {
			/* well, we tried to find: it wasn't written and isn't a real waypoint */
			mps_waypoint_w(mps_file_out, mps_ver_out, wpt, (1==1));
			mps_wpt_q_add(&written_route_wpt_head, wpt);
		}
		else {
			mps_waypoint_w(mps_file_out, mps_ver_out, wpt, (1==0));
			/* Simulated real user waypoint */
			mps_wpt_q_add(&written_wpt_head, wpt);
		}
	}
}

/*
 * wrapper to include the mps_ver_out information
 * This one always writes a waypoint. If it has been written before
 * then generate a unique name before writing
 *
 */
static void
mps_waypoint_w_uniqloc_wrapper(waypoint *wpt)
{
	waypoint *wptfound = NULL;
	char			*newName;
	unsigned int	uniqueNum = 0;

	/* Search for this waypoint in the ones already written */
	wptfound = mps_find_wpt_q_by_name(&written_wpt_head, wpt->shortname);
	/* is the next line necessary? Assumes we know who's called us and in what order */
	if (wptfound == NULL) 
		wptfound = mps_find_wpt_q_by_name(&written_route_wpt_head, wpt->shortname);

	if (wptfound != NULL) {
		/* check if this is the same waypoint by looking at the lat lon
			not ideal, but better then having two same named waypoints
			that kills MapSource.  If it is the same then don't bother
			adding it in. If it isn't, then rename it
		*/
		if (((wpt->latitude - wptfound->latitude) != 0) || 
			((wpt->longitude - wptfound->longitude) != 0)) {
			/* Not the same lat lon, so rename and add */
			newName = mkshort(written_wpt_mkshort_handle, wpt->shortname);
			wptfound = waypt_dupe(wpt);
			xfree(wptfound->shortname);
			wptfound->shortname = newName;
			mps_waypoint_w(mps_file_out, mps_ver_out, wptfound, (1==0));
			mps_wpt_q_add(&written_wpt_head, wpt);
		}
	}
	else {
		mps_waypoint_w(mps_file_out, mps_ver_out, wpt, (1==0));
		/* ensure we record in out "private" queue what has been 
		written so that we don't write it again */
		mps_wpt_q_add(&written_wpt_head, wpt);
	}
}

/*
 * read in from file a route record
 * MRCB
 */
static void
mps_route_r(FILE *mps_file, int mps_ver, route_head **rte)
{
	char tbuf[100];
	char rtename[MPSNAMEBUFFERLEN];
	char wptname[MPSNAMEBUFFERLEN];
	int lat;
	int lon;
	short int	rte_autoname = 0;
	int	interlinkStepCount;
	int	thisInterlinkStep;
	unsigned int	mpsclass;
	int	FFsRead;

	time_t	dateTime = 0;
	route_head *rte_head;
	int rte_count;

	waypoint	*thisWaypoint;
	waypoint	*tempWpt;

	double	mps_altitude = unknown_alt;
	double	mps_depth = unknown_alt;

	mps_readstr(mps_file, rtename, sizeof(rtename));
#ifdef	MPS_DEBUG
	fprintf(stderr, "mps_route_r: reading route %s\n", rtename);
#endif

	fread(&rte_autoname, 2, 1, mps_file);	/* autoname flag */
	rte_autoname = le_read16(&rte_autoname);

	fread(&lat, 4, 1, mps_file); 
	fread(&lon, 4, 1, mps_file); 
	lat = le_read32(&lat);			/* max lat of whole route */
	lon = le_read32(&lon);			/* max lon of whole route */

	fread(tbuf, 1, 1, mps_file);			/* altitude validity */
	if (tbuf[0] == 1) {
		le_fread64(&mps_altitude,sizeof(mps_altitude),1,mps_file);	/* max alt of the whole route */
	}
	else {
		mps_altitude = unknown_alt;
		le_fread64(tbuf,sizeof(mps_altitude),1, mps_file);
	}

	fread(&lat, 4, 1, mps_file); 
	fread(&lon, 4, 1, mps_file); 
	lat = le_read32(&lat);			/* min lat of whole route */
	lon = le_read32(&lon);			/* min lon of whole route */

	fread(tbuf, 1, 1, mps_file);			/* altitude validity */
	if (tbuf[0] == 1) {
		le_fread64(&mps_altitude,sizeof(mps_altitude),1,mps_file);	/* min alt of the whole route */
	}
	else {
		mps_altitude = unknown_alt;
		le_fread64(tbuf,sizeof(mps_altitude),1, mps_file);
	}

	fread(&rte_count, 4, 1, mps_file);			/* number of waypoints in route */
	rte_count = le_read32(&rte_count);

	/* This might be rather presumptuous, but is it valid in any format to have route with no points? */
	/* Let's assume not, so if the route count is zero or less, let's get out of here and allow the   */
	/* caller to do any file resync                                                                   */
	if (rte_count < 0) return;

#ifdef	MPS_DEBUG
	fprintf(stderr, "mps_route_r: route contains %d waypoints\n", rte_count);
#endif

	rte_head = route_head_alloc();
	rte_head->rte_name = xstrdup(rtename);
	route_add_head(rte_head);
	*rte = rte_head;

	rte_count--;			/* need to loop round for one less than the number of waypoints */

	while (rte_count--) {

		mps_readstr(mps_file, wptname, sizeof(wptname));
#ifdef	MPS_DEBUG
		fprintf(stderr, "mps_route_r: reading route waypoint %s\n", wptname);
#endif

		fread(&mpsclass, 4, 1, mps_file);			/* class */
		mpsclass = le_read32(&mpsclass);
		mps_readstr(mps_file, tbuf, sizeof(tbuf));	/* country */

		if ((mps_ver == 4) || (mps_ver == 5)) {
			fread(tbuf, 22, 1, mps_file);				/* subclass data */

			/* This is a bit unpleasant. Routes have a variable length of
			   data (min 22 bytes) terminated by a zero */
			do {
				fread(tbuf, 1, 1, mps_file);
			} while (tbuf[0]);

			/* The next thing is the unknown 0x03 0x00 .. 0x00 (18 bytes) */
			fread(tbuf, 18, 1, mps_file);
		}
		else {
			fread(tbuf, 17, 1, mps_file);				/* subclass data */
			fread(tbuf, 18, 1, mps_file);				/* unknown 0x00 0x03 0x00 .. 0x00 */
		}

		/* link details */
		fread(&interlinkStepCount, 4, 1, mps_file);					/* NOT always 2, but will assume > 0 */
		interlinkStepCount = le_read32(&interlinkStepCount);

#ifdef	MPS_DEBUG
		fprintf(stderr, "mps_route_r: interlink steps are %d\n", interlinkStepCount);
#endif

		/* Basically we're knackered if the step count is less than one since we hard code reading of the */
		/* first, so if there isn't one, we'd lose sync on the file and read junk                         */
		/* Given we've already done some route head allocation, do we return or do we die? It'd be good   */
		/* do some clean up before returning.                                                             */
		if (interlinkStepCount < 1) {
			/* For RJL - are the following lines correct ? */
			/* route_free(rte_head);
			route_del_head(rte_head); */
			return;
		}

		/* first end of link */
		fread(&lat, 4, 1, mps_file); 
		fread(&lon, 4, 1, mps_file); 
		lat = le_read32(&lat);
		lon = le_read32(&lon);
	
		fread(tbuf, 1, 1, mps_file);			/* altitude validity */
		if (tbuf[0] == 1) {
			le_fread64(&mps_altitude,sizeof(mps_altitude),1,mps_file);
		}
		else {
			mps_altitude = unknown_alt;
			le_fread64(tbuf,sizeof(mps_altitude),1, mps_file);
		}

		/* with MapSource routes, the real waypoint details are held as a separate waypoint, so copy from there
		   if found. With MapSource, one should consider the real waypoint list as definitive */
		tempWpt = find_waypt_by_name(wptname);

		if (tempWpt != NULL) {
			thisWaypoint = waypt_dupe(tempWpt);
		}
		else {
			tempWpt = mps_find_wpt_q_by_name(&read_route_wpt_head, wptname);

			if (tempWpt != NULL) {
				thisWaypoint = waypt_dupe(tempWpt);
			}
			else {
				/* should never reach here, but we do need a fallback position */
#ifdef	MPS_DEBUG
				fprintf(stderr, "mps_route_r: reached the point we never should\n");
#endif
				thisWaypoint = waypt_new();
				thisWaypoint->shortname = xstrdup(wptname);
				thisWaypoint->latitude = lat / 2147483648.0 * 180.0;
				thisWaypoint->longitude = lon / 2147483648.0 * 180.0;
				thisWaypoint->altitude = mps_altitude;
				thisWaypoint->depth = mps_depth;
			}
		}

		route_add_wpt(rte_head, thisWaypoint);

		/* take two off the count since we separately read the start and end parts of the link */
		/* MRCB 2004/09/15 - NOPE, sorry, this needs to one, since interlink steps can be > 0 */
		for (thisInterlinkStep = interlinkStepCount - 1; thisInterlinkStep > 0; thisInterlinkStep--) {
			/* Could do this by doing a calculation on length of each co-ordinate and just doing one read
			   but doing it this way makes it easier in the future to make use of this data */
			fread(&lat, 4, 1, mps_file); 
			fread(&lon, 4, 1, mps_file); 
			lat = le_read32(&lat);
			lon = le_read32(&lon);
		
			fread(tbuf, 1, 1, mps_file);			/* altitude validity */
			if (tbuf[0] == 1) {
				le_fread64(&mps_altitude,sizeof(mps_altitude),1,mps_file);
			}
			else {
				mps_altitude = unknown_alt;
				le_fread64(tbuf,sizeof(mps_altitude),1, mps_file);
			}
		}

		fread(tbuf, 1, 1, mps_file);			/* NULL */

		fread(tbuf, 4, 1, mps_file);			/* link max lat */
		fread(tbuf, 4, 1, mps_file);			/* link max lon */
		fread(tbuf, 9, 1, mps_file);			/* link max alt validity + alt */

		fread(tbuf, 4, 1, mps_file);			/* link min lat */
		fread(tbuf, 4, 1, mps_file);			/* link min lon */
		fread(tbuf, 9, 1, mps_file);			/* link min alt validity + alt */

	}		/* while (trk_count--) */

	/* when the loop is done, there's still one waypoint to read with a small trailer */
	/* all we want is the waypoint name; lat, lon and alt are already set from above  */
	mps_readstr(mps_file, wptname, sizeof(wptname));
#ifdef	MPS_DEBUG
	fprintf(stderr, "mps_route_r: reading final route waypoint %s\n", wptname);
#endif


	fread(&mpsclass, 4, 1, mps_file);			/* class */
	mpsclass = le_read32(&mpsclass);
	mps_readstr(mps_file, tbuf, sizeof(tbuf));	/* country */

	if ((mps_ver == 4) || (mps_ver == 5)) {
		fread(tbuf, 22, 1, mps_file);				/* subclass data */

		/* This is a bit unpleasant. Routes have a variable length of
			data (min 22 bytes) terminated by a zero */
		do {
			fread(tbuf, 1, 1, mps_file);
		} while (tbuf[0]);

		/* The next thing is the unknown 0x03 0x00 .. 0x00 (18 bytes) */
		fread(tbuf, 18, 1, mps_file);
	}
	else {
		fread(tbuf, 17, 1, mps_file);				/* subclass data */
		fread(tbuf, 18, 1, mps_file);				/* unknown 0x00 0x03 0x00 .. 0x00 */
	}

	fread(tbuf, 5, 1, mps_file);					/* 5 byte trailer */
	/* with MapSource routes, the real waypoint details are held as a separate waypoint, so copy from there
		if found because there is more info held in a real waypoint than in its route counterpart,
		e.g. the display symbol (aka icon)
	*/
	tempWpt = find_waypt_by_name(wptname);

	if (tempWpt != NULL) {
		thisWaypoint = waypt_dupe(tempWpt);
	}
	else {
		tempWpt = mps_find_wpt_q_by_name(&read_route_wpt_head, wptname);

		if (tempWpt != NULL) {
			thisWaypoint = waypt_dupe(tempWpt);
		}
		else {
			/* should never reach here, but we do need a fallback position */
			thisWaypoint = waypt_new();
			thisWaypoint->shortname = xstrdup(wptname);
			thisWaypoint->latitude = lat / 2147483648.0 * 180.0;
			thisWaypoint->longitude = lon / 2147483648.0 * 180.0;
			thisWaypoint->altitude = mps_altitude;
		}
	}

	route_add_wpt(rte_head, thisWaypoint);

	return;
}

/*
 * write out to file a route header
 * MRCB
 */
static void
mps_routehdr_w(FILE *mps_file, int mps_ver, const route_head *rte)
{
	unsigned int reclen;
	unsigned int rte_datapoints;
	unsigned int colour = 0;		/* unknown colour */
	int			rname_len;
	char		*rname;
	char		hdr[20];
	char		zbuf[20];
	char		*src;
	char		*ident;

	waypoint	*testwpt;
	time_t		uniqueValue;
	int			allWptNameLengths;

	double		maxlat=-90.0;
	double		maxlon=-180.0;
	double		minlat=90.0;
	double		minlon=180.0;
	double		maxalt=unknown_alt;
	double		minalt=unknown_alt;

	int lat;
	int lon;

	queue *elem, *tmp;

	prevRouteWpt = NULL;		/* clear the stateful flag used to know when the start of route wpts happens */

	memset(zbuf, 0, sizeof(zbuf));

	/* total nodes (waypoints) this route */
	rte_datapoints = 0;
	allWptNameLengths = 0;

	if (rte->waypoint_list.next) {		/* this test doesn't do what I want i.e test if this is a valid route - treat as a placeholder for now */
		QUEUE_FOR_EACH(&rte->waypoint_list, elem, tmp) {
			testwpt = (waypoint *)elem;
			if (rte_datapoints == 0) {
				uniqueValue = testwpt->creation_time;
			}
			if (testwpt->latitude > maxlat) maxlat = testwpt->latitude;
			if (testwpt->latitude < minlat) minlat = testwpt->latitude;
			if (testwpt->longitude > maxlon) maxlon = testwpt->longitude;
			if (testwpt->longitude < minlon) minlon = testwpt->longitude;
			if (testwpt->altitude != unknown_alt) {
				if ((testwpt->altitude > maxalt) || 
					(maxalt == unknown_alt)) maxalt = testwpt->altitude;
				if ((testwpt->altitude < minalt) ||
					(minalt == unknown_alt)) minalt = testwpt->altitude;
			}

			if(testwpt->description) src = testwpt->description;
			if(testwpt->notes) src = testwpt->notes;
			ident = global_opts.synthesize_shortnames ?
						mkshort(mkshort_handle, src) :
						testwpt->shortname;
			allWptNameLengths += strlen(ident) + 1;

			rte_datapoints++;
		}		

		if (uniqueValue == 0) {
			uniqueValue = current_time();
		}

		/* route name */
		if (!rte->rte_name) {
			sprintf(hdr, "Route%04x", uniqueValue);
			rname = xstrdup(hdr);
		}
		else
			rname = xstrdup(rte->rte_name);

		rname_len = strlen(rname);
		reclen = rname_len + 42;		/* "T" (1) + strlen(tname) + NULL (1) + autoname flag (2) + 
										route lat lon max (2x4) + route max alt (9) +
										route lat lon min (2x4) + route min alt (9) +
										num route datapoints value (4) */
		
		/* V3 - each waypoint: waypoint name + NULL (1) + class (4) + country + NULL (1) + 
								subclass (17) + unknown (18) */
		/* V4,5 - each waypoint: waypoint name + NULL (1) + class (4) + country + NULL (1) + 
								subclass (18) + unknown (4) + unknown (19) */
		/* V* - each route link: 0x00000002 (4) + end 1 lat (4) + end 1 lon (4) + end 1 alt (9) +
								end 2 lat (4) + end 2 lon (4) + end 2 alt (9) + NULL (1) +
								link max lat (4) + link max lon (4) + link max alt (9) +
								link min lat (4) + link min lon (4) + link min alt (9) */

		if ((mps_ver == 4) || (mps_ver == 5)) {
			reclen += allWptNameLengths + rte_datapoints * 46 + 
					(rte_datapoints - 1) * 73 + 4;				/* link details plus overall trailing bytes */
		}
		else {
			reclen += allWptNameLengths + rte_datapoints * 40 + 
					(rte_datapoints - 1) * 73 + 4;				/* link details plus overall trailing bytes */
		}

		le_write32(&reclen, reclen);
		fwrite(&reclen, 4, 1, mps_file);

		hdr[0] = 'R';
		fwrite(hdr, 1, 1, mps_file);

		fwrite(rname, rname_len, 1, mps_file);
		xfree(rname);

		hdr[0] = 0;						/* NULL of string termination */
		hdr[1] = 0;						/* don't autoname */
		hdr[2] = 0;						/* MSB of don't autoname */
		fwrite(hdr, 3, 1, mps_file);	/* NULL string terminator + route autoname flag */

		lat = maxlat / 180.0 * 2147483648.0;
		lon = maxlon / 180.0 * 2147483648.0;

		le_write32(&lat, lat);
		le_write32(&lon, lon);

		fwrite(&lat, 4, 1, mps_file);
		fwrite(&lon, 4, 1, mps_file);

		if (maxalt == unknown_alt) {
			fwrite(zbuf, 9, 1, mps_file);
		}
		else {
			hdr[0] = 1;
			fwrite(hdr, 1 , 1, mps_file);
			le_fwrite64(&maxalt, 8 , 1, mps_file);
		}

		lat = minlat / 180.0 * 2147483648.0;
		lon = minlon / 180.0 * 2147483648.0;

		le_write32(&lat, lat);
		le_write32(&lon, lon);

		fwrite(&lat, 4, 1, mps_file);
		fwrite(&lon, 4, 1, mps_file);

		if (minalt == unknown_alt) {
			fwrite(zbuf, 9, 1, mps_file);
		}
		else {
			unsigned char cbuf[8];
			hdr[0] = 1;

			fwrite(hdr, 1 , 1, mps_file);
			le_fwrite64(&minalt, 8 , 1, mps_file);
		}

		le_write32(&rte_datapoints, rte_datapoints);
		fwrite(&rte_datapoints, 4, 1, mps_file);
	}
}

static void
mps_routehdr_w_wrapper(const route_head *rte)
{
	mps_routehdr_w(mps_file_out, mps_ver_out, rte);
}


/*
 * write out to file a route datapoint
 * MRCB
 */
static void
mps_routedatapoint_w(FILE *mps_file, int mps_ver, const waypoint *rtewpt)
{
	unsigned char hdr[10];
	int			lat;
	int			lon;
	time_t		t = rtewpt->creation_time;
	char		zbuf[20];
	char		ffbuf[20];
	char		*src;
	char		*ident;
	int			reclen;

	int			maxlat;
	int			maxlon;
	int			minlat;
	int			minlon;
	double		maxalt=unknown_alt;
	double		minalt=unknown_alt;

	double		mps_altitude;
	waypoint	*wptfound;

	memset(zbuf, 0, sizeof(zbuf));
	memset(ffbuf, 0xff, sizeof(ffbuf));

	if (prevRouteWpt != NULL) {
		/* output the route link details */
		reclen = 2;
		le_write32(&reclen, reclen);
		fwrite(&reclen, 4, 1, mps_file);

		/* output end point 1 */
		lat = prevRouteWpt->latitude  / 180.0 * 2147483648.0;
		lon = prevRouteWpt->longitude  / 180.0 * 2147483648.0;
		le_write32(&lat, lat);
		le_write32(&lon, lon);

		fwrite(&lat, 4, 1, mps_file);
		fwrite(&lon, 4, 1, mps_file);

		mps_altitude = prevRouteWpt->altitude;
		if (mps_altitude == unknown_alt) {
			fwrite(zbuf, 9, 1, mps_file);
		}
		else {
			hdr[0] = 1;
			fwrite(hdr, 1 , 1, mps_file);
			le_fwrite64(&mps_altitude, 8 , 1, mps_file);
		}

		/* output end point 2 */
		lat = rtewpt->latitude  / 180.0 * 2147483648.0;
		lon = rtewpt->longitude  / 180.0 * 2147483648.0;
		le_write32(&lat, lat);
		le_write32(&lon, lon);

		fwrite(&lat, 4, 1, mps_file);
		fwrite(&lon, 4, 1, mps_file);

		mps_altitude = rtewpt->altitude;
		if (mps_altitude == unknown_alt) {
			fwrite(zbuf, 9, 1, mps_file);
		}
		else {
			hdr[0] = 1;
			fwrite(hdr, 1 , 1, mps_file);
			le_fwrite64(&mps_altitude, 8 , 1, mps_file);
		}

		if (rtewpt->latitude > prevRouteWpt->latitude) {
			maxlat = rtewpt->latitude  / 180.0 * 2147483648.0;
			minlat = prevRouteWpt->latitude  / 180.0 * 2147483648.0;
		}
		else {
			minlat = rtewpt->latitude  / 180.0 * 2147483648.0;
			maxlat = prevRouteWpt->latitude  / 180.0 * 2147483648.0;
		}

		if (rtewpt->longitude > prevRouteWpt->longitude) {
			maxlon = rtewpt->longitude  / 180.0 * 2147483648.0;
			minlon = prevRouteWpt->longitude  / 180.0 * 2147483648.0;
		}
		else {
			minlon = rtewpt->longitude  / 180.0 * 2147483648.0;
			maxlon = prevRouteWpt->longitude  / 180.0 * 2147483648.0;
		}

		if (rtewpt->altitude != unknown_alt) maxalt = rtewpt->altitude;
		if (rtewpt->altitude != unknown_alt) minalt = rtewpt->altitude;
		if (prevRouteWpt->altitude != unknown_alt) {
			if ((prevRouteWpt->altitude > maxalt) || 
				(maxalt == unknown_alt)) maxalt = prevRouteWpt->altitude;
			if ((prevRouteWpt->altitude < minalt) ||
				(minalt == unknown_alt)) minalt = prevRouteWpt->altitude;
		}
		
		fwrite (zbuf, 1, 1, mps_file);

		/* output max coords of the link */
		le_write32(&maxlat, maxlat);
		le_write32(&maxlon, maxlon);

		fwrite(&maxlat, 4, 1, mps_file);
		fwrite(&maxlon, 4, 1, mps_file);

		if (maxalt == unknown_alt) {
			fwrite(zbuf, 9, 1, mps_file);
		}
		else {
			hdr[0] = 1;
			fwrite(hdr, 1 , 1, mps_file);
			le_fwrite64(&maxalt, 8 , 1, mps_file);
		}

		/* output min coords of the link */
		le_write32(&minlat, minlat);
		le_write32(&minlon, minlon);

		fwrite(&minlat, 4, 1, mps_file);
		fwrite(&minlon, 4, 1, mps_file);

		if (minalt == unknown_alt) {
			fwrite(zbuf, 9, 1, mps_file);
		}
		else {
			hdr[0] = 1;
			fwrite(hdr, 1 , 1, mps_file);
			le_fwrite64(&minalt, 8 , 1, mps_file);
		}

	}

	if(rtewpt->description) src = rtewpt->description;
	if(rtewpt->notes) src = rtewpt->notes;
	ident = global_opts.synthesize_shortnames ?
				mkshort(mkshort_handle, src) :
				rtewpt->shortname;

	fputs(ident, mps_file);
	fwrite(zbuf, 1, 1, mps_file);	/* NULL termination to ident */

	wptfound = mps_find_wpt_q_by_name(&written_route_wpt_head, ident);
	if (wptfound != NULL)	zbuf[0] = (char)MPSHIDDENROUTEWPTCLASS;
	else					zbuf[0] = (char)MPSDEFAULTWPTCLASS;
	fwrite(zbuf, 4, 1, mps_file);			/* class */

	zbuf[0]=0;
	fwrite(zbuf, 1, 1, mps_file);			/* country - i.e. empty string */

	if ((mps_ver == 4) || (mps_ver == 5)) {
		fwrite(zbuf, 4, 1, mps_file);		/* subclass part 1 */
		fwrite(ffbuf, 12, 1, mps_file);		/* subclass part 2 */
		fwrite(zbuf, 2, 1, mps_file);		/* subclass part 3 */
		fwrite(ffbuf, 4, 1, mps_file);		/* unknown */

		fwrite(zbuf, 1, 1, mps_file);
		hdr[0] = 3;
		fwrite(hdr, 1, 1, mps_file);
		fwrite(zbuf, 17, 1, mps_file);
	}
	else {
		fwrite(zbuf, 8, 1, mps_file);		/* subclass part 1 */
		fwrite(ffbuf, 8, 1, mps_file);		/* subclass part 2 */
		fwrite(zbuf, 1, 1, mps_file);		/* subclass part 3 */

		/* unknown */
		fwrite(zbuf, 1, 1, mps_file);
		hdr[0] = 3;
		fwrite(hdr, 1, 1, mps_file);
		fwrite(zbuf, 16, 1, mps_file);
	}

	prevRouteWpt = rtewpt;
}

static void
mps_routedatapoint_w_wrapper(const waypoint *rte)
{
	mps_routedatapoint_w(mps_file_out, mps_ver_out, rte);
}


/*
 * write out to file a route trailer
 * MRCB
 */
static void
mps_routetrlr_w(FILE *mps_file, int mps_ver, const route_head *rte)
{
	char		hdr[2];
	int			value = 0;

	hdr[0] = 1;

	if (rte->waypoint_list.next) {		/* this test doesn't do what I want i.e test if this is a valid route - treat as a placeholder for now */
		fwrite(&value, 4, 1, mps_file);
		fwrite(hdr, 1, 1, mps_file);
	}
}
	
static void
mps_routetrlr_w_wrapper(const route_head *rte)
{
	mps_routetrlr_w(mps_file_out, mps_ver_out, rte);
}


/*
 * read in from file a track record
 * MRCB
 */
static void
mps_track_r(FILE *mps_file, int mps_ver, route_head **trk)
{
	char tbuf[100];
	char trkname[MPSNAMEBUFFERLEN];
	int lat;
	int lon;

	int	dateTime = 0;
	route_head *track_head;
	int trk_count;

	waypoint	*thisWaypoint;
	double	mps_altitude = unknown_alt;
	double	mps_depth = unknown_alt;

	mps_readstr(mps_file, trkname, sizeof(trkname));
#ifdef	MPS_DEBUG
	fprintf(stderr, "mps_track_r: reading track %s\n", trkname);
#endif


	fread(tbuf, 1, 1, mps_file);				/* display flag */
	fread(tbuf, 4, 1, mps_file);				/* colour */

	fread(&trk_count, 4, 1, mps_file);			/* number of datapoints in tracklog */
	trk_count = le_read32(&trk_count);

	/* I don't know, but perhaps it's valid to have a track with no waypoints   */
	/* Seems dumb, but truth is stranger than fiction. Of course, it could be   */
	/* that there are more than MAXINT / 2 waypoints, yeah sure                 */
	/* Allow the caller the perform the file resync caused by bombing out early */
	if (trk_count < 0) return;
#ifdef	MPS_DEBUG
	fprintf(stderr, "mps_track_r: there are %d track waypoints %d\n", trk_count);
#endif

	track_head = route_head_alloc();
	track_head->rte_name = xstrdup(trkname);
	track_add_head(track_head);
	*trk = track_head;

	while (trk_count--) {

		fread(&lat, 4, 1, mps_file); 
		fread(&lon, 4, 1, mps_file); 
		lat = le_read32(&lat);
		lon = le_read32(&lon);
	
		fread(tbuf, 1, 1, mps_file);			/* altitude validity */
		if (tbuf[0] == 1) {
			le_fread64(&mps_altitude,sizeof(mps_altitude),1,mps_file);
		}
		else {
			mps_altitude = unknown_alt;
			le_fread64(tbuf,sizeof(mps_altitude),1, mps_file);
		}

		fread(tbuf, 1, 1, mps_file);			/* date/time validity */
		if (tbuf[0] == 1) {
			fread(&dateTime,sizeof(dateTime),1,mps_file);
		}
		else {
			fread(tbuf,sizeof(dateTime),1, mps_file);
		}

		fread(tbuf, 1, 1, mps_file);			/* depth validity */
		if (tbuf[0] == 1) {
			le_fread64(&mps_depth,sizeof(mps_depth),1,mps_file);
		}
		else {
			mps_depth = unknown_alt;
			le_fread64(tbuf,sizeof(mps_depth),1, mps_file);
		}

		thisWaypoint = waypt_new();
		thisWaypoint->latitude = lat / 2147483648.0 * 180.0;
		thisWaypoint->longitude = lon / 2147483648.0 * 180.0;
		thisWaypoint->creation_time = le_read32(&dateTime);
		thisWaypoint->centiseconds = 0;
		thisWaypoint->altitude = mps_altitude;
		thisWaypoint->depth = mps_depth;
		route_add_wpt(track_head, thisWaypoint);

	}		/* while (trk_count--) */

	return;

}

/*
 * write out to file a tracklog header
 * MRCB
 */
static void
mps_trackhdr_w(FILE *mps_file, int mps_ver, const route_head *trk)
{
	unsigned int reclen;
	unsigned int trk_datapoints;
	unsigned int colour = 0;		/* unknown colour */
	int			tname_len;
	char		*tname;
	char		hdr[20];
	waypoint	*testwpt;
	time_t		uniqueValue;

	queue *elem, *tmp;

	/* total nodes (waypoints) this track */
	trk_datapoints = 0;
	if (trk->waypoint_list.next) {	/* this test doesn't do what I want i.e test if this is a valid track - treat as a placeholder for now */
		QUEUE_FOR_EACH(&trk->waypoint_list, elem, tmp) {
			if (trk_datapoints == 0) {
				testwpt = (waypoint *)elem;
				uniqueValue = testwpt->creation_time;
			}
			trk_datapoints++;
		}

		if (uniqueValue == 0) {
			uniqueValue = current_time();
		}

		/* track name */
		if (!trk->rte_name) {
			sprintf(hdr, "Track%04x", uniqueValue);
			tname = xstrdup(hdr);
		}
		else
			tname = xstrdup(trk->rte_name);

		tname_len = strlen(tname);
		reclen = tname_len + 11;		/* "T" (1) + strlen(tname) + NULL (1) + display flag (1) + colour (4) +
										num track datapoints value (4) */
		
		reclen += (trk_datapoints * 31) - 1;	/* lat (4) + lon (4) + alt (9) + date (5) + depth (9) ;*/
												/* -1 is because reclen starts from 0 which means a length of 1 */
		le_write32(&reclen, reclen);
		fwrite(&reclen, 4, 1, mps_file);

		hdr[0] = 'T';
		fwrite(hdr, 1, 1, mps_file);

		fwrite(tname, tname_len, 1, mps_file);
		xfree(tname);

		hdr[0] = 0;
		hdr[1] = 1;
		fwrite(hdr, 2, 1, mps_file);	/* NULL string terminator + display flag */

		le_write32(&colour, colour);
		fwrite(&colour, 4, 1, mps_file);

		le_write32(&trk_datapoints, trk_datapoints);
		fwrite(&trk_datapoints, 4, 1, mps_file);
	}

}

static void
mps_trackhdr_w_wrapper(const route_head *trk)
{
	mps_trackhdr_w(mps_file_out, mps_ver_out, trk);
}


/*
 * write out to file a tracklog datapoint
 * MRCB
 */
static void
mps_trackdatapoint_w(FILE *mps_file, int mps_ver, const waypoint *wpt)
{
	unsigned char hdr[10];
	int lat = wpt->latitude  / 180.0 * 2147483648.0;
	int lon = wpt->longitude  / 180.0 * 2147483648.0;
	time_t	t = wpt->creation_time;
	char zbuf[10];

	double	mps_altitude = wpt->altitude;
	double	mps_depth = (mpsusedepth ? wpt->depth : unknown_alt);

	memset(zbuf, 0, sizeof(zbuf));

	le_write32(&lat, lat);
	le_write32(&lon, lon);
	fwrite(&lat, 4, 1, mps_file);
	fwrite(&lon, 4, 1, mps_file);

	if (mps_altitude == unknown_alt) {
		fwrite(zbuf, 9, 1, mps_file);
	}
	else {
		hdr[0] = 1;
		fwrite(hdr, 1 , 1, mps_file);
		le_fwrite64(&mps_altitude, 8 , 1, mps_file);
	}

	if (t > 0) {					/* a valid time is assumed to > 0 */
		hdr[0] = 1;
		fwrite(hdr, 1 , 1, mps_file);
		le_write32(&t, t);
		fwrite(&t, 4, 1, mps_file);
	}
	else {
		fwrite(zbuf, 5, 1, mps_file);
	}

	if (mps_depth == unknown_alt) {
		fwrite(zbuf, 9, 1, mps_file);
	}
	else {
		hdr[0] = 1;
		fwrite(hdr, 1 , 1, mps_file);
		le_fwrite64(&mps_depth, 8 , 1, mps_file);
	}
}

static void
mps_trackdatapoint_w_wrapper(const waypoint *wpt)
{
	mps_trackdatapoint_w(mps_file_out, mps_ver_out, wpt);
}


static void
mps_read(void)
{
	waypoint		*wpt;
	route_head		*rte;
	route_head		*trk;

	char			recType;
	int				reclen;
	int				morework;
	unsigned int	mpsWptClass;
	long			mpsFileInPos;

	mps_ver_in = 0;		/* although initialised at declaration, what happens if there are two mapsource
						   input files? */
	mps_fileHeader_r(mps_file_in, &mps_ver_in);

#ifdef DUMP_ICON_TABLE
	printf("static icon_mapping_t garmin_icon_table[] = {\n");
#endif

	morework = 1;
	while (morework && !feof(mps_file_in)) {

		/* Read record length of next section */
		fread(&reclen, 4, 1, mps_file_in);
		reclen = le_read32(&reclen);

		if (reclen < 0) fatal (MYNAME ": a record length read from the input file is invalid. \nEither the file is corrupt or unsupported");

		/* Read the record type "flag" in - using fread in case in the future need more than one char */
		fread(&recType, 1, 1, mps_file_in);
		mpsFileInPos = ftell(mps_file_in);
		switch (recType) {
		case 'W':
			/* Waypoint record */
			/* With routes, we need the waypoint info that reveals, for example, the symbol type */
			mps_waypoint_r(mps_file_in, mps_ver_in, &wpt, &mpsWptClass);

#ifdef	MPS_DEBUG
			fprintf(stderr,"Read a waypoint - %s\n", wpt->shortname);
#endif

			if (ftell(mps_file_in) != mpsFileInPos + reclen) {
				/* should junk this record and not save it since we're out of sync with the file */
				/* Should and how do we warn the user?                                           */
#ifdef	MPS_DEBUG
				fprintf(stderr,"Lost sync with the file reading waypoint - %s\n", wpt->shortname);
#endif
				fseek (mps_file_in, mpsFileInPos + reclen, SEEK_SET);
				waypt_free( wpt );
			}
			else {
				/* only add to the "real" list if a "user" waypoint otherwise add to the private list */
				if (mpsWptClass == MPSDEFAULTWPTCLASS) waypt_add(wpt);
				else {
					mps_wpt_q_add(&read_route_wpt_head, wpt);
					waypt_free( wpt );
				}
#ifdef DUMP_ICON_TABLE
				printf("\t{  %4u, \"%s\" },\n", icon, wpt->shortname);
#endif
			}
			break;

		case 'R':
			/* Route record */
			mps_route_r(mps_file_in, mps_ver_in, &rte);
			if (ftell(mps_file_in) != mpsFileInPos + reclen) {
				/* should junk this record and not save it since we're out of sync with the file */
				/* Should and how do we warn the user?                                           */
#ifdef	MPS_DEBUG
				fprintf(stderr,"Lost sync with the file reading route - %s\n", rte->rte_name);
#endif
				fseek (mps_file_in, mpsFileInPos + reclen, SEEK_SET);
			}
			break;

		case 'T':
			/* Track record */
			mps_track_r(mps_file_in, mps_ver_in, &trk);
			if (ftell(mps_file_in) != mpsFileInPos + reclen) {
				/* should junk this record and not save it since we're out of sync with the file */
				/* Should and how do we warn the user?                                           */
#ifdef	MPS_DEBUG
				fprintf(stderr,"Lost sync with the file reading track - %s\n", trk->rte_name);
#endif
				fseek (mps_file_in, mpsFileInPos + reclen, SEEK_SET);
			}
			break;

		case 'L':
			/* Map segment record */
			mps_mapsegment_r(mps_file_in, mps_ver_in);
			if (ftell(mps_file_in) != mpsFileInPos + reclen) {
				/* should junk this record and not save it since we're out of sync with the file */
				/* Should and how do we warn the user?                                           */
				fseek (mps_file_in, mpsFileInPos + reclen, SEEK_SET);
			}
			break;

		case 'V':
			/* Mapset record */
			mps_mapsetname_r(mps_file_in, mps_ver_in);
			/* Last record in the file */
			morework = 0;
			break;
		default:
			/* Unknown record type.  Skip over it. */
			fseek(mps_file_in, reclen, SEEK_CUR); 
		}

	}	/* while (!feof(mps_file_in)) */

#ifdef DUMP_ICON_TABLE
	printf("\t{ -1, NULL },\n");
	printf("};\n");
#endif

	return ;

}

void
mps_write(void)
{
	int				short_length;
	waypoint		*wpt;
	route_head		*rte;
	route_head		*trk;

	char			recType;
	int				reclen;
	int				reclen2;
	unsigned int	tocopy;
	long			tempFilePos;
	unsigned int	mpsWptClass;

	unsigned char	copybuf[8192];

	if (snlen)
		short_length = atoi(snlen);
	else
		short_length = 10;

	if (mpsmergeout) {
		/* need to skip over the merging header and test merge version */
		mps_fileHeader_r(mps_file_temp, &mps_ver_temp);

		if (mpsverout) {
			if (mps_ver_temp != atoi(mpsverout)) {
				/* Need to clean up after a junk version specified */
				/* close the real output file + renamed original output file */
				/* then delete the "real" file and rename the temporarily renamed file back */
				fclose(mps_file_temp);
				fclose(mps_file_out);
				remove(origname);
				rename(tempname,origname);
				fatal (MYNAME ": merge source version is %d, requested out version is %d\n", mps_ver_temp, atoi(mpsverout));
			}
		}
		else {
			mpsverout = xmalloc(10);
			sprintf(mpsverout,"%d", mps_ver_temp);
		}
	}

	if (mpsverout)
		mps_ver_out = atoi(mpsverout);
	else
		mps_ver_out = 5;

	mkshort_handle = mkshort_new_handle();

	setshort_length(mkshort_handle, short_length);

	if (snwhiteopt)
		setshort_whitespace_ok(mkshort_handle, atoi(snwhiteopt));
	else
		setshort_whitespace_ok(mkshort_handle, 0);

	mps_fileHeader_w(mps_file_out, mps_ver_out);

	/* .mps file order is wpts, rtes, trks then mapsets. If we've not been asked to write
	   wpts, but we are merging, then read in the waypoints from the original file and 
	   write them out, prior to doing rtes.
	*/
	/* if ((mpsmergeout) && (global_opts.objective != wptdata)) { */
	if ((mpsmergeout) && (! doing_wpts)) {
		while (!feof(mps_file_temp)) {

			fread(&reclen, 4, 1, mps_file_temp);
			reclen2 = le_read32(&reclen);

			/* Read the record type "flag" in - using fread in case in the future need more than one char */
			fread(&recType, 1, 1, mps_file_temp);

			if (recType == 'W')  {
				fwrite(&reclen, 4, 1, mps_file_out);	/* write out untouched */
				fwrite(&recType, 1, 1, mps_file_out);

				tempFilePos = ftell(mps_file_temp);
				/* need to read in the waypoint info only because later we may need to check for uniqueness
				   since we're here because the user didn't request waypoints, this should be acceptable */
				mps_waypoint_r(mps_file_temp, mps_ver_temp, &wpt, &mpsWptClass);
				mps_wpt_q_add(&written_wpt_head, wpt);
				waypt_free( wpt );
				/* now return to the start of the waypoint data to do a "clean" copy */
				fseek(mps_file_temp, tempFilePos, SEEK_SET);

				/* copy the data using a "reasonably" sized buffer */
				for(tocopy = reclen2; tocopy > 0; tocopy -= sizeof(copybuf)) {
					fread(copybuf, (tocopy > sizeof(copybuf) ? sizeof(copybuf) : tocopy), 1, mps_file_temp);
					fwrite(copybuf, (tocopy > sizeof(copybuf) ? sizeof(copybuf) : tocopy), 1, mps_file_out);
				}
			}
			else break;
		}	/* while (!feof(mps_file_temp)) */
	}	/* if (mpsmergeout) */

	/* irrespective of merging, now write out any waypoints */
	/* if (global_opts.objective == wptdata) { */
	if (doing_wpts) {

		if (mpsmergeout) {
			/* since we're processing waypoints, we should read in from whatever version and write out */
			/* in the selected version */
			while (!feof(mps_file_temp)) {

				fread(&reclen, 4, 1, mps_file_temp);
				reclen2 = le_read32(&reclen);

				/* Read the record type "flag" in - using fread in case in the future need more than one char */
				fread(&recType, 1, 1, mps_file_temp);

				if (recType == 'W')  {
					/* need to be careful that we aren't duplicating a wpt defined from elsewhere */
					mps_waypoint_r(mps_file_temp, mps_ver_temp, &wpt, &mpsWptClass);
					if (mpsWptClass == MPSDEFAULTWPTCLASS) waypt_add(wpt);else waypt_free(wpt);
				}
				else break;
			}
		}
		waypt_disp_all(mps_waypoint_w_unique_wrapper);
	}

	/* prior to writing any tracks as requested, if we're doing a merge, read in the rtes
	   from the original file and then write them out, ready for tracks to follow
	*/
	/* if ((mpsmergeout) && (global_opts.objective != rtedata)) { */
	if ((mpsmergeout) && (! doing_rtes)) {
		while (!feof(mps_file_temp)) {

			/* this might all fail if the relevant waypoints haven't been written */
			if (recType == 'R')  {
				fwrite(&reclen, 4, 1, mps_file_out);	/* write out untouched */
				fwrite(&recType, 1, 1, mps_file_out);

				for(tocopy = reclen2; tocopy > 0; tocopy -= sizeof(copybuf)) {
					fread(copybuf, (tocopy > sizeof(copybuf) ? sizeof(copybuf) : tocopy), 1, mps_file_temp);
					fwrite(copybuf, (tocopy > sizeof(copybuf) ? sizeof(copybuf) : tocopy), 1, mps_file_out);
				}
			}
			else break;
			fread(&reclen, 4, 1, mps_file_temp);
			reclen2 = le_read32(&reclen);

			/* Read the record type "flag" in - using fread in case in the future need more than one char */
			fread(&recType, 1, 1, mps_file_temp);

		}	/* while (!feof(mps_file_temp)) */
	}	/* if (mpsmergeout) */

	/* routes are next in the wpts, rtes, trks, mapset sequence */
	/* if (global_opts.objective == rtedata) { */
	if (doing_rtes) {

		if (mpsmergeout) {
			/* since we're processing routes, we should read in from whatever version and write out */
			/* in the selected version */
			while (!feof(mps_file_temp)) {

				if (recType == 'R')  {
					mps_route_r(mps_file_temp, mps_ver_temp, &rte);
				}
				else break;

				fread(&reclen, 4, 1, mps_file_temp);
				reclen2 = le_read32(&reclen);

				/* Read the record type "flag" in - using fread in case in the future need more than one char */
				fread(&recType, 1, 1, mps_file_temp);
			}
		}
		/* need to make sure there is a "real" waypoint for each route waypoint
		   Need to be careful about creating duplicate wpts as MapSource chokes on these
		   so, if the user requested waypoints to be output too, then write the route
		   waypoints only if unique in the total list of waypoints ("real" and route derived) 
		   If the user didn't request waypoints to be output, then output the route derived
		   waypoints without consideration for uniqueness for "real" waypoints that haven't
		   been output (phew!)
		*/
		route_disp_all(mps_noop, mps_noop, mps_route_wpt_w_unique_wrapper);

		route_disp_all(mps_routehdr_w_wrapper, mps_routetrlr_w_wrapper, mps_routedatapoint_w_wrapper);
	}

	/* If merging but we haven't been requested to write out tracks, then read in tracks from
	   the original file and write these out prior to any mapset writes later on
	*/
	/* if ((mpsmergeout) && (global_opts.objective != trkdata)) { */
	if ((mpsmergeout) && (! doing_trks)) {
		while (!feof(mps_file_temp)) {

			if (recType == 'T')  {
				fwrite(&reclen, 4, 1, mps_file_out);	/* write out untouched */
				fwrite(&recType, 1, 1, mps_file_out);

				for(tocopy = reclen2; tocopy > 0; tocopy -= sizeof(copybuf)) {
					fread(copybuf, (tocopy > sizeof(copybuf) ? sizeof(copybuf) : tocopy), 1, mps_file_temp);
					fwrite(copybuf, (tocopy > sizeof(copybuf) ? sizeof(copybuf) : tocopy), 1, mps_file_out);
				}
			}
			else break;
			fread(&reclen, 4, 1, mps_file_temp);
			reclen2 = le_read32(&reclen);

			/* Read the record type "flag" in - using fread in case in the future need more than one char */
			fread(&recType, 1, 1, mps_file_temp);

		}	/* while (!feof(mps_file_temp)) */
	}	/* if (mpsmergeout) */

	/* tracks are next in the wpts, rte, trks, mapset sequence in .mps files */
	/* if (global_opts.objective == trkdata) { */
	if (doing_trks) {
		if (mpsmergeout) {
			/* since we're processing tracks, we should read in from whatever version and write out
			   in the selected version */
			while (!feof(mps_file_temp)) {

				if (recType == 'T')  {
					mps_track_r(mps_file_temp, mps_ver_temp, &trk);
				}
				else break;

				fread(&reclen, 4, 1, mps_file_temp);
				reclen2 = le_read32(&reclen);

				/* Read the record type "flag" in - using fread in case in the future need more than one char */
				fread(&recType, 1, 1, mps_file_temp);
			}
		}
		track_disp_all(mps_trackhdr_w_wrapper, mps_noop, mps_trackdatapoint_w_wrapper);
	}

	if (mpsmergeout) {
		/* should now be reading a either a map segment or a mapset - since we would write out an empty one,
		   let's use the one from the merge file which may well have decent data in */
		for (;;) {
			fwrite(&reclen, 4, 1, mps_file_out);	/* write out untouched */
			fwrite(&recType, 1, 1, mps_file_out);

			for(tocopy = reclen2; tocopy > 0; tocopy -= sizeof(copybuf)) {
				fread(copybuf, (tocopy > sizeof(copybuf) ? sizeof(copybuf) : tocopy), 1, mps_file_temp);
				fwrite(copybuf, (tocopy > sizeof(copybuf) ? sizeof(copybuf) : tocopy), 1, mps_file_out);
			}
			if (recType != 'V') {
				fread(&reclen, 4, 1, mps_file_temp);
				reclen2 = le_read32(&reclen);

				/* Read the record type "flag" in - using fread in case in the future need more than one char */
				fread(&recType, 1, 1, mps_file_temp);
			}
			else break;
		}
		
	}
	else mps_mapsetname_w(mps_file_out, mps_ver_out);

	mkshort_del_handle(mkshort_handle);

}

ff_vecs_t mps_vecs = {
	ff_type_file,
	mps_rd_init,
	mps_wr_init,
	mps_rd_deinit,
	mps_wr_deinit,
	mps_read,
	mps_write,
	NULL,
	mps_args
};