File: cxtree.c

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

/*
 * $Author: rpalsa $
 * $Date: 2011/02/21 14:15:31 $
 * $Revision: 1.9 $
 * $Name: cpl-6_1_1 $
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include "cxmemory.h"
#include "cxmessages.h"
#include "cxtree.h"



/**
 * @defgroup cxtree Balanced Binary Trees
 *
 * The module implements a balanced binary tree type, i.e. a container
 * managing key/value pairs as elements. The container is optimized for
 * lookup operations.
 *
 * @par Synopsis:
 * @code
 *   #include <cxtree.h>
 * @endcode
 */

/**@{*/

/*
 * Tree node color, tree node and tree opaque data types
 */

enum _cx_tnode_color_ {
    CX_TNODE_RED = 0,
    CX_TNODE_BLACK
};

typedef enum _cx_tnode_color_ cx_tnode_color;

struct _cx_tnode_ {
    struct _cx_tnode_ *left;
    struct _cx_tnode_ *right;
    struct _cx_tnode_ *parent;
    cx_tnode_color color;
    cxptr key;
    cxptr value;
};

typedef struct _cx_tnode_ cx_tnode;

struct _cx_tree_ {
    cx_tnode *header;
    cxsize node_count;
    cx_tree_compare_func key_compare;
    cx_free_func key_destroy;
    cx_free_func value_destroy;
};



/*
 * Some macros, mostly defined for readability purposes.
 */

#define _cx_tnode_left(node)     ((node)->left)
#define _cx_tnode_right(node)    ((node)->right)
#define _cx_tnode_parent(node)   ((node)->parent)
#define _cx_tnode_grandpa(node)  ((node)->parent->parent)
#define _cx_tnode_color(node)    ((node)->color)
#define _cx_tnode_key(node)      ((node)->key)
#define _cx_tnode_value(node)    ((node)->value)

#define _cx_tree_head(tree)           ((tree)->header)
#define _cx_tree_root(tree)           ((tree)->header->parent)
#define _cx_tree_leftmost(tree)       ((tree)->header->left)
#define _cx_tree_rightmost(tree)      ((tree)->header->right)
#define _cx_tree_node_count(tree)     ((tree)->node_count)
#define _cx_tree_key_destroy(tree)    ((tree)->key_destroy)
#define _cx_tree_value_destroy(tree)  ((tree)->value_destroy)
#define _cx_tree_compare(tree)        ((tree)->key_compare)

#define _cx_tree_key_compare(tree, a, b)  ((tree)->key_compare((a), (b)))


/*
 * Internal, node related methods
 */


inline static cx_tnode *
_cx_tnode_create(cxcptr key, cxcptr value)
{
    cx_tnode *node = cx_malloc(sizeof(cx_tnode));

    _cx_tnode_left(node) = NULL;
    _cx_tnode_right(node) = NULL;
    _cx_tnode_parent(node) = NULL;
    _cx_tnode_key(node) = (cxptr)key;
    _cx_tnode_value(node) = (cxptr)value;

    return node;
}


inline static void
_cx_tnode_destroy(cx_tnode *node, cx_free_func key_destroy,
                  cx_free_func value_destroy)
{

    if (node) {
        if (key_destroy) {
            key_destroy(_cx_tnode_key(node));
            _cx_tnode_key(node) = NULL;
        }

        if (value_destroy) {
            value_destroy(_cx_tnode_value(node));
            _cx_tnode_value(node) = NULL;
        }

        _cx_tnode_left(node) = NULL;
        _cx_tnode_right(node) = NULL;
        _cx_tnode_parent(node) = NULL;

        cx_free(node);
    }

    return;

}


inline static cx_tnode *
_cx_tnode_minimum(const cx_tnode *node)
{

    register cx_tnode *n = (cx_tnode *)node;

    while (_cx_tnode_left(n) != NULL)
        n = _cx_tnode_left(n);

    return n;

}


inline static cx_tnode *
_cx_tnode_maximum(const cx_tnode *node)
{

    register cx_tnode *n = (cx_tnode *)node;

    while (_cx_tnode_right(n) != NULL)
        n = _cx_tnode_right(n);

    return n;

}


inline static cxptr
_cx_tnode_get_key(const cx_tnode *node)
{

    return node->key;

}


inline static void
_cx_tnode_set_key(cx_tnode *node, cxcptr key)
{

    node->key = (cxptr)key;
    return;

}


inline static cxptr
_cx_tnode_get_value(const cx_tnode *node)
{

    return node->value;

}


inline static void
_cx_tnode_set_value(cx_tnode *node, cxcptr value)
{

    node->value = (cxptr)value;
    return;

}


inline static cx_tnode *
_cx_tnode_next(const cx_tnode *node)
{

    register cx_tnode *n = (cx_tnode *)node;

    if (_cx_tnode_right(n) != NULL) {
        n = _cx_tnode_right(n);
        while (_cx_tnode_left(n) != NULL)
            n = _cx_tnode_left(n);
    }
    else {
        cx_tnode *m = _cx_tnode_parent(n);

        while (n == _cx_tnode_right(m)) {
            n = m;
            m = _cx_tnode_parent(m);
        }

        if (_cx_tnode_right(n) != m)
            n = m;
    }

    return n;

}


inline static cx_tnode *
_cx_tnode_previous(const cx_tnode *node)
{

    register cx_tnode *n = (cx_tnode *)node;


    if (_cx_tnode_color(n) == CX_TNODE_RED && _cx_tnode_grandpa(n) == n)
        n = _cx_tnode_right(n);
    else
        if (_cx_tnode_left(n) != NULL) {
            cx_tnode *m = _cx_tnode_left(n);

            while (_cx_tnode_right(m) != NULL)
                m = _cx_tnode_right(m);

            n = m;
        }
        else {
            cx_tnode *m = _cx_tnode_parent(n);

            while (n == _cx_tnode_left(m)) {
                n = m;
                m = _cx_tnode_parent(m);
            }

            n = m;
        }

    return n;

}


/*
 * Internal, tree related methods
 */


inline static void
_cx_tree_rotate_left(cx_tnode *node, cx_tnode **root)
{

    register cx_tnode *y = _cx_tnode_right(node);


    _cx_tnode_right(node) = _cx_tnode_left(y);

    if (_cx_tnode_left(y) != NULL)
        _cx_tnode_parent(_cx_tnode_left(y)) = node;

    _cx_tnode_parent(y) = _cx_tnode_parent(node);

    if (node == *root)
        *root = y;
    else
        if (node == _cx_tnode_left(_cx_tnode_parent(node)))
            _cx_tnode_left(_cx_tnode_parent(node)) = y;
        else
            _cx_tnode_right(_cx_tnode_parent(node)) = y;

    _cx_tnode_left(y) = node;
    _cx_tnode_parent(node) = y;

    return;

}


inline static void
_cx_tree_rotate_right(cx_tnode *node, cx_tnode **root)
{

    register cx_tnode *y = _cx_tnode_left(node);


    _cx_tnode_left(node) = _cx_tnode_right(y);

    if (_cx_tnode_right(y) != NULL)
        _cx_tnode_parent(_cx_tnode_right(y)) = node;

    _cx_tnode_parent(y) = _cx_tnode_parent(node);

    if (node == *root)
        *root = y;
    else
        if (node == _cx_tnode_right(_cx_tnode_parent(node)))
            _cx_tnode_right(_cx_tnode_parent(node)) = y;
        else
            _cx_tnode_left(_cx_tnode_parent(node)) = y;

    _cx_tnode_right(y) = node;
    _cx_tnode_parent(node) = y;

    return;

}


inline static void
_cx_tree_rebalance(cx_tnode *node, cx_tnode **root)
{

    _cx_tnode_color(node) = CX_TNODE_RED;

    while (node != *root &&
           _cx_tnode_color(_cx_tnode_parent(node)) == CX_TNODE_RED) {

        if (_cx_tnode_parent(node) ==
            _cx_tnode_left(_cx_tnode_grandpa(node))) {
            cx_tnode *y = _cx_tnode_right(_cx_tnode_grandpa(node));

            if (y && _cx_tnode_color(y) == CX_TNODE_RED) {
                _cx_tnode_color(_cx_tnode_parent(node)) = CX_TNODE_BLACK;
                _cx_tnode_color(_cx_tnode_grandpa(node)) = CX_TNODE_RED;
                _cx_tnode_color(y) = CX_TNODE_BLACK;
                node = _cx_tnode_grandpa(node);
            }
            else {
                if (node == _cx_tnode_right(_cx_tnode_parent(node))) {
                    node = _cx_tnode_parent(node);
                    _cx_tree_rotate_left(node, root);
                }

                _cx_tnode_color(_cx_tnode_parent(node)) = CX_TNODE_BLACK;
                _cx_tnode_color(_cx_tnode_grandpa(node)) = CX_TNODE_RED;

                _cx_tree_rotate_right(_cx_tnode_grandpa(node), root);
            }
        }
        else {
            cx_tnode *y = _cx_tnode_left(_cx_tnode_grandpa(node));

            if (y && _cx_tnode_color(y) == CX_TNODE_RED) {
                _cx_tnode_color(_cx_tnode_parent(node)) = CX_TNODE_BLACK;
                _cx_tnode_color(_cx_tnode_grandpa(node)) = CX_TNODE_RED;
                _cx_tnode_color(y) = CX_TNODE_BLACK;
                node = _cx_tnode_grandpa(node);
            }
            else {
                if (node == _cx_tnode_left(_cx_tnode_parent(node))) {
                    node = _cx_tnode_parent(node);
                    _cx_tree_rotate_right(node, root);
                }

                _cx_tnode_color(_cx_tnode_parent(node)) = CX_TNODE_BLACK;
                _cx_tnode_color(_cx_tnode_grandpa(node)) = CX_TNODE_RED;

                _cx_tree_rotate_left(_cx_tnode_grandpa(node), root);
            }
        }
    }

    _cx_tnode_color((*root)) = CX_TNODE_BLACK;

    return;

}


inline static cx_tnode *
_cx_tree_rebalance_for_erase(cx_tnode *node, cx_tnode **root,
                             cx_tnode **leftmost, cx_tnode **rightmost)
{

    cx_tnode *y = node;
    cx_tnode *x = NULL;
    cx_tnode *x_parent = NULL;


    if (_cx_tnode_left(y) == NULL) {

        /*
         * node has at most one non-null child. y == node. x might be null.
         */

        x = _cx_tnode_right(y);
    }
    else {
        if (_cx_tnode_right(y) == NULL) {

            /*
             * node has exactly one non-null child. y == node. x is not null.
             */

            x = _cx_tnode_left(y);
        }
        else {

            /*
             * node has 2 non-null children. Set y to node's successor.
             * x might be null.
             */

            y = _cx_tnode_right(y);

            while (_cx_tnode_left(y) != NULL)
                y = _cx_tnode_left(y);

            x = _cx_tnode_right(y);
        }
    }

    if (y != node) {

        cx_tnode_color tcolor;

        /*
         * relink y in place of node. y is node's successor
         */

        _cx_tnode_parent(_cx_tnode_left(node)) = y;
        _cx_tnode_left(y) = _cx_tnode_left(node);

        if (y != _cx_tnode_right(node)) {
            x_parent = _cx_tnode_parent(y);

            if (x)
                _cx_tnode_parent(x) = _cx_tnode_parent(y);

            _cx_tnode_left(_cx_tnode_parent(y)) = x;
            _cx_tnode_right(y) = _cx_tnode_right(node);
            _cx_tnode_parent(_cx_tnode_right(node)) = y;
        }
        else
            x_parent = y;


        if (*root == node)
            *root = y;
        else
            if (_cx_tnode_left(_cx_tnode_parent(node)) == node)
                _cx_tnode_left(_cx_tnode_parent(node)) = y;
            else
                _cx_tnode_right(_cx_tnode_parent(node)) = y;

        _cx_tnode_parent(y) = _cx_tnode_parent(node);

        /*
         * Swap the colors of y an node.
         */

        tcolor = _cx_tnode_color(node);
        _cx_tnode_color(node) = _cx_tnode_color(y);
        _cx_tnode_color(y) = tcolor;

        /*
         * Make y point to the node to be actually deleted.
         */

        y = node;
    }
    else {

        /*
         * y == node
         */

        x_parent = _cx_tnode_parent(y);

        if (x)
            _cx_tnode_parent(x) = _cx_tnode_parent(y);

        if (*root == node)
            *root = x;
        else
            if (_cx_tnode_left(_cx_tnode_parent(node)) == node)
                _cx_tnode_left(_cx_tnode_parent(node)) = x;
            else
                _cx_tnode_right(_cx_tnode_parent(node)) = x;

        if (*leftmost == node) {
            if (_cx_tnode_right(node) == NULL) {

                /*
                 * If node == *root, *leftmost will be the header node.
                 */

                *leftmost = _cx_tnode_parent(node);
            }
            else
                *leftmost = _cx_tnode_minimum(x);
        }

        if (*rightmost == node) {
            if (_cx_tnode_left(node) == NULL) {

                /*
                 *  If node == *root, *rightmost will be the header node.
                 */

                *rightmost = _cx_tnode_parent(node);
            }
            else
                *rightmost = _cx_tnode_maximum(x);
        }
    }

    if (_cx_tnode_color(y) != CX_TNODE_RED) {
        while (x != *root &&
               (x == NULL || _cx_tnode_color(x) == CX_TNODE_BLACK))
            if (x == _cx_tnode_left(x_parent)) {
                cx_tnode *w = _cx_tnode_right(x_parent);

                if (_cx_tnode_color(w) == CX_TNODE_RED) {
                    _cx_tnode_color(w) = CX_TNODE_BLACK;
                    _cx_tnode_color(x_parent) = CX_TNODE_RED;
                    _cx_tree_rotate_left(x_parent, root);
                    w = _cx_tnode_right(x_parent);
                }

                if ((_cx_tnode_left(w) == NULL ||
                     _cx_tnode_color(_cx_tnode_left(w)) == CX_TNODE_BLACK) &&
                    (_cx_tnode_right(w) == NULL ||
                     _cx_tnode_color(_cx_tnode_right(w)) == CX_TNODE_BLACK)) {

                    _cx_tnode_color(w) = CX_TNODE_RED;
                    x = x_parent;
                    x_parent = _cx_tnode_parent(x_parent);

                }
                else {
                    if (_cx_tnode_right(w) == NULL ||
                        _cx_tnode_color(_cx_tnode_right(w)) ==
                        CX_TNODE_BLACK) {
                        if (_cx_tnode_left(w)) {
                            cx_tnode *v = _cx_tnode_left(w);
                            _cx_tnode_color(v) = CX_TNODE_BLACK;
                        }

                        _cx_tnode_color(w) = CX_TNODE_RED;
                        _cx_tree_rotate_right(w, root);
                        w = _cx_tnode_right(x_parent);
                    }

                    _cx_tnode_color(w) = _cx_tnode_color(x_parent);
                    _cx_tnode_color(x_parent) = CX_TNODE_BLACK;

                    if (_cx_tnode_right(w))
                        _cx_tnode_color(_cx_tnode_right(w)) = CX_TNODE_BLACK;

                    _cx_tree_rotate_left(x_parent, root);
                    break;
                }
            }
            else {

                /*
                 * Same as above with left and right exchanged.
                 */

                cx_tnode *w = _cx_tnode_left(x_parent);

                if (_cx_tnode_color(w) == CX_TNODE_RED) {
                    _cx_tnode_color(w) = CX_TNODE_BLACK;
                    _cx_tnode_color(x_parent) = CX_TNODE_RED;
                    _cx_tree_rotate_right(x_parent, root);
                    w = _cx_tnode_left(x_parent);
                }

                if ((_cx_tnode_right(w) == NULL ||
                     _cx_tnode_color(_cx_tnode_right(w)) == CX_TNODE_BLACK) &&
                    (_cx_tnode_left(w) == NULL ||
                     _cx_tnode_color(_cx_tnode_left(w)) == CX_TNODE_BLACK)) {

                    _cx_tnode_color(w) = CX_TNODE_RED;
                    x = x_parent;
                    x_parent = _cx_tnode_parent(x_parent);

                }
                else {
                    if (_cx_tnode_left(w) == NULL ||
                        _cx_tnode_color(_cx_tnode_left(w)) ==
                        CX_TNODE_BLACK) {
                        if (_cx_tnode_right(w)) {
                            cx_tnode *v = _cx_tnode_right(w);
                            _cx_tnode_color(v) = CX_TNODE_BLACK;
                        }

                        _cx_tnode_color(w) = CX_TNODE_RED;
                        _cx_tree_rotate_left(w, root);
                        w = _cx_tnode_left(x_parent);
                    }

                    _cx_tnode_color(w) = _cx_tnode_color(x_parent);
                    _cx_tnode_color(x_parent) = CX_TNODE_BLACK;

                    if (_cx_tnode_left(w))
                        _cx_tnode_color(_cx_tnode_left(w)) = CX_TNODE_BLACK;

                    _cx_tree_rotate_right(x_parent, root);
                    break;
                }
            }

        if (x)
            _cx_tnode_color(x) = CX_TNODE_BLACK;

    }

    return y;

}


/*
 * Convenience function used in cx_tree_verify()
 */

inline static cxsize
_cx_tree_black_count(cx_tnode *node, cx_tnode *root)
{
    cxsize sum = 0;

    if (node == NULL)
        return 0;

    do {
        if (_cx_tnode_color(node) == CX_TNODE_BLACK)
            ++sum;

        if (node == root)
            break;

        node = _cx_tnode_parent(node);
    } while (1);

    return sum;

}


/*
 * Initialize a tree to a valid empty tree.
 */

inline static void
_cx_tree_initialize(cx_tree *tree, cx_tree_compare_func compare,
                    cx_free_func key_destroy, cx_free_func value_destroy)
{

    /*
     * Used to distinguish header from root in the next operator.
     * Check this!!
     */

    _cx_tnode_color(_cx_tree_head(tree)) = CX_TNODE_RED;
    _cx_tree_root(tree) = NULL;
    _cx_tree_leftmost(tree) = _cx_tree_head(tree);
    _cx_tree_rightmost(tree) = _cx_tree_head(tree);

    _cx_tree_node_count(tree) = 0;
    _cx_tree_compare(tree) = compare;
    _cx_tree_key_destroy(tree) = key_destroy;
    _cx_tree_value_destroy(tree) = value_destroy;

    return;

}


/*
 * Inserting elements
 */

inline static cx_tnode *
_cx_tree_insert(cx_tree *tree, cx_tnode *x, cx_tnode *y, cxcptr key,
                cxcptr value)
{

    cx_tnode *z;


    if (y == _cx_tree_head(tree) || x != NULL ||
        _cx_tree_key_compare(tree, key, _cx_tnode_key(y))) {
        z = _cx_tnode_create(key, value);

        /*
         * This also makes _cx_tree_leftmost(tree) = z, if
         *  y == _cx_tree_head(tree).
         */

        _cx_tnode_left(y) = z;

        if (y == _cx_tree_head(tree)) {
            _cx_tree_root(tree) = z;
            _cx_tree_rightmost(tree) = z;
        }
        else {
            if (y == _cx_tree_leftmost(tree)) {

                /*
                 * Maintain _cx_tree_leftmost(tree) pointing to the
                 * minimum node.
                 */

                _cx_tree_leftmost(tree) = z;
            }
        }
    }
    else {
        z = _cx_tnode_create(key, value);
        _cx_tnode_right(y) = z;

        if (y == _cx_tree_rightmost(tree)) {

            /*
             * Maintain _cx_tree_rightmost(tree) pointing to the
             * maximum node.
             */

            _cx_tree_rightmost(tree) = z;
        }
    }

    _cx_tnode_parent(z) = y;
    _cx_tnode_left(z) = NULL;
    _cx_tnode_right(z) = NULL;

    _cx_tree_rebalance(z, &_cx_tree_root(tree));
    ++_cx_tree_node_count(tree);

    return z;

}


inline static cx_tnode *
_cx_tree_insert_equal(cx_tree *tree, cxcptr key, cxcptr value)
{

    cx_tnode *x = _cx_tree_root(tree);
    cx_tnode *y = _cx_tree_head(tree);


    while (x != NULL) {
        cxbool result;

        y = x;
        result = _cx_tree_key_compare(tree, key, _cx_tnode_key(x));
        x = result ? _cx_tnode_left(x) : _cx_tnode_right(x);
    }

    return _cx_tree_insert(tree, x, y, key, value);

}


inline static cx_tnode *
_cx_tree_insert_unique(cx_tree *tree, cxcptr key, cxcptr value)
{

    cx_tnode *x = _cx_tree_root(tree);
    cx_tnode *y = _cx_tree_head(tree);
    cx_tnode *pos;

    cxbool result = TRUE;


    while (x != NULL) {
        y = x;
        result = _cx_tree_key_compare(tree, key, _cx_tnode_key(x));
        x = result ? _cx_tnode_left(x) : _cx_tnode_right(x);
    }

    pos = y;

    if (result) {
        if (pos == _cx_tree_leftmost(tree))
            return _cx_tree_insert(tree, x, y, key, value);
        else
            pos = _cx_tnode_previous(pos);
    }

    if (_cx_tree_key_compare(tree, _cx_tnode_key(pos), key))
        return _cx_tree_insert(tree, x, y, key, value);

    return NULL;

}


/*
 * Element removal
 */

/*
 * Recursive erase without rebalancing
 */

inline static void
_cx_tree_erase_all(cx_tree *tree, cx_tnode *x)
{

    while (x != NULL) {
        cx_tnode *y;

        _cx_tree_erase_all(tree, _cx_tnode_right(x));
        y = _cx_tnode_left(x);
        _cx_tnode_destroy(x, _cx_tree_key_destroy(tree),
                          _cx_tree_value_destroy(tree));
        --_cx_tree_node_count(tree);
        x = y;
    }

    return;
}


inline static void
_cx_tree_erase(cx_tree *tree, cx_tnode *x)
{

   cx_tnode *y = _cx_tree_rebalance_for_erase(x, &_cx_tree_root(tree),
                                               &_cx_tree_leftmost(tree),
                                               &_cx_tree_rightmost(tree));

    _cx_tnode_destroy(y, _cx_tree_key_destroy(tree),
                      _cx_tree_value_destroy(tree));
    --_cx_tree_node_count(tree);

    return;

}


inline static void
_cx_tree_clear(cx_tree *tree)
{

    cx_assert(tree != NULL);

    if (_cx_tree_node_count(tree) != 0) {
        _cx_tree_erase_all(tree, _cx_tree_root(tree));
        _cx_tree_root(tree) = NULL;
        _cx_tree_leftmost(tree) = _cx_tree_head(tree);
        _cx_tree_rightmost(tree) = _cx_tree_head(tree);

        cx_assert(_cx_tree_node_count(tree) == 0);
    }

    return;

}


/*
 * Iteration
 */

inline static cx_tree_iterator
_cx_tree_begin(const cx_tree *tree)
{

    return _cx_tree_leftmost(tree);

}


inline static cx_tree_iterator
_cx_tree_end(const cx_tree *tree)
{

    return _cx_tree_head(tree);

}


/*
 * Basic search
 */

inline static cx_tnode *
_cx_tree_lower_bound(const cx_tree *tree, cxcptr key)
{

    cx_tnode *x = _cx_tree_root(tree);  /* Last node not less than key */
    cx_tnode *y = _cx_tree_head(tree);  /* Current node */


    while (x != NULL) {
        if (!_cx_tree_key_compare(tree, _cx_tnode_key(x), key)) {
            y = x;
            x = _cx_tnode_left(x);
        }
        else
            x = _cx_tnode_right(x);
    }

    return y;

}


inline static cx_tnode *
_cx_tree_upper_bound(const cx_tree *tree, cxcptr key)
{

    cx_tnode *x = _cx_tree_root(tree);  /* Last node greater than key */
    cx_tnode *y = _cx_tree_head(tree);  /* Current node */


    while (x != NULL) {
        if (_cx_tree_key_compare(tree, key, _cx_tnode_key(x))) {
            y = x;
            x = _cx_tnode_left(x);
        }
        else
            x = _cx_tnode_right(x);
    }

    return y;

}


inline static cx_tnode *
_cx_tree_find(const cx_tree *tree, cxcptr key)
{

    cx_tnode *x = _cx_tree_root(tree);
    cx_tnode *y = _cx_tree_head(tree);
    cx_tnode *pos;


    while (x != NULL) {
        if (!_cx_tree_key_compare(tree, _cx_tnode_key(x), key)) {
            y = x;
            x = _cx_tnode_left(x);
        }
        else
            x = _cx_tnode_right(x);
    }

    pos = y;

    if (pos == _cx_tree_head(tree) ||
        _cx_tree_key_compare(tree, key, _cx_tnode_key(pos)))
        return _cx_tree_head(tree);

    return pos;

}


inline static cxbool
_cx_tree_exists(const cx_tree *tree, cx_tnode *x)
{

    cx_tnode *y;
    cxptr key = _cx_tnode_key(x);


    y = _cx_tree_lower_bound(tree, key);

    if (y != x) {
        cx_tnode *z = _cx_tree_upper_bound(tree, key);

        y = _cx_tnode_next(y);
        while (y != x && y != z)
            y = _cx_tnode_next(y);
    }

    return x == y ? TRUE : FALSE;

}


/*
 * Public methods
 */

/**
 * @brief
 *   Get an iterator to the first pair in the tree.
 *
 * @param tree  The tree to query.
 *
 * @return Iterator for the first pair or @b cx_tree_end() if the tree is
 *   empty.
 *
 * The function returns a handle for the first pair in the tree @em tree.
 * The returned iterator cannot be used directly to access the value field
 * of the key/value pair, but only through the appropriate methods.
 */

cx_tree_iterator
cx_tree_begin(const cx_tree *tree)
{

    cx_assert(tree != NULL);

    return _cx_tree_begin(tree);

}


/**
 * @brief
 *   Get an iterator for the position after the last pair in the tree.
 *
 * @param tree  The tree to query.
 *
 * @return Iterator for the end of the tree.
 *
 * The function returns an iterator for the position one past the last pair
 * in the tree @em tree. The iteration is done in ascending order according
 * to the keys. The returned iterator cannot be used directly to access the
 * value field of the key/value pair, but only through the appropriate
 * methods.
 */

cx_tree_iterator
cx_tree_end(const cx_tree *tree)
{

    cx_assert(tree != NULL);

    return _cx_tree_end(tree);

}


/**
 * @brief
 *   Get an iterator for the next pair in the tree.
 *
 * @param tree      A tree.
 * @param position  Current iterator position.
 *
 * @return Iterator for the pair immediately following @em position.
 *
 * The function returns an iterator for the next pair in the tree @em tree
 * with respect to the current iterator position @em position. Iteration
 * is done in ascending order according to the keys. If the tree is empty
 * or @em position points to the end of the tree the function returns
 * @b cx_tree_end().
 */

cx_tree_iterator
cx_tree_next(const cx_tree *tree, cx_tree_const_iterator position)
{

    cx_assert(tree != NULL);
    cx_assert(position != NULL);
    cx_assert(position == _cx_tree_end(tree) ||
              _cx_tree_exists(tree, (cx_tree_iterator)position));

    if (position == _cx_tree_end(tree)) {
        return _cx_tree_end(tree);
    }

    return _cx_tnode_next(position);

}


/**
 * @brief
 *   Get an iterator for the previous pair in the tree.
 *
 * @param tree      A tree.
 * @param position  Current iterator position.
 *
 * @return Iterator for the pair immediately preceding @em position.
 *
 * The function returns an iterator for the previous pair in the tree
 * @em tree with respect to the current iterator position @em position.
 * Iteration is done in ascending order according to the keys. If the
 * tree is empty or @em position points to the beginning of the tree the
 * function returns @b cx_tree_end().
 */

cx_tree_iterator
cx_tree_previous(const cx_tree *tree, cx_tree_const_iterator position)
{

    cx_assert(tree != NULL);
    cx_assert(position != NULL);
    cx_assert(position == _cx_tree_end(tree) ||
              _cx_tree_exists(tree, (cx_tree_iterator)position));

    if (position == _cx_tree_begin(tree)) {
        return _cx_tree_begin(tree);
    }

    return _cx_tnode_previous(position);

}


/**
 * @brief
 *   Remove all pairs from a tree.
 *
 * @param tree  Tree to be cleared.
 *
 * @return Nothing.
 *
 * The tree @em tree is cleared, i.e. all pairs are removed from the tree.
 * Keys and values are destroyed using the key and value destructors set up
 * during tree creation. After calling this function the tree is empty.
 */

void
cx_tree_clear(cx_tree *tree)
{

    cx_assert(tree != NULL);
    _cx_tree_clear(tree);

    return;

}


/**
 * @brief
 *   Check whether a tree is empty.
 *
 * @param tree  A tree.
 *
 * @return The function returns @c TRUE if the tree is empty, and @c FALSE
 *   otherwise.
 *
 * The function checks if the tree contains any pairs. Calling this function
 * is equivalent to the statement:
 * @code
 *   return (cx_tree_size(tree) == 0);
 * @endcode
 */

cxbool
cx_tree_empty(const cx_tree *tree)
{

    return (_cx_tree_node_count(tree) == 0);

}


/**
 * @brief
 *   Create a new tree without any elements.
 *
 * @param  compare        Function used to compare keys.
 * @param  key_destroy    Destructor for the keys.
 * @param  value_destroy  Destructor for the value field.
 *
 * @return Handle for the newly allocated tree.
 *
 * Memory for a new tree is allocated and the tree is initialized to be a
 * valid empty tree.
 *
 * The tree's key comparison function is set to @em compare. It must
 * return @c TRUE or @c FALSE if the comparison of the first argument
 * passed to it with the second argument is found to be true or false
 * respectively.
 *
 * The destructors for a tree node's key and value field are set to
 * @em key_destroy and @em value_destroy. Whenever a tree node is
 * destroyed these functions are used to deallocate the memory used
 * by the key and the value. Each of the destructors might be @c NULL, i.e.
 * keys and values are not deallocated during destroy operations.
 *
 * @see cx_tree_compare_func()
 */

cx_tree *
cx_tree_new(cx_tree_compare_func compare, cx_free_func key_destroy,
            cx_free_func value_destroy)
{

    cx_tree *tree;


    cx_assert(compare != NULL);

    tree = cx_malloc(sizeof *tree);
    _cx_tree_head(tree) = cx_malloc(sizeof(cx_tnode));

    _cx_tree_initialize(tree, compare, key_destroy, value_destroy);

    return tree;

}


/**
 * @brief
 *   Destroy a tree and all its elements.
 *
 * @param tree  The tree to destroy.
 *
 * @return Nothing.
 *
 * The tree @em tree is deallocated. All data values and keys are
 * deallocated using the tree's key and value destructor. If no
 * key and/or value destructor was set when the @em tree was created
 * the keys and the stored data values are left untouched. In this
 * case the key and value deallocation is the responsibility of the
 * user.
 *
 * @see cx_tree_new()
 */

void
cx_tree_delete(cx_tree *tree)
{

    if (tree) {
        _cx_tree_clear(tree);
        cx_free(_cx_tree_head(tree));
        cx_free(tree);
    }

    return;

}


/**
 * @brief
 *   Get the actual number of pairs in the tree.
 *
 * @param tree  A tree.
 *
 * @return The current number of pairs, or 0 if the tree is empty.
 *
 * Retrieves the current number of pairs stored in the tree.
 */

cxsize
cx_tree_size(const cx_tree *tree)
{

    cx_assert(tree != NULL);

    return _cx_tree_node_count(tree);

}


/**
 * @brief
 *   Get the maximum number of pairs possible.
 *
 * @param tree  A tree.
 *
 * @return The maximum number of pairs that can be stored in the tree.
 *
 * Retrieves the tree's capacity, i.e. the maximum possible number of
 * pairs a tree can manage.
 */

cxsize
cx_tree_max_size(const cx_tree *tree)
{

    cx_assert(tree != NULL);

    return (cxsize)(-1);

}


/**
 * @brief
 *   Get the key comparison function.
 *
 * @param tree  The tree to query.
 *
 * @return Handle for the tree's key comparison function.
 *
 * The function retrieves the function used by the tree methods
 * for comparing keys. The key comparison function is set during
 * tree creation.
 *
 * @see cx_tree_new()
 */

cx_tree_compare_func
cx_tree_key_comp(const cx_tree *tree)
{

    cx_assert(tree != NULL);

    return _cx_tree_compare(tree);

}


/**
 * @brief
 *   Swap the contents of two trees.
 *
 * @param tree1  First tree.
 * @param tree2  Second tree.
 *
 * @return Nothing.
 *
 * All pairs stored in the first tree @em tree1 are moved to the second tree
 * @em tree2, while the pairs from @em tree2 are moved to @em tree1. Also
 * the key comparison function, the key and the value destructor are
 * exchanged.
 */

void
cx_tree_swap(cx_tree *tree1, cx_tree *tree2)
{

    cx_tnode *tmp;
    cxsize sz;
    cx_tree_compare_func cmp;
    cx_free_func destroy;


    cx_assert(tree1 != NULL);
    cx_assert(tree2 != NULL);

    tmp = _cx_tree_head(tree2);
    _cx_tree_head(tree2) = _cx_tree_head(tree1);
    _cx_tree_head(tree1) = tmp;

    sz = _cx_tree_node_count(tree2);
    _cx_tree_node_count(tree2) = _cx_tree_node_count(tree1);
    _cx_tree_node_count(tree1) = sz;

    cmp = _cx_tree_compare(tree2);
    _cx_tree_compare(tree2) = _cx_tree_compare(tree1);
    _cx_tree_compare(tree1) = cmp;

    destroy = _cx_tree_key_destroy(tree2);
    _cx_tree_key_destroy(tree2) = _cx_tree_key_destroy(tree1);
    _cx_tree_key_destroy(tree1) = destroy;

    destroy = _cx_tree_value_destroy(tree2);
    _cx_tree_value_destroy(tree2) = _cx_tree_value_destroy(tree1);
    _cx_tree_value_destroy(tree1) = destroy;

    return;

}


/**
 * @brief
 *   Assign data to an iterator position.
 *
 * @param tree      A tree.
 * @param position  Iterator positions where the data will be stored.
 * @param data      Data to store.
 *
 * @return Handle to the previously stored data object.
 *
 * The function assigns a data object reference @em data to the iterator
 * position @em position of the tree @em tree.
 */

cxptr
cx_tree_assign(cx_tree *tree, cx_tree_iterator position, cxcptr data)
{

    cxptr tmp;


    cx_assert(tree != NULL);
    cx_assert(position != NULL);
    cx_assert(_cx_tree_exists(tree, position));

    tmp = _cx_tnode_get_value(position);
    _cx_tnode_set_value(position, data);

    return tmp;

}


/**
 * @brief
 *   Get the key from a given iterator position.
 *
 * @param tree      A tree.
 * @param position  Iterator position the data is retrieved from.
 *
 * @return Reference for the key.
 *
 * The function returns a reference to the key associated with the iterator
 * position @em position in the tree @em tree.
 *
 * @note
 *   One must not modify the key of @em position through the returned
 *   reference, since this might corrupt the tree!
 */

cxptr
cx_tree_get_key(const cx_tree *tree, cx_tree_const_iterator position)
{

    cx_assert(tree != NULL);
    cx_assert(position != NULL);
    cx_assert(_cx_tree_exists(tree, (cx_tree_iterator)position));

    return _cx_tnode_get_key(position);

}


/**
 * @brief
 *   Get the data from a given iterator position.
 *
 * @param tree      A tree.
 * @param position  Iterator position the data is retrieved from.
 *
 * @return Handle for the data object.
 *
 * The function returns a reference to the data stored at iterator position
 * @em position in the tree @em tree.
 */

cxptr
cx_tree_get_value(const cx_tree *tree, cx_tree_const_iterator position)
{

    cx_assert(tree != NULL);
    cx_assert(position != NULL);
    cx_assert(_cx_tree_exists(tree, (cx_tree_iterator)position));

    return _cx_tnode_get_value(position);

}


/**
 * @brief
 *   Locate an element in the tree.
 *
 * @param tree  A tree.
 * @param key   Key of the (key, value) pair to locate.
 *
 * @return Iterator pointing to the sought-after element, or @b cx_tree_end()
 *   if it was not found.
 *
 * The function searches the tree @em tree for an element with a key
 * matching @em key. If the search was successful an iterator to the
 * sought-after pair is returned. If the search did not succeed, i.e.
 * @em key is not present in the tree, a one past the end iterator is
 * returned.
 */

cx_tree_iterator
cx_tree_find(const cx_tree *tree, cxcptr key)
{

    cx_assert(tree != NULL);
    cx_assert(key != NULL);

    return _cx_tree_find(tree, key);

}


/**
 * @brief
 *   Find the beginning of a subsequence.
 *
 * @param tree  A tree.
 * @param key   Key of the (key, value) pair(s) to locate.
 *
 * @return Iterator pointing to the first position where an element with
 *   key @em key would get inserted, i.e. the first element with a key greater
 *   or equal than @em key.
 *
 * The function returns the first element of a subsequence of elements in the
 * tree that match the given key @em key. If @em key is not present in the
 * tree @em tree an iterator pointing to the first element that has a greater
 * key than @em key or @b cx_tree_end() if no such element exists.
 */

cx_tree_iterator
cx_tree_lower_bound(const cx_tree *tree, cxcptr key)
{

    cx_assert(tree != NULL);
    cx_assert(key != NULL);

    return _cx_tree_lower_bound(tree, key);

}


/**
 * @brief
 *   Find the end of a subsequence.
 *
 * @param tree  A tree.
 * @param key   Key of the (key, value) pair(s) to locate.
 *
 * @return Iterator pointing to the last position where an element with
 *   key @em key would get inserted, i.e. the first element with a key
 *   greater than @em key.
 *
 * The function returns the last element of a subsequence of elements in the
 * tree that match the given key @em key. If @em key is not present in the
 * tree @em tree an iterator pointing to the first element that has a greater
 * key than @em key or @b cx_tree_end() if no such element exists.
 */

cx_tree_iterator
cx_tree_upper_bound(const cx_tree *tree, cxcptr key)
{

    cx_assert(tree != NULL);
    cx_assert(key != NULL);

    return _cx_tree_upper_bound(tree, key);
}


/**
 * @brief
 *   Find a subsequence matching a given key.
 *
 * @param tree   A tree.
 * @param key    The key of the (key, value) pair(s) to be located.
 * @param begin  First element with key @em key.
 * @param end    Last element with key @em key.
 *
 * @return Nothing.
 *
 * The function returns the beginning and the end of a subsequence of
 * tree elements with the key @em key through through the @em begin and
 * @em end arguments. After calling this function @em begin possibly points
 * to the first element of @em tree matching the key @em key and @em end
 * possibly points to the last element of the sequence. If key is not
 * present in the tree @em begin points to the next greater element or,
 * if no such element exists, to @b cx_tree_end().
 */

void
cx_tree_equal_range(const cx_tree *tree, cxcptr key,
                    cx_tree_iterator *begin, cx_tree_iterator *end)
{

    cx_assert(tree != NULL);
    cx_assert(key != NULL);

    *begin = _cx_tree_lower_bound(tree, key);
    *end = _cx_tree_upper_bound(tree, key);

    return;

}


/**
 * @brief
 *   Get the number of elements matching a key.
 *
 * @param tree  A tree.
 * @param key   Key of the (key, value) pair(s) to locate.
 *
 * @return The number of elements with the specified key.
 *
 * Counts all elements of the tree @em tree matching the key @em key.
 */

cxsize
cx_tree_count(const cx_tree *tree, cxcptr key)
{

    cx_tnode *x, *y;
    cxsize count = 0;


    cx_assert(tree != NULL);
    cx_assert(key != NULL);

    x = _cx_tree_lower_bound(tree, key);
    y = _cx_tree_upper_bound(tree, key);

    /*
     * Only if key is not present in the tree x and y are identical,
     * pointing to the element with the next greater key.
     */

    while (x != y) {
        ++count;
        x = _cx_tnode_next(x);
    }

    return count;

}


/**
 * @brief
 *   Attempt to insert data into a tree.
 *
 * @param tree  A tree.
 * @param key   Key used to store the data.
 * @param data  Data to insert.
 *
 * @return An iterator that points to the inserted pair, or @c NULL if the
 *   pair could not be inserted.
 *
 * This function attempts to insert a (key, value) pair into the tree
 * @em tree. The insertion fails if the key already present in the tree,
 * i.e. if the key is not unique.
 */

cx_tree_iterator
cx_tree_insert_unique(cx_tree *tree, cxcptr key, cxcptr data)
{

    cx_assert(tree != NULL);
    cx_assert(key != NULL);

    return _cx_tree_insert_unique(tree, key, data);

}


/**
 * @brief
 *   Insert data into a tree.
 *
 * @param tree  A tree.
 * @param key   Key used to store the data.
 * @param data  Data to insert.
 *
 * @return An iterator that points to the inserted pair.
 *
 * This function inserts a (key, value) pair into the tree @em tree.
 * Contrary to @b cx_tree_insert_unique() the key @em key used for inserting
 * @em data may already be present in the tree.
 */

cx_tree_iterator
cx_tree_insert_equal(cx_tree *tree, cxcptr key, cxcptr data)
{

    cx_assert(tree != NULL);
    cx_assert(key != NULL);

    return _cx_tree_insert_equal(tree, key, data);

}


/**
 * @brief
 *   Erase an element from a tree.
 *
 * @param tree      A tree.
 * @param position  Iterator position of the element to be erased.
 *
 * @return Nothing.
 *
 * This function erases an element, specified by the iterator @em position,
 * from @em tree. Key and value associated with the erased pair are
 * deallocated using the tree's key and value destructors, provided
 * they have been set.
 */

void
cx_tree_erase_position(cx_tree *tree, cx_tree_iterator position)
{

    cx_assert(tree != NULL);

    if (!position) {
        return;
    }

    cx_assert(_cx_tree_exists(tree, position));
    _cx_tree_erase(tree, position);

    return;

}


/**
 * @brief
 *   Erase a range of elements from a tree.
 *
 * @param tree   A tree.
 * @param begin  Iterator pointing to the start of the range to erase.
 * @param end    Iterator pointing to the end of the range to erase.
 *
 * @return Nothing.
 *
 * This function erases all elements in the range [begin, end) from
 * the tree @em tree. Key and value associated with the erased pair(s) are
 * deallocated using the tree's key and value destructors, provided
 * they have been set.
 */

void
cx_tree_erase_range(cx_tree *tree, cx_tree_iterator begin,
                    cx_tree_iterator end)
{

    cx_assert(tree != NULL);
    cx_assert(begin == _cx_tree_head(tree) || _cx_tree_exists(tree, begin));
    cx_assert(end == _cx_tree_head(tree) || _cx_tree_exists(tree, end));

    while (begin != end) {
        cx_tnode *pos = begin;

        begin = _cx_tnode_next(pos);
        _cx_tree_erase(tree, pos);
    }

    return;

}


/**
 * @brief
 *   Erase all elements from a tree matching the provided key.
 *
 * @param tree  A tree.
 * @param key   Key of the element to be erased.
 *
 * @return The number of removed elements.
 *
 * This function erases all elements with the specified key @em key,
 * from @em tree. Key and value associated with the erased pairs are
 * deallocated using the tree's key and value destructors, provided
 * they have been set.
 */

cxsize
cx_tree_erase(cx_tree *tree, cxcptr key)
{

    cx_tnode *x, *y;
    cxsize count = 0;


    cx_assert(tree != NULL);
    cx_assert(key != NULL);

    x = _cx_tree_lower_bound(tree, key);
    y = _cx_tree_upper_bound(tree, key);

    while (x != y) {
        cx_tnode *pos = x;

        x = _cx_tnode_next(x);
        _cx_tree_erase(tree, pos);

        ++count;
    }

    return count;

}


/**
 * @brief
 *   Validate a tree.
 *
 * @param tree  The tree to verify.
 *
 * @return Returns @c TRUE if the tree is valid, or @c FALSE otherwise.
 *
 * The function is provided for debugging purposes. It verifies that
 * the internal tree structure of @em tree is valid.
 */

cxbool
cx_tree_verify(const cx_tree *tree)
{

    cx_tnode *it;
    cxsize len = 0;


    cx_assert(tree != NULL);

    if (_cx_tree_node_count(tree) == 0 ||
        _cx_tree_begin(tree) == _cx_tree_end(tree)) {
        if (_cx_tree_node_count(tree) == 0 &&
            _cx_tree_begin(tree) == _cx_tree_end(tree) &&
            _cx_tnode_left(_cx_tree_head(tree)) == _cx_tree_head(tree) &&
            _cx_tnode_right(_cx_tree_head(tree)) == _cx_tree_head(tree))
            return TRUE;
        else
            return FALSE;
    }

    len = _cx_tree_black_count(_cx_tree_leftmost(tree), _cx_tree_root(tree));

    for (it = _cx_tree_begin(tree); it != _cx_tree_end(tree);
         it = _cx_tnode_next(it)) {

        cx_tnode *x = it;
        cx_tnode *L = _cx_tnode_left(x);
        cx_tnode *R = _cx_tnode_right(x);

        if (_cx_tnode_color(x) == CX_TNODE_RED)
            if ((L && _cx_tnode_color(L) == CX_TNODE_RED) ||
                (R && _cx_tnode_color(R) == CX_TNODE_RED))
                return FALSE;

        if (L && _cx_tree_key_compare(tree, _cx_tnode_key(x),
                                      _cx_tnode_key(L)))
            return FALSE;

        if (R && _cx_tree_key_compare(tree, _cx_tnode_key(R),
                                      _cx_tnode_key(x)))
            return FALSE;

        if (!L && !R && _cx_tree_black_count(x, _cx_tree_root(tree)) != len)
            return FALSE;

    }

    if (_cx_tree_leftmost(tree) != _cx_tnode_minimum(_cx_tree_root(tree)))
        return FALSE;

    if (_cx_tree_rightmost(tree) != _cx_tnode_maximum(_cx_tree_root(tree)))
        return FALSE;

    return TRUE;

}
/**@}*/