This file is indexed.

/usr/include/bm/bmblocks.h is in bmagic 3.7.0-3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
#ifndef BM_BLOCKS__H__INCLUDED__
#define BM_BLOCKS__H__INCLUDED__
/*
Copyright(c) 2002-2010 Anatoliy Kuznetsov(anatoliy_kuznetsov at yahoo.com)

Permission is hereby granted, free of charge, to any person 
obtaining a copy of this software and associated documentation 
files (the "Software"), to deal in the Software without restriction, 
including without limitation the rights to use, copy, modify, merge, 
publish, distribute, sublicense, and/or sell copies of the Software, 
and to permit persons to whom the Software is furnished to do so, 
subject to the following conditions:

The above copyright notice and this permission notice shall be included 
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 
OTHER DEALINGS IN THE SOFTWARE.

For more information please visit:  http://bmagic.sourceforge.net

*/


#include "bmfwd.h"

#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4100)
#endif


namespace bm
{


/*!
   @brief bitvector blocks manager
        Embedded class managing bit-blocks on very low level.
        Includes number of functor classes used in different bitset algorithms. 
   @ingroup bvector
   @internal
*/

template<class Alloc/*, class MS*/> 
class blocks_manager
{
public:

    typedef Alloc allocator_type;

    /** Base functor class (block visitor)*/
    class bm_func_base
    {
    public:
        bm_func_base(blocks_manager& bman) : bm_(bman) {}

        void on_empty_top(unsigned /* top_block_idx*/ ) {}
        void on_empty_block(unsigned /* block_idx*/ ) {}
    private:
        bm_func_base(const bm_func_base&);
        bm_func_base& operator=(const bm_func_base&);
    protected:
        blocks_manager&  bm_;
    };


    /** Base functor class connected for "constant" functors*/
    class bm_func_base_const
    {
    public:
        bm_func_base_const(const blocks_manager& bman) : bm_(bman) {}

        void on_empty_top(unsigned /* top_block_idx*/ ) {}
        void on_empty_block(unsigned /* block_idx*/ ) {}
    private:
        bm_func_base_const(const bm_func_base_const&);
        bm_func_base_const& operator=(const bm_func_base_const&);
    protected:
        const blocks_manager&  bm_;
    };


    /** Base class for bitcounting functors */
    class block_count_base : public bm_func_base_const
    {
    protected:
        block_count_base(const blocks_manager& bm) 
            : bm_func_base_const(bm) {}

        bm::id_t block_count(const bm::word_t* block) const
        {
            return this->bm_.block_bitcount(block);
        }
    };


    /** Bitcounting functor */
    class block_count_func : public block_count_base
    {
    public:
        block_count_func(const blocks_manager& bm) 
            : block_count_base(bm), count_(0) {}

        bm::id_t count() const { return count_; }

        void operator()(const bm::word_t* block)
        {
            count_ += this->block_count(block);
        }

    private:
        bm::id_t count_;
    };


    /** Bitcounting functor filling the block counts array*/
    class block_count_arr_func : public block_count_base
    {
    public:
        block_count_arr_func(const blocks_manager& bm, unsigned* arr) 
            : block_count_base(bm), arr_(arr), last_idx_(0) 
        {
            arr_[0] = 0;
        }

        void operator()(const bm::word_t* block, unsigned idx)
        {
            while (++last_idx_ < idx)
            {
                arr_[last_idx_] = 0;
            }
            arr_[idx] = this->block_count(block);
            last_idx_ = idx;
        }

        unsigned last_block() const { return last_idx_; }

    private:
        unsigned*  arr_;
        unsigned   last_idx_;
    };

    /** bit value change counting functor */
    class block_count_change_func : public bm_func_base_const
    {
    public:
        block_count_change_func(const blocks_manager& bm) 
            : bm_func_base_const(bm),
                count_(0),
                prev_block_border_bit_(0)
        {}

        bm::id_t block_count(const bm::word_t* block, unsigned idx)
        {
            bm::id_t count = 0;
            bm::id_t first_bit;
            
            if (IS_FULL_BLOCK(block) || (block == 0))
            {
                count = 1;
                if (idx)
                {
                    first_bit = block ? 1 : 0;
                    count -= !(prev_block_border_bit_ ^ first_bit);
                }
                prev_block_border_bit_ = block ? 1 : 0;
            }
            else
            {
                if (BM_IS_GAP(block))
                {
                    gap_word_t* gap_block = BMGAP_PTR(block);
                    count = gap_length(gap_block) - 1;
                    if (idx)
                    {
                        first_bit = gap_test(gap_block, 0);
                        count -= !(prev_block_border_bit_ ^ first_bit);
                    }
                        
                    prev_block_border_bit_ = 
                        gap_test(gap_block, gap_max_bits-1);
                }
                else // bitset
                {
                    unsigned bit_count;
                    count = bit_block_calc_count_change(block,
                                                block + bm::set_block_size,
                                                &bit_count);
                    if (idx)
                    {
                        first_bit = block[0] & 1;
                        count -= !(prev_block_border_bit_ ^ first_bit);
                    }
                    prev_block_border_bit_ = 
                        block[set_block_size-1] >> ((sizeof(block[0]) * 8) - 1);
                    
                }
            }
            return count;
        }
        
        bm::id_t count() const { return count_; }

        void operator()(const bm::word_t* block, unsigned idx)
        {
            count_ += block_count(block, idx);
        }

    private:
        bm::id_t   count_;
        bm::id_t   prev_block_border_bit_;
    };


    /** Functor detects if any bit set*/
    class block_any_func : public bm_func_base_const
    {
    public:
        block_any_func(const blocks_manager& bm) 
            : bm_func_base_const(bm) 
        {}

        bool operator()(const bm::word_t* block, unsigned /* idx */)
        {
            if (IS_FULL_BLOCK(block)) return true;

            if (BM_IS_GAP(block)) // gap block
            {
                if (!gap_is_all_zero(BMGAP_PTR(block), bm::gap_max_bits))
                {
                    return true;
                }
            }
            else  // bitset
            {
                bm::wordop_t* blk1 = (wordop_t*)block;
                bm::wordop_t* blk2 = 
                    (wordop_t*)(block + bm::set_block_size);
                if (!bit_is_all_zero(blk1, blk2))
                {
                    return true;
                }
            }
            return false;
        }
    };

    /*! Change GAP level lengths functor */
    class gap_level_func : public bm_func_base
    {
    public:
        gap_level_func(blocks_manager& bm, const gap_word_t* glevel_len)
            : bm_func_base(bm),
                glevel_len_(glevel_len)
        {
            BM_ASSERT(glevel_len);
        }

        void operator()(bm::word_t* block, unsigned idx)
        {
            blocks_manager& bman = this->bm_;
            
            if (!BM_IS_GAP(block))
                return;

            gap_word_t* gap_blk = BMGAP_PTR(block);

            // TODO: Use the same code as in the optimize functor
            if (gap_is_all_zero(gap_blk, bm::gap_max_bits))
            {
                bman.set_block_ptr(idx, 0);
                goto free_block;
            }
            else 
            if (gap_is_all_one(gap_blk, bm::gap_max_bits))
            {
                bman.set_block_ptr(idx, FULL_BLOCK_ADDR);
            free_block:
                bman.get_allocator().free_gap_block(gap_blk, 
                                                    bman.glen());
                bman.set_block_bit(idx);
                return;
            }

            unsigned len = gap_length(gap_blk);
            int level = gap_calc_level(len, glevel_len_);
            if (level == -1)
            {
                bm::word_t* blk = 
                    bman.get_allocator().alloc_bit_block();
                bman.set_block_ptr(idx, blk);
                bman.set_block_bit(idx);
                gap_convert_to_bitset(blk, gap_blk);
            }
            else
            {
                gap_word_t* gap_blk_new = 
                    bman.allocate_gap_block(level, gap_blk, glevel_len_);

                bm::word_t* p = (bm::word_t*) gap_blk_new;
                BMSET_PTRGAP(p);
                bman.set_block_ptr(idx, p);
            }
            bman.get_allocator().free_gap_block(gap_blk, bman.glen());
        }

    private:
        const gap_word_t* glevel_len_;
    };


    /*! Bitblock optimization functor */
    class block_opt_func : public bm_func_base
    {
    public:
        block_opt_func(blocks_manager& bm, 
                        bm::word_t*     temp_block,
                        int             opt_mode,
                        bv_statistics*  bv_stat=0) 
            : bm_func_base(bm),
              temp_block_(temp_block),
              opt_mode_(opt_mode),
              stat_(bv_stat),
              empty_(0)
        {
            BM_ASSERT(temp_block);
        }

        void on_empty_top(unsigned i)
        {
            bm::word_t*** blk_root = this->bm_.get_rootblock();
            bm::word_t** blk_blk = blk_root[i];
            if (blk_blk) 
            {
                this->bm_.get_allocator().free_ptr(blk_blk);
                blk_root[i] = 0;
            }
            if (stat_)
            {
                stat_->max_serialize_mem += sizeof(unsigned) + 1;
            }
        }
        void on_empty_block(unsigned /* block_idx*/ ) { ++empty_; }

        void operator()(bm::word_t* block, unsigned idx)
        {
            blocks_manager& bman = this->bm_;
            if (IS_FULL_BLOCK(block)) 
            {
                ++empty_;
                return;
            }

            if (stat_) 
            {
                stat_->max_serialize_mem += empty_ << 2;
                empty_ = 0;
            }

            gap_word_t* gap_blk;
            if (BM_IS_GAP(block)) // gap block
            {
                gap_blk = BMGAP_PTR(block);
                // check if block is empty (or all 1)
                if (gap_is_all_zero(gap_blk, bm::gap_max_bits))
                {
                    bman.set_block_ptr(idx, 0);
                    this->free_block(gap_blk, idx);
                    ++empty_;
                }
                else 
                if (gap_is_all_one(gap_blk, bm::gap_max_bits))
                {
                    bman.set_block_ptr(idx, FULL_BLOCK_ADDR);
                    this->free_block(gap_blk, idx);
                    ++empty_;
                }
                else
                {
                    // regular gap block - compute statistics
                    if (stat_)
                    {
                        stat_->add_gap_block(
                                    bm::gap_capacity(gap_blk, bman.glen()),
                                    bm::gap_length(gap_blk));
                    }
                }
            }
            else // bit block
            {
                if (opt_mode_ < 3) // free_01 optimization
                {  
                    bm::wordop_t* blk1 = (wordop_t*)block;
                    bm::wordop_t* blk2 = 
                        (wordop_t*)(block + bm::set_block_size);
                
                    bool b = bit_is_all_zero(blk1, blk2);
                    if (b)
                    {
                        bman.get_allocator().free_bit_block(block);
                        bman.set_block_ptr(idx, 0);
                        ++empty_;
                    } 
                    else
                    if (opt_mode_ == 2) // check if it is all 1 block
                    {
                        b = is_bits_one(blk1, blk2);
                        if (b) 
                        {
                            bman.get_allocator().free_bit_block(block);
                            bman.set_block_ptr(idx, FULL_BLOCK_ADDR);
                            ++empty_;
                        }
                    }

                    if (!b && stat_)
                        stat_->add_bit_block();

                    return;
                }
            
                // try to compress
            
                gap_word_t* tmp_gap_blk = (gap_word_t*)temp_block_;
                *tmp_gap_blk = bm::gap_max_level << 1;

                unsigned threashold = bman.glen(bm::gap_max_level)-4;

                unsigned len = bit_convert_to_gap(tmp_gap_blk, 
                                                    block, 
                                                    bm::gap_max_bits, 
                                                    threashold);
                if (len)    // compression successful                
                {                
                    bman.get_allocator().free_bit_block(block);

                    // check if new gap block can be eliminated
                    if (gap_is_all_zero(tmp_gap_blk, bm::gap_max_bits))
                    {
                        bman.set_block_ptr(idx, 0);
                        ++empty_;
                    }
                    else if (gap_is_all_one(tmp_gap_blk, bm::gap_max_bits))
                    {
                        bman.set_block_ptr(idx, FULL_BLOCK_ADDR);
                        ++empty_;
                    }
                    else
                    {
                        int level = bm::gap_calc_level(len, bman.glen());

                        gap_blk = 
                            bman.allocate_gap_block(level, tmp_gap_blk);
                        bman.set_block_ptr(idx, (bm::word_t*)gap_blk);
                        bman.set_block_gap(idx);
                        if (stat_)
                        {
                            stat_->add_gap_block(
                                    bm::gap_capacity(gap_blk, bman.glen()),
                                    bm::gap_length(gap_blk));
                        }
                    }
                }  
                else  // non-compressable bit-block
                {
                    if (stat_)
                        stat_->add_bit_block();
                }
            }
        }
    private:
        void free_block(gap_word_t* gap_blk, unsigned idx)
        {
            this->bm_.get_allocator().free_gap_block(gap_blk,
                                                     this->bm_.glen());
            this->bm_.set_block_bit(idx);
        }

    private:
        bm::word_t*         temp_block_;
        int                 opt_mode_;
        bv_statistics*      stat_;
        unsigned            empty_;
    };

    /** Bitblock invert functor */
    class block_invert_func : public bm_func_base
    {
    public:
        block_invert_func(blocks_manager& bm) 
            : bm_func_base(bm) {}

        void operator()(bm::word_t* block, unsigned idx)
        {
            if (!block)
            {
                this->bm_.set_block(idx, FULL_BLOCK_ADDR);
            }
            else
            if (IS_FULL_BLOCK(block))
            {
                this->bm_.set_block_ptr(idx, 0);
            }
            else
            {
                if (BM_IS_GAP(block)) // gap block
                {
                    gap_invert(BMGAP_PTR(block));
                }
                else  // bit block
                {
                    bm::wordop_t* wrd_ptr = (wordop_t*) block;
                    bm::wordop_t* wrd_end = 
                            (wordop_t*) (block + bm::set_block_size);
                    bit_invert(wrd_ptr, wrd_end);
                }
            }

        }
    };

    /** Set block zero functor */
    class block_zero_func : public bm_func_base
    {
    public:
        block_zero_func(blocks_manager& bm) 
        : bm_func_base(bm)
        {}

        void operator()(bm::word_t* block, unsigned idx)
        {
            if (BM_IS_GAP(block))
                gap_set_all(BMGAP_PTR(block), bm::gap_max_bits, 0);
            else  // BIT block
            {
                if (IS_FULL_BLOCK(block))
                    this->bm_.set_block_ptr(idx, 0);
                else
                    bit_block_set(block, 0);
            }
        }
    };

    /** Fill block with all-one bits functor */
    class block_one_func : public bm_func_base
    {
    public:
        block_one_func(blocks_manager& bm) : bm_func_base(bm) {}

        void operator()(bm::word_t* block, unsigned idx)
        {
            if (!IS_FULL_BLOCK(block))
            {
                this->bm_.set_block_all_set(idx);
            }
        }
    };

    /** Block deallocation functor */
    class block_free_func : public bm_func_base
    {
    public:
        block_free_func(blocks_manager& bm) : bm_func_base(bm) {}

        void operator()(bm::word_t* block)//, unsigned idx)
        {
            blocks_manager& bman = this->bm_;
            if (BM_IS_GAP(block)) // gap block
            {
                bman.get_allocator().free_gap_block(BMGAP_PTR(block),
                                                    bman.glen());
            }
            else
            {
                bman.get_allocator().free_bit_block(block);
            }
        }
    };

    /** Block copy functor */
    class block_copy_func : public bm_func_base
    {
    public:
        block_copy_func(blocks_manager&        bm_target, 
                        const blocks_manager&  bm_src) 
            : bm_func_base(bm_target), 
              bm_src_(bm_src) 
        {}

        void operator()(bm::word_t* block, unsigned idx)
        {
            bm::word_t* new_blk;            
            blocks_manager& bman = this->bm_;

            bool is_gap = BM_IS_GAP(block);
            if (is_gap)
            {
                bm::gap_word_t* gap_block = BMGAP_PTR(block); 
                unsigned level = gap_level(gap_block);
                new_blk = (bm::word_t*)
                    bman.get_allocator().alloc_gap_block(level, 
                                                        bman.glen());
                int len = gap_length(BMGAP_PTR(block));
                ::memcpy(new_blk, gap_block, len * sizeof(gap_word_t));
            }
            else
            {
                new_blk = block;
                if (!IS_FULL_BLOCK(block))
                {
                    new_blk = bman.get_allocator().alloc_bit_block();
                    bit_block_copy(new_blk, block);
                }
            }
            bman.set_block(idx, new_blk, is_gap);
        }

    private:
        block_copy_func(const block_copy_func&);
        block_copy_func& operator=(const block_copy_func&);
    private:
        const blocks_manager&  bm_src_;
    };


public:

    blocks_manager(const gap_word_t* glevel_len, 
                    bm::id_t          max_bits,
                    const Alloc&      alloc = Alloc())
        : temp_block_(0),
          alloc_(alloc)
    {
        ::memcpy(glevel_len_, glevel_len, sizeof(glevel_len_));
        blocks_ = 0;
        top_block_size_ = effective_top_block_size_ = 0;
        if (max_bits) 
        {
            top_block_size_ = compute_top_block_size(max_bits);
            init_tree();
        } 
        volatile const char* vp = _copyright<true>::_p;
        char c = *vp;
        c = 0;
    }

    blocks_manager(const blocks_manager& blockman)
        : blocks_(0),
            top_block_size_(blockman.top_block_size_),
            effective_top_block_size_(blockman.effective_top_block_size_),
        #ifdef BM_DISBALE_BIT_IN_PTR
            gap_flags_(blockman.gap_flags_),
        #endif
            temp_block_(0),
            alloc_(blockman.alloc_)
    {
        ::memcpy(glevel_len_, blockman.glevel_len_, sizeof(glevel_len_));

        init_tree();

        blocks_manager* bm = 
            const_cast<blocks_manager*>(&blockman);

        word_t*** blk_root = bm->blocks_root();

        block_copy_func copy_func(*this, blockman);
        for_each_nzblock(blk_root, top_block_size_, copy_func);
    }

    ~blocks_manager()
    {
        alloc_.free_bit_block(temp_block_);
        deinit_tree();
    }

    void free_ptr(bm::word_t** ptr)
    {
        if (ptr) alloc_.free_ptr(ptr);
    }

    /**
        \brief Compute size of the block array needed to store bits
        \param bits_to_store - supposed capacity (number of bits)
        \return size of the top level block
    */
    unsigned compute_top_block_size(bm::id_t bits_to_store)
    {
        if (bits_to_store == bm::id_max)  // working in full-range mode
        {
            return bm::set_array_size;
        }

        unsigned top_block_size = 
            bits_to_store / (bm::set_block_size * sizeof(bm::word_t) * 
                                                bm::set_array_size * 8);
        return top_block_size + (top_block_size < bm::set_array_size);
    }

    /**
        Returns current capacity (bits)
    */
    bm::id_t capacity() const
    {
        // arithmetic overflow protection...
        return top_block_size_ == bm::set_array_size ? bm::id_max :
            top_block_size_ * bm::set_array_size * bm::bits_in_block;
    }

    /**
        \brief Finds block in 2-level blocks array  
        \param nb - Index of block (logical linear number)
        \return block adress or NULL if not yet allocated
    */
    bm::word_t* get_block(unsigned nb) const
    {
        unsigned block_idx = nb >> bm::set_array_shift;
        if (block_idx >= top_block_size_)
        {
            return 0;
        }
        bm::word_t** blk_blk = blocks_[block_idx];
        return blk_blk ? blk_blk[nb & bm::set_array_mask] : 0;
    }

    /**
        \brief Finds block in 2-level blocks array  
        Specilized version of get_block(unsigned), returns an additional
        condition when there are no more blocks

        \param nb - Index of block (logical linear number)
        \param no_more_blocks - 1 if there are no more blocks at all
        \return block adress or NULL if not yet allocated
    */
    bm::word_t* get_block(unsigned nb, int* no_more_blocks) const
    {
        unsigned block_idx = nb >> bm::set_array_shift;
        if (block_idx >= top_block_size_)
        {
            *no_more_blocks = 1;
            return 0;
        }
        *no_more_blocks = 0;
        bm::word_t** blk_blk = blocks_[block_idx];
        return blk_blk ? blk_blk[nb & bm::set_array_mask] : 0;
    }

    /** 
    Recalculate absolute block address into coordinates
    */
    void get_block_coord(unsigned nb, unsigned* i, unsigned* j) const
    {
        BM_ASSERT(i);
        BM_ASSERT(j);

        *i = nb >> bm::set_array_shift; // top block address
        *j = nb &  bm::set_array_mask;  // address in sub-block
    }

    /**
    Find the next non-zero block starting from nb
    \param nb - block index
    \param deep_scan - flag to perform detailed bit-block analysis
    @return bm::set_total_blocks - no more blocks
    */
    unsigned find_next_nz_block(unsigned nb, bool deep_scan = true) const
    {
        unsigned i,j;
        get_block_coord(nb, &i, &j);
        for (;i < effective_top_block_size_; ++i) 
        { 
            bm::word_t** blk_blk = blocks_[i];
            if (blk_blk)
            {
               unsigned r = i * bm::set_array_size;
               do
               {
                   if (blk_blk[j] && !is_block_zero(r + j, blk_blk[j], deep_scan)) 
                       return r + j;
                   ++j;
               } while (j < bm::set_array_size);
            }
            j = 0;
        } // for i

        return bm::set_total_blocks;
    }

    /**
        \brief Finds block in 2-level blocks array
        \param i - top level block index
        \param j - second level block index
        \return block adress or NULL if not yet allocated
    */
    const bm::word_t* get_block(unsigned i, unsigned j) const
    {
        if (i >= top_block_size_) return 0;
        const bm::word_t* const* blk_blk = blocks_[i];
        return (blk_blk == 0) ? 0 : blk_blk[j];
    }

    /**
        \brief Function returns top-level block in 2-level blocks array
        \param i - top level block index
        \return block adress or NULL if not yet allocated
    */
    const bm::word_t* const * get_topblock(unsigned i) const
    {
        return (i >= top_block_size_) ? 0 : blocks_[i];
    }

    /** 
        \brief Returns root block in the tree.
    */
    bm::word_t*** get_rootblock() const
    {
        blocks_manager* bm = 
            const_cast<blocks_manager*>(this);
        return bm->blocks_root();
    }

    void free_block(bm::word_t* block)
    {
        if (BM_IS_GAP(block))
        {
            alloc_.free_gap_block(BMGAP_PTR(block), glevel_len_);
        }
        else
        {
            alloc_.free_bit_block(block);
        }
    }

    void set_block_all_set(unsigned nb)
    {
        bm::word_t* block = 
            set_block(nb, const_cast<bm::word_t*>(FULL_BLOCK_ADDR));
        free_block(block);
    }

    /**
        Create(allocate) bit block. Old block (if exists) gets deleted.
    */
    bm::word_t* alloc_bit_block(unsigned nb)
    {
        bm::word_t* block = this->get_allocator().alloc_bit_block();
        bm::word_t* old_block = set_block(nb, block);
        if (IS_VALID_ADDR(old_block))
        {
            free_block(old_block);
        }
        return block;
    }

    /**
        Create all-zeros bit block. Old block (if exists) gets deleted.
    */
    bm::word_t* make_bit_block(unsigned nb)
    {
        bm::word_t* block = this->alloc_bit_block(nb);
        bit_block_set(block, 0);
        return block;
    }

    /**
        Create bit block as a copy of source block (bit or gap).
        Old block (if exists) gets deleted.
    */
    bm::word_t* copy_bit_block(unsigned          nb, 
                               const bm::word_t* block_src, int is_src_gap)
    {
        if (block_src == 0)
        {
            zero_block(nb);
            return 0;
        }
        bm::word_t* block = alloc_bit_block(nb);
        if (is_src_gap)
        {
            gap_word_t* gap_block = BMGAP_PTR(block_src);
            gap_convert_to_bitset(block, gap_block);
        }
        else
        {            
            bit_block_copy(block, block_src);
        }
        return block;
    }

    /**
        Copy block from another vector.
        Note:Target block is always replaced through re-allocation.
    */
    bm::word_t* copy_block(unsigned idx, const blocks_manager& bm_src)
    {
        const bm::word_t* block = bm_src.get_block(idx);
		if (block == 0)
		{
			zero_block(idx);
			return 0;
		}
        bm::word_t* new_blk = 0;
        bool is_gap = BM_IS_GAP(block);

        if (is_gap)
        {
            bm::gap_word_t* gap_block = BMGAP_PTR(block); 
            unsigned level = gap_level(gap_block);
            new_blk = (bm::word_t*)
                get_allocator().alloc_gap_block(level, glen());
            int len = gap_length(BMGAP_PTR(block));
            ::memcpy(new_blk, gap_block, len * sizeof(gap_word_t));
            set_gap_level(new_blk, level);
        }
        else
        {
            if (IS_FULL_BLOCK(block))
            {
                new_blk = FULL_BLOCK_ADDR;
            }
            else
            {
                new_blk = get_allocator().alloc_bit_block();
                bit_block_copy(new_blk, block);
            }
        }
        set_block(idx, new_blk, is_gap);
        return new_blk;
    }


    /** 
        Function checks if block is not yet allocated, allocates it and sets to
        all-zero or all-one bits. 

        If content_flag == 1 (ALLSET block) requested and taken block is already ALLSET,
        function will return NULL

        initial_block_type and actual_block_type : 0 - bitset, 1 - gap
    */
    bm::word_t* check_allocate_block(unsigned nb, 
                                     unsigned content_flag,
                                     int      initial_block_type,
                                     int*     actual_block_type,
                                     bool     allow_null_ret=true)
    {
        bm::word_t* block = this->get_block(nb);

        if (!IS_VALID_ADDR(block)) // NULL block or ALLSET
        {
            // if we wanted ALLSET and requested block is ALLSET return NULL
            unsigned block_flag = IS_FULL_BLOCK(block);
            *actual_block_type = initial_block_type;
            if (block_flag == content_flag && allow_null_ret)
            {
                return 0; // it means nothing to do for the caller
            }

            if (initial_block_type == 0) // bitset requested
            {
                block = alloc_.alloc_bit_block();
                // initialize block depending on its previous status
                bit_block_set(block, block_flag ? 0xFF : 0);
                set_block(nb, block, false /*bit*/);
            }
            else // gap block requested
            {
                bm::gap_word_t* gap_block = allocate_gap_block(0);
                gap_set_all(gap_block, bm::gap_max_bits, block_flag);
                set_block(nb, (bm::word_t*)gap_block, true/*gap*/);
                return (bm::word_t*)gap_block;
            }
        }
        else // block already exists
        {
            *actual_block_type = BM_IS_GAP(block);
        }

        return block;
    }

    /*! @brief Fills all blocks with 0.
        @param free_mem - if true function frees the resources
    */
    void set_all_zero(bool free_mem)
    {        
        if (free_mem)
        {
            // TODO: optimization of top-level realloc
            deinit_tree();
            init_tree();
        }
        else
        {
            block_zero_func zero_func(*this);
            unsigned top_size = this->effective_top_block_size();
            for_each_nzblock(blocks_, top_size,  zero_func);
        }
    }

    /*! Replaces all blocks with ALL_ONE block.
    */
    void set_all_one()
    {
        block_one_func func(*this);
        for_each_block(blocks_, top_block_size_, 
                                bm::set_array_size, func);
    }

    /**
        Places new block into descriptors table, returns old block's address.
        NOTE:Old block is not deleted.
    */
    bm::word_t* set_block(unsigned nb, bm::word_t* block)
    {
        register unsigned nblk_blk = nb >> bm::set_array_shift;

        // auto-resize the top block array
        if (nblk_blk >= top_block_size_)
            reserve_top_blocks(nblk_blk + 1);
        if (nblk_blk >= effective_top_block_size_)
            effective_top_block_size_ = nblk_blk + 1;

        // If first level array not yet allocated, allocate it and
        // assign block to it
        if (blocks_[nblk_blk] == 0) 
        {
            blocks_[nblk_blk] = (bm::word_t**)alloc_.alloc_ptr();
            ::memset(blocks_[nblk_blk], 0, 
                bm::set_array_size * sizeof(bm::word_t*));
        }

        // NOTE: block will be replaced without freeing
        unsigned j = nb & bm::set_array_mask;
        bm::word_t* old_block = blocks_[nblk_blk][j];
        blocks_[nblk_blk][j] = block;

        return old_block;
    }


    /**
    Allocate an place new GAP block (copy of provided block)
    */
    bm::word_t* set_gap_block(unsigned      nb,
                          const gap_word_t* gap_block_src,
                          int               level)
    {
        if (level == -1)
        {
            bm::word_t* blk = get_allocator().alloc_bit_block();
            set_block(nb, blk);
            gap_convert_to_bitset(blk, gap_block_src);
            return blk;
        }
        else
        {
            gap_word_t* gap_blk = get_allocator().alloc_gap_block(
                                                         level, this->glen());
            gap_word_t* gap_blk_ptr = BMGAP_PTR(gap_blk);
            ::memcpy(gap_blk_ptr, gap_block_src, 
                                  gap_length(gap_block_src) * sizeof(gap_word_t));
            set_gap_level(gap_blk_ptr, level);
            set_block(nb, (bm::word_t*)gap_blk, true /*GAP*/);
            return (bm::word_t*)gap_blk;
        }
    }

    /**
        Places new block into descriptors table, returns old block's address.
        Old block is not deleted.
    */
    bm::word_t* set_block(unsigned nb, bm::word_t* block, bool gap)
    {
        if (block)
        {
            block = 
                (bm::word_t*) (gap ? BMPTR_SETBIT0(block) : BMPTR_CLEARBIT0(block));
        }

        // top block index
        register unsigned nblk_blk = nb >> bm::set_array_shift;

        // auto-resize the top block array
        if (nblk_blk >= top_block_size_)
            reserve_top_blocks(nblk_blk + 1);
        if (nblk_blk >= effective_top_block_size_)
            effective_top_block_size_ = nblk_blk + 1;

        // If first level array not yet allocated, allocate it and
        // assign block to it
        if (blocks_[nblk_blk] == 0) 
        {
            blocks_[nblk_blk] = (bm::word_t**)alloc_.alloc_ptr();
            ::memset(blocks_[nblk_blk], 0, 
                bm::set_array_size * sizeof(bm::word_t*));
        }

        // NOTE: block will be replaced without freeing
        unsigned j = nb & bm::set_array_mask;
        bm::word_t* old_block = blocks_[nblk_blk][j];
        blocks_[nblk_blk][j] = block; 

        return old_block;
    }

    /**
        Places new block into blocks table.
    */
    void set_block_ptr(unsigned nb, bm::word_t* block)
    {
        BM_ASSERT((nb >> bm::set_array_shift) < effective_top_block_size_);
        blocks_[nb >> bm::set_array_shift][nb & bm::set_array_mask] = block;
    }
        
    /** 
        \brief Converts block from type gap to conventional bitset block.
        \param nb - Block's index. 
        \param gap_block - Pointer to the gap block, 
                            if NULL block nb will be taken
        \param gap_len - GAP block length (optional)
        \return new bit block's memory
    */
    bm::word_t* convert_gap2bitset(unsigned nb, 
                                   const gap_word_t* gap_block=0, 
                                   unsigned gap_len=0)
    {
        bm::word_t* block = this->get_block(nb);
        if (gap_block == 0)
        {
            gap_block = BMGAP_PTR(block);
        }

        BM_ASSERT(IS_VALID_ADDR((bm::word_t*)gap_block));

        bm::word_t* new_block = alloc_.alloc_bit_block();
        gap_convert_to_bitset_l(new_block, gap_block, gap_len);

        // new block will replace the old one(no deletion)
        //set_block_ptr(nb, new_block); 
        if (block)
        {
            set_block_ptr(nb, new_block); 
            alloc_.free_gap_block(BMGAP_PTR(block), glen());
        }
        else
        {
            set_block(nb, new_block); 
        }

        return new_block;
    }

    /**
        Make sure block turns into true bit-block if it is GAP or a full block
    */
    bm::word_t* deoptimize_block(unsigned nb)
    {
        bm::word_t* block = this->get_block(nb);
        if (BM_IS_GAP(block))
        {
            return convert_gap2bitset(nb);
        }
        if (IS_FULL_BLOCK(block)) 
        {
            bm::word_t* new_block = get_allocator().alloc_bit_block();
            bit_block_copy(new_block, block);
            set_block(nb, new_block);
            return new_block;
        }
        return block;
    }

    /**
    Free block, make it zero pointer in the tree
    */
    bm::word_t* zero_block(unsigned nb)
    {
        bm::word_t* block = this->get_block(nb);
        if (!block) return block;
        free_block(block);
        set_block(nb, 0);
        return 0;
    }

    /**
    Free block, make it zero pointer in the tree
    */
    bm::word_t* zero_block(unsigned i, unsigned j)
    {
        bm::word_t** blk_blk = blocks_[i];
        bm::word_t* block = blk_blk[j];
        blk_blk[j] = 0;

        free_block(block);

        return 0;
    }


    /**
        Count number of bits ON in the block
    */
    bm::id_t block_bitcount(const bm::word_t* block) const
    { 
        if (!block) return 0;
        id_t count;

        if (BM_IS_GAP(block))
        {
            count = gap_bit_count(BMGAP_PTR(block));
        }
        else // bitset
        {
            count = (IS_FULL_BLOCK(block)) ? bm::bits_in_block
                : bit_block_calc_count(block, block + bm::set_block_size);
        }
        return count;
    }

    /**
        \brief Extends GAP block to the next level or converts it to bit block.
        \param nb - Block's linear index.
        \param blk - Blocks's pointer 

        \return new GAP block pointer or NULL if block type mutated
    */
    bm::gap_word_t* extend_gap_block(unsigned nb, gap_word_t* blk)
    {
        unsigned level = bm::gap_level(blk);
        unsigned len = bm::gap_length(blk);
        if (level == bm::gap_max_level || len >= gap_max_buff_len)
        {
            convert_gap2bitset(nb);
        }
        else
        {
            bm::gap_word_t* new_gap_blk = allocate_gap_block(++level, blk);
            bm::word_t* new_blk = (bm::word_t*)new_gap_blk;

            BMSET_PTRGAP(new_blk);

            set_block_ptr(nb, new_blk);
            alloc_.free_gap_block(blk, glen());

            return new_gap_blk;
        }
        return 0;
    }

    bool is_block_gap(unsigned nb) const 
    {
        bm::word_t* block = get_block(nb);
        return BMPTR_TESTBIT0(block) != 0;
    }

    void set_block_bit(unsigned nb) 
    { 
        bm::word_t* block = get_block(nb);
        block = (bm::word_t*) BMPTR_CLEARBIT0(block);
        set_block_ptr(nb, block);
    }

    void set_block_gap(unsigned nb) 
    {
        bm::word_t* block = get_block(nb);
        block = (bm::word_t*)BMPTR_SETBIT0(block);
        set_block_ptr(nb, block);
    }

    /**
        \fn bool bm::bvector::blocks_manager::is_block_zero(unsigned nb, bm::word_t* blk)
        \brief Checks all conditions and returns true if block consists of only 0 bits
        \param nb - Block's linear index.
        \param blk - Blocks's pointer
        \param deep_scan - flag to do full bit block verification (scan)
                           when deep scan is not requested result can be approximate
        \returns true if all bits are in the block are 0.
    */
    bool is_block_zero(unsigned          nb, 
                       const bm::word_t* blk, 
                       bool              deep_scan = true) const
    {
        if (blk == 0) return true;

        if (BM_IS_GAP(blk))
        {
            gap_word_t* b = BMGAP_PTR(blk);
            return gap_is_all_zero(b, bm::gap_max_bits);
        }

        if (!deep_scan) 
            return false; // block exists - presume it has bits

        // BIT
        for (unsigned i = 0; i <  bm::set_block_size; ++i)
        {
            if (blk[i] != 0)
                return false;
        }
        return true;
    }

    /**
        \brief Checks if block has only 1 bits
        \param nb - Index of the block.
        \param blk - Block's pointer
        \param deep_scan - flag to do full bit block verification (scan)
                           when deep scan is not requested result can be approximate
        \return true if block consists of 1 bits.
    */
    bool is_block_one(unsigned          nb, 
                      const bm::word_t* blk,
                      bool              deep_scan = true) const
    {
        if (blk == 0) return false;

        if (BM_IS_GAP(blk))
        {
            gap_word_t* b = BMGAP_PTR(blk);
            return gap_is_all_one(b, bm::gap_max_bits);
        }

        // BIT block
        if (IS_FULL_BLOCK(blk))
        {
            return true;
        }
        if (!deep_scan) 
            return false; // block exists - presume it has 0 bits

        return is_bits_one((wordop_t*)blk, 
                           (wordop_t*)(blk + bm::set_block_size));
    }

    /*! Returns temporary block, allocates if needed. */
    bm::word_t* check_allocate_tempblock()
    {
        return temp_block_ ? temp_block_ 
                            : (temp_block_ = alloc_.alloc_bit_block());
    }

    /*! Assigns new GAP lengths vector */
    void set_glen(const gap_word_t* glevel_len)
    {
        ::memcpy(glevel_len_, glevel_len, sizeof(glevel_len_));
    }


    bm::gap_word_t* allocate_gap_block(unsigned level, 
                                       const gap_word_t* src = 0,
                                       const gap_word_t* glevel_len = 0)
    {
        if (!glevel_len)
            glevel_len = glevel_len_;
        gap_word_t* ptr = alloc_.alloc_gap_block(level, glevel_len);
        if (src)
        {
            unsigned len = gap_length(src);
            ::memcpy(ptr, src, len * sizeof(gap_word_t));
            // Reconstruct the mask word using the new level code.
            *ptr = (gap_word_t)(((len-1) << 3) | (level << 1) | (*src & 1));
        }
        else
        {
            *ptr = (gap_word_t)(level << 1);
        }
        return ptr;
    }

    unsigned mem_used() const
    {
        unsigned mem_used = sizeof(*this);
        mem_used += temp_block_ ? sizeof(word_t) * bm::set_block_size : 0;
        mem_used += sizeof(bm::word_t**) * top_block_size_;

        for (unsigned i = 0; i < top_block_size_; ++i)
        {
            mem_used += blocks_[i] ? sizeof(void*) * bm::set_array_size : 0;
        }

        return mem_used;
    }

    /** Returns true if second level block pointer is 0.
    */
    bool is_subblock_null(unsigned nsub) const
    {
        return blocks_[nsub] == NULL;
    }


    bm::word_t***  blocks_root()
    {
        return blocks_;
    }

    /*! \brief Returns current GAP level vector
    */
    const gap_word_t* glen() const
    {
        return glevel_len_;
    }

    /*! \brief Returns GAP level length for specified level
        \param level - level number
    */
    unsigned glen(unsigned level) const
    {
        return glevel_len_[level];
    }

    /*! \brief Swaps content 
        \param bm  another blocks manager
    */
    void swap(blocks_manager& bm)
    {
        BM_ASSERT(this != &bm);

        word_t*** btmp = blocks_;
        blocks_ = bm.blocks_;
        bm.blocks_ = btmp;

		xor_swap(this->top_block_size_, bm.top_block_size_);
        xor_swap(this->effective_top_block_size_, bm.effective_top_block_size_);

        BM_ASSERT(sizeof(glevel_len_) / sizeof(glevel_len_[0]) 
                                    == bm::gap_levels); // paranoiya check
        for (unsigned i = 0; i < bm::gap_levels; ++i)
        {
		    xor_swap(glevel_len_[i], bm.glevel_len_[i]);
        }
    }

    /*! \brief Returns size of the top block array in the tree 
    */
    unsigned top_block_size() const
    {
        return top_block_size_;
    }

    /*! \brief Returns effective size of the top block array in the tree 
    Effective size excludes NULL pointers at the top descriptor end
    */
    unsigned effective_top_block_size() const
    {
        return effective_top_block_size_;
    }

    /**
        \brief reserve capacity for specified number of bits
    */
    void reserve(unsigned max_bits)
    {
        if (max_bits) 
        {
            unsigned b = compute_top_block_size(max_bits);
            reserve_top_blocks(b);
        }
    }

    /*!
        \brief Make sure blocks manager has enough blocks capacity
    */
    void reserve_top_blocks(unsigned top_blocks) 
    {
        BM_ASSERT(top_blocks <= bm::set_array_size);
        if (top_blocks <= top_block_size_) return; // nothing to do
        bm::word_t*** new_blocks = 
            (bm::word_t***)alloc_.alloc_ptr(top_blocks);

        for (unsigned i = 0; i < top_block_size_; ++i)
        {
            new_blocks[i] = blocks_[i];
        }
        for (unsigned j = top_block_size_; j < top_blocks; ++j)
        {
            new_blocks[j] = 0;
        }
        alloc_.free_ptr(blocks_, top_block_size_);
        blocks_ = new_blocks;
        top_block_size_ = top_blocks;
    }
    
    /** \brief Returns reference on the allocator
    */
    allocator_type& get_allocator() { return alloc_; }

    /** \brief Returns allocator
    */
    allocator_type get_allocator() const { return alloc_; }

private:

    void operator =(const blocks_manager&);

    void deinit_tree()
    {
        if (blocks_ == 0) return;
        unsigned top_size = this->effective_top_block_size();
        block_free_func  free_func(*this);
        for_each_nzblock2(blocks_, top_size, free_func);
        free_top_block();
        alloc_.free_ptr(blocks_, top_block_size_);
        blocks_ = 0;
    }

    void free_top_block()
    {
        for(unsigned i = 0; i < top_block_size_; ++i)
        {
            bm::word_t** blk_blk = blocks_[i];
            if (blk_blk) 
            {
                alloc_.free_ptr(blk_blk); blocks_[i] = 0;
            }
        }
    }

    /// allocate first level of descr. of blocks 
    void init_tree()
    {
        if (top_block_size_)
        {
            blocks_ = (bm::word_t***) alloc_.alloc_ptr(top_block_size_); 
            ::memset(blocks_, 0, top_block_size_ * sizeof(bm::word_t**));
        }
        else
        {
            blocks_ = 0;
        }
        effective_top_block_size_ = 1;
    }

private:
    /// Tree of blocks.
    bm::word_t***                          blocks_;
    /// Size of the top level block array in blocks_ tree
    unsigned                               top_block_size_;
    /// Effective size of the top level block array in blocks_ tree
    unsigned                               effective_top_block_size_;
    /// Temp block.
    bm::word_t*                            temp_block_; 
    /// vector defines gap block lengths for different levels 
    gap_word_t                             glevel_len_[bm::gap_levels];
    /// allocator
    allocator_type                         alloc_;
};

/**
    Bit block buffer guard
    \internal
*/
template<class BlocksManager>
class bit_block_guard
{
public:
    bit_block_guard(BlocksManager& bman, bm::word_t* blk=0) 
        : bman_(bman), 
          block_(blk)
    {}
    ~bit_block_guard()
    {
        bman_.get_allocator().free_bit_block(block_, 3);
    }
    void attach(bm::word_t* blk)
    {
        bman_.get_allocator().free_bit_block(block_);
        block_ = blk;
    }
    bm::word_t* allocate()
    {
        attach(bman_.get_allocator().alloc_bit_block(3));
        return block_;
    }
    bm::word_t* get() { return block_; }

private:
    bit_block_guard(const bit_block_guard&);
    bit_block_guard& operator=(const bit_block_guard&);
private:
    BlocksManager& bman_;
    bm::word_t*    block_;
};


}

#ifdef _MSC_VER
#pragma warning( pop )
#endif

#endif