File: Route.cs

package info (click to toggle)
quickroute-gps 2.5-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 19,576 kB
  • sloc: cs: 74,488; makefile: 72; sh: 43
file content (2078 lines) | stat: -rw-r--r-- 90,955 bytes parent folder | download | duplicates (3)
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
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Wintellect.PowerCollections;

namespace QuickRoute.BusinessEntities
{
  [Serializable]
  public class Route : ISerializable
  {
    private readonly List<RouteSegment> segments = new List<RouteSegment>();
    private OrderedBag<DateTime> lapTimes;
    private Interval speedSmoothingInterval = new Interval(0, 0); // for backwards compatibility only, do not use in new code
    private Dictionary<WaypointAttribute, Interval> smoothingIntervals = SessionSettings.CreateDefaultSmoothingIntervals();
    private bool suppressWaypointAttributeCalculation;
    [NonSerialized] private Dictionary<WaypointAttribute, bool> waypointAttributeExists;

    public Route(List<RouteSegment> segments)
    {
      this.segments = segments;
    }

    protected Route(SerializationInfo info, StreamingContext context)
    {
      segments = (List<RouteSegment>)(info.GetValue("segments", typeof(List<RouteSegment>)));
    }

    #region ISerializable Members

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
      info.AddValue("segments", segments, typeof(List<RouteSegment>));
    }

    #endregion

    #region Public properties

    public List<RouteSegment> Segments
    {
      get { return segments; }
    }

    public Dictionary<WaypointAttribute, Interval> SmoothingIntervals
    {
      get
      {
        if (smoothingIntervals == null)
        {
          smoothingIntervals = SessionSettings.CreateDefaultSmoothingIntervals();
          smoothingIntervals[WaypointAttribute.Speed] = speedSmoothingInterval;
          smoothingIntervals[WaypointAttribute.Pace] = speedSmoothingInterval;
        }
        return smoothingIntervals;
      }
      set
      {
        smoothingIntervals = value;
        CalculateWaypointAttributes(true);
      }
    }

    public Waypoint FirstWaypoint
    {
      get { return segments.Count == 0 ? null : segments[0].Waypoints[0]; }
    }

    public Waypoint LastWaypoint
    {
      get
      {
        return segments.Count == 0
                 ? null
                 : segments[segments.Count - 1].Waypoints[segments[segments.Count - 1].Waypoints.Count - 1];
      }
    }

    public ParameterizedLocation FirstPL
    {
      get { return new ParameterizedLocation(0, 0); }
    }

    public ParameterizedLocation LastPL
    {
      get { return new ParameterizedLocation(segments.Count - 1, segments[segments.Count - 1].Waypoints.Count - 1); }
    }

    public OrderedBag<DateTime> LapTimes
    {
      get { return lapTimes; }
      set { lapTimes = value; }
    }

    public bool SuppressWaypointAttributeCalculation
    {
      get { return suppressWaypointAttributeCalculation; }
      set { suppressWaypointAttributeCalculation = value; }
    }

    #endregion

    #region  Public methods

    public void Initialize()
    {
      CalculateWaypointAttributes(true);
    }

    public void EnsureUtcTimes()
    {
      foreach (var segment in segments)
      {
        foreach (var waypoint in segment.Waypoints)
        {
          waypoint.Time = waypoint.Time.ToUniversalTime();
        }
      }
    }

    public LongLat CenterLongLat()
    {
      RectangleD boundingRectangle = BoundingRectangle();
      return new LongLat(boundingRectangle.Center.X, boundingRectangle.Center.Y);
    }

    public RectangleD BoundingProjectedRectangle(LongLat projectionOrigin)
    {
      double minX = 0;
      double minY = 0;
      double maxX = 0;
      double maxY = 0;

      for (int i = 0; i < segments.Count; i++)
      {
        for (int j = 0; j < segments[i].Waypoints.Count; j++)
        {
          PointD projectedLocation = segments[i].Waypoints[j].LongLat.Project(projectionOrigin);
          if (projectedLocation.X < minX || (i == 0 && j == 0)) minX = projectedLocation.X;
          if (projectedLocation.Y < minY || (i == 0 && j == 0)) minY = projectedLocation.Y;
          if (projectedLocation.X > maxX || (i == 0 && j == 0)) maxX = projectedLocation.X;
          if (projectedLocation.Y > maxY || (i == 0 && j == 0)) maxY = projectedLocation.Y;
        }
      }
      return new RectangleD(new PointD(minX, minY), new SizeD(maxX - minX, maxY - minY));
    }

    public RectangleD BoundingRectangle()
    {
      double minX = 0;
      double minY = 0;
      double maxX = 0;
      double maxY = 0;

      for (int i = 0; i < segments.Count; i++)
      {
        for (int j = 0; j < segments[i].Waypoints.Count; j++)
        {
          LongLat longLat = segments[i].Waypoints[j].LongLat;
          if (longLat.Longitude < minX || (i == 0 && j == 0)) minX = longLat.Longitude;
          if (longLat.Latitude < minY || (i == 0 && j == 0)) minY = longLat.Latitude;
          if (longLat.Longitude > maxX || (i == 0 && j == 0)) maxX = longLat.Longitude;
          if (longLat.Latitude > maxY || (i == 0 && j == 0)) maxY = longLat.Latitude;
        }
      }
      return new RectangleD(new PointD(minX, minY), new SizeD(maxX - minX, maxY - minY));
    }

    public PointD GetProjectedLocationFromParameterizedLocation(ParameterizedLocation parameterizedLocation,
                                                                LongLat projectionOrigin)
    {
      List<Waypoint> waypoints = segments[parameterizedLocation.SegmentIndex].Waypoints;
      if (parameterizedLocation.IsNode) return waypoints[(int)parameterizedLocation.Value].LongLat.Project(projectionOrigin);
      var i = (int)parameterizedLocation.Floor().Value;
      if (i >= waypoints.Count - 1) i = waypoints.Count - 2;
      if (waypoints.Count < 2) return waypoints[0].LongLat.Project(projectionOrigin);
      double d = parameterizedLocation.Value - i;

      PointD p0 = waypoints[i].LongLat.Project(projectionOrigin);
      PointD p1 = waypoints[i + 1].LongLat.Project(projectionOrigin);

      return new PointD(p0.X + d * (p1.X - p0.X), p0.Y + d * (p1.Y - p0.Y));
    }

    public LongLat GetLocationFromParameterizedLocation(ParameterizedLocation parameterizedLocation)
    {
      List<Waypoint> waypoints = segments[parameterizedLocation.SegmentIndex].Waypoints;
      if (parameterizedLocation.IsNode) return waypoints[(int)parameterizedLocation.Value].LongLat;
      var i = (int)parameterizedLocation.Floor().Value;
      if (i >= waypoints.Count - 1) i = waypoints.Count - 2;
      if (waypoints.Count < 2) return waypoints[0].LongLat;
      double d = parameterizedLocation.Value - i;
      LongLat p0 = waypoints[i].LongLat;
      LongLat p1 = waypoints[i + 1].LongLat;

      return new LongLat(p0.Longitude + d * (p1.Longitude - p0.Longitude), p0.Latitude + d * (p1.Latitude - p0.Latitude));
    }

    public DateTime GetTimeFromParameterizedLocation(ParameterizedLocation parameterizedLocation)
    {
      List<Waypoint> waypoints = segments[parameterizedLocation.SegmentIndex].Waypoints;
      if (parameterizedLocation.IsNode) return waypoints[(int)parameterizedLocation.Value].Time;
      var i = (int)parameterizedLocation.Floor().Value;
      if (i >= waypoints.Count - 1) i = waypoints.Count - 2;
      if (waypoints.Count < 2) return waypoints[0].Time;
      double d = parameterizedLocation.Value - i;

      DateTime dt0 = waypoints[i].Time;
      DateTime dt1 = waypoints[i + 1].Time;
      return new DateTime(dt0.Ticks + (long)(d * (dt1.Ticks - dt0.Ticks)), dt0.Kind);
    }

    public double? GetOriginalAttributeFromParameterizedLocation(WaypointAttribute attribute, ParameterizedLocation parameterizedLocation)
    {
      if (attribute != WaypointAttribute.HeartRate && attribute != WaypointAttribute.Altitude) throw new ArgumentException("The 'attribute' parameter must be either WaypointAttribute.HeartRate or WaypointAttribute.Altitude");

      List<Waypoint> waypoints = segments[parameterizedLocation.SegmentIndex].Waypoints;
      if (parameterizedLocation.IsNode) return waypoints[(int)parameterizedLocation.Value].GetOriginalAttribute(attribute);
      var i = (int)parameterizedLocation.Floor().Value;
      if (i >= waypoints.Count - 1) i = waypoints.Count - 2;
      if (waypoints.Count < 2) return waypoints[0].GetOriginalAttribute(attribute);
      double d = parameterizedLocation.Value - i;

      var v0 = waypoints[i].GetOriginalAttribute(attribute);
      var v1 = waypoints[i + 1].GetOriginalAttribute(attribute);
      if (v0.HasValue && v1.HasValue) return v0 + d * (v1 - v0);
      return null;
    }

    public double? GetAttributeFromParameterizedLocation(WaypointAttribute attribute, ParameterizedLocation parameterizedLocation)
    {
      List<Waypoint> waypoints = segments[parameterizedLocation.SegmentIndex].Waypoints;
      if (parameterizedLocation.IsNode)
      {
        return waypoints[(int)parameterizedLocation.Value].Attributes.ContainsKey(attribute) 
          ? waypoints[(int)parameterizedLocation.Value].Attributes[attribute] 
          : null;
      }
      var i = (int)parameterizedLocation.Floor().Value;
      if (i >= waypoints.Count - 1) i = waypoints.Count - 2;
      if (waypoints.Count < 2) return waypoints[0].Attributes[attribute];
      double d = parameterizedLocation.Value - i;

      return GetAttributeValueBetweenWaypoints(waypoints[i], waypoints[i + 1], d, attribute);
    }

    /// <summary>
    /// Relatively slow, use the three parameter overload if possible.
    /// </summary>
    /// <param name="time"></param>
    /// <returns></returns>
    public ParameterizedLocation GetParameterizedLocationFromTime(DateTime time)
    {
      return GetParameterizedLocationFromTime(time, false);
    }

    /// <summary>
    /// Relatively slow, use the three parameter overload if possible.
    /// </summary>
    /// <param name="time"></param>
    /// <param name="strict">If true, returns null if outside segments</param>
    /// <returns></returns>
    public ParameterizedLocation GetParameterizedLocationFromTime(DateTime time, bool strict)
    {
      if (time <= FirstWaypoint.Time) return FirstPL;
      if (time >= LastWaypoint.Time) return LastPL;
      for (int i = 0; i < segments.Count; i++)
      {
        RouteSegment segment = segments[i];
        if (!(strict && (time < segment.FirstWaypoint.Time || time > segment.LastWaypoint.Time))) // don't look outside segment if in strict mode
        {
          if (time <= segment.FirstWaypoint.Time) return new ParameterizedLocation(i, 0);
          if (time <= segment.LastWaypoint.Time)
          {
            int lo = 0;
            int hi = segment.Waypoints.Count - 2;
            while (hi >= lo)
            {
              int mi = (lo + hi) / 2;
              if (time < segment.Waypoints[mi].Time)
              {
                hi = mi - 1;
              }
              else if (time > segment.Waypoints[mi + 1].Time)
              {
                lo = mi + 1;
              }
              else
              {
                var delta = segment.Waypoints[mi + 1].Time.Ticks - segment.Waypoints[mi].Time.Ticks;
                if (delta == 0) return new ParameterizedLocation(i, mi);
                return new ParameterizedLocation(i,
                                                 mi +
                                                 (double)(time.Ticks - segment.Waypoints[mi].Time.Ticks) /
                                                 (segment.Waypoints[mi + 1].Time.Ticks -
                                                  segment.Waypoints[mi].Time.Ticks));
              }
            }
          }
        }
      }
      return null;
    }

    public ParameterizedLocation GetParameterizedLocationFromTime(DateTime time, ParameterizedLocation initialGuess,
                                                                  ParameterizedLocation.Direction direction)
    {
      if (time <= FirstWaypoint.Time) return FirstPL;
      if (time >= LastWaypoint.Time) return LastPL;
      if (initialGuess == null) return GetParameterizedLocationFromTime(time);
      ParameterizedLocation pl = new ParameterizedLocation(initialGuess).Floor();

      if (direction == ParameterizedLocation.Direction.Forward)
      {
        ParameterizedLocation lastPL = LastPL;
        while (pl < lastPL)
        {
          var w2pl = new ParameterizedLocation(pl.SegmentIndex, (int)pl.Value + 1);
          if (!IsLastPLInSegment(w2pl))
          {
            Waypoint w1 = segments[pl.SegmentIndex].Waypoints[(int)pl.Value];
            Waypoint w2 = segments[w2pl.SegmentIndex].Waypoints[(int)w2pl.Value];
            if (w2 != null && time >= w1.Time && time <= w2.Time)
            {
              if (w2.Time.Ticks == w1.Time.Ticks) return new ParameterizedLocation(pl.SegmentIndex, (int)pl.Value);
              return new ParameterizedLocation(pl.SegmentIndex,
                                               (int)pl.Value +
                                               (double)(time.Ticks - w1.Time.Ticks) / (w2.Time.Ticks - w1.Time.Ticks));
            }
          }
          pl = GetNextPLNode(pl, ParameterizedLocation.Direction.Forward);
        }
      }
      else
      {
        ParameterizedLocation firstPL = FirstPL;
        while (pl > firstPL)
        {
          var w2pl = new ParameterizedLocation(pl.SegmentIndex, (int)pl.Value + 1);
          if (!IsLastPLInSegment(w2pl))
          {
            Waypoint w1 = segments[pl.SegmentIndex].Waypoints[(int)pl.Value];
            Waypoint w2 = segments[w2pl.SegmentIndex].Waypoints[(int)w2pl.Value];
            if (w2 != null && time >= w1.Time && time <= w2.Time)
            {
              return new ParameterizedLocation(pl.SegmentIndex,
                                               (int)pl.Value +
                                               (double)(time.Ticks - w1.Time.Ticks) / (w2.Time.Ticks - w1.Time.Ticks));
            }
          }
          pl = GetNextPLNode(pl, ParameterizedLocation.Direction.Backward);
        }
      }
      return GetParameterizedLocationFromTime(time);
    }

    /// <summary>
    /// Relatively slow.
    /// </summary>
    /// <param name="distance"></param>
    /// <returns></returns>
    public ParameterizedLocation GetParameterizedLocationFromDistance(double distance)
    {
      if (distance <= FirstWaypoint.Attributes[WaypointAttribute.Distance].Value) return FirstPL;
      if (distance >= LastWaypoint.Attributes[WaypointAttribute.Distance].Value) return LastPL;
      for (int i = 0; i < segments.Count; i++)
      {
        RouteSegment segment = segments[i];
        for (int j = 0; j < segment.Waypoints.Count - 1; j++)
        {
          if (distance >= segment.Waypoints[j].Attributes[WaypointAttribute.Distance].Value && distance <= segment.Waypoints[j + 1].Attributes[WaypointAttribute.Distance].Value)
          {
            return new ParameterizedLocation(i,
                                             j +
                                             (distance - segment.Waypoints[j].Attributes[WaypointAttribute.Distance].Value) /
                                             (segment.Waypoints[j + 1].Attributes[WaypointAttribute.Distance].Value - segment.Waypoints[j].Attributes[WaypointAttribute.Distance].Value));
          }
          if (distance < segment.Waypoints[j].Attributes[WaypointAttribute.Distance].Value)
          {
            return new ParameterizedLocation(i, j);
          }
        }
      }
      return null;
    }

    /// <summary>
    /// Only to be used inside a route segment!
    /// </summary>
    /// <param name="startTime"></param>
    /// <param name="endTime"></param>
    /// <param name="interval"></param>
    /// <returns></returns>
    public List<ParameterizedLocation> GetEquallySpacedParameterizedLocations(DateTime startTime, DateTime endTime,
                                                                              TimeSpan interval)
    {
      return GetEquallySpacedParameterizedLocations(startTime, endTime, interval,
                                                    new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc));
    }

    /// <summary>
    /// Only to be used inside a route segment!
    /// </summary>
    /// <param name="startTime"></param>
    /// <param name="endTime"></param>
    /// <param name="interval"></param>
    /// <param name="referenceTime"></param>
    /// <returns></returns>
    public List<ParameterizedLocation> GetEquallySpacedParameterizedLocations(DateTime startTime, DateTime endTime,
                                                                              TimeSpan interval, DateTime referenceTime)
    {
      decimal offset = Math.Ceiling(((decimal)startTime.Ticks - referenceTime.Ticks) / interval.Ticks);
      var time = new DateTime(Convert.ToInt64(referenceTime.Ticks + offset * interval.Ticks), startTime.Kind);
      var pls = new List<ParameterizedLocation>();
      ParameterizedLocation pl = GetParameterizedLocationFromTime(time);
      while (time <= endTime)
      {
        pls.Add(pl);
        time += interval;
        pl = GetParameterizedLocationFromTime(time, pl, ParameterizedLocation.Direction.Forward);
      }
      return pls;
    }

    /// <summary>
    /// Only to be used inside a route segment!
    /// </summary>
    /// <param name="startTime"></param>
    /// <param name="endTime"></param>
    /// <param name="interval"></param>
    /// <returns></returns>
    public List<DateTime> GetEquallySpacedTimes(DateTime startTime, DateTime endTime, TimeSpan interval)
    {
      return GetEquallySpacedTimes(startTime, endTime, interval, new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc));
    }

    /// <summary>
    /// Only to be used inside a route segment!
    /// </summary>
    /// <param name="startTime"></param>
    /// <param name="endTime"></param>
    /// <param name="interval"></param>
    /// <param name="referenceTime"></param>
    /// <returns></returns>
    public List<DateTime> GetEquallySpacedTimes(DateTime startTime, DateTime endTime, TimeSpan interval, DateTime referenceTime)
    {
      decimal offset = Math.Ceiling(((decimal)startTime.Ticks - referenceTime.Ticks) / interval.Ticks);
      var time = new DateTime(Convert.ToInt64(referenceTime.Ticks + offset * interval.Ticks), startTime.Kind);
      var times = new List<DateTime>();
      while (time <= endTime)
      {
        times.Add(time);
        time += interval;
      }
      return times;
    }

    /// <summary>
    /// Only to be used inside a route segment!
    /// </summary>
    /// <param name="startTime"></param>
    /// <param name="endTime"></param>
    /// <param name="interval"></param>
    /// <param name="referenceTime"></param>
    /// <returns></returns>
    public List<Waypoint> GetEquallySpacedWaypoints(DateTime startTime, DateTime endTime, TimeSpan interval,
                                                    DateTime referenceTime)
    {
      decimal offset = Math.Ceiling(((decimal)startTime.Ticks - referenceTime.Ticks) / interval.Ticks);
      var time = new DateTime(Convert.ToInt64(referenceTime.Ticks + offset * interval.Ticks), startTime.Kind);
      List<ParameterizedLocation> pls = GetEquallySpacedParameterizedLocations(startTime, endTime, interval,
                                                                               referenceTime);
      var waypoints = new List<Waypoint>();
      foreach (ParameterizedLocation pl in pls)
      {
        var w = CreateWaypointFromParameterizedLocation(pl);
        w.Time = time; // to prevent rounding errors
        waypoints.Add(w);
        time += interval;
      }
      return waypoints;
    }

    /// <summary>
    /// Only to be used inside a route segment!
    /// </summary>
    /// <param name="startTime"></param>
    /// <param name="endTime"></param>
    /// <param name="interval"></param>
    /// <returns></returns>
    public List<Waypoint> GetEquallySpacedWaypoints(DateTime startTime, DateTime endTime, TimeSpan interval)
    {
      return GetEquallySpacedWaypoints(startTime, endTime, interval, new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc));
    }

    /// <summary>
    /// Calculates elapsed time, distance, direction and speed for all waypoints in the route.
    /// </summary>
    public void CalculateWaypointAttributes(bool routeChanged)
    {
      if (suppressWaypointAttributeCalculation) return;
      // first pass: location, elapsed time, distance, direction

      if (routeChanged)
      {
        double distance = 0;
        double elapsedTime = 0;
        for (int i = 0; i < segments.Count; i++)
        {
          for (int j = 0; j < segments[i].Waypoints.Count; j++)
          {
            Waypoint w = segments[i].Waypoints[j];
            double deltaDistance = 0;
            double deltaTime = 0;

            w.Attributes[WaypointAttribute.Longitude] = w.LongLat.Longitude;
            w.Attributes[WaypointAttribute.Latitude] = w.LongLat.Latitude;
            if (j > 0)
            {
              deltaDistance = LinearAlgebraUtil.DistancePointToPointLongLat(w.LongLat,
                                                                            segments[i].Waypoints[j - 1].LongLat);
              deltaTime = w.Time.Subtract(segments[i].Waypoints[j - 1].Time).TotalSeconds;
            }
            elapsedTime += deltaTime;
            distance += deltaDistance;
            w.Attributes[WaypointAttribute.Distance] = distance;
            w.Attributes[WaypointAttribute.ElapsedTime] = elapsedTime;
          }
        }

        // check existence of heart rate, altitude and map reading
        waypointAttributeExists = new Dictionary<WaypointAttribute, bool>();
        var attributesToCheckExistenceFor = new List<WaypointAttribute>
                                              {
                                                WaypointAttribute.HeartRate,
                                                WaypointAttribute.Altitude,
                                                WaypointAttribute.MapReadingDuration
                                              };
        foreach (var wa in attributesToCheckExistenceFor)
        {
          waypointAttributeExists[wa] = CheckIfWaypointAttributeExists(wa);
        }

        // second pass: the rest
        CalculateSpeeds();
        CalculateSlidingAverageAttributes(WaypointAttribute.HeartRate, SmoothingIntervals[WaypointAttribute.HeartRate]);
        CalculateSlidingAverageAttributes(WaypointAttribute.Altitude, SmoothingIntervals[WaypointAttribute.Altitude]);
        CalculateInclinations();
        CalculateMapReadings();
      }
      // CalculateDirectionDeviationsToNextLap is also dependent on laps, not just route change
      CalculateDirectionDeviationsToNextLap();
    }

    public Waypoint CreateWaypointFromParameterizedLocation(ParameterizedLocation parameterizedLocation)
    {
      var w = new Waypoint();
      List<Waypoint> waypoints = segments[parameterizedLocation.SegmentIndex].Waypoints;
      var i = (int)parameterizedLocation.Floor().Value;
      if (i >= waypoints.Count - 1) i = waypoints.Count - 2;
      if (waypoints.Count < 2) return waypoints[0];
      double d = parameterizedLocation.Value - i;

      // time
      DateTime dt0 = waypoints[i].Time;
      DateTime dt1 = waypoints[i + 1].Time;
      w.Time = new DateTime(dt0.Ticks + (long)(d * (dt1.Ticks - dt0.Ticks)), dt0.Kind);

      // location
      LongLat p0 = waypoints[i].LongLat;
      LongLat p1 = waypoints[i + 1].LongLat;
      w.LongLat = new LongLat(p0.Longitude + d * (p1.Longitude - p0.Longitude),
                              p0.Latitude + d * (p1.Latitude - p0.Latitude));

      // altitude
      if (waypoints[i].Altitude.HasValue && waypoints[i + 1].Altitude.HasValue)
      {
        w.Altitude = waypoints[i].Altitude + d * (waypoints[i + 1].Altitude - waypoints[i].Altitude);
      }

      // heart rate
      if (waypoints[i].HeartRate.HasValue && waypoints[i + 1].HeartRate.HasValue)
      {
        w.HeartRate = waypoints[i].HeartRate + d * (waypoints[i + 1].HeartRate - waypoints[i].HeartRate);
      }

      var attributes = new List<WaypointAttribute>
                         {
                           WaypointAttribute.Pace,
                           WaypointAttribute.HeartRate,
                           WaypointAttribute.Altitude,
                           WaypointAttribute.Speed,
                           WaypointAttribute.DirectionDeviationToNextLap,
                           WaypointAttribute.ElapsedTime,
                           WaypointAttribute.Distance,
                           WaypointAttribute.Inclination,
                           WaypointAttribute.Direction,
                           WaypointAttribute.Longitude,
                           WaypointAttribute.Latitude
                         };

      // map reading
      if(waypointAttributeExists[WaypointAttribute.MapReadingDuration])
      {
        if(parameterizedLocation.IsNode)
        {
          w.MapReadingState = waypoints[i].MapReadingState;
        }
        else
        {
          w.MapReadingState = waypoints[i].MapReadingState == MapReadingState.NotReading || waypoints[i + 1].MapReadingState == MapReadingState.NotReading
            ? MapReadingState.NotReading
            : MapReadingState.Reading;
        }
        attributes.AddRange(new[]
                              {
                                WaypointAttribute.MapReadingDuration,
                                WaypointAttribute.MapReadingState,
                                WaypointAttribute.PreviousMapReadingEnd,
                                WaypointAttribute.NextMapReadingStart
                              });
      }

      foreach (var attribute in attributes)
      {
        w.Attributes[attribute] = GetAttributeValueBetweenWaypoints(waypoints[i], waypoints[i + 1], d, attribute);
      }

      return w;
    }

    public Waypoint CreateWaypointFromTime(DateTime time)
    {
      return CreateWaypointFromParameterizedLocation(GetParameterizedLocationFromTime(time));
    }

    public CutRouteData Cut(ParameterizedLocation parameterizedLocation, CutType cutType)
    {
      var cutRoute = new CutRouteData { CutType = cutType };
      switch (cutType)
      {
        case CutType.Before:
          cutRoute.Segments.AddRange(segments.GetRange(0, parameterizedLocation.SegmentIndex));
          if (!parameterizedLocation.IsNode)
          {
            // cut between two waypoints: create cut waypoint
            Waypoint cutWaypoint = CreateWaypointFromParameterizedLocation(parameterizedLocation);
            var rs = new RouteSegment();
            segments.RemoveRange(0, parameterizedLocation.SegmentIndex);
            rs.Waypoints.AddRange(segments[0].Waypoints.GetRange(0, (int)parameterizedLocation.Ceiling().Value));
            cutRoute.Segments.Add(rs);
            segments[0].Waypoints.RemoveRange(0, (int)parameterizedLocation.Ceiling().Value);
            segments[0].Waypoints.Insert(0, cutWaypoint);
            cutRoute.WaypointInsertedAtCut = cutWaypoint;
          }
          else
          {
            // cut exactly at a waypoint
            var rs = new RouteSegment();
            segments.RemoveRange(0, parameterizedLocation.SegmentIndex);
            rs.Waypoints.AddRange(segments[0].Waypoints.GetRange(0, (int)parameterizedLocation.Value));
            cutRoute.Segments.Add(rs);
            segments[0].Waypoints.RemoveRange(0, (int)parameterizedLocation.Value);
          }
          // handle map readings nicely
          if (waypointAttributeExists[WaypointAttribute.MapReadingDuration] &&
             segments[0].FirstWaypoint.MapReadingState == MapReadingState.Reading)
          {
            segments[0].FirstWaypoint.MapReadingState = MapReadingState.StartReading;
          }
          break;

        case CutType.After:
          if (parameterizedLocation.SegmentIndex < segments.Count - 1)
          {
            cutRoute.Segments.AddRange(segments.GetRange(parameterizedLocation.SegmentIndex + 1,
                                                         segments.Count - 1 - parameterizedLocation.SegmentIndex));
            segments.RemoveRange(parameterizedLocation.SegmentIndex + 1,
                                 segments.Count - 1 - parameterizedLocation.SegmentIndex);
          }
          var i = (int)parameterizedLocation.Ceiling().Value;
          int count = segments[parameterizedLocation.SegmentIndex].Waypoints.Count;
          if (!parameterizedLocation.IsNode)
          {
            // cut between two waypoints: create cut waypoint
            Waypoint cutWaypoint = CreateWaypointFromParameterizedLocation(parameterizedLocation);
            var rs = new RouteSegment();
            rs.Waypoints.AddRange(segments[parameterizedLocation.SegmentIndex].Waypoints.GetRange(i, count - i));
            cutRoute.Segments.Insert(0, rs);
            segments[parameterizedLocation.SegmentIndex].Waypoints.RemoveRange(i, count - i);
            segments[parameterizedLocation.SegmentIndex].Waypoints.Insert(i, cutWaypoint);
            cutRoute.WaypointInsertedAtCut = cutWaypoint;
          }
          else
          {
            // cut exactly at a waypoint
            var rs = new RouteSegment();
            rs.Waypoints.AddRange(segments[parameterizedLocation.SegmentIndex].Waypoints.GetRange(i + 1, count - 1 - i));
            cutRoute.Segments.Insert(0, rs);
            segments[parameterizedLocation.SegmentIndex].Waypoints.RemoveRange(i + 1, count - 1 - i);
          }
          // handle map readings nicely
          var lastWaypoint = segments[segments.Count - 1].LastWaypoint;
          if (waypointAttributeExists[WaypointAttribute.MapReadingDuration] &&
             lastWaypoint.MapReadingState == MapReadingState.Reading)
          {
            lastWaypoint.MapReadingState = MapReadingState.EndReading;
          }
          break;
      }
      return cutRoute;
    }

    public void UnCut(CutRouteData cutRouteData)
    {
      Waypoint cutWaypoint;
      switch (cutRouteData.CutType)
      {
        case CutType.Before:
          cutWaypoint = segments[0].FirstWaypoint;
          var beforeCutWaypoint = cutRouteData.Segments[cutRouteData.Segments.Count - 1].LastWaypoint;
          if (cutRouteData.WaypointInsertedAtCut != null)
          {
            segments[0].Waypoints.Remove(cutRouteData.WaypointInsertedAtCut);
          }
          segments.InsertRange(0, cutRouteData.Segments.GetRange(0, cutRouteData.Segments.Count - 1));
          segments[cutRouteData.Segments.Count - 1].Waypoints.
            InsertRange(0, cutRouteData.Segments[cutRouteData.Segments.Count - 1].Waypoints);
          // handle map reading
          if (cutRouteData.WaypointInsertedAtCut == null)
          {
            if (cutWaypoint.MapReadingState == MapReadingState.StartReading &&
               (beforeCutWaypoint.MapReadingState == MapReadingState.Reading || beforeCutWaypoint.MapReadingState == MapReadingState.StartReading))
            {
              cutWaypoint.MapReadingState = MapReadingState.Reading;
            }
          }
          break;

        case CutType.After:
          cutWaypoint = segments[segments.Count - 1].LastWaypoint;
          var afterCutWaypoint = cutRouteData.Segments[0].FirstWaypoint;
          if (cutRouteData.WaypointInsertedAtCut != null)
          {
            segments[segments.Count - 1].Waypoints.Remove(cutRouteData.WaypointInsertedAtCut);
          }
          segments[segments.Count - 1].Waypoints.AddRange(cutRouteData.Segments[0].Waypoints);
          segments.AddRange(cutRouteData.Segments.GetRange(1, cutRouteData.Segments.Count - 1));
          // handle map reading
          if (cutRouteData.WaypointInsertedAtCut == null)
          {
            if (cutWaypoint.MapReadingState == MapReadingState.EndReading &&
               (afterCutWaypoint.MapReadingState == MapReadingState.Reading || afterCutWaypoint.MapReadingState == MapReadingState.EndReading))
            {
              cutWaypoint.MapReadingState = MapReadingState.Reading;
            }
          }
          break;
      }
    }

    public List<double?> GetMomentaneousValueList(WaypointAttribute attribute, ParameterizedLocation startPL,
                                                  ParameterizedLocation endPL, TimeSpan samplingInterval)
    {
      DateTime time = GetTimeFromParameterizedLocation(startPL);
      DateTime endTime = GetTimeFromParameterizedLocation(endPL);
      ParameterizedLocation previousPL = GetParameterizedLocationOfPreviousWaypoint(startPL, false);
      ParameterizedLocation nextPL = GetParameterizedLocationOfNextWaypoint(startPL, true);
      Waypoint previousWaypoint = GetClosestWaypointFromParameterizedLocation(previousPL);
      Waypoint nextWaypoint = GetClosestWaypointFromParameterizedLocation(nextPL);
      var values = new List<double?>();

      while (time < endTime)
      {
        double t0 = time.Subtract(previousWaypoint.Time).TotalSeconds;
        double t1 = nextWaypoint.Time.Subtract(previousWaypoint.Time).TotalSeconds;
        double t = (t1 > 0 ? t0 / t1 : 0);
        double? value = GetAttributeValueBetweenWaypoints(previousWaypoint, nextWaypoint, 1 - t, attribute);
        values.Add(value);

        // is there a waypoint before next sample time?
        DateTime nextSampleTime = time.Add(samplingInterval);
        while (nextWaypoint.Time <= nextSampleTime && nextSampleTime < endTime)
        {
          previousPL = nextPL;
          nextPL = GetParameterizedLocationOfNextWaypoint(nextPL, true);
          if (previousPL.SegmentIndex != nextPL.SegmentIndex)
          {
            // moved to next segment
            previousPL = nextPL;
            nextPL = GetParameterizedLocationOfNextWaypoint(nextPL, true);
            previousWaypoint = GetClosestWaypointFromParameterizedLocation(previousPL);
            nextWaypoint = GetClosestWaypointFromParameterizedLocation(nextPL);
            nextSampleTime = previousWaypoint.Time;
          }
          else
          {
            previousWaypoint = nextWaypoint;
            nextWaypoint = GetClosestWaypointFromParameterizedLocation(nextPL);
          }
        }
        time = nextSampleTime;
      }
      return values;
    }

    /// <summary>
    /// Gets the values at the specified percentage when the attribute values are sorted.
    /// </summary>
    /// <param name="attribute"></param>
    /// <param name="percentage"></param>
    /// <param name="samplingInterval"></param>
    /// <returns></returns>
    public double? GetOrderedValue(WaypointAttribute attribute, double percentage, TimeSpan samplingInterval)
    {
      List<double?> list = GetMomentaneousValueList(
        attribute,
        GetParameterizedLocationFromTime(FirstWaypoint.Time),
        GetParameterizedLocationFromTime(LastWaypoint.Time),
        samplingInterval);
      list.Sort();

      var i = (int)(percentage * list.Count);
      return list[Math.Min(i, list.Count - 1)];
    }

    /// <summary>
    /// Gets the values at each percentage specified in the percentages list when the attribute values are sorted.
    /// </summary>
    /// <param name="attribute"></param>
    /// <param name="percentages"></param>
    /// <param name="samplingInterval"></param>
    /// <returns></returns>
    public List<double?> GetOrderedValues(WaypointAttribute attribute, List<double> percentages,
                                          TimeSpan samplingInterval)
    {
      List<double?> list = GetMomentaneousValueList(
        attribute,
        GetParameterizedLocationFromTime(FirstWaypoint.Time),
        GetParameterizedLocationFromTime(LastWaypoint.Time),
        samplingInterval);
      list.Sort();

      var values = new List<double?>();
      foreach (double percentage in percentages)
      {
        var i = (int)(percentage * list.Count);
        int index = Math.Min(i, list.Count - 1);
        if (index >= 0) values.Add(list[index]);
      }
      return values;
    }

    public double CalculatePaceStandardDeviation(ParameterizedLocation start, ParameterizedLocation end)
    {
      return CalculatePaceStandardDeviation(start, end, new Interval(0, 0));
    }

    public double CalculatePaceStandardDeviation(ParameterizedLocation start, ParameterizedLocation end,
                                                 Interval slidingAverageInterval)
    {
      // first collect all waypoints
      var nodes = new List<Pair<ParameterizedLocation, Waypoint>>();
      ParameterizedLocation adjustedStart = GetParameterizedLocationOfNextWaypoint(start, false);
      ParameterizedLocation adjustedEnd = GetParameterizedLocationOfPreviousWaypoint(end, false);
      var pl = new ParameterizedLocation(adjustedStart);

      if (!start.IsNode)
        nodes.Add(new Pair<ParameterizedLocation, Waypoint>(start, CreateWaypointFromParameterizedLocation(start)));
      while (pl != null && pl <= adjustedEnd)
      {
        if (pl.Value > segments[pl.SegmentIndex].Waypoints.Count - 1)
        {
          pl.SegmentIndex++;
          pl.Value = 0;
        }
        nodes.Add(new Pair<ParameterizedLocation, Waypoint>(pl, GetClosestWaypointFromParameterizedLocation(pl)));
        pl = GetNextPLNode(pl, ParameterizedLocation.Direction.Forward);
      }
      if (!end.IsNode)
        nodes.Add(new Pair<ParameterizedLocation, Waypoint>(end, CreateWaypointFromParameterizedLocation(end)));


      var paces = new List<StatisticsUtil.WeightedItem>();
      if (slidingAverageInterval.Length == 0)
      {
        for (int i = 0; i < nodes.Count; i++)
        {
          ParameterizedLocation p = nodes[i].First;
          Waypoint w = nodes[i].Second;
          double beforeWeight = (i == 0 || IsFirstPLInSegment(p)
                                   ? 0
                                   : (double)(w.Time.Ticks - nodes[i - 1].Second.Time.Ticks) / TimeSpan.TicksPerSecond / 2);
          double afterWeight = (i == nodes.Count - 1 || IsLastPLInSegment(p)
                                  ? 0
                                  : (double)(nodes[i + 1].Second.Time.Ticks - w.Time.Ticks) / TimeSpan.TicksPerSecond / 2);
          paces.Add(
            new StatisticsUtil.WeightedItem(
              beforeWeight + afterWeight,
              ConvertUtil.ToPace(segments[p.SegmentIndex].Waypoints[(int)p.Value].Attributes[WaypointAttribute.Speed].Value).TotalSeconds
              )
            );
        }
      }
      else
      {
        ParameterizedLocation siStartPL =
          GetParameterizedLocationFromTime(nodes[0].Second.Time.AddSeconds(slidingAverageInterval.Start));
        ParameterizedLocation siEndPL =
          GetParameterizedLocationFromTime(nodes[0].Second.Time.AddSeconds(slidingAverageInterval.End));
        for (int i = 0; i < nodes.Count; i++)
        {
          // start of sliding interval
          siStartPL =
            GetParameterizedLocationFromTime(nodes[i].Second.Time.AddSeconds(slidingAverageInterval.Start), siStartPL,
                                             ParameterizedLocation.Direction.Forward);
          // end of sliding interval
          siEndPL =
            GetParameterizedLocationFromTime(nodes[i].Second.Time.AddSeconds(slidingAverageInterval.End), siEndPL,
                                             ParameterizedLocation.Direction.Forward);
          if (siStartPL != null && siEndPL != null)
          {
            if (siStartPL.SegmentIndex < nodes[i].First.SegmentIndex)
              siStartPL = new ParameterizedLocation(nodes[i].First.SegmentIndex, 0);
            if (siEndPL.SegmentIndex > nodes[i].First.SegmentIndex)
              siEndPL = new ParameterizedLocation(nodes[i].First.SegmentIndex,
                                                  segments[nodes[i].First.SegmentIndex].Waypoints.Count - 1);
            ParameterizedLocation p = nodes[i].First;
            Waypoint w = nodes[i].Second;
            double pace = ConvertUtil.ToPace(w.Attributes[WaypointAttribute.Speed].Value).TotalSeconds;
            double siStartDistance = GetAttributeFromParameterizedLocation(WaypointAttribute.Distance, siStartPL).Value;
            double siEndDistance = GetAttributeFromParameterizedLocation(WaypointAttribute.Distance, siEndPL).Value;
            double siLength =
              GetTimeFromParameterizedLocation(siEndPL).Subtract(GetTimeFromParameterizedLocation(siStartPL)).
                TotalSeconds;
            double meanSpeed = (siLength == 0 ? 0 : (siEndDistance - siStartDistance) / siLength);
            double meanPace = ConvertUtil.ToPace(meanSpeed).TotalSeconds;

            double beforeWeight = (i == 0 || IsFirstPLInSegment(p)
                                     ? 0
                                     : (double)(w.Time.Ticks - nodes[i - 1].Second.Time.Ticks) / TimeSpan.TicksPerSecond /
                                       2);
            double afterWeight = (i == nodes.Count - 1 || IsLastPLInSegment(p)
                                    ? 0
                                    : (double)(nodes[i + 1].Second.Time.Ticks - w.Time.Ticks) / TimeSpan.TicksPerSecond / 2);
            paces.Add(new StatisticsUtil.WeightedItem((beforeWeight + afterWeight), pace - meanPace));
          }
        }
      }
      return StatisticsUtil.GetStandardDeviation(paces);
    }

    public double CalculateSpeedPercentualStandardDeviation(ParameterizedLocation start, ParameterizedLocation end)
    {
      return CalculateSpeedPercentualStandardDeviation(start, end, new Interval(0, 0));
    }

    public double CalculateSpeedPercentualStandardDeviation(ParameterizedLocation start, ParameterizedLocation end,
                                                            Interval slidingAverageInterval)
    {
      // first collect all waypoints
      var nodes = new List<Pair<ParameterizedLocation, Waypoint>>();
      ParameterizedLocation adjustedStart = GetParameterizedLocationOfNextWaypoint(start, false);
      ParameterizedLocation adjustedEnd = GetParameterizedLocationOfPreviousWaypoint(end, false);
      var pl = new ParameterizedLocation(adjustedStart);

      if (!start.IsNode)
        nodes.Add(new Pair<ParameterizedLocation, Waypoint>(start, CreateWaypointFromParameterizedLocation(start)));
      while (pl != null && pl <= adjustedEnd)
      {
        if (pl.Value > segments[pl.SegmentIndex].Waypoints.Count - 1)
        {
          pl.SegmentIndex++;
          pl.Value = 0;
        }
        nodes.Add(new Pair<ParameterizedLocation, Waypoint>(pl, GetClosestWaypointFromParameterizedLocation(pl)));
        pl = GetNextPLNode(pl, ParameterizedLocation.Direction.Forward);
      }
      if (!end.IsNode)
        nodes.Add(new Pair<ParameterizedLocation, Waypoint>(end, CreateWaypointFromParameterizedLocation(end)));


      var speeds = new List<StatisticsUtil.WeightedItem>();
      if (slidingAverageInterval.Length == 0)
      {
        double elapsedTime = GetAttributeFromParameterizedLocation(WaypointAttribute.ElapsedTime, LastPL).Value;
        double meanSpeed = (GetAttributeFromParameterizedLocation(WaypointAttribute.Distance, LastPL).Value - GetAttributeFromParameterizedLocation(WaypointAttribute.Distance, FirstPL).Value) /
                           (elapsedTime == 0 ? 0 : elapsedTime);
        for (int i = 0; i < nodes.Count; i++)
        {
          ParameterizedLocation p = nodes[i].First;
          Waypoint w = nodes[i].Second;
          double beforeWeight = (i == 0 || IsFirstPLInSegment(p)
                                   ? 0
                                   : (double)(w.Time.Ticks - nodes[i - 1].Second.Time.Ticks) / TimeSpan.TicksPerSecond / 2);
          double afterWeight = (i == nodes.Count - 1 || IsLastPLInSegment(p)
                                  ? 0
                                  : (double)(nodes[i + 1].Second.Time.Ticks - w.Time.Ticks) / TimeSpan.TicksPerSecond / 2);
          speeds.Add(
            new StatisticsUtil.WeightedItem(
              beforeWeight + afterWeight,
              (meanSpeed == 0 ? 0 : segments[p.SegmentIndex].Waypoints[(int)p.Value].Attributes[WaypointAttribute.Speed].Value / meanSpeed)
              )
            );
        }
      }
      else
      {
        ParameterizedLocation siStartPL =
          GetParameterizedLocationFromTime(nodes[0].Second.Time.AddSeconds(slidingAverageInterval.Start));
        ParameterizedLocation siEndPL =
          GetParameterizedLocationFromTime(nodes[0].Second.Time.AddSeconds(slidingAverageInterval.End));
        for (int i = 0; i < nodes.Count; i++)
        {
          // start of sliding interval
          siStartPL =
            GetParameterizedLocationFromTime(nodes[i].Second.Time.AddSeconds(slidingAverageInterval.Start), siStartPL,
                                             ParameterizedLocation.Direction.Forward);
          // end of sliding interval
          siEndPL =
            GetParameterizedLocationFromTime(nodes[i].Second.Time.AddSeconds(slidingAverageInterval.End), siEndPL,
                                             ParameterizedLocation.Direction.Forward);
          if (siStartPL != null && siEndPL != null)
          {
            if (siStartPL.SegmentIndex < nodes[i].First.SegmentIndex)
              siStartPL = new ParameterizedLocation(nodes[i].First.SegmentIndex, 0);
            if (siEndPL.SegmentIndex > nodes[i].First.SegmentIndex)
              siEndPL = new ParameterizedLocation(nodes[i].First.SegmentIndex,
                                                  segments[nodes[i].First.SegmentIndex].Waypoints.Count - 1);
            ParameterizedLocation p = nodes[i].First;
            Waypoint w = nodes[i].Second;
            double siStartDistance = GetAttributeFromParameterizedLocation(WaypointAttribute.Distance, siStartPL).Value;
            double siEndDistance = GetAttributeFromParameterizedLocation(WaypointAttribute.Distance, siEndPL).Value;
            double siLength =
              GetTimeFromParameterizedLocation(siEndPL).Subtract(GetTimeFromParameterizedLocation(siStartPL)).
                TotalSeconds;
            double meanSpeed = (siLength == 0 ? 0 : (siEndDistance - siStartDistance) / siLength);

            double beforeWeight = (i == 0 || IsFirstPLInSegment(p)
                                     ? 0
                                     : (double)(w.Time.Ticks - nodes[i - 1].Second.Time.Ticks) / TimeSpan.TicksPerSecond /
                                       2);
            double afterWeight = (i == nodes.Count - 1 || IsLastPLInSegment(p)
                                    ? 0
                                    : (double)(nodes[i + 1].Second.Time.Ticks - w.Time.Ticks) / TimeSpan.TicksPerSecond / 2);
            speeds.Add(new StatisticsUtil.WeightedItem((beforeWeight + afterWeight),
                                                       (meanSpeed == 0 ? 0 : w.Attributes[WaypointAttribute.Speed].Value / meanSpeed)));
          }
        }
      }
      return StatisticsUtil.GetStandardDeviation(speeds);
    }

    public double CalculateAverageDirectionDeviationToNextLap(ParameterizedLocation start, ParameterizedLocation end)
    {
      ParameterizedLocation adjustedStart = GetParameterizedLocationOfNextWaypoint(start, false);
      ParameterizedLocation adjustedEnd = GetParameterizedLocationOfPreviousWaypoint(end, false);
      DateTime previousTime = GetTimeFromParameterizedLocation(start);
      var pl = new ParameterizedLocation(adjustedStart);
      double sum = 0;
      double weightSum = 0;
      while (pl != null && pl <= adjustedEnd)
      {
        if (pl.Value > segments[pl.SegmentIndex].Waypoints.Count - 1)
        {
          pl.SegmentIndex++;
          pl.Value = 0;
          previousTime = GetTimeFromParameterizedLocation(pl);
        }
        DateTime time = GetTimeFromParameterizedLocation(pl);
        long weight = time.Ticks - previousTime.Ticks;
        sum += weight * GetAttributeFromParameterizedLocation(WaypointAttribute.DirectionDeviationToNextLap, pl).Value;
        weightSum += weight;
        previousTime = time;
        pl = GetNextPLNode(pl, ParameterizedLocation.Direction.Forward);
      }
      return (weightSum == 0 ? 0 : sum / weightSum);
    }

    /// <summary>
    /// Returns true if there are NO null values for the specified attributes in the segments.
    /// </summary>
    /// <param name="attribute"></param>
    /// <returns></returns>
    public bool ContainsWaypointAttribute(WaypointAttribute attribute)
    {
      return waypointAttributeExists[attribute];
    }

    public List<DateTime> GetMapReadingsList()
    {
      if(!waypointAttributeExists[WaypointAttribute.MapReadingDuration]) return null;
      var mapReadingsList = new List<DateTime>();
      for (var i = 0; i < segments.Count; i++)
      {
        for (var j = 0; j < segments[i].Waypoints.Count; j++)
        {
          var w = segments[i].Waypoints[j];
          if(w.MapReadingState == MapReadingState.StartReading || w.MapReadingState == MapReadingState.EndReading) mapReadingsList.Add(w.Time);
        }
      }
      return mapReadingsList.Count == 0 ? null : mapReadingsList;
    }

    #region  ParameterizedLocation helpers

    public bool IsFirstPLInSegment(ParameterizedLocation pl)
    {
      return (pl.Value <= 0);
    }

    public bool IsLastPLInSegment(ParameterizedLocation pl)
    {
      return (pl.Value >= segments[pl.SegmentIndex].Waypoints.Count - 1);
    }

    public bool IsFirstPL(ParameterizedLocation pl)
    {
      return (pl <= FirstPL);
    }

    public bool IsLastPL(ParameterizedLocation pl)
    {
      return (pl >= LastPL);
    }

    public ParameterizedLocation GetNextPLNode(ParameterizedLocation pl, ParameterizedLocation.Direction direction)
    {
      if (direction == ParameterizedLocation.Direction.Forward)
      {
        if (pl.Floor().Value + 1 > segments[pl.SegmentIndex].Waypoints.Count - 1)
        {
          if (pl.SegmentIndex + 1 > segments.Count - 1) return null;
          return new ParameterizedLocation(pl.SegmentIndex + 1, 0);
        }
        return new ParameterizedLocation(pl.SegmentIndex, pl.Floor().Value + 1);
      }
      else
      {
        if (pl.Ceiling().Value - 1 < 0)
        {
          if (pl.SegmentIndex <= 0) return null;
          return new ParameterizedLocation(pl.SegmentIndex - 1, segments[pl.SegmentIndex - 1].Waypoints.Count - 1);
        }
        return new ParameterizedLocation(pl.SegmentIndex, pl.Ceiling().Value - 1);
      }
    }

    public bool IsFirstSegment(ParameterizedLocation pl)
    {
      return (pl.SegmentIndex <= 0);
    }

    public bool IsLastSegment(ParameterizedLocation pl)
    {
      return (pl.SegmentIndex >= segments.Count - 1);
    }

    #endregion

    #endregion

    #region  Private methods

    private double GetAverageSpeed(int currentSegmentIndex, int currentWaypointIndex, DateTime startTime,
                                   DateTime endTime)
    {
      if (startTime == endTime)
      {
        // can't have zero-length interval, so make very small interval to calculate speed for
        startTime = startTime.AddMilliseconds(-0.5);
        endTime = endTime.AddMilliseconds(0.5);
      }
      if (startTime < segments[currentSegmentIndex].FirstWaypoint.Time)
        startTime = Segments[currentSegmentIndex].FirstWaypoint.Time;
      if (endTime > Segments[currentSegmentIndex].LastWaypoint.Time)
        endTime = Segments[currentSegmentIndex].LastWaypoint.Time;

      if (startTime == endTime) return 0; // same time for both first and last waypoint of this segment

      int i = currentWaypointIndex;
      List<Waypoint> waypoints = Segments[currentSegmentIndex].Waypoints;

      if (waypoints[i].Time < startTime)
      {
        while (waypoints[i].Time < startTime)
        {
          i += 1;
        }
      }
      else
      {
        while (waypoints[i].Time > startTime)
        {
          i -= 1;
        }
      }

      double distance = 0.0;
      while (waypoints[i].Time < endTime)
      {
        long ticks0 = Math.Max(startTime.Ticks, waypoints[i].Time.Ticks);
        long ticks1 = Math.Min(endTime.Ticks, waypoints[i + 1].Time.Ticks);
        long ticksDuration = waypoints[i + 1].Time.Ticks - waypoints[i].Time.Ticks;
        if (ticksDuration != 0)
        {
          double t = (ticks1 - ticks0) / (double)ticksDuration;
          distance += t * LinearAlgebraUtil.DistancePointToPointLongLat(waypoints[i].LongLat, waypoints[i + 1].LongLat);
        }
        i++;
      }

      TimeSpan timeSpan = endTime.Subtract(startTime);
      return distance / timeSpan.TotalSeconds;
    }

    private ParameterizedLocation GetParameterizedLocationOfPreviousWaypoint(
      ParameterizedLocation parameterizedLocation, bool forceAdvance)
    {
      if (!parameterizedLocation.IsNode)
      {
        return new ParameterizedLocation(parameterizedLocation.SegmentIndex, parameterizedLocation.Floor().Value);
      }
      else if (parameterizedLocation.Value > 0)
      {
        return new ParameterizedLocation(parameterizedLocation.SegmentIndex,
                                         parameterizedLocation.Value - (forceAdvance ? 1 : 0));
      }
      else if (forceAdvance && parameterizedLocation.SegmentIndex > 0)
      {
        return new ParameterizedLocation(parameterizedLocation.SegmentIndex - 1,
                                         segments[parameterizedLocation.SegmentIndex - 1].Waypoints.Count - 1);
      }
      else
      {
        return new ParameterizedLocation(parameterizedLocation.SegmentIndex, 0);
      }
    }

    private ParameterizedLocation GetParameterizedLocationOfNextWaypoint(ParameterizedLocation parameterizedLocation,
                                                                         bool forceAdvance)
    {
      if (!parameterizedLocation.IsNode)
      {
        return new ParameterizedLocation(parameterizedLocation.SegmentIndex, parameterizedLocation.Ceiling().Value);
      }
      else if (parameterizedLocation.Value < segments[parameterizedLocation.SegmentIndex].Waypoints.Count - 1)
      {
        return new ParameterizedLocation(parameterizedLocation.SegmentIndex,
                                         parameterizedLocation.Value + (forceAdvance ? 1 : 0));
      }
      else if (forceAdvance && parameterizedLocation.SegmentIndex < segments.Count - 1)
      {
        return new ParameterizedLocation(parameterizedLocation.SegmentIndex + 1, 0);
      }
      else
      {
        return new ParameterizedLocation(parameterizedLocation.SegmentIndex,
                                         segments[parameterizedLocation.SegmentIndex].Waypoints.Count - 1);
      }
    }

    private Waypoint GetClosestWaypointFromParameterizedLocation(ParameterizedLocation parameterizedLocation)
    {
      if (parameterizedLocation.SegmentIndex < 0 || parameterizedLocation.SegmentIndex > segments.Count - 1)
        return null;
      if (parameterizedLocation.Value < 0 ||
          parameterizedLocation.Value > segments[parameterizedLocation.SegmentIndex].Waypoints.Count - 1) return null;
      return segments[parameterizedLocation.SegmentIndex].Waypoints[(int)parameterizedLocation.Value];
    }

    private Waypoint GetNextWaypoint(ParameterizedLocation parameterizedLocation, bool forceAdvance)
    {
      return
        GetClosestWaypointFromParameterizedLocation(GetParameterizedLocationOfNextWaypoint(parameterizedLocation,
                                                                                           forceAdvance));
    }

    private Waypoint GetPreviousWaypoint(ParameterizedLocation parameterizedLocation, bool forceAdvance)
    {
      return
        GetClosestWaypointFromParameterizedLocation(GetParameterizedLocationOfPreviousWaypoint(parameterizedLocation,
                                                                                               forceAdvance));
    }

    // w0 and w1 are adjacent, t measured from w0
    private static double? GetAttributeValueBetweenWaypoints(Waypoint w0, Waypoint w1, double t, WaypointAttribute attribute)
    {
      switch(attribute)
      {
        case WaypointAttribute.MapReadingDuration:
          return w0.MapReadingState == MapReadingState.StartReading || w0.MapReadingState == MapReadingState.Reading 
            ? w0.Attributes[WaypointAttribute.MapReadingDuration]
            : null;
        case WaypointAttribute.MapReadingState:
          return GetAttributeValueBetweenWaypoints(w0, w1, t, WaypointAttribute.MapReadingDuration) != null ? 1 : 0;
        case WaypointAttribute.PreviousMapReadingEnd:
          return w1.Attributes[WaypointAttribute.PreviousMapReadingEnd] != null
          ? (double?)(w1.Attributes[WaypointAttribute.PreviousMapReadingEnd].Value - (1 - t) * (w1.Time - w0.Time).TotalSeconds)
          : null;
        case WaypointAttribute.NextMapReadingStart:
          return w0.Attributes[WaypointAttribute.NextMapReadingStart] != null
          ? (double?)(w0.Attributes[WaypointAttribute.NextMapReadingStart].Value - t * (w1.Time - w0.Time).TotalSeconds)
          : null;
        default:
          var d0 = w0.Attributes[attribute];
          var d1 = w1.Attributes[attribute];
          if (d0.HasValue && d1.HasValue) return d0 + t * (d1 - d0);
          if (!d0.HasValue && !d1.HasValue) return null;
          return (t < 0.5 ? d0 : d1);
      }
    }


    private void CalculateSlidingAverageAttributes(WaypointAttribute attribute, Interval smoothingInterval)
    {
      // using optimized but hard-to-understand algorithm
      if (attribute != WaypointAttribute.HeartRate && attribute != WaypointAttribute.Altitude) throw new ArgumentException("The 'attribute' parameter must be either WaypointAttribute.HeartRate or WaypointAttribute.Altitude");

      bool zeroLengthInterval = smoothingInterval.Length == 0;
      bool containsAttribute = ContainsWaypointAttribute(attribute);

      ParameterizedLocation siStartPL = null;
      ParameterizedLocation siEndPL = null;
      if (!zeroLengthInterval)
      {
        siStartPL = GetParameterizedLocationFromTime(FirstWaypoint.Time.AddSeconds(smoothingInterval.Start));
        siEndPL = GetParameterizedLocationFromTime(FirstWaypoint.Time.AddSeconds(smoothingInterval.End));
      }
      for (int i = 0; i < segments.Count; i++)
      {
        double[] valueSums = null;
        bool[] valueIsSet = null;
        DateTime[] valueTimes = null;
        var nullValueFound = false;
        if (containsAttribute && !zeroLengthInterval)
        {
          valueSums = new double[segments[i].Waypoints.Count];
          valueIsSet = new bool[segments[i].Waypoints.Count];
          valueTimes = new DateTime[segments[i].Waypoints.Count];
          valueSums[0] = 0;
          if (segments[i].Waypoints.Count > 0)
          {
            valueIsSet[0] = segments[i].Waypoints[0].GetOriginalAttribute(attribute).HasValue;
            valueTimes[0] = segments[i].Waypoints[0].Time;
            nullValueFound = !valueIsSet[0];
          }
          for (int j = 1; j < segments[i].Waypoints.Count; j++)
          {
            var previousWaypoint = segments[i].Waypoints[j - 1];
            var thisWaypoint = segments[i].Waypoints[j];
            var previousOriginalAttribute = previousWaypoint.GetOriginalAttribute(attribute);
            var thisOriginalAttribute = thisWaypoint.GetOriginalAttribute(attribute);
            valueIsSet[j] = thisOriginalAttribute.HasValue;
            valueTimes[j] = thisWaypoint.Time;
            nullValueFound = nullValueFound || !valueIsSet[j];
            if (valueIsSet[j - 1] && valueIsSet[j])
            {
              valueSums[j] = valueSums[j - 1] +
                             (valueTimes[j] - valueTimes[j - 1]).TotalSeconds *
                             (previousOriginalAttribute.Value + thisOriginalAttribute.Value) / 2;
            }
            else
            {
              valueSums[j] = valueSums[j - 1];
            }
          }
        }

        for (int j = 0; j < segments[i].Waypoints.Count; j++)
        {
          Waypoint w = segments[i].Waypoints[j];
          if (!containsAttribute)
          {
            w.Attributes[attribute] = null;
          }
          else if (zeroLengthInterval)
          {
            w.Attributes[attribute] = w.GetOriginalAttribute(attribute);
          }
          else
          {
            // start of sliding interval
            siStartPL =
              GetParameterizedLocationFromTime(w.Time.AddSeconds(smoothingInterval.Start), siStartPL,
                                               ParameterizedLocation.Direction.Forward);
            // end of sliding interval
            siEndPL =
              GetParameterizedLocationFromTime(w.Time.AddSeconds(smoothingInterval.End), siEndPL,
                                               ParameterizedLocation.Direction.Forward);
            if (siStartPL != null && siEndPL != null)
            {
              if (siStartPL.SegmentIndex < i) siStartPL = new ParameterizedLocation(i, 0);
              if (siEndPL.SegmentIndex > i) siEndPL = new ParameterizedLocation(i, segments[i].Waypoints.Count - 1);

              double startSum;
              double endSum;
              var adjustedIntervalLength = (GetTimeFromParameterizedLocation(siEndPL) - GetTimeFromParameterizedLocation(siStartPL)).TotalSeconds;
              int startIndex;
              int endIndex;
              if (siStartPL.IsNode)
              {
                startSum = valueSums[(int)siStartPL.Value];
                startIndex = (int)siStartPL.Value;
              }
              else
              {
                var d = siStartPL.Value - Math.Floor(siStartPL.Value);
                startSum = (1 - d) * valueSums[(int)siStartPL.Value] + d * valueSums[(int)siStartPL.Value + 1];
                startIndex = (int)siStartPL.Value;
              }
              if (siEndPL.IsNode)
              {
                endSum = valueSums[(int)siEndPL.Value];
                endIndex = (int)siEndPL.Value;
              }
              else
              {
                var d = siEndPL.Value - Math.Floor(siEndPL.Value);
                endSum = (1 - d) * valueSums[(int)siEndPL.Value] + d * valueSums[(int)siEndPL.Value + 1];
                endIndex = (int)siEndPL.Value + 1;
              }

              if (adjustedIntervalLength == 0)
              {
                w.Attributes[attribute] = w.GetOriginalAttribute(attribute);
              }
              else
              {
                // check if there are any null values in this interval
                bool nullValueFoundInInterval;
                if (!nullValueFound)
                {
                  // no null value in whole route, don't need to check this interval
                  nullValueFoundInInterval = false;
                }
                else
                {
                  // there is at least one null value in the route, need to check if there exists any in this interval
                  nullValueFoundInInterval = false;
                  for (var k = startIndex; k <= endIndex; k++)
                  {
                    if (!valueIsSet[k])
                    {
                      nullValueFoundInInterval = true;
                      break;
                    }
                  }
                }
                if (!nullValueFoundInInterval)
                {
                  // no null values in this interval, perform normal calculation
                  w.Attributes[attribute] = (endSum - startSum) / adjustedIntervalLength;
                }
                else
                {
                  // null value found, calculate based on each non-null value waypoint pair
                  adjustedIntervalLength = 0;
                  double sum = 0;
                  for (var k = startIndex; k < endIndex; k++)
                  {
                    if (valueIsSet[k] && valueIsSet[k + 1])
                    {
                      double start = Math.Max(k, siStartPL.Value);
                      double end = Math.Min(k + 1, siEndPL.Value);
                      adjustedIntervalLength += (end - start) * (valueTimes[k + 1] - valueTimes[k]).TotalSeconds;
                      sum += (end - start) * (valueSums[k + 1] - valueSums[k]);
                    }
                  }
                  w.Attributes[attribute] = (adjustedIntervalLength == 0 ? (double?)null : sum / adjustedIntervalLength);
                }
              }
            }
            else
            {
              w.Attributes[attribute] = null;
            }
          }
        }
      }
    }

    /// <summary>
    /// Calculates speeds and paces.
    /// </summary>
    private void CalculateSpeeds()
    {
      // using optimized but hard-to-understand algorithm
      var actualInterval = new Interval(SmoothingIntervals[WaypointAttribute.Speed]);
      if (actualInterval.Length == 0)
      {
        // need to have non-zero smothing interval when calculating speed, set it to a millisecond
        var center = actualInterval.Start;
        actualInterval = new Interval(center - 0.0005, center + 0.0005);
      }
      ParameterizedLocation siStartPL =
        GetParameterizedLocationFromTime(FirstWaypoint.Time.AddSeconds(actualInterval.Start));
      ParameterizedLocation siEndPL = GetParameterizedLocationFromTime(FirstWaypoint.Time.AddSeconds(actualInterval.End));
      for (int i = 0; i < segments.Count; i++)
      {
        for (int j = 0; j < segments[i].Waypoints.Count; j++)
        {
          Waypoint w = segments[i].Waypoints[j];
          // start of sliding interval
          siStartPL =
            GetParameterizedLocationFromTime(w.Time.AddSeconds(actualInterval.Start), siStartPL,
                                             ParameterizedLocation.Direction.Forward);
          // end of sliding interval
          siEndPL =
            GetParameterizedLocationFromTime(w.Time.AddSeconds(actualInterval.End), siEndPL,
                                             ParameterizedLocation.Direction.Forward);
          if (siStartPL != null && siEndPL != null)
          {
            if (siStartPL.SegmentIndex < i) siStartPL = new ParameterizedLocation(i, 0);
            if (siEndPL.SegmentIndex > i) siEndPL = new ParameterizedLocation(i, segments[i].Waypoints.Count - 1);
            double siStartDistance = GetAttributeFromParameterizedLocation(WaypointAttribute.Distance, siStartPL).Value;
            double siEndDistance = GetAttributeFromParameterizedLocation(WaypointAttribute.Distance, siEndPL).Value;
            double siLength = (GetTimeFromParameterizedLocation(siEndPL) - GetTimeFromParameterizedLocation(siStartPL)).TotalSeconds;
            w.Attributes[WaypointAttribute.Speed] = (siLength == 0 ? 0 : 3.6 * (siEndDistance - siStartDistance) / siLength);
          }
          else
          {
            w.Attributes[WaypointAttribute.Speed] = 0;
          }
          w.Attributes[WaypointAttribute.Pace] = ConvertUtil.ToPace(w.Attributes[WaypointAttribute.Speed].Value).TotalSeconds;
        }
      }
    }

    private void CalculateDirectionDeviationsToNextLap()
    {
      if (lapTimes.Count >= 2)
      {
        int lapIndex = 0;
        var lapStartPL = GetParameterizedLocationFromTime(lapTimes[lapIndex]);
        var lapEndPL = GetParameterizedLocationFromTime(lapTimes[lapIndex + 1]);
        // using optimized but hard-to-understand algorithm
        var actualInterval = new Interval(SmoothingIntervals[WaypointAttribute.DirectionDeviationToNextLap]);
        if (actualInterval.Length == 0)
        {
          // need to have non-zero smothing interval when calculating direction vectors, set it to a millisecond
          var center = actualInterval.Start;
          actualInterval = new Interval(center - 0.0005, center + 0.0005);
        }
        ParameterizedLocation siStartPL =
          GetParameterizedLocationFromTime(FirstWaypoint.Time.AddSeconds(actualInterval.Start));
        ParameterizedLocation siEndPL =
          GetParameterizedLocationFromTime(FirstWaypoint.Time.AddSeconds(actualInterval.End));
        for (int i = 0; i < segments.Count; i++)
        {
          // 1. calculate the direction angles in this segment, taking laps into account (never consider positions outside current lap)
          var directionAngles = new double[segments[i].Waypoints.Count];
          var startLapIndexInThisSegment = lapIndex;
          var lapStartPLInThisSegment = GetParameterizedLocationFromTime(lapTimes[lapIndex]);
          var lapEndPLInThisSegment = GetParameterizedLocationFromTime(lapTimes[lapIndex + 1]);
          for (int j = 0; j < segments[i].Waypoints.Count; j++)
          {
            Waypoint w = segments[i].Waypoints[j];
            while (w.Time > lapTimes[lapIndex] && lapIndex < lapTimes.Count - 1)
            {
              lapIndex++;
              lapStartPL = GetParameterizedLocationFromTime(lapTimes[lapIndex - 1]);
              lapEndPL = GetParameterizedLocationFromTime(lapTimes[lapIndex]);
            }

            // start of sliding interval
            siStartPL =
              GetParameterizedLocationFromTime(w.Time.AddSeconds(actualInterval.Start), siStartPL,
                                               ParameterizedLocation.Direction.Forward);
            // end of sliding interval
            siEndPL =
              GetParameterizedLocationFromTime(w.Time.AddSeconds(actualInterval.End), siEndPL,
                                               ParameterizedLocation.Direction.Forward);
            if (siStartPL != null && siEndPL != null)
            {
              if (siStartPL.SegmentIndex < i) siStartPL = new ParameterizedLocation(i, 0);
              if (siEndPL.SegmentIndex > i) siEndPL = new ParameterizedLocation(i, segments[i].Waypoints.Count - 1);
              if (siStartPL < lapStartPL) siStartPL = new ParameterizedLocation(lapStartPL);
              if (siEndPL > lapEndPL) siEndPL = new ParameterizedLocation(lapEndPL);
              var siStartLocation = GetLocationFromParameterizedLocation(siStartPL);
              var siEndLocation = GetLocationFromParameterizedLocation(siEndPL);
              var middle = (siStartLocation / 2 + siEndLocation / 2);
              var p0 = siStartLocation.Project(middle);
              var p1 = siEndLocation.Project(middle);
              directionAngles[j] = LinearAlgebraUtil.GetAngleD(LinearAlgebraUtil.Normalize(p1 - p0));
            }
            else
            {
              directionAngles[j] = 0;
            }
          }


          // 2. calculate the directions and direction deviations based on values achieved in step 1
          lapIndex = startLapIndexInThisSegment;
          lapStartPL = lapStartPLInThisSegment;
          lapEndPL = lapEndPLInThisSegment;
          var lapLongLat = GetLocationFromParameterizedLocation(GetParameterizedLocationFromTime(lapTimes[lapIndex + 1]));
          for (int j = 0; j < segments[i].Waypoints.Count; j++)
          {
            Waypoint w = segments[i].Waypoints[j];

            // direction (clockwise from north: n = 0, e = 90, s = 180, w = 270)
            var direction = -directionAngles[j] + 90;
            if (direction < 0) direction += 360;
            w.Attributes[WaypointAttribute.Direction] = direction;

            // direction deviation to next lap
            while (w.Time > lapTimes[lapIndex] && lapIndex < lapTimes.Count - 1)
            {
              lapIndex++;
              lapLongLat = GetLocationFromParameterizedLocation(GetParameterizedLocationFromTime(lapTimes[lapIndex]));
            }
            LongLat middle = (w.LongLat / 2 + lapLongLat / 2);
            PointD p0 = w.LongLat.Project(middle);
            PointD p1 = lapLongLat.Project(middle);
            PointD directionVectorToNextLap = LinearAlgebraUtil.Normalize(p1 - p0);
            w.Attributes[WaypointAttribute.DirectionDeviationToNextLap] = Math.Abs(LinearAlgebraUtil.GetAngleD(directionVectorToNextLap, LinearAlgebraUtil.CreateNormalizedVectorFromAngleD(directionAngles[j])));
          }
        }
      }
    }

    private void CalculateInclinations()
    {
      var containsAltitude = ContainsWaypointAttribute(WaypointAttribute.Altitude);
      var altitudeSmoothingInterval = new Interval(-0.005, 0.005);
      var distanceSmoothingInterval = SmoothingIntervals[WaypointAttribute.Altitude];
      if (distanceSmoothingInterval.Length == 0) distanceSmoothingInterval = altitudeSmoothingInterval;

      for (int i = 0; i < segments.Count; i++)
      {
        for (int j = 0; j < segments[i].Waypoints.Count; j++)
        {
          var waypoint = segments[i].Waypoints[j];
          if (containsAltitude)
          {
            var pl = new ParameterizedLocation(i, j);
            var startDirection = altitudeSmoothingInterval.Start < 0
                                   ? ParameterizedLocation.Direction.Backward
                                   : ParameterizedLocation.Direction.Forward;
            var endDirection = altitudeSmoothingInterval.End < 0
                                 ? ParameterizedLocation.Direction.Backward
                                 : ParameterizedLocation.Direction.Forward;

            // altitude calculations
            var altitudeStartTime = waypoint.Time.AddSeconds(altitudeSmoothingInterval.Start);
            var altitudeEndTime = waypoint.Time.AddSeconds(altitudeSmoothingInterval.End);
            var altitudeStartPL = GetParameterizedLocationFromTime(altitudeStartTime, pl, startDirection);
            var altitudeEndPL = GetParameterizedLocationFromTime(altitudeEndTime, pl, endDirection);
            if (altitudeStartPL.SegmentIndex < i)
            {
              altitudeStartPL = new ParameterizedLocation(i, 0);
              altitudeStartTime = segments[i].FirstWaypoint.Time;
            }
            if (altitudeEndPL.SegmentIndex > i)
            {
              altitudeEndPL = new ParameterizedLocation(i, segments[i].Waypoints.Count - 1);
              altitudeEndTime = segments[i].LastWaypoint.Time;
            }
            var altitudeDifference = GetAttributeFromParameterizedLocation(WaypointAttribute.Altitude, altitudeEndPL) -
                                     GetAttributeFromParameterizedLocation(WaypointAttribute.Altitude, altitudeStartPL);
            var altitudeDuration = (altitudeEndTime - altitudeStartTime).TotalSeconds;

            // distance calculations
            var distanceStartTime = waypoint.Time.AddSeconds(distanceSmoothingInterval.Start);
            var distanceEndTime = waypoint.Time.AddSeconds(distanceSmoothingInterval.End);
            var distanceStartPL = GetParameterizedLocationFromTime(distanceStartTime, pl, startDirection);
            var distanceEndPL = GetParameterizedLocationFromTime(distanceEndTime, pl, endDirection);
            if (distanceStartPL.SegmentIndex < i)
            {
              distanceStartPL = new ParameterizedLocation(i, 0);
              distanceStartTime = segments[i].FirstWaypoint.Time;
            }
            if (distanceEndPL.SegmentIndex > i)
            {
              distanceEndPL = new ParameterizedLocation(i, segments[i].Waypoints.Count - 1);
              distanceEndTime = segments[i].LastWaypoint.Time;
            }
            var distanceDifference = GetAttributeFromParameterizedLocation(WaypointAttribute.Distance, distanceEndPL) -
                                     GetAttributeFromParameterizedLocation(WaypointAttribute.Distance, distanceStartPL);
            var distanceDuration = (distanceEndTime - distanceStartTime).TotalSeconds;

            // calculate the inclination
            if (!distanceDifference.HasValue || !altitudeDifference.HasValue)
            {
              waypoint.Attributes[WaypointAttribute.Inclination] = null;
            }
            else if (altitudeDuration == 0 || distanceDuration == 0)
            {
              waypoint.Attributes[WaypointAttribute.Inclination] = 0;
            }
            else
            {
              waypoint.Attributes[WaypointAttribute.Inclination] = LinearAlgebraUtil.ToDegrees(Math.Atan2(altitudeDifference.Value / altitudeDuration, distanceDifference.Value / distanceDuration));
            }
          }
          else
          {
            waypoint.Attributes[WaypointAttribute.Inclination] = null;
          }
        }
      }
    }

    private void CalculateMapReadings()
    {
      if (waypointAttributeExists[WaypointAttribute.MapReadingDuration])
      {
        for (int i = 0; i < segments.Count; i++)
        {
          double? duration = null;
          for (int j = 0; j < segments[i].Waypoints.Count; j++)
          {
            var waypoint = segments[i].Waypoints[j];
            if (waypoint.MapReadingState == MapReadingState.StartReading)
            {
              var k = j + 1;
              while (segments[i].Waypoints[k].MapReadingState == MapReadingState.Reading) k++;
              duration = (segments[i].Waypoints[k].Time - waypoint.Time).TotalSeconds;
            }
            waypoint.Attributes[WaypointAttribute.MapReadingDuration] = duration;
            waypoint.Attributes[WaypointAttribute.MapReadingState] = duration != null ? 1 : 0;
            if (waypoint.MapReadingState == MapReadingState.EndReading)
            {
              duration = null;
            }
          }

          DateTime? previousEndReadingTime = null;
          for (int j = 0; j < segments[i].Waypoints.Count; j++)
          {
            var waypoint = segments[i].Waypoints[j];
            waypoint.Attributes[WaypointAttribute.PreviousMapReadingEnd] = previousEndReadingTime == null ? null : (double?)(waypoint.Time - previousEndReadingTime.Value).TotalSeconds;
            if (waypoint.MapReadingState == MapReadingState.EndReading)
            {
              previousEndReadingTime = waypoint.Time;
            }
          }

          DateTime? nextStartReadingTime = null;
          for (int j = segments[i].Waypoints.Count - 1; j >= 0; j--)
          {
            var waypoint = segments[i].Waypoints[j];
            waypoint.Attributes[WaypointAttribute.NextMapReadingStart] = nextStartReadingTime == null ? null : (double?)(nextStartReadingTime.Value - waypoint.Time).TotalSeconds; ;
            if (waypoint.MapReadingState == MapReadingState.StartReading)
            {
              nextStartReadingTime = waypoint.Time;
            }
          }

        }
      }
      else
      {
        for (int i = 0; i < segments.Count; i++)
        {
          for (int j = 0; j < segments[i].Waypoints.Count; j++)
          {
            var waypoint = segments[i].Waypoints[j];
            waypoint.Attributes[WaypointAttribute.MapReadingState] = null;
            waypoint.Attributes[WaypointAttribute.MapReadingDuration] = null;
            waypoint.Attributes[WaypointAttribute.PreviousMapReadingEnd] = null;
            waypoint.Attributes[WaypointAttribute.NextMapReadingStart] = null;
          }
        }
      }
    }

    private int GetNextLapIndexFromTime(DateTime time)
    {
      int lo = 0;
      int hi = lapTimes.Count - 1;
      while (hi >= lo)
      {
        int mi = (lo + hi) / 2;
        if (time < lapTimes[mi])
        {
          hi = mi - 1;
        }
        else if (time > lapTimes[mi + 1])
        {
          lo = mi + 1;
        }
        else
        {
          return Math.Min(mi + 1, lapTimes.Count - 1);
        }
      }
      return lo;
    }

    private bool CheckIfWaypointAttributeExists(WaypointAttribute attribute)
    {
      foreach (RouteSegment segment in Segments)
      {
        foreach (Waypoint waypoint in segment.Waypoints)
        {
          switch (attribute)
          {
            case WaypointAttribute.Altitude:
              if (waypoint.Altitude != null) return true;
              break;

            case WaypointAttribute.HeartRate:
              if (waypoint.HeartRate != null) return true;
              break;

            case WaypointAttribute.MapReadingDuration:
              if (waypoint.MapReadingState != null) return true;
              break;
          }
        }
      }
      return false;
    }
    #endregion

    #region Public static methods
    public static List<RouteSegment> AddMapReadingWaypoints(List<RouteSegment> routeSegments, List<DateTime> mapReadings)
    {
      if (mapReadings.Count == 0) return routeSegments;
      var newRouteSegments = new List<RouteSegment>();
      foreach (var routeSegment in routeSegments)
      {
        var newRouteSegment = new RouteSegment();
        var waypointCount = 0;
        var mapReadingIndex = -1; // just to be sure, could probably be removed
        foreach (var waypoint in routeSegment.Waypoints)
        {
          while (mapReadingIndex < mapReadings.Count - 1 && mapReadings[mapReadingIndex+1] <= waypoint.Time)
          {
            mapReadingIndex++;
          }
          var newWaypoint = waypoint.Clone();
          if (waypoint == routeSegment.FirstWaypoint)
          {
            newWaypoint.MapReadingState = mapReadingIndex % 2 == 0 ? MapReadingState.StartReading : MapReadingState.NotReading;
            newRouteSegment.Waypoints.Add(newWaypoint);
          }
          else if (waypoint == routeSegment.LastWaypoint)
          {
            newWaypoint.MapReadingState = newRouteSegment.LastWaypoint.MapReadingState == MapReadingState.StartReading || newRouteSegment.LastWaypoint.MapReadingState == MapReadingState.Reading
                                         ? MapReadingState.EndReading
                                         : MapReadingState.NotReading;
            newRouteSegment.Waypoints.Add(newWaypoint);
            break;
          }
          else
          {
            if (mapReadingIndex != -1 && mapReadings[mapReadingIndex] == newWaypoint.Time)
            {
              newWaypoint.MapReadingState = mapReadingIndex % 2 == 0 ? MapReadingState.StartReading : MapReadingState.EndReading;
            }
            else
            {
              newWaypoint.MapReadingState = mapReadingIndex % 2 == 0 ? MapReadingState.Reading : MapReadingState.NotReading;
            }
            newRouteSegment.Waypoints.Add(newWaypoint);
          }
          var nextWaypoint = routeSegment.Waypoints[waypointCount + 1];
          while (mapReadingIndex < mapReadings.Count - 1 && mapReadings[mapReadingIndex + 1] < nextWaypoint.Time)
          {
            var time = mapReadings[mapReadingIndex + 1];
            var t = (double)(time - waypoint.Time).Ticks / (nextWaypoint.Time - waypoint.Time).Ticks;
            var longLat = (1 - t) * waypoint.LongLat + t * nextWaypoint.LongLat;
            var altitude = waypoint.Altitude.HasValue && nextWaypoint.Altitude.HasValue
              ? (double?)((1 - t) * waypoint.Altitude.Value + t * nextWaypoint.Altitude.Value)
              : null;
            var heartRate = waypoint.HeartRate.HasValue && nextWaypoint.HeartRate.HasValue
              ? (double?)((1 - t) * waypoint.HeartRate.Value + t * nextWaypoint.HeartRate.Value)
              : null;
            var mapReadingState = (mapReadingIndex + 1) % 2 == 0 ? MapReadingState.StartReading : MapReadingState.EndReading;
            newRouteSegment.Waypoints.Add(new Waypoint(time, longLat, altitude, heartRate, mapReadingState));
            mapReadingIndex++;
          }
          waypointCount++;
        }
        newRouteSegments.Add(newRouteSegment);
      }
      return newRouteSegments;
    }

    #endregion

    #region Nested classes

    public class CutRouteData
    {
      private List<RouteSegment> segments = new List<RouteSegment>();

      public List<RouteSegment> Segments
      {
        get { return segments; }
        set { segments = value; }
      }

      public CutType CutType { get; set; }
      public Waypoint WaypointInsertedAtCut { get; set; }
    }

    private class TimedAttribute
    {
      public DateTime Time { get; set; }
      public double? Value { get; set; }
    }

    #endregion

    public void AddTimeOffset(TimeSpan offset)
    {
      foreach (RouteSegment segment in Segments)
      {
        foreach (Waypoint waypoint in segment.Waypoints)
        {
          waypoint.Time = waypoint.Time.Add(offset);
        }
      }
    }

    /// <summary>
    /// Returns the parameterized location of the start of the corresponding lap, given a parameterized location.
    /// </summary>
    /// <param name="pl">The parameterized location that defines the lap.</param>
    /// <returns></returns>
    public ParameterizedLocation GetLapStartParameterizedLocation(ParameterizedLocation pl)
    {
      var currentTime = GetTimeFromParameterizedLocation(pl);
      var lastLapTime = lapTimes[0];
      foreach (var lapTime in lapTimes)
      {
        if (lapTime > lastLapTime && lapTime < currentTime)
        {
          lastLapTime = lapTime;
        }
      }
      return GetParameterizedLocationFromTime(lastLapTime, pl, ParameterizedLocation.Direction.Backward);
    }

    /// <summary>
    /// Returns the parameterized location of the end of the corresponding lap, given a parameterized location.
    /// </summary>
    /// <param name="pl">The parameterized location that defines the lap.</param>
    /// <returns></returns>
    public ParameterizedLocation GetLapEndParameterizedLocation(ParameterizedLocation pl)
    {
      var currentTime = GetTimeFromParameterizedLocation(pl);
      var nextLapTime = lapTimes[lapTimes.Count - 1];
      foreach (var lapTime in lapTimes)
      {
        if (lapTime < nextLapTime && lapTime >= currentTime)
        {
          nextLapTime = lapTime;
        }
      }
      return GetParameterizedLocationFromTime(nextLapTime, pl, ParameterizedLocation.Direction.Forward);
    }
  }

  [Serializable]
  public class RouteSegment
  {
    private List<Waypoint> waypoints = new List<Waypoint>();

    public List<Waypoint> Waypoints
    {
      get { return waypoints; }
      set { waypoints = value; }
    }

    public Waypoint FirstWaypoint
    {
      get { return waypoints.Count == 0 ? null : waypoints[0]; }
    }

    public Waypoint LastWaypoint
    {
      get { return waypoints.Count == 0 ? null : waypoints[waypoints.Count - 1]; }
    }
  }

  [Serializable]
  public class Waypoint
  {
    // core data of a waypoint
    private double? altitude;
    private double? heartRate;
    private LongLat longLat;
    private DateTime time;
    private MapReadingState? mapReadingState;
    // dictionary for storing calculated (possibly smoothed) attribute values (speed, altitude, etc) of this waypoint.
    [NonSerialized]
    private Dictionary<WaypointAttribute, double?> attributes;

    public Waypoint()
    {
      attributes = new Dictionary<WaypointAttribute, double?>();
    }

    public Waypoint(DateTime time, LongLat longLat, double? altitude, double? heartRate, MapReadingState? mapReadingState)
      : this()
    {
      this.time = time;
      this.longLat = longLat;
      this.altitude = altitude;
      this.heartRate = heartRate;
      this.mapReadingState = mapReadingState;
    }

    public DateTime Time
    {
      get { return time; }
      set { time = value; }
    }

    public LongLat LongLat
    {
      get { return longLat; }
      set { longLat = value; }
    }

    public double? Altitude
    {
      get { return altitude; }
      set { altitude = value; }
    }

    public double? HeartRate
    {
      get { return heartRate; }
      set { heartRate = value; }
    }

    public MapReadingState? MapReadingState
    {
      get { return mapReadingState; }
      set { mapReadingState = value; }
    }

    public Waypoint Clone()
    {
      var newWaypoint = new Waypoint(time, longLat, altitude, heartRate, mapReadingState);
      foreach (var attributeKey in Attributes.Keys)
      {
        newWaypoint.Attributes[attributeKey] = Attributes[attributeKey];
      }
      return newWaypoint;
    }

    public Dictionary<WaypointAttribute, double?> Attributes
    {
      get
      {
        // need to ensure that this is not null due to backward compatibility
        if (attributes == null) attributes = new Dictionary<WaypointAttribute, double?>();
        return attributes;
      }
    }

    /// <summary>
    /// Returns the original heart rate or altitude.
    /// </summary>
    /// <param name="attribute">Must be WaypointAttribute.HeartRate or WaypointAttribute.Altitude</param>
    /// <returns></returns>
    public double? GetOriginalAttribute(WaypointAttribute attribute)
    {
      if (attribute != WaypointAttribute.HeartRate && attribute != WaypointAttribute.Altitude) throw new ArgumentException("The 'attribute' parameter must be either WaypointAttribute.HeartRate or WaypointAttribute.Altitude.");
      switch (attribute)
      {
        case WaypointAttribute.HeartRate:
          return HeartRate;
        case WaypointAttribute.Altitude:
          return Altitude;
      }
      return null;
    }

  }
}