File: interval_tree.h

package info (click to toggle)
seqan2 2.4.0%2Bdfsg-17
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 224,224 kB
  • sloc: cpp: 256,886; ansic: 91,672; python: 8,330; sh: 995; xml: 570; makefile: 255; awk: 51; javascript: 21
file content (1914 lines) | stat: -rw-r--r-- 60,520 bytes parent folder | download | duplicates (6)
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
// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2018, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Anne-Katrin Emde <emde@fu-berlin.de>
// ==========================================================================


// TODO(holtgrew): Bring back random center computation using new random module?

// (weese:) This header needs improvement
//
// documentation lacks:
//   - is createIntervalTree clearing the tree first (what happens after a second call of createIntervalTree?)
//   - where is clear(itree)?
//   - some flags are missing in the dddoc entries, e.g. ..cat:, class:, or ..type: of arguments
//
// interface flaws:
//   - there are 2 interfaces for createIntervalTree
//      - based on IntervalTree
//      - based on Graph and PropertyMap (should be removed)
//   - addInterval


#ifndef SEQAN_HEADER_MISC_INTERVAL_TREE_H
#define SEQAN_HEADER_MISC_INTERVAL_TREE_H

#include <seqan/graph_types.h>


namespace seqan {
//////////////////////////////////////////////////////////////////////////////
// Graph - Interval Tree Types
//////////////////////////////////////////////////////////////////////////////

///---------------------------------------------------------------///

//////////////////// Interval and ID type ///////////////////

// TODO(holtgrew): Are these actual the first/last or begin/end entries?

/*!
 * @class IntervalAndCargo
 * @headerfile <seqan/misc/interval_tree.h>
 * @brief A simple record type that stores an interval and a cargo value.
 *
 * @signature template <[typename TValue[, typename TCargo]]>
 *            class IntervalAndCargo;
 *
 * @tparam TValue The value type.  Default: <tt>int</tt>.
 * @tparam TCargo The cargo type.  Default: <tt>int</tt>.
 *
 * @fn IntervalAndCargo::IntervalAndCargo
 * @brief Constructor
 *
 * @signature IntervalAndCargo::IntervalAndCargo();
 * @signature IntervalAndCargo::IntervalAndCargo(i1, i2, cargo);
 *
 * @param[in] i1    The first element in the interval.
 * @param[in] i2    The last element in the interval.
 * @param[in] cargo The cargo to store together with the interval.
 *
 * @var TValue IntervalAndCargo::i1;
 * @brief The first element in the interval.
 *
 * @var TValue IntervalAndCargo::i2;
 * @brief The last element in the interval.
 *
 * @var TCargo IntervalAndCargo::cargo;
 * @brief The stored cargo.
 */

template <typename TValue = int, typename TCargo = int>
class IntervalAndCargo
{
public:
    TValue i1;

    TValue i2;

    TCargo cargo;

    IntervalAndCargo() :
        i1(), i2(), cargo()
    {}

    IntervalAndCargo(TValue i1, TValue i2, TCargo cargo) :
        i1(i1), i2(i2), cargo(cargo)
    {
    }

};



/////////////////////// Point and ID type ////////////////

/*!
 * @class PointAndCargo
 * @headerfile <seqan/misc/interval_tree.h>
 * @brief Simple record class storing a point (one-value) interval and cargo.
 *
 * @signature template <[typename TValue[, typename TCargo]]>
 *            class PointAndCargo;
 *
 * @tparam TValue The value type.
 * @tparam TCargo The cargo type.
 *
 * @fn PointAndCargo::PointAndCargo
 * @brief Constructor
 *
 * @signature PointAndCargo::PointAndCargo();
 * @signature PointAndCargo::PointAndCargo(point, cargo);
 *
 * @param[in] point The point to store.
 * @param[in] cargo The cargo to store.
 *
 * @var TValue PointAndCargo::point
 * @brief The point to store.
 *
 * @var TCargo PointAndCargo::cargo
 * @brief The cargo to store.
 */

template <typename TValue = int, typename TCargo = int>
class PointAndCargo
{
public:
    TValue point;

    TCargo cargo;

    PointAndCargo() :
        point(), cargo()
    {}

    PointAndCargo(TValue point, TCargo cargo) :
        point(point), cargo(cargo)
    {}
};

///////////////////////////////////////////////////////////////////////////
/////////////////////////// IntervalTreeNode    ///////////////////////////

/*!
 * @defgroup IntervalTreeNodeTypeTags IntervalTree Node Types Tags
 * @brief Tags to select the node type for @link IntervalTree @endlink.
 *
 * @tag IntervalTreeNodeTypeTags#StorePointsOnly
 * @headerfile <seqan/misc/interval_tree.h>
 * @signature struct StorePointsOnly {};
 * @brief The tree nodes store points.
 *
 * @tag IntervalTreeNodeTypeTags#StoreIntervals
 * @headerfile <seqan/misc/interval_tree.h>
 * @signature struct StoreIntervals {};
 * @brief The tree nodes store intervals.
 */

struct StorePointsOnly {};


struct StoreIntervals {};

/*!
 * @class IntervalTreeNode
 * @headerfile <seqan/misc/interval_tree.h>
 * @brief Element of @link IntervalTree @endlink.
 *
 * @signature template <typename TInterval[, typename TSpec]>
 *            class IntervalTreeNode;
 *
 * @tparam TInterval The type to use for intervals.
 * @tparam TSpec     The specializing tag.  Default: @link IntervalTreeNodeTypeTags#StorePointsOnly @endlink.
 */


template <typename TInterval, typename TSpec = StorePointsOnly>
class IntervalTreeNode;

/*!
 * @class StoreIntervalsIntervalTreeNode
 * @extends IntervalTreeNode
 * @headerfile <seqan/misc/interval_tree.h>
 * @brief An IntervalTreeNode that stores intervals explicitely in each node.
 *
 * @signature template <typename TInterval>
 *            class IntervalTreeNode<TInterval, StoreIntervals>;
 *
 * @tparam TInterval The Interval type to use.
 */

/*!
 * @var TValue StoreIntervalsIntervalTreeNode::center;
 * @brief Center of the interval tree node.
 *
 * @var TString StoreIntervalsIntervalTreeNode::list1;
 * @brief @link AllocString @endlink of intervals sorted by begin point.
 *
 * @var TString StoreIntervalsIntervalTreeNode::list;
 * @brief @link AllocString @endlink of intervals sorted by end point.
 */

template <typename TInterval>
class IntervalTreeNode<TInterval, StoreIntervals>
{
public:
    typedef typename Value<TInterval>::Type TValue;

    TValue center;
    String<TInterval> list1;
    String<TInterval> list2;

    IntervalTreeNode() :
        center()
    {}
};

/*!
 * @class StorePointsOnlyIntervalTreeNode
 * @extends IntervalTreeNode
 * @headerfile <seqan/misc/interval_tree.h>
 * @brief An IntervalTreeNode that stores only the relevant points in each node.
 *
 * Only the end points of the intervals in the list sorted by endpoints (list2) and only the begin point of the interval
 * list sorted by begin points (list1) are stored.
 *
 * @signature template <typename TInterval>
 *            class IntervalTreeNode<TInterval, StoreIntervals>;
 *
 * @tparam TInterval The Interval type to use.
 */

/*!
 * @var TValue StorePointsOnlyIntervalTreeNode::center;
 * @brief Center of the interval.
 *
 * @var TString StorePointsOnlyIntervalTreeNode::list1;
 * @brief Points with cargo sorted by the begin points.
 *
 * @var TString StorePointsOnlyIntervalTreeNode::list2;
 * @brief Points with cargo sorted by the end points.
 */

template <typename TInterval>
class IntervalTreeNode<TInterval, StorePointsOnly>
{
public:
    typedef typename Cargo<TInterval>::Type TCargo;
    typedef typename Value<TInterval>::Type TValue;

    TValue center;
    String<PointAndCargo<TValue, TCargo> > list1;
    String<PointAndCargo<TValue, TCargo> > list2;

    IntervalTreeNode() :
        center()
    {
    }

    IntervalTreeNode(IntervalTreeNode const & other) :
        center(other.center),
        list1(other.list1),
        list2(other.list2)
    {
    }

};





//////////////////////////////////////////////////////////////////////////////
// Graph - Interval Tree
//////////////////////////////////////////////////////////////////////////////

/*!
 * @class IntervalTree
 * @headerfile <seqan/misc/interval_tree.h>
 * @brief Data structure for efficient interval storage.
 *
 * @signature template <[typename TValue[, typename TCargo]]>
 *            class IntervalTree;
 *
 * @tparam TValue The type to use for coordinates.  Default: <tt>int</tt>.
 * @tparam TCargo The type to use for cargo.  Default: <tt>unsigned</tt>.
 *
 * @section Remarks
 *
 * If the intervals are not associated with cargos/IDs, they will be numbered consecutively.
 *
 * @section Example
 *
 * The following example creates an integer interval tree with string keys.  This tree is quired for keys of intervals
 * that overlap the interval <tt>[550, 990)</tt>.
 *
 * @include demos/dox/misc/interval_tree_example.cpp
 *
 * The resulting keys are:
 *
 * @code{.console}
 * gene
 * exon2
 * coding2
 * @endcode
 *
 *
 * @fn IntervalTree::IntervalTree
 * @brief Constructor
 *
 * @signature IntervalTree::IntervalTree();
 * @signature IntervalTree::IntervalTree(intervals);
 * @signature IntervalTree::IntervalTree(intervals[, center]);
 * @signature IntervalTree::IntervalTree(intervals[, tag]);
 * @signature IntervalTree::IntervalTree(intervalBegins, intervalEnds, [intervalCargos,] len);
 *
 * @param[in] intervals Container of intervals.  A strin gof <tt>IntervalAndCargo&lt;Value, TCargo&gt;</tt>
 *                      objects, see @link IntervalAndCargo @endlink.
 * @param[in] intervalBegins
 *                      Iterator pointing to begin position of first interval.
 * @param[in] intervalEnds
 *                      Iterator pointing to end position of first interval.
 * @param[in] intervalCargos
 *                      Iterator pointing to cargo/ids for intervals.
 * @param[in] len       Number of intervals to store in tree.
 * @param[in] tag       Tag for tree construction method.
 */

template <typename TValue = int, typename TCargo = unsigned int>
class IntervalTree
{
public:
    typedef Graph<Directed<void, WithoutEdgeId> > TGraph;
    typedef IntervalAndCargo<TValue, TCargo> TInterval;
    typedef IntervalTreeNode<TInterval> TNode;
    typedef String<TNode> TPropertyMap;

    TGraph g;
    TPropertyMap pm;
    size_t interval_counter;

    IntervalTree()
    {
            interval_counter = 0;
    }

    template <typename TIterator, typename TCargoIterator>
    IntervalTree(TIterator interval_begins,
                 TIterator interval_ends,
                 TCargoIterator interval_cargos,
                 size_t len)
    {
        String<TInterval> intervals;
        resize(intervals, len);
        size_t i = 0;
        while (i < len)
        {
            intervals[i].i1 = value(interval_begins);
            ++interval_begins;
            intervals[i].i2 = value(interval_ends);
            ++interval_ends;
            intervals[i].cargo = value(interval_cargos);
            ++interval_cargos;
            ++i;
        }
        createIntervalTree(*this, intervals);
    }

    template <typename TIterator>
    IntervalTree(TIterator interval_begins,
                 TIterator interval_ends,
                 size_t len)
    {
        String<TInterval> intervals;
        resize(intervals, len);
        size_t i = 0;
        while (i < len)
        {
            intervals[i].i1 = value(interval_begins);
            ++interval_begins;
            intervals[i].i2 = value(interval_ends);
            ++interval_ends;
            intervals[i].cargo = i;
            ++i;
        }
        createIntervalTree(*this, intervals);
    }

    IntervalTree(String<TInterval> intervals)
    {
            createIntervalTree(*this, intervals);
    }

    template <typename TTagSpec>
    IntervalTree(String<TInterval> intervals, Tag<TTagSpec> const tag)
    {
            interval_counter = length(intervals);
        createIntervalTree(g, pm, intervals, tag);
    }

    IntervalTree(String<TInterval> intervals, TValue center)
    {
            interval_counter = length(intervals);
        createIntervalTree(g, pm, intervals, center);
    }

};



///////Specs for the way interval centers are determined

//template <typename TSpec = SpecPointAndCargo>
struct TagComputeCenter_;
typedef Tag<TagComputeCenter_> const ComputeCenter;


///////////////////////////////////////////////////////////////////////////
///////////////////// IntervalAndCargo functions //////////////////////////
///////////////////////////////////////////////////////////////////////////

/*!
 * @fn IntervalAndCargo#leftBoundary
 * @brief Access to left boundary.
 *
 * @signature TBoundary leftBoundary(interval);
 *
 * @param[in] interval The IntervalAndCargo to query for its left boundary.
 *
 * @return TBoundary Reference to the left boundary value.
 */

template <typename TValue, typename TCargo>
TValue &
leftBoundary(IntervalAndCargo<TValue, TCargo> & interval)
{
    return interval.i1;
}

template <typename TValue, typename TCargo>
TValue const &
leftBoundary(IntervalAndCargo<TValue, TCargo> const & interval)
{
    return interval.i1;
}

/*!
 * @fn IntervalAndCargo#rightBoundary
 * @brief Access to right boundary.
 *
 * @signature TBoundary rightBoundary(interval);
 *
 * @param[in] interval The IntervalAndCargo to query for its right boundary.
 *
 * @return TBoundary Reference to the right boundary value.
 */

template <typename TValue, typename TCargo>
TValue &
rightBoundary(IntervalAndCargo<TValue, TCargo> & interval)
{
    return interval.i2;
}

template <typename TValue, typename TCargo>
TValue const &
rightBoundary(IntervalAndCargo<TValue, TCargo> const & interval)
{
    return interval.i2;
}

/*!
 * @fn IntervalAndCargo#getLeftBoundary
 * @brief Access to getLeft boundary.
 *
 * @signature TBoundary getLeftBoundary(interval);
 *
 * @param[in] interval The IntervalAndCargo to query for its left boundary.
 *
 * @return TBoundary Copy of the left boundary value.
 */

template <typename TValue, typename TCargo>
TValue
getLeftBoundary(IntervalAndCargo<TValue, TCargo> const & interval)
{
    return interval.i1;
}

/*!
 * @fn IntervalAndCargo#getRightBoundary
 * @brief Access to getRight boundary.
 *
 * @signature TBoundary getRightBoundary(interval);
 *
 * @param[in] interval The IntervalAndCargo to query for its right boundary.
 *
 * @return TBoundary Copy of the right boundary value.
 */

template <typename TValue, typename TCargo>
TValue
getRightBoundary(IntervalAndCargo<TValue, TCargo> const & interval)
{
    return interval.i2;
}

/*!
 * @fn IntervalAndCargo#cargo
 * @brief Access to the cargo.
 *
 * @signature TCargo cargo(interval);
 *
 * @param[in] interval The IntervalAndCargo to query for its cargo.
 *
 * @return TCargo Reference to the cargo member.
 */

template <typename TValue, typename TCargo>
TCargo const &
cargo(IntervalAndCargo<TValue, TCargo> const & interval)
{
    return interval.cargo;
}

template <typename TValue, typename TCargo>
TCargo &
cargo(IntervalAndCargo<TValue, TCargo> & interval)
{
    return interval.cargo;
}

/*!
 * @fn IntervalAndCargo#getCargo
 * @brief Access to the cargo.
 *
 * @signature TCargo getCargo(interval);
 *
 * @param[in] interval The IntervalAndCargo to query for its cargo.
 *
 * @return TCargo Copy of the cargo member.
 */

template <typename TValue, typename TCargo>
TCargo
getCargo(IntervalAndCargo<TValue, TCargo> const & interval)
{
    return interval.cargo;
}

/////////////////// Metafunctions //////////////////////

/*!
 * @mfn IntervalAndCargo#Value
 * @brief Return the value type.
 *
 * @signature Value<TIntervalAndCargo>::Type;
 */

template <typename TValue, typename TCargo>
struct Value<IntervalAndCargo<TValue, TCargo> >
{
    typedef TValue Type;
};

/*!
 * @mfn IntervalAndCargo#Cargo
 * @brief Return the cargo type.
 *
 * @signature Cargo<TIntervalAndCargo>::Type;
 */

template <typename TValue, typename TCargo>
struct Cargo<IntervalAndCargo<TValue, TCargo> >
{
    typedef TCargo Type;
};


///////////////////////////////////////////////////////////////////////////
///////////////////// PointAndCargo functions /////////////////////////////
///////////////////////////////////////////////////////////////////////////

/*!
 * @fn PointAndCargo#leftBoundary
 * @brief Access to left boundary.
 *
 * @signature TBoundary leftBoundary(point);
 *
 * @param[in] point The PointAndCargo to query for its left boundary.
 *
 * @return TBoundary Reference to the left boundary value.
 */

template <typename TValue, typename TCargo>
TValue const &
leftBoundary(PointAndCargo<TValue, TCargo> const & point)
{
    return point.point;
}

template <typename TValue, typename TCargo>
TValue &
leftBoundary(PointAndCargo<TValue, TCargo> & point)
{
    return point.point;
}

/*!
 * @fn PointAndCargo#rightBoundary
 * @brief Access to right boundary.
 *
 * @signature TBoundary rightBoundary(point);
 *
 * @param[in] point The PointAndCargo to query for its right boundary.
 *
 * @return TBoundary Reference to the right boundary value.
 */

template <typename TValue, typename TCargo>
TValue const &
rightBoundary(PointAndCargo<TValue, TCargo> const & point)
{
    return point.point;
}

template <typename TValue, typename TCargo>
TValue &
rightBoundary(PointAndCargo<TValue, TCargo> & point)
{
    return point.point;
}

template <typename TValue, typename TCargo>
TValue
getLeftBoundary(PointAndCargo<TValue, TCargo> const & point)
{
    return point.point;
}

/*!
 * @fn PointAndCargo#getLeftBoundary
 * @brief Access to getLeft boundary.
 *
 * @signature TBoundary getLeftBoundary(point);
 *
 * @param[in] point The PointAndCargo to query for its left boundary.
 *
 * @return TBoundary Copy of the left boundary value.
 */

template <typename TValue, typename TCargo>
TValue
getRightBoundary(PointAndCargo<TValue, TCargo> const & point)
{
    return point.point;
}

/*!
 * @fn PointAndCargo#cargo
 * @brief Access to the cargo.
 *
 * @signature TCargo cargo(point);
 *
 * @param[in] point The PointAndCargo to query for its cargo.
 *
 * @return TCargo Reference to the cargo member.
 */


template <typename TValue, typename TCargo>
TCargo const &
cargo(PointAndCargo<TValue, TCargo> const & point)
{
    return point.cargo;
}

template <typename TValue, typename TCargo>
TCargo &
cargo(PointAndCargo<TValue, TCargo> & point)
{
    return point.cargo;
}

/*!
 * @fn PointAndCargo#getCargo
 * @brief Access to the cargo.
 *
 * @signature TCargo getCargo(point);
 *
 * @param[in] point The PointAndCargo to query for its cargo.
 *
 * @return TCargo Copy of the cargo member.
 */

template <typename TValue, typename TCargo>
TCargo
getCargo(PointAndCargo<TValue, TCargo> const & point)
{
    return point.cargo;
}

////////////////// Metafunctions //////////////////

/*!
 * @mfn PointAndCargo#Value
 * @brief Return the value type.
 *
 * @signature Value<TPointAndCargo>::Type;
 */

template <typename TValue, typename TCargo>
struct Value<PointAndCargo<TValue, TCargo> >
{
    typedef TValue Type;
};

/*!
 * @mfn PointAndCargo#Cargo
 * @brief Return the cargo type.
 *
 * @signature Cargo<TPointAndCargo>::Type;
 */

template <typename TValue, typename TCargo>
struct Cargo<PointAndCargo<TValue, TCargo> >
{
    typedef TCargo Type;
};


//// Comparators
template <typename TPair>
bool _less_compI1_ITree(TPair const & p1, TPair const & p2)
{
    return leftBoundary(p1) < leftBoundary(p2);
}

template <typename TPair>
bool _greater_compI2_ITree(TPair const & p1, TPair const & p2)
{
    return rightBoundary(p1) > rightBoundary(p2);
}

///////////////////////////////////////////////////////////////////////////
///////////////////// IntervalTreeNode functions //////////////////////////
///////////////////////////////////////////////////////////////////////////





// internal set node functions
template <typename TValue, typename TInterval>
void
_setIntervalTreeNode(IntervalTreeNode<TInterval, StoreIntervals> & knot, TValue center, TInterval const & interval)
{
    knot.center = center;
    appendValue(knot.list1, interval);
    appendValue(knot.list2, interval);
}

// append intervals to lists in node knot
template <typename TInterval>
void
_appendIntervalTreeNodeLists(IntervalTreeNode<TInterval, StoreIntervals> & knot, TInterval const & interval)
{
    appendValue(knot.list1, interval);
    appendValue(knot.list2, interval);
}

//internal set node functions
template <typename TValue, typename TInterval>
void
_setIntervalTreeNode(IntervalTreeNode<TInterval, StorePointsOnly> & knot, TValue center, TInterval const & interval)
{
    knot.center = center;
    appendValue(knot.list1, PointAndCargo<TValue, typename Cargo<TInterval>::Type>(leftBoundary(interval), cargo(interval)));
    appendValue(knot.list2, PointAndCargo<TValue, typename Cargo<TInterval>::Type>(rightBoundary(interval), cargo(interval)));
}

template <typename TInterval>
void
_appendIntervalTreeNodeLists(IntervalTreeNode<TInterval, StorePointsOnly> & knot, TInterval const & interval)
{
    appendValue(knot.list1, PointAndCargo<typename Value<TInterval>::Type, typename Cargo<TInterval>::Type>(leftBoundary(interval), cargo(interval)));
    appendValue(knot.list2, PointAndCargo<typename Value<TInterval>::Type, typename Cargo<TInterval>::Type>(rightBoundary(interval), cargo(interval)));


}

/////////////////// Metafunctions ///////////////////////

/*!
 * @mfn IntervalTreeNode#Value
 * @brief Return value type.
 *
 * @signature Value<TNode>::Type;
 */

template <typename TInterval, typename TSpec>
struct Value<IntervalTreeNode<TInterval, TSpec> >
{
    typedef typename Value<TInterval>::Type Type;
};

/*!
 * @mfn IntervalTreeNode#Cargo
 * @brief Return cargo type.
 *
 * @signature Cargo<TNode>::Type;
 */

template <typename TInterval, typename TSpec>
struct Cargo<IntervalTreeNode<TInterval, TSpec> >
{
    typedef typename Cargo<TInterval>::Type Type;
};


/*!
 * @mfn IntervalTreeNode#ListType
 * @brief Type of the lists in tree nodes.
 *
 * @signature ListType<T>::Type;
 */

template <typename T>
struct ListType;


template <typename TInterval>
struct ListType<IntervalTreeNode<TInterval, StorePointsOnly> >
{
    typedef String<PointAndCargo<typename Value<TInterval>::Type, typename Cargo<TInterval>::Type> > Type;

};


template <typename TInterval>
struct ListType<IntervalTreeNode<TInterval, StoreIntervals> >
{
    typedef String<IntervalAndCargo<typename Value<TInterval>::Type, typename Cargo<TInterval>::Type> > Type;

};



///////////////////////////////////////////////////////////////////////////
/////////////////////// IntervalTree functions ////////////////////////////
///////////////////////////////////////////////////////////////////////////

/*!
 * @fn IntervalTree#createIntervalTree
 * @brief Create an interval tree.
 *
 * @signature void createIntervalTree(intervalTree, intervals[, tag]);
 * @signature void createIntervalTree(g, pm, intervals[, tag]);
 * @signature void createIntervalTree(g, pm, intervals, center[, tag]]);
 *
 * @param[in,out] intervalTree An interval tree Types: IntervalTree
 * @param[in,out] g            DirectedGraph to create interval tree in. Types: @link Graph @endlink.
 * @param[in,out] pm           Property map to use for the created interval tree.
 * @param[in]     tag          Tag for tree construction method;
 * @param[in]     intervals    Container of intervals.  A string of <tt>IntervalAndCargo&lt;TValue, TCargo&gt;</tt>
 *                             objects, see @link IntervalAndCargo @endlink. Types: @link AllocString @endlink.
 */

template <typename TGraph, typename TPropertyMap, typename TIntervals, typename TSpec>
inline void
createIntervalTree(TGraph & g,
                   TPropertyMap & pm,
                   TIntervals & intervals,
                   Tag<TSpec> const tag)
{
    typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor;
    typedef typename Value<TIntervals>::Type TInterval;
    typedef typename Value<TInterval>::Type TValue;

    reserve(g.data_vertex, length(intervals));
    reserve(pm, length(intervals));

    TVertexDescriptor root = addVertex(g);
    resizeVertexMap(pm, g);

    if (length(intervals) > 0u)
    {
        TValue center = _calcIntervalTreeRootCenter(intervals);

        std::sort(begin(intervals, Standard()), end(intervals, Standard()), _less_compI1_ITree<TInterval>);

        String<TInterval *> interval_pointers;
        // interval tree stores pointers to intervals, not original intervals
        _makePointerInterval(intervals, interval_pointers);

        _createIntervalTree(g, pm, interval_pointers, root, (TValue)0.0, center, length(intervals), tag);
        reserve(pm, length(pm), Exact());
        reserve(g.data_vertex, length(g.data_vertex), Exact());
    }
}

template <typename TGraph, typename TPropertyMap, typename TIntervals>
inline void
createIntervalTree(TGraph & g,
                   TPropertyMap & pm,
                   TIntervals & intervals)
{
    createIntervalTree(g, pm, intervals, ComputeCenter());
}

template <typename TGraph, typename TPropertyMap, typename TIntervals, typename TSpec>
inline void
createIntervalTree(TGraph & g,
                   TPropertyMap & pm,
                   TIntervals & intervals,
                   typename Value<typename Value<TIntervals>::Type>::Type center,
                   Tag<TSpec> const tag)
{
    typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor;
    typedef typename Value<TIntervals>::Type TInterval;
    typedef typename Value<typename Value<TIntervals>::Type>::Type TValue;

    reserve(g.data_vertex, length(intervals));
    reserve(pm, length(intervals));

    TVertexDescriptor root = addVertex(g);
    resizeVertexMap(pm, g);

    if (length(intervals) > 0u)
    {
        TInterval a;
        typename Iterator<TIntervals, Standard>::Type begin_ = begin(intervals, Standard());
        typename Iterator<TIntervals, Standard>::Type end_ = end(intervals, Standard());
        std::sort(begin_, end_, _less_compI1_ITree<TInterval>);

        String<TInterval const *> interval_pointers;
        _makePointerInterval(intervals, interval_pointers);

        if (length(intervals) == 1) // if there is just one interval ->  center = center of this interval
            center = (rightBoundary(intervals[0]) - leftBoundary(intervals[0])) / (TValue)2.0;

        _createIntervalTree(g, pm, interval_pointers, root, (TValue)0.0, center, length(intervals), tag);

        reserve(pm, length(pm), Exact());
        reserve(g.data_vertex, length(g.data_vertex), Exact());
    }
}

// ComputeCenter tag as default construction method
template <typename TGraph, typename TPropertyMap, typename TIntervals>
inline void
createIntervalTree(TGraph & g, TPropertyMap & pm,
                   TIntervals & intervals,
                   typename Value<typename Value<TIntervals>::Type>::Type center)
{
    createIntervalTree(g, pm, intervals, center, ComputeCenter());
}

template <typename TValue, typename TCargo, typename TIntervals, typename TSpec>
inline void
createIntervalTree(IntervalTree<TValue, TCargo> & it,
                   TIntervals & intervals,
                   Tag<TSpec> const tag)
{
    it.interval_counter = length(intervals);
    createIntervalTree(it.g, it.pm, intervals, tag);
}

template <typename TValue, typename TCargo, typename TIntervals>
inline void
createIntervalTree(IntervalTree<TValue, TCargo> & it,
                   TIntervals & intervals)
{
    createIntervalTree(it, intervals, ComputeCenter());
}

//////////////////////////////////////////////////////////////////////////////
//remembers minimum and maximum of point values in intervals and sets the center
//of each node to min+(max-min)/2
template <typename TGraph, typename TPropertyMap, typename TIntervalPointer, typename TValue>
inline void
_createIntervalTree(TGraph & g, TPropertyMap & pm,
                    String<TIntervalPointer *> & intervals,
                    typename VertexDescriptor<TGraph>::Type & knot,
                    TValue,
                    TValue center,
                    typename VertexDescriptor<TGraph>::Type len,
                    Tag<TagComputeCenter_> const tag)
{
    //  Rekursionsanker
    if (len == 1)
    {
        _setIntervalTreeNode(value(pm, knot), center, *intervals[0]);
        return;
    }

    typedef typename Value<TPropertyMap>::Type TNode;
    typedef typename ListType<TNode>::Type TList;
    typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor;
    typedef String<TIntervalPointer *> TIntervalPointers;

    // one list of interval pointers for the intervals to the left of center
    TIntervalPointers S_left;
    // one list of interval pointers for the intervals to the right of center
    TIntervalPointers S_right;

    TValue min1 = std::numeric_limits<TValue>::max();
    TValue min2 = std::numeric_limits<TValue>::max();
    TValue max1 = std::numeric_limits<TValue>::min();
    TValue max2 = std::numeric_limits<TValue>::min();

    value(pm, knot).center = center;


    typedef typename Iterator<TIntervalPointers, Standard>::Type TIntervalIterator;
    TIntervalIterator it = begin(intervals, Standard());
    TIntervalIterator it_end = end(intervals, Standard());

    // walk through intervals
    while (it != it_end)
    {
        // interval belongs to the left list
        if ((**it).i2 <= center)
        {
            appendValue(S_left, *it, Generous());
            //remember right most and left most point in left list
            if ((**it).i2 > max1)
                max1 = (**it).i2;
            if ((**it).i1 < min1)
                min1 = (**it).i1;
        }
        else
        {
            // interval belongs to the right list
            if ((**it).i1 > center)
            {
                appendValue(S_right, (*it), Generous());
                //remember right most and left most point in right list
                if ((**it).i2 > max2)
                    max2 = (**it).i2;
                if ((**it).i1 < min2)
                    min2 = (**it).i1;
            }
            else // interval belongs to this node
            {
                _appendIntervalTreeNodeLists(value(pm, knot), **it);
            }
        }
        ++it;
    }

//    std::sort(begin(value(pm,knot).list1),end(value(pm,knot).list1),_less_compI1_ITree<typename Value<TList>::Type>);
    std::sort(begin(value(pm, knot).list2), end(value(pm, knot).list2), _greater_compI2_ITree<typename Value<TList>::Type>);

    // build subtree to the left
    if (!empty(S_left))
    {
        TVertexDescriptor vd = addVertex(g);
        resize(pm, vd + 1);
        addEdge(g, knot, vd);
        _createIntervalTree(g, pm, S_left, vd, center, min1 + (max1 - min1) / 2, length(S_left), tag);
    }
    // build subtree to the right
    if (!empty(S_right))
    {
        TVertexDescriptor vd = addVertex(g);
        resize(pm, vd + 1);
        addEdge(g, knot, vd);
        _createIntervalTree(g, pm, S_right, vd, center, min2 + (max2 - min2) / 2, length(S_right), tag);
    }
}

//////////////////////////////////////////////////////////////////////////////
//createIntervalTree for all specs except CompCenter, the center value of each
//node is determined by functions _calcIntervalTreeNodeCenterLeft and
//_calcIntervalTreeNodeCenterRight
template <typename TGraph, typename TPropertyMap, typename TSpec, typename TInterval, typename TValue>
inline void
_createIntervalTree(TGraph & g, TPropertyMap & pm,
                    String<TInterval *> & intervals,
                    typename VertexDescriptor<TGraph>::Type & knot,
                    TValue last_center, TValue center,
                    typename VertexDescriptor<TGraph>::Type len,
                    Tag<TSpec> const tag)
{
    // Rekursionsanker
    if (len == 1)
    {
        _setIntervalTreeNode(value(pm, knot), center, *value(intervals, 0));
        return;
    }

    typedef typename Value<TPropertyMap>::Type TNode;
    typedef typename ListType<TNode>::Type TList;
    typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor;
    typedef String<TInterval *> TIntervalPointers;

    // one list of interval pointers for the intervals to the left of center
    TIntervalPointers S_left;
    // one list of interval pointers for the intervals to the right of center
    TIntervalPointers S_right;

    value(pm, knot).center = center;

    typedef typename Iterator<TIntervalPointers, Standard>::Type TIntervalIterator;
    TIntervalIterator it = begin(intervals, Standard());
    TIntervalIterator it_end = end(intervals, Standard());

    // walk through intervals
    while (it != it_end)
    {
        // interval belongs to the left list
        if ((**it).i2 <= center)
        {
            appendValue(S_left, *it, Generous());
        }
        else
        {   // interval belongs to the right list
            if ((**it).i1 > center)
                appendValue(S_right, (*it), Generous());
            else
                // interval belongs to the current node
                _appendIntervalTreeNodeLists(value(pm, knot), **it);
        }
        ++it;
    }

//    std::sort(begin(value(pm,knot).list1),end(value(pm,knot).list1),_less_compI1_ITree<typename Value<TList>::Type>);
    std::sort(begin(value(pm, knot).list2), end(value(pm, knot).list2), _greater_compI2_ITree<typename Value<TList>::Type>);

    // build subtree to the left
    if (!empty(S_left))
    {
        TVertexDescriptor vd = addVertex(g);
        resizeVertexMap(pm, g);
        addEdge(g, knot, vd);
        TValue next_center = _calcIntervalTreeNodeCenterLeft(S_left, last_center, center, tag);
        _createIntervalTree(g, pm, S_left, vd, center, next_center, length(S_left), tag);
    }
    // build subtree to the right
    if (!empty(S_right))
    {
        TVertexDescriptor vd = addVertex(g);
        resizeVertexMap(pm, g);
        addEdge(g, knot, vd);
        TValue next_center = _calcIntervalTreeNodeCenterRight(S_right, last_center, center, tag);
        _createIntervalTree(g, pm, S_right, vd, center, next_center, length(S_right), tag);
    }
}

// fill the container interval_pointers with pointers to the corresponding objects in intervals.
// this is done to avoid copying and passing the whole IntervalAndCargo objects during interval tree construction
template <typename TIntervals, typename TIntervalPointers>
void
_makePointerInterval(TIntervals & intervals, TIntervalPointers & interval_pointers)
{
    typedef typename Iterator<TIntervals, Standard>::Type TIntervalIterator;
    typedef typename Iterator<TIntervalPointers, Standard>::Type TIntervalPointerIterator;

    resize(interval_pointers, length(intervals));
    if (empty(intervals))
        return;

    TIntervalIterator it = begin(intervals, Standard());
    TIntervalIterator itEnd = end(intervals, Standard());
    TIntervalPointerIterator iit = begin(interval_pointers, Standard());

    for (; it != itEnd; ++it, ++iit)
        *iit = it;
}

// if the center of the root is not given, it is placed in the "ComputeCenter way": in the middle of minValue and maxValue
// where minValue is the minimum left boundary and maxValue is the maximum right boundary of all intervals
template <typename TIntervals>
typename Value<typename Value<TIntervals>::Type>::Type
_calcIntervalTreeRootCenter(TIntervals & intervals)
{

    SEQAN_ASSERT_GT(length(intervals), 0u);

    typedef typename Value<typename Value<TIntervals>::Type>::Type TValue;
    typedef typename Iterator<TIntervals, Standard>::Type TIntervalIterator;

    TIntervalIterator it = begin(intervals);
    TIntervalIterator it_end = end(intervals);

    TValue min = std::numeric_limits<TValue>::max();
    TValue max = std::numeric_limits<TValue>::min();

    // get min and max
    while (it != it_end)
    {
        if (leftBoundary(*it) < min)
            min = leftBoundary(*it);
        if (rightBoundary(*it) > max)
            max = rightBoundary(*it);
        SEQAN_ASSERT_LEQ(min, max);
        ++it;
    }

    SEQAN_ASSERT_LEQ(min, max);

    // return middle between max and min
    return min + (max - min) / (TValue)2.0;

}

/*!
 * @fn IntervalTree#addInterval
 *
 * @headerfile <seqan/misc/interval_tree.h>
 *
 * @brief Adds an interval to an interval tree.
 *
 * @signature void addInterval(intervalTree, interval);
 * @signature void addInterval(intervalTree, begin, end[, cargo]);
 * @signature void addInterval(graph, propertyMap, interval);
 *
 * @param[in,out] intervalTree The interval tree to add the interval to. Types: @link IntervalTree @endlink.
 * @param[in]     interval     The interval to be added to the interval tree.
 * @param[in]     begin        Begin position of interval of type TValue.
 * @param[in]     end          End position of interval of type TValue.
 * @param[in]     cargo        Cargo to attach to the interval. Types: @link IntervalAndCargo @endlink.
 * @param[in,out] graph        The directed graph that contains the topography of the interval tree.
 * @param[in,out] propertyMap  The property map containing the node properties of the interval tree.
 */


template <typename TGraph, typename TPropertyMap, typename TInterval>
void
addInterval(TGraph & g, TPropertyMap & pm, TInterval interval)
{

    typedef typename Iterator<TGraph, OutEdgeIterator>::Type TOutEdgeIterator;
    typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor;
    typedef typename Value<TPropertyMap>::Type TProperty;
    typedef typename Value<TInterval>::Type TValue;
    typedef typename ListType<TProperty>::Type TList;


    if (empty(pm))
    {
        TVertexDescriptor vd = addVertex(g);
        resizeVertexMap(pm, g);
        _setIntervalTreeNode(property(pm, vd), (rightBoundary(interval) + leftBoundary(interval)) / 2, interval);
        return;

    }
    // start at root
    TVertexDescriptor act_knot = 0;
    TProperty act_prop = property(pm, act_knot);
    TProperty next_prop;

    // look for the right node to add interval to
    while (true)
    {
        TOutEdgeIterator it(g, act_knot);
        act_prop = property(pm, act_knot);
        if (act_prop.center < leftBoundary(interval)) // interval to the left of current node?
        {
            if (atEnd(it))
            {
                TVertexDescriptor vd = addVertex(g);
                resizeVertexMap(pm, g);
                addEdge(g, act_knot, vd);
                _setIntervalTreeNode(property(pm, vd), (rightBoundary(interval) + leftBoundary(interval)) / (TValue)2.0, interval);
                break;
            }
            else
            {
                next_prop = property(pm, targetVertex(it));
                if (next_prop.center <= act_prop.center)
                {
                    goNext(it);
                    if (atEnd(it))
                    {
                        TVertexDescriptor vd = addVertex(g);
                        resizeVertexMap(pm, g);
                        addEdge(g, act_knot, vd);
                        _setIntervalTreeNode(property(pm, vd), (rightBoundary(interval) + leftBoundary(interval)) / (TValue)2.0, interval);
                        break;
                    }
                }
            }
            act_knot = targetVertex(it);
        }
        else
        {
            if (rightBoundary(interval) <= act_prop.center) // interval to the right of current node?
            {
                if (atEnd(it))
                {
                    TVertexDescriptor vd = addVertex(g);
                    resizeVertexMap(pm, g);
                    addEdge(g, act_knot, vd);
                    _setIntervalTreeNode(property(pm, vd), (rightBoundary(interval) + leftBoundary(interval)) / 2, interval);
                    break;
                }
                else
                {
                    next_prop = property(pm, targetVertex(it));
                    if (next_prop.center >= act_prop.center)
                    {
                        goNext(it);
                        if (atEnd(it))
                        {
                            TVertexDescriptor vd = addVertex(g);
                            resizeVertexMap(pm, g);
                            addEdge(g, act_knot, vd);
                            _setIntervalTreeNode(property(pm, vd), (rightBoundary(interval) + leftBoundary(interval)) / 2, interval);
                            break;
                        }
                    }
                }
                act_knot = targetVertex(it);
            }
            else  // need to create new node for interval
            {
                _appendIntervalTreeNodeLists(property(pm, act_knot), interval);
                std::sort(begin(property(pm, act_knot).list1), end(property(pm, act_knot).list1), _less_compI1_ITree<typename Value<TList>::Type>);
                std::sort(begin(property(pm, act_knot).list2), end(property(pm, act_knot).list2), _greater_compI2_ITree<typename Value<TList>::Type>);
                break;
            }
        }
    }

}

template <typename TValue, typename TCargo, typename TInterval>
void
addInterval(IntervalTree<TValue, TCargo> & itree, TInterval interval)
{

    ++ itree.interval_counter;
    addInterval(itree.g, itree.pm, interval);

}

template <typename TValue, typename TCargo>
void
addInterval(IntervalTree<TValue, TCargo> & itree, TValue begin, TValue end, TCargo cargo)
{

    IntervalAndCargo<TValue, TCargo> interval;
    interval.i1 = begin;
    interval.i2 = end;
    interval.cargo = cargo;
    ++itree.interval_counter;
    addInterval(itree.g, itree.pm, interval);

}

template <typename TValue, typename TCargo>
void
addInterval(IntervalTree<TValue, TCargo> & itree, TValue begin, TValue end)
{

    IntervalAndCargo<TValue, TCargo> interval;
    interval.i1 = begin;
    interval.i2 = end;
    interval.cargo = itree.interval_counter;
    ++itree.interval_counter;
    addInterval(itree.g, itree.pm, interval);

}

/*!
 * @fn IntervalTree#findIntervals
 * @brief Find all intervals that contain the query point or overlap with the query interval.
 *
 * @signature void findIntervals(result, intervalTree, query);
 * @signature void findIntervals(result, intervalTree, queryBegin, queryEnd);
 * @signature void findIntervals(result, graph, propertyMap, query);
 *
 * @param[out] result       A reference to the result string of <tt>TCargo</tt> objects. Types: @link String @endlink.
 * @param[in]  intervalTree An IntervalTree.
 * @param[in]  graph        The directed @link Graph graph @endlink that contains the topography of the interval tree.
 * @param[in]  propertyMap  The property map containing the node properties of the interval tree.
 * @param[in]  query        A query point.
 * @param[in]  queryBegin   The begin position of the query interval.
 * @param[in]  queryEnd     The end position of the query interval.
 */

template <typename TSpec, typename TPropertyMap, typename TValue, typename TCargo>
inline void
findIntervals(
        String<TCargo> & result,
        Graph<TSpec> const & g,
        TPropertyMap const & pm,
        TValue query)
{
    typedef Graph<TSpec> const TGraph;
    typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor;
    typedef typename Value<TPropertyMap>::Type TProperty;
    typedef typename Value<TProperty>::Type TPropertyValue;
    typedef typename Iterator<TGraph, OutEdgeIterator>::Type TOutEdgeIterator;

    resize(result, 0);
    if (empty(g))
        return;

    // start at root
    TVertexDescriptor act_knot = 0;
    TProperty act_prop = property(pm, act_knot);
    TProperty next_prop;

    while (true)
    {
        typename Iterator<Graph<TSpec>, OutEdgeIterator>::Type it7;
        Iter<Graph<TSpec>, GraphIterator<InternalOutEdgeIterator<OutEdgeIterator> > > it5(g, act_knot);
        TOutEdgeIterator it4;
        TOutEdgeIterator it(g, act_knot);
        act_prop = property(pm, act_knot);
        if (act_prop.center < (TPropertyValue)query) // look in current node and right subtree
        {
            unsigned int i = 0;
            while (i<length(act_prop.list2) && rightBoundary(value(act_prop.list2, i))>(TPropertyValue) query)
            {
                appendValue(result, cargo(value(act_prop.list2, i)), Generous());
                ++i;
            }
            if (atEnd(it))
                break;

            next_prop = property(pm, targetVertex(it));
            if (next_prop.center <= act_prop.center)
            {
                goNext(it);
                if (atEnd(it))
                    break;
            }
            act_knot = targetVertex(it);
        }
        else
        {
            if ((TPropertyValue)query < act_prop.center) // look in current node and left subtree
            {
                unsigned int i = 0;
                while (i < length(act_prop.list1) && leftBoundary(value(act_prop.list1, i)) <= (TPropertyValue)query)
                {
                    appendValue(result, cargo(value(act_prop.list1, i)), Generous());
                    ++i;
                }
                if (atEnd(it))
                    break;

                next_prop = property(pm, targetVertex(it));
                if (next_prop.center >= act_prop.center)
                {
                    goNext(it);
                    if (atEnd(it))
                        break;
                }
                act_knot = targetVertex(it);
            }
            else  // look in current node only, as query is center
            {
                for (unsigned int i = 0; i < length(act_prop.list1); ++i)
                    appendValue(result, cargo(value(act_prop.list1, i)), Generous());
                break;
            }
        }
    }

}

template <typename TValue, typename TCargo, typename TValue2>
inline void
findIntervals(
        String<TCargo> & result,
        IntervalTree<TValue, TCargo> const & it,
        TValue2 query)
{
    findIntervals(result, it.g, it.pm, query);
}

template <typename TValue, typename TCargo, typename TValue2>
inline void
findIntervals(
        String<TCargo> & result,
        IntervalTree<TValue, TCargo> const & tree,
        TValue2 query_begin,
        TValue2 query_end)
{
    findIntervals(result, tree.g, tree.pm, query_begin, query_end);
}

template <typename TSpec, typename TPropertyMap, typename TValue, typename TCargo>
inline void
findIntervals(
        String<TCargo> & result,
        Graph<TSpec> const & g,
        TPropertyMap const & pm,
        TValue query_begin,
        TValue query_end)
{
    typedef Graph<TSpec> const TGraph;
    typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor;

    resize(result, 0);

    // start at root
    TVertexDescriptor act_knot = 0;
    findIntervals(result, g, pm, act_knot, query_begin, query_end);
}

template <
    typename TSpec,
    typename TPropertyMap,
    typename TVertexDescriptor,
    typename TValue,
    typename TCargo>
inline void
findIntervals(
        String<TCargo> & result,
        Graph<TSpec> const & g,
        TPropertyMap const & pm,
        TVertexDescriptor & act_knot,
        TValue query_begin,
        TValue query_end)
{
    typedef typename Value<TPropertyMap>::Type TProperty;
    typedef typename Iterator<Graph<TSpec>, OutEdgeIterator>::Type TOutEdgeIterator;

    if (empty(g))
        return;

    TProperty act_prop = property(pm, act_knot);
    TProperty next_prop;

    while (true)
    {
        TOutEdgeIterator it(g, act_knot);
        act_prop = property(pm, act_knot);
        //
        if (act_prop.center < query_begin) // query interval is to the right of node center
        {
            unsigned int i = 0;
            while (i<length(act_prop.list2) && rightBoundary(value(act_prop.list2, i))> query_begin)
            {
                appendValue(result, cargo(value(act_prop.list2, i)), Generous());
                ++i;
            }
            if (atEnd(it))
                break;

            next_prop = property(pm, targetVertex(it));
            if (next_prop.center <= act_prop.center)
            {
                goNext(it);
                if (atEnd(it))
                    break;
            }
            act_knot = targetVertex(it);
        }
        else
        {
            if (query_end <= act_prop.center) // query interval is to the left of node center
            {
                unsigned int i = 0;
                while (i < length(act_prop.list1) && leftBoundary(value(act_prop.list1, i)) < query_end)
                {
                    appendValue(result, cargo(value(act_prop.list1, i)), Generous());
                    ++i;
                }

                if (atEnd(it))
                    break;

                next_prop = property(pm, targetVertex(it));
                if (next_prop.center >= act_prop.center)
                {
                    goNext(it);
                    if (atEnd(it))
                        break;
                }
                act_knot = targetVertex(it);
            }
            else
            { //node center is contained in query interval
                for (unsigned int i = 0; i < length(act_prop.list1); ++i)
                    appendValue(result, cargo(value(act_prop.list1, i)), Generous());

                while (!atEnd(it))
                {
                    TVertexDescriptor next_knot = targetVertex(it);
                    findIntervals(result, g, pm, next_knot, query_begin, query_end);
                    goNext(it);
                }
                break;

                //break; //dont break! continue in both subtrees!!
            }
        }
    }
}

/*!
 * @fn IntervalTree#findIntervalsExcludeTouching
 * @brief Find all intervals that contain the query point, exclude intervals that touch the query, i.e. where the query
 *        point equals the start or end point.
 *
 * @signature void findIntervalsExcludeTouching(result, intervalTree, query);
 * @signature void findIntervalsExcludeTouching(result, graph, propertyMap, query,);
 *
 * @param[out] result      The resulting string of cargos/ids of the intervals that contain the query point.  Should
 *                         be a string of TCargo. Types: String
 * @param[in] intervalTree An interval tree Types: IntervalTree
 * @param[in] graph        The directed graph that contains the topography of the interval tree.
 * @param[in] query        The TValue to query here.
 * @param[in] propertyMap  The property map containing the node properties of the interval tree
 */

template <typename TSpec, typename TPropertyMap, typename TValue, typename TCargo>
inline void
findIntervalsExcludeTouching(
        String<TCargo> & result,
        Graph<TSpec> const & g,
        TPropertyMap const & pm,
        TValue query)
{
    typedef Graph<TSpec> const TGraph;
    typedef typename Iterator<TGraph, OutEdgeIterator>::Type TOutEdgeIterator;
    typedef typename VertexDescriptor<TGraph>::Type TVertexDescriptor;
    typedef typename Value<TPropertyMap>::Type TProperty;

    resize(result, 0);
    if (empty(g))
        return;

    // start at root
    TVertexDescriptor act_knot = 0;
    TProperty act_prop = property(pm, act_knot);
    TProperty next_prop;

    while (true)
    {
        TOutEdgeIterator it(g, act_knot);
        act_prop = property(pm, act_knot);
        if ((TValue) act_prop.center < query) // look in current node and right subtree
        {
            int i = 0;
            while (i < (int)length(act_prop.list2) && (TValue)rightBoundary(value(act_prop.list2, i)) > query)
            {
                appendValue(result, cargo(value(act_prop.list2, i)), Generous());
                ++i;
            }
            if (atEnd(it))
                break;

            next_prop = property(pm, targetVertex(it));
            if (next_prop.center <= act_prop.center)
            {
                goNext(it);
                if (atEnd(it))
                    break;
            }
            act_knot = targetVertex(it);
        }
        else
        {
            if (query < (TValue) act_prop.center) // look in current node and left subtree
            {
                int i = 0;
                while (i < (int)length(act_prop.list1) && (TValue)leftBoundary(value(act_prop.list1, i)) < query)
                {
                    appendValue(result, cargo(value(act_prop.list1, i)), Generous());
                    ++i;
                }
                if (atEnd(it))
                    break;

                next_prop = property(pm, targetVertex(it));
                if (next_prop.center >= act_prop.center)
                {
                    goNext(it);
                    if (atEnd(it))
                        break;
                }
                act_knot = targetVertex(it);
            }
            else  // look in current node only
            {
                int i = 0;
                while (i < (int)length(act_prop.list1) && (TValue)leftBoundary(value(act_prop.list1, i)) < query)
                {
                    appendValue(result, cargo(value(act_prop.list1, i)), Generous());
                    ++i;
                }
                break;
            }
        }
    }

}

template <typename TValue, typename TCargo>
inline void
findIntervalsExcludeTouching(
        String<TCargo> & result,
        IntervalTree<TValue, TCargo> const & tree,
        TValue query)
{
    findIntervalsExcludeTouching(result, tree.g, tree.pm, query);
}

/*!
 * @fn IntervalTree#removeInterval
 * @brief Removes an interval from the interval tree.
 *
 * @signature bool removeInterval(intervalTree, iBegin, iEnd, iId);
 *
 * @param[in,out] intervalTree An interval tree Types: IntervalTree
 * @param[in]     iBegin       The begin position of the interval to be removed.
 * @param[in]     iEnd         The end position of the interval to be removed.
 * @param[in]     iId          The ID of the interval to be removed.
 *
 * @return bool <tt>true</tt> on success, <tt>false</tt> on failure.
 */

template <
    typename TSpec,
    typename TPropertyMap,
    typename TVertexDescriptor,
    typename TValue,
    typename TCargo>
inline bool
removeInterval(
    Graph<TSpec> & g,
    TPropertyMap & pm,
    TVertexDescriptor & act_knot,
    TValue i_begin,
    TValue i_end,
    TCargo i_id)
{

    typedef typename Value<TPropertyMap>::Type TProperty;
    typedef typename ListType<TProperty>::Type TList;
    typedef typename Iterator<TList, Standard>::Type TListIterator;
    typedef typename Iterator<Graph<TSpec>, OutEdgeIterator>::Type TOutEdgeIterator;

    if (empty(g))
        return false;

    TProperty act_prop = property(pm, act_knot);
    TProperty next_prop;

    while (true)
    {
        TOutEdgeIterator it(g, act_knot);
        act_prop = property(pm, act_knot);
        //
        if (act_prop.center < i_begin) // interval is to the right of node center
        {
            if (atEnd(it))
                break;

            next_prop = property(pm, targetVertex(it));
            if (next_prop.center <= act_prop.center)
            {
                goNext(it);
                if (atEnd(it))
                    break;
            }
            act_knot = targetVertex(it);
        }
        else
        {
            if (i_end < act_prop.center) // interval is to the left of node center
            {
                if (atEnd(it))
                    break;

                next_prop = property(pm, targetVertex(it));
                if (next_prop.center >= act_prop.center)
                {
                    goNext(it);
                    if (atEnd(it))
                        break;
                }
                act_knot = targetVertex(it);
            }
            else //node center is contained in interval, this is where we should find the interval to be removed
            {   // remove from list1
                TProperty & change_prop = property(pm, act_knot);
                bool foundInLeft = false;
                TListIterator list_it_keep = begin(change_prop.list1, Standard());
                TListIterator list_it = begin(change_prop.list1, Standard());
                while (list_it != end(change_prop.list1, Standard()))
                {
                    //std::cout << "Element: " << getLeftBoundary(*list_it) << ".." << getRightBoundary(*list_it) << " " << cargo(*list_it) << std::endl;
                    if (getLeftBoundary(*list_it) == i_begin && cargo(*list_it) == i_id)
                    {
                        foundInLeft = true;
                        ++list_it;
                        continue;
                    }
                    *list_it_keep = *list_it;
                    //std::cout << "Element keep: " << getLeftBoundary(*list_it_keep) << ".." << getRightBoundary(*list_it_keep) << " " << cargo(*list_it_keep) << std::endl;
                    ++list_it; ++list_it_keep;
                }

                bool foundInRight = false;
                list_it_keep = begin(change_prop.list2, Standard());
                list_it = begin(change_prop.list2, Standard());
                while (list_it != end(change_prop.list2, Standard()))
                {
                    //std::cout << "Element: " << getLeftBoundary(*list_it) << ".." << getRightBoundary(*list_it) << " " << cargo(*list_it) << std::endl;
                    if (getRightBoundary(*list_it) == i_end && cargo(*list_it) == i_id)
                    {
                        foundInRight = true;
                        ++list_it;
                        continue;
                    }
                    *list_it_keep = *list_it;
                    //std::cout << "Element keep: " << getLeftBoundary(*list_it_keep) << ".." << getRightBoundary(*list_it_keep) << " " << cargo(*list_it_keep) << std::endl;
                    ++list_it; ++list_it_keep;

                }


                // TODO: if node is empty and does not have child nodes --> remove node.
                // keeping these empty leaf nodes just takes space unnecessarily
                if (foundInRight && foundInLeft)
                {
                    resize(change_prop.list2, length(change_prop.list2) - 1);
                    resize(change_prop.list1, length(change_prop.list1) - 1);
                    return true;
                }

            }
        }
    }
    return false;
}

template <
    typename TSpec,
    typename TPropertyMap,
    typename TValue,
    typename TCargo>
inline bool
removeInterval(
    Graph<TSpec> & g,
    TPropertyMap & pm,
    TValue i_begin,
    TValue i_end,
    TCargo i_id)
{
    typedef typename VertexDescriptor<Graph<TSpec> >::Type TVertexDescriptor;

    // start looking at root
    TVertexDescriptor act_knot = 0;
    return removeInterval(g, pm, act_knot, i_begin, i_end, i_id);
}

template <typename TValue, typename TCargo>
inline bool
removeInterval(
    IntervalTree<TValue, TCargo> & tree,
    TValue i_begin,
    TValue i_end,
    TCargo i_id)
{
    return removeInterval(tree.g, tree.pm, i_begin, i_end, i_id);
    // we do not decrease the interval_counter of tree, as it would mix up interval IDs
}

/////////////////// Metafunctions ///////////////////////

template <typename TValue, typename TCargo>
struct Value<IntervalTree<TValue, TCargo> >
{
    typedef TValue Type;
};


template <typename TValue, typename TCargo>
struct Cargo<IntervalTree<TValue, TCargo> >
{
    typedef TCargo Type;
};

}  // namespace seqan

#endif  //#ifndef SEQAN_MISC_INTERVAL_TREE_H