1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
#include "moab/Interface.hpp"
#include "moab/ParallelComm.hpp"
#include "moab/WriteUtilIface.hpp"
#include "moab/ReadUtilIface.hpp"
#include "SequenceManager.hpp"
#include "moab/Error.hpp"
#include "EntitySequence.hpp"
#include "MBTagConventions.hpp"
#include "moab/Skinner.hpp"
#include "MBParallelConventions.h"
#include "moab/Core.hpp"
#include "ElementSequence.hpp"
#include "moab/CN.hpp"
#include "moab/RangeMap.hpp"
#include "moab/MeshTopoUtil.hpp"
#include "TagInfo.hpp"
#include "DebugOutput.hpp"
#include "SharedSetData.hpp"
#include "moab/ScdInterface.hpp"
#include "moab/TupleList.hpp"
#include "moab/gs.hpp"

#include <iostream>
#include <sstream>
#include <algorithm>
#include <functional>
#include <numeric>

#include <cmath>
#include <cstdlib>
#include <cassert>

#ifdef MOAB_HAVE_MPI
#include "moab_mpi.h"
#endif
#ifdef MOAB_HAVE_MPE
#include "mpe.h"
int IFACE_START, IFACE_END;
int GHOST_START, GHOST_END;
int SHAREDV_START, SHAREDV_END;
int RESOLVE_START, RESOLVE_END;
int ENTITIES_START, ENTITIES_END;
int RHANDLES_START, RHANDLES_END;
int OWNED_START, OWNED_END;
#endif

namespace moab
{

const unsigned int ParallelComm::INITIAL_BUFF_SIZE = 1024;

const int MAX_BCAST_SIZE = ( 1 << 28 );

std::vector< ParallelComm::Buffer* > msgs;
unsigned int __PACK_num = 0, __UNPACK_num = 0, __PACK_count = 0, __UNPACK_count = 0;
std::string __PACK_string, __UNPACK_string;

#ifdef DEBUG_PACKING_TIMES
#define PC( n, m )                                                            \
    {                                                                         \
        if( __PACK_num == (unsigned int)n && __PACK_string == m )             \
            __PACK_count++;                                                   \
        else                                                                  \
        {                                                                     \
            if( __PACK_count > 1 ) std::cerr << " (" << __PACK_count << "x)"; \
            __PACK_count  = 1;                                                \
            __PACK_string = m;                                                \
            __PACK_num    = n;                                                \
            std::cerr << std::endl << "PACK: " << n << m;                     \
        }                                                                     \
    }
#define UPC( n, m )                                                              \
    {                                                                            \
        if( __UNPACK_num == (unsigned int)n && __UNPACK_string == m )            \
            __UNPACK_count++;                                                    \
        else                                                                     \
        {                                                                        \
            if( __UNPACK_count > 1 ) std::cerr << "(" << __UNPACK_count << "x)"; \
            __UNPACK_count  = 1;                                                 \
            __UNPACK_string = m;                                                 \
            __UNPACK_num    = n;                                                 \
            std::cerr << std::endl << "UNPACK: " << n << m;                      \
        }                                                                        \
    }
#else
#define PC( n, m )
#define UPC( n, m )
#endif

template < typename T >
static inline void UNPACK( unsigned char*& buff, T* val, size_t count )
{
    memcpy( val, buff, count * sizeof( T ) );
    buff += count * sizeof( T );
}

template < typename T >
static inline void PACK( unsigned char*& buff, const T* val, size_t count )
{
    memcpy( buff, val, count * sizeof( T ) );
    buff += count * sizeof( T );
}

static inline void PACK_INTS( unsigned char*& buff, const int* int_val, size_t num )
{
    PACK( buff, int_val, num );
    PC( num, " ints" );
}

static inline void PACK_INT( unsigned char*& buff, int int_val )
{
    PACK_INTS( buff, &int_val, 1 );
}

static inline void PACK_DBLS( unsigned char*& buff, const double* dbl_val, size_t num )
{
    PACK( buff, dbl_val, num );
    PC( num, " doubles" );
}

// static inline
// void PACK_DBL(unsigned char*& buff, const double dbl_val)
//{ PACK_DBLS(buff, &dbl_val, 1); }

static inline void PACK_EH( unsigned char*& buff, const EntityHandle* eh_val, size_t num )
{
    PACK( buff, eh_val, num );
    PC( num, " handles" );
}

// static inline
// void PACK_CHAR_64(unsigned char*& buff, const char* str)
//{
//  memcpy(buff, str, 64);
//  buff += 64;
//  PC(64, " chars");
//}

static inline void PACK_VOID( unsigned char*& buff, const void* val, size_t num )
{
    PACK( buff, reinterpret_cast< const unsigned char* >( val ), num );
    PC( num, " void" );
}

static inline void PACK_BYTES( unsigned char*& buff, const void* val, int num )
{
    PACK_INT( buff, num );
    PACK_VOID( buff, val, num );
}

static inline void PACK_RANGE( unsigned char*& buff, const Range& rng )
{
    PACK_INT( buff, rng.psize() );
    Range::const_pair_iterator cit;
    for( cit = rng.const_pair_begin(); cit != rng.const_pair_end(); ++cit )
    {
        EntityHandle eh[2] = { cit->first, cit->second };
        PACK_EH( buff, eh, 2 );
    }
    PC( rng.psize(), "-subranged range" );
}

static inline void UNPACK_INTS( unsigned char*& buff, int* int_val, size_t num )
{
    UNPACK( buff, int_val, num );
    UPC( num, " ints" );
}

static inline void UNPACK_INT( unsigned char*& buff, int& int_val )
{
    UNPACK_INTS( buff, &int_val, 1 );
}

static inline void UNPACK_DBLS( unsigned char*& buff, double* dbl_val, size_t num )
{
    UNPACK( buff, dbl_val, num );
    UPC( num, " doubles" );
}

static inline void UNPACK_DBL( unsigned char*& buff, double& dbl_val )
{
    UNPACK_DBLS( buff, &dbl_val, 1 );
}

static inline void UNPACK_EH( unsigned char*& buff, EntityHandle* eh_val, size_t num )
{
    UNPACK( buff, eh_val, num );
    UPC( num, " handles" );
}

// static inline
// void UNPACK_CHAR_64(unsigned char*& buff, char* char_val)
//{
//  memcpy(buff, char_val, 64);
//  buff += 64;
//  UPC(64, " chars");
//}

static inline void UNPACK_VOID( unsigned char*& buff, void* val, size_t num )
{
    UNPACK( buff, reinterpret_cast< unsigned char* >( val ), num );
    UPC( num, " void" );
}

static inline void UNPACK_TYPE( unsigned char*& buff, EntityType& type )
{
    int int_type = MBMAXTYPE;
    UNPACK_INT( buff, int_type );
    type = static_cast< EntityType >( int_type );
    assert( type >= MBVERTEX && type <= MBMAXTYPE );
}

static inline void UNPACK_RANGE( unsigned char*& buff, Range& rng )
{
    int num_subs;
    EntityHandle eh[2];
    UNPACK_INT( buff, num_subs );
    for( int i = 0; i < num_subs; i++ )
    {
        UPC( num_subs, "-subranged range" );
        UNPACK_EH( buff, eh, 2 );
        rng.insert( eh[0], eh[1] );
    }
}

enum MBMessageTag
{
    MB_MESG_ANY = MPI_ANY_TAG,
    MB_MESG_ENTS_ACK,
    MB_MESG_ENTS_SIZE,
    MB_MESG_ENTS_LARGE,
    MB_MESG_REMOTEH_ACK,
    MB_MESG_REMOTEH_SIZE,
    MB_MESG_REMOTEH_LARGE,
    MB_MESG_TAGS_ACK,
    MB_MESG_TAGS_SIZE,
    MB_MESG_TAGS_LARGE
};

static inline size_t RANGE_SIZE( const Range& rng )
{
    return 2 * sizeof( EntityHandle ) * rng.psize() + sizeof( int );
}

#define PRINT_DEBUG_ISEND( A, B, C, D, E )    print_debug_isend( ( A ), ( B ), ( C ), ( D ), ( E ) )
#define PRINT_DEBUG_IRECV( A, B, C, D, E, F ) print_debug_irecv( ( A ), ( B ), ( C ), ( D ), ( E ), ( F ) )
#define PRINT_DEBUG_RECD( A )                 print_debug_recd( ( A ) )
#define PRINT_DEBUG_WAITANY( A, B, C )        print_debug_waitany( ( A ), ( B ), ( C ) )

void ParallelComm::print_debug_isend( int from, int to, unsigned char* buff, int tag, int sz )
{
    myDebug->tprintf( 3, "Isend, %d->%d, buffer ptr = %p, tag=%d, size=%d\n", from, to, (void*)buff, tag, sz );
}

void ParallelComm::print_debug_irecv( int to, int from, unsigned char* buff, int sz, int tag, int incoming )
{
    myDebug->tprintf( 3, "Irecv, %d<-%d, buffer ptr = %p, tag=%d, size=%d", to, from, (void*)buff, tag, sz );
    if( tag < MB_MESG_REMOTEH_ACK )
        myDebug->printf( 3, ", incoming1=%d\n", incoming );
    else if( tag < MB_MESG_TAGS_ACK )
        myDebug->printf( 3, ", incoming2=%d\n", incoming );
    else
        myDebug->printf( 3, ", incoming=%d\n", incoming );
}

void ParallelComm::print_debug_recd( MPI_Status status )
{
    if( myDebug->get_verbosity() == 3 )
    {
        int this_count;
        int success = MPI_Get_count( &status, MPI_UNSIGNED_CHAR, &this_count );
        if( MPI_SUCCESS != success ) this_count = -1;
        myDebug->tprintf( 3, "Received from %d, count = %d, tag = %d\n", status.MPI_SOURCE, this_count,
                          status.MPI_TAG );
    }
}

void ParallelComm::print_debug_waitany( std::vector< MPI_Request >& reqs, int tag, int proc )
{
    if( myDebug->get_verbosity() == 3 )
    {
        myDebug->tprintf( 3, "Waitany, p=%d, ", proc );
        if( tag < MB_MESG_REMOTEH_ACK )
            myDebug->print( 3, ", recv_ent_reqs=" );
        else if( tag < MB_MESG_TAGS_ACK )
            myDebug->print( 3, ", recv_remoteh_reqs=" );
        else
            myDebug->print( 3, ", recv_tag_reqs=" );
        for( unsigned int i = 0; i < reqs.size(); i++ )
            myDebug->printf( 3, " %p", (void*)(intptr_t)reqs[i] );
        myDebug->print( 3, "\n" );
    }
}

/** Name of tag used to store ParallelComm Index on mesh paritioning sets */
const char* PARTITIONING_PCOMM_TAG_NAME = "__PRTN_PCOMM";

/** \brief Tag storing parallel communication objects
 *
 * This tag stores pointers to ParallelComm communication
 * objects; one of these is allocated for each different
 * communicator used to read mesh. ParallelComm stores
 * partition and interface sets corresponding to its parallel mesh.
 * By default, a parallel read uses the first ParallelComm object
 * on the interface instance; if instantiated with one, ReadParallel
 * adds this object to the interface instance too.
 *
 * Tag type: opaque
 * Tag size: MAX_SHARING_PROCS*sizeof(ParallelComm*)
 */
#define PARALLEL_COMM_TAG_NAME "__PARALLEL_COMM"

ParallelComm::ParallelComm( Interface* impl, MPI_Comm cm, int* id )
    : mbImpl( impl ), procConfig( cm ), sharedpTag( 0 ), sharedpsTag( 0 ), sharedhTag( 0 ), sharedhsTag( 0 ),
      pstatusTag( 0 ), ifaceSetsTag( 0 ), partitionTag( 0 ), globalPartCount( -1 ), partitioningSet( 0 ),
      myDebug( NULL )
{
    initialize();
    sharedSetData = new SharedSetData( *impl, pcommID, procConfig.proc_rank() );
    if( id ) *id = pcommID;
}

ParallelComm::ParallelComm( Interface* impl, std::vector< unsigned char >& /*tmp_buff*/, MPI_Comm cm, int* id )
    : mbImpl( impl ), procConfig( cm ), sharedpTag( 0 ), sharedpsTag( 0 ), sharedhTag( 0 ), sharedhsTag( 0 ),
      pstatusTag( 0 ), ifaceSetsTag( 0 ), partitionTag( 0 ), globalPartCount( -1 ), partitioningSet( 0 ),
      myDebug( NULL )
{
    initialize();
    sharedSetData = new SharedSetData( *impl, pcommID, procConfig.proc_rank() );<--- Class 'ParallelComm' does not have a copy constructor which is recommended since it has dynamic memory/resource allocation(s).<--- Class 'ParallelComm' does not have a operator= which is recommended since it has dynamic memory/resource allocation(s).
    if( id ) *id = pcommID;
}

ParallelComm::~ParallelComm()
{
    remove_pcomm( this );
    delete_all_buffers();
    delete myDebug;
    delete sharedSetData;
}

void ParallelComm::initialize()
{
    Core* core      = dynamic_cast< Core* >( mbImpl );
    sequenceManager = core->sequence_manager();
    mbImpl->query_interface( errorHandler );

    // Initialize MPI, if necessary
    int flag   = 1;
    int retval = MPI_Initialized( &flag );
    if( MPI_SUCCESS != retval || !flag )
    {
        int argc    = 0;
        char** argv = NULL;

        // mpi not initialized yet - initialize here
        retval = MPI_Init( &argc, &argv );
        assert( MPI_SUCCESS == retval );
    }

    // Reserve space for vectors
    buffProcs.reserve( MAX_SHARING_PROCS );
    localOwnedBuffs.reserve( MAX_SHARING_PROCS );
    remoteOwnedBuffs.reserve( MAX_SHARING_PROCS );

    pcommID = add_pcomm( this );

    if( !myDebug )
    {
        myDebug = new DebugOutput( "ParallelComm", std::cerr );
        myDebug->set_rank( procConfig.proc_rank() );
    }
}

int ParallelComm::add_pcomm( ParallelComm* pc )
{
    // Add this pcomm to instance tag
    std::vector< ParallelComm* > pc_array( MAX_SHARING_PROCS, (ParallelComm*)NULL );
    Tag pc_tag = pcomm_tag( mbImpl, true );
    assert( 0 != pc_tag );

    const EntityHandle root = 0;
    ErrorCode result        = mbImpl->tag_get_data( pc_tag, &root, 1, (void*)&pc_array[0] );
    if( MB_SUCCESS != result && MB_TAG_NOT_FOUND != result ) return -1;
    int index = 0;
    while( index < MAX_SHARING_PROCS && pc_array[index] )
        index++;
    if( index == MAX_SHARING_PROCS )
    {
        index = -1;
        assert( false );
    }
    else
    {
        pc_array[index] = pc;
        mbImpl->tag_set_data( pc_tag, &root, 1, (void*)&pc_array[0] );
    }
    return index;
}

void ParallelComm::remove_pcomm( ParallelComm* pc )
{
    // Remove this pcomm from instance tag
    std::vector< ParallelComm* > pc_array( MAX_SHARING_PROCS );
    Tag pc_tag = pcomm_tag( mbImpl, true );

    const EntityHandle root                      = 0;
    ErrorCode result                             = mbImpl->tag_get_data( pc_tag, &root, 1, (void*)&pc_array[0] );
    std::vector< ParallelComm* >::iterator pc_it = std::find( pc_array.begin(), pc_array.end(), pc );
    assert( MB_SUCCESS == result && pc_it != pc_array.end() );
    // Empty if test to get around compiler warning about unused var
    if( MB_SUCCESS == result )
    {
    }

    *pc_it = NULL;
    mbImpl->tag_set_data( pc_tag, &root, 1, (void*)&pc_array[0] );
}

//! Assign a global id space, for largest-dimension or all entities (and
//! in either case for vertices too)
ErrorCode ParallelComm::assign_global_ids( EntityHandle this_set,
                                           const int dimension,
                                           const int start_id,
                                           const bool largest_dim_only,
                                           const bool parallel,
                                           const bool owned_only )
{
    Range entities[4];
    ErrorCode result;
    std::vector< unsigned char > pstatus;
    for( int dim = 0; dim <= dimension; dim++ )
    {
        if( dim == 0 || !largest_dim_only || dim == dimension )
        {
            result = mbImpl->get_entities_by_dimension( this_set, dim, entities[dim] );MB_CHK_SET_ERR( result, "Failed to get vertices in assign_global_ids" );
        }

        // Need to filter out non-locally-owned entities!!!
        pstatus.resize( entities[dim].size() );
        result = mbImpl->tag_get_data( pstatus_tag(), entities[dim], &pstatus[0] );MB_CHK_SET_ERR( result, "Failed to get pstatus in assign_global_ids" );

        Range dum_range;
        Range::iterator rit;
        unsigned int i;
        for( rit = entities[dim].begin(), i = 0; rit != entities[dim].end(); ++rit, i++ )
            if( pstatus[i] & PSTATUS_NOT_OWNED ) dum_range.insert( *rit );
        entities[dim] = subtract( entities[dim], dum_range );
    }

    return assign_global_ids( entities, dimension, start_id, parallel, owned_only );
}

//! Assign a global id space, for largest-dimension or all entities (and
//! in either case for vertices too)
ErrorCode ParallelComm::assign_global_ids( Range entities[],
                                           const int dimension,
                                           const int start_id,
                                           const bool parallel,
                                           const bool owned_only )
{
    int local_num_elements[4];
    ErrorCode result;
    for( int dim = 0; dim <= dimension; dim++ )
    {
        local_num_elements[dim] = entities[dim].size();
    }

    // Communicate numbers
    std::vector< int > num_elements( procConfig.proc_size() * 4 );
#ifdef MOAB_HAVE_MPI
    if( procConfig.proc_size() > 1 && parallel )
    {
        int retval =
            MPI_Allgather( local_num_elements, 4, MPI_INT, &num_elements[0], 4, MPI_INT, procConfig.proc_comm() );
        if( 0 != retval ) return MB_FAILURE;
    }
    else
#endif
        for( int dim = 0; dim < 4; dim++ )
            num_elements[dim] = local_num_elements[dim];

    // My entities start at one greater than total_elems[d]
    int total_elems[4] = { start_id, start_id, start_id, start_id };

    for( unsigned int proc = 0; proc < procConfig.proc_rank(); proc++ )
    {
        for( int dim = 0; dim < 4; dim++ )
            total_elems[dim] += num_elements[4 * proc + dim];
    }

    // Assign global ids now
    Tag gid_tag = mbImpl->globalId_tag();

    for( int dim = 0; dim < 4; dim++ )
    {
        if( entities[dim].empty() ) continue;
        num_elements.resize( entities[dim].size() );
        int i = 0;
        for( Range::iterator rit = entities[dim].begin(); rit != entities[dim].end(); ++rit )
            num_elements[i++] = total_elems[dim]++;

        result = mbImpl->tag_set_data( gid_tag, entities[dim], &num_elements[0] );MB_CHK_SET_ERR( result, "Failed to set global id tag in assign_global_ids" );
    }

    if( owned_only ) return MB_SUCCESS;

    // Exchange tags
    for( int dim = 1; dim < 4; dim++ )
        entities[0].merge( entities[dim] );

    return exchange_tags( gid_tag, entities[0] );
}

int ParallelComm::get_buffers( int to_proc, bool* is_new )
{
    int ind                                   = -1;
    std::vector< unsigned int >::iterator vit = std::find( buffProcs.begin(), buffProcs.end(), to_proc );
    if( vit == buffProcs.end() )
    {
        assert( "shouldn't need buffer to myself" && to_proc != (int)procConfig.proc_rank() );
        ind = buffProcs.size();
        buffProcs.push_back( (unsigned int)to_proc );
        localOwnedBuffs.push_back( new Buffer( INITIAL_BUFF_SIZE ) );
        remoteOwnedBuffs.push_back( new Buffer( INITIAL_BUFF_SIZE ) );
        if( is_new ) *is_new = true;
    }
    else
    {
        ind = vit - buffProcs.begin();
        if( is_new ) *is_new = false;
    }
    assert( ind < MAX_SHARING_PROCS );
    return ind;
}

ErrorCode ParallelComm::broadcast_entities( const int from_proc,
                                            Range& entities,
                                            const bool adjacencies,
                                            const bool tags )
{
#ifndef MOAB_HAVE_MPI
    return MB_FAILURE;
#else

    ErrorCode result = MB_SUCCESS;<--- Variable 'result' is assigned a value that is never used.
    int success;
    int buff_size;

    Buffer buff( INITIAL_BUFF_SIZE );
    buff.reset_ptr( sizeof( int ) );
    if( (int)procConfig.proc_rank() == from_proc )
    {
        result = add_verts( entities );MB_CHK_SET_ERR( result, "Failed to add adj vertices" );

        buff.reset_ptr( sizeof( int ) );
        result = pack_buffer( entities, adjacencies, tags, false, -1, &buff );MB_CHK_SET_ERR( result, "Failed to compute buffer size in broadcast_entities" );
        buff.set_stored_size();
        buff_size = buff.buff_ptr - buff.mem_ptr;
    }

    success = MPI_Bcast( &buff_size, 1, MPI_INT, from_proc, procConfig.proc_comm() );
    if( MPI_SUCCESS != success )
    {
        MB_SET_ERR( MB_FAILURE, "MPI_Bcast of buffer size failed" );
    }

    if( !buff_size )  // No data
        return MB_SUCCESS;

    if( (int)procConfig.proc_rank() != from_proc ) buff.reserve( buff_size );

    size_t offset = 0;
    while( buff_size )
    {
        int sz  = std::min( buff_size, MAX_BCAST_SIZE );
        success = MPI_Bcast( buff.mem_ptr + offset, sz, MPI_UNSIGNED_CHAR, from_proc, procConfig.proc_comm() );
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "MPI_Bcast of buffer failed" );
        }

        offset += sz;
        buff_size -= sz;
    }

    if( (int)procConfig.proc_rank() != from_proc )
    {
        std::vector< std::vector< EntityHandle > > dum1a, dum1b;
        std::vector< std::vector< int > > dum1p;
        std::vector< EntityHandle > dum2, dum4;
        std::vector< unsigned int > dum3;
        buff.reset_ptr( sizeof( int ) );
        result = unpack_buffer( buff.buff_ptr, false, from_proc, -1, dum1a, dum1b, dum1p, dum2, dum2, dum3, dum4 );MB_CHK_SET_ERR( result, "Failed to unpack buffer in broadcast_entities" );
        std::copy( dum4.begin(), dum4.end(), range_inserter( entities ) );
    }

    return MB_SUCCESS;
#endif
}

ErrorCode ParallelComm::scatter_entities( const int from_proc,<--- The function 'scatter_entities' is never used.
                                          std::vector< Range >& entities,
                                          const bool adjacencies,
                                          const bool tags )
{
#ifndef MOAB_HAVE_MPI
    return MB_FAILURE;
#else
    ErrorCode result = MB_SUCCESS;<--- Variable 'result' is assigned a value that is never used.
    int i, success, buff_size, prev_size;
    int nProcs         = (int)procConfig.proc_size();
    int* sendCounts    = new int[nProcs];
    int* displacements = new int[nProcs];
    sendCounts[0]      = sizeof( int );
    displacements[0]   = 0;
    Buffer buff( INITIAL_BUFF_SIZE );
    buff.reset_ptr( sizeof( int ) );
    buff.set_stored_size();
    unsigned int my_proc = procConfig.proc_rank();

    // Get buffer size array for each remote processor
    if( my_proc == (unsigned int)from_proc )
    {
        for( i = 1; i < nProcs; i++ )
        {
            prev_size = buff.buff_ptr - buff.mem_ptr;
            buff.reset_ptr( prev_size + sizeof( int ) );
            result = add_verts( entities[i] );MB_CHK_SET_ERR( result, "Failed to add verts" );

            result = pack_buffer( entities[i], adjacencies, tags, false, -1, &buff );
            if( MB_SUCCESS != result )
            {
                delete[] sendCounts;
                delete[] displacements;
                MB_SET_ERR( result, "Failed to pack buffer in scatter_entities" );
            }

            buff_size                               = buff.buff_ptr - buff.mem_ptr - prev_size;
            *( (int*)( buff.mem_ptr + prev_size ) ) = buff_size;
            sendCounts[i]                           = buff_size;
        }
    }

    // Broadcast buffer size array
    success = MPI_Bcast( sendCounts, nProcs, MPI_INT, from_proc, procConfig.proc_comm() );
    if( MPI_SUCCESS != success )
    {
        delete[] sendCounts;
        delete[] displacements;
        MB_SET_ERR( MB_FAILURE, "MPI_Bcast of buffer size failed" );
    }

    for( i = 1; i < nProcs; i++ )
    {
        displacements[i] = displacements[i - 1] + sendCounts[i - 1];
    }

    Buffer rec_buff;
    rec_buff.reserve( sendCounts[my_proc] );

    // Scatter actual geometry
    success = MPI_Scatterv( buff.mem_ptr, sendCounts, displacements, MPI_UNSIGNED_CHAR, rec_buff.mem_ptr,
                            sendCounts[my_proc], MPI_UNSIGNED_CHAR, from_proc, procConfig.proc_comm() );

    if( MPI_SUCCESS != success )
    {
        delete[] sendCounts;
        delete[] displacements;
        MB_SET_ERR( MB_FAILURE, "MPI_Scatterv of buffer failed" );
    }

    // Unpack in remote processors
    if( my_proc != (unsigned int)from_proc )
    {
        std::vector< std::vector< EntityHandle > > dum1a, dum1b;
        std::vector< std::vector< int > > dum1p;
        std::vector< EntityHandle > dum2, dum4;
        std::vector< unsigned int > dum3;
        rec_buff.reset_ptr( sizeof( int ) );
        result = unpack_buffer( rec_buff.buff_ptr, false, from_proc, -1, dum1a, dum1b, dum1p, dum2, dum2, dum3, dum4 );
        if( MB_SUCCESS != result )
        {
            delete[] sendCounts;
            delete[] displacements;
            MB_SET_ERR( result, "Failed to unpack buffer in scatter_entities" );
        }

        std::copy( dum4.begin(), dum4.end(), range_inserter( entities[my_proc] ) );
    }

    delete[] sendCounts;
    delete[] displacements;

    return MB_SUCCESS;
#endif
}

ErrorCode ParallelComm::send_entities( const int to_proc,<--- The function 'send_entities' is never used.
                                       Range& orig_ents,
                                       const bool adjs,
                                       const bool tags,
                                       const bool store_remote_handles,
                                       const bool is_iface,
                                       Range& /*final_ents*/,
                                       int& incoming1,
                                       int& incoming2,
                                       TupleList& entprocs,
                                       std::vector< MPI_Request >& recv_remoteh_reqs,
                                       bool /*wait_all*/ )
{
#ifndef MOAB_HAVE_MPI
    return MB_FAILURE;
#else
    // Pack entities to local buffer
    int ind = get_buffers( to_proc );
    localOwnedBuffs[ind]->reset_ptr( sizeof( int ) );

    // Add vertices
    ErrorCode result = add_verts( orig_ents );MB_CHK_SET_ERR( result, "Failed to add verts in send_entities" );

    // Filter out entities already shared with destination
    Range tmp_range;
    result = filter_pstatus( orig_ents, PSTATUS_SHARED, PSTATUS_AND, to_proc, &tmp_range );MB_CHK_SET_ERR( result, "Failed to filter on owner" );
    if( !tmp_range.empty() )
    {
        orig_ents = subtract( orig_ents, tmp_range );
    }

    result = pack_buffer( orig_ents, adjs, tags, store_remote_handles, to_proc, localOwnedBuffs[ind], &entprocs );MB_CHK_SET_ERR( result, "Failed to pack buffer in send_entities" );

    // Send buffer
    result = send_buffer( to_proc, localOwnedBuffs[ind], MB_MESG_ENTS_SIZE, sendReqs[2 * ind], recvReqs[2 * ind + 1],
                          (int*)( remoteOwnedBuffs[ind]->mem_ptr ),
                          //&ackbuff,
                          incoming1, MB_MESG_REMOTEH_SIZE,
                          ( !is_iface && store_remote_handles ? localOwnedBuffs[ind] : NULL ),
                          &recv_remoteh_reqs[2 * ind], &incoming2 );MB_CHK_SET_ERR( result, "Failed to send buffer" );

    return MB_SUCCESS;
#endif
}

ErrorCode ParallelComm::send_entities( std::vector< unsigned int >& send_procs,
                                       std::vector< Range* >& send_ents,
                                       int& incoming1,
                                       int& incoming2,
                                       const bool store_remote_handles )
{
#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( OWNED_START, procConfig.proc_rank(), "Starting send_entities." );
    }
#endif
    myDebug->tprintf( 1, "Entering send_entities\n" );
    if( myDebug->get_verbosity() == 4 )
    {
        msgs.clear();
        msgs.reserve( MAX_SHARING_PROCS );
    }

    unsigned int i;
    int ind;
    ErrorCode result = MB_SUCCESS;<--- Variable 'result' is assigned a value that is never used.

    // Set buffProcs with communicating procs
    unsigned int n_proc = send_procs.size();
    for( i = 0; i < n_proc; i++ )
    {
        ind    = get_buffers( send_procs[i] );
        result = add_verts( *send_ents[i] );MB_CHK_SET_ERR( result, "Failed to add verts" );

        // Filter out entities already shared with destination
        Range tmp_range;
        result = filter_pstatus( *send_ents[i], PSTATUS_SHARED, PSTATUS_AND, buffProcs[ind], &tmp_range );MB_CHK_SET_ERR( result, "Failed to filter on owner" );
        if( !tmp_range.empty() )
        {
            *send_ents[i] = subtract( *send_ents[i], tmp_range );
        }
    }

    //===========================================
    // Get entities to be sent to neighbors
    // Need to get procs each entity is sent to
    //===========================================
    Range allsent, tmp_range;
    int npairs = 0;
    TupleList entprocs;
    for( i = 0; i < n_proc; i++ )
    {
        int n_ents = send_ents[i]->size();
        if( n_ents > 0 )
        {
            npairs += n_ents;  // Get the total # of proc/handle pairs
            allsent.merge( *send_ents[i] );
        }
    }

    // Allocate a TupleList of that size
    entprocs.initialize( 1, 0, 1, 0, npairs );
    entprocs.enableWriteAccess();

    // Put the proc/handle pairs in the list
    for( i = 0; i < n_proc; i++ )
    {
        for( Range::iterator rit = send_ents[i]->begin(); rit != send_ents[i]->end(); ++rit )
        {
            entprocs.vi_wr[entprocs.get_n()]  = send_procs[i];
            entprocs.vul_wr[entprocs.get_n()] = *rit;
            entprocs.inc_n();
        }
    }

    // Sort by handle
    moab::TupleList::buffer sort_buffer;
    sort_buffer.buffer_init( npairs );
    entprocs.sort( 1, &sort_buffer );
    entprocs.disableWriteAccess();
    sort_buffer.reset();

    myDebug->tprintf( 1, "allsent ents compactness (size) = %f (%lu)\n", allsent.compactness(),
                      (unsigned long)allsent.size() );

    //===========================================
    // Pack and send ents from this proc to others
    //===========================================
    for( i = 0; i < n_proc; i++ )
    {
        if( send_ents[i]->size() > 0 )
        {
            ind = get_buffers( send_procs[i] );
            myDebug->tprintf( 1, "Sent ents compactness (size) = %f (%lu)\n", send_ents[i]->compactness(),
                              (unsigned long)send_ents[i]->size() );
            // Reserve space on front for size and for initial buff size
            localOwnedBuffs[ind]->reset_buffer( sizeof( int ) );
            result = pack_buffer( *send_ents[i], false, true, store_remote_handles, buffProcs[ind],<--- result is assigned
                                  localOwnedBuffs[ind], &entprocs, &allsent );

            if( myDebug->get_verbosity() == 4 )
            {
                msgs.resize( msgs.size() + 1 );
                msgs.back() = new Buffer( *localOwnedBuffs[ind] );
            }

            // Send the buffer (size stored in front in send_buffer)
            result = send_buffer( send_procs[i], localOwnedBuffs[ind], MB_MESG_ENTS_SIZE, sendReqs[2 * ind],<--- result is overwritten
                                  recvReqs[2 * ind + 1], &ackbuff, incoming1, MB_MESG_REMOTEH_SIZE,
                                  ( store_remote_handles ? localOwnedBuffs[ind] : NULL ), &recvRemotehReqs[2 * ind],
                                  &incoming2 );MB_CHK_SET_ERR( result, "Failed to Isend in ghost send" );
        }
    }
    entprocs.reset();

#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( ENTITIES_END, procConfig.proc_rank(), "Ending send_entities." );
    }
#endif

    return MB_SUCCESS;
}

/////////////////////////////////////////////////////////////////////////////////
// Send and Receive routines for a sequence of entities: use case UMR
/////////////////////////////////////////////////////////////////////////////////
void print_buff( unsigned char* ch, int size )<--- The function 'print_buff' is never used.
{
    for( int i = 0; i < size; i++ )
        std::cout << ch[i];
    std::cout << "\n";
}
ErrorCode ParallelComm::send_recv_entities( std::vector< int >& send_procs,<--- The function 'send_recv_entities' is never used.
                                            std::vector< std::vector< int > >& msgsizes,
                                            std::vector< std::vector< EntityHandle > >& senddata,
                                            std::vector< std::vector< EntityHandle > >& recvdata )
{
#ifdef USE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( OWNED_START, procConfig.proc_rank(), "Starting send_recv_entities." );
    }
#endif
    myDebug->tprintf( 1, "Entering send_recv_entities\n" );
    if( myDebug->get_verbosity() == 4 )
    {
        msgs.clear();
        msgs.reserve( MAX_SHARING_PROCS );
    }

    // unsigned int i;
    int i, ind, success;
    ErrorCode error = MB_SUCCESS;<--- Variable 'error' is assigned a value that is never used.

    //===========================================
    // Pack and send ents from this proc to others
    //===========================================

    // std::cout<<"resetting all buffers"<<std::endl;

    reset_all_buffers();
    sendReqs.resize( 3 * buffProcs.size(), MPI_REQUEST_NULL );
    std::vector< MPI_Request > recv_ent_reqs( 3 * buffProcs.size(), MPI_REQUEST_NULL );
    int ack_buff;
    int incoming = 0;

    std::vector< unsigned int >::iterator sit;

    for( ind = 0, sit = buffProcs.begin(); sit != buffProcs.end(); ++sit, ind++ )
    {
        incoming++;
        PRINT_DEBUG_IRECV( *sit, procConfig.proc_rank(), remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE,
                           MB_MESG_ENTS_SIZE, incoming );

        success = MPI_Irecv( remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE, MPI_UNSIGNED_CHAR, *sit,
                             MB_MESG_ENTS_SIZE, procConfig.proc_comm(), &recv_ent_reqs[3 * ind] );
        if( success != MPI_SUCCESS )
        {
            MB_SET_ERR( MB_FAILURE, "Failed to post irecv in send_recv_entities" );
        }
    }

    //  std::set<unsigned int>::iterator it;
    for( i = 0; i < (int)send_procs.size(); i++ )
    {
        // Get index of the shared processor in the local buffer
        ind = get_buffers( send_procs[i] );
        localOwnedBuffs[ind]->reset_buffer( sizeof( int ) );

        int buff_size = msgsizes[i].size() * sizeof( int ) + senddata[i].size() * sizeof( EntityHandle );
        localOwnedBuffs[ind]->check_space( buff_size );

        // Pack entities
        std::vector< int > msg;
        msg.insert( msg.end(), msgsizes[i].begin(), msgsizes[i].end() );
        PACK_INTS( localOwnedBuffs[ind]->buff_ptr, &msg[0], msg.size() );

        std::vector< EntityHandle > entities;
        entities.insert( entities.end(), senddata[i].begin(), senddata[i].end() );
        PACK_EH( localOwnedBuffs[ind]->buff_ptr, &entities[0], entities.size() );
        localOwnedBuffs[ind]->set_stored_size();

        if( myDebug->get_verbosity() == 4 )
        {
            msgs.resize( msgs.size() + 1 );
            msgs.back() = new Buffer( *localOwnedBuffs[ind] );
        }

        // Send the buffer (size stored in front in send_buffer)
        error = send_buffer( send_procs[i], localOwnedBuffs[ind], MB_MESG_ENTS_SIZE, sendReqs[3 * ind],
                             recv_ent_reqs[3 * ind + 2], &ack_buff, incoming );MB_CHK_SET_ERR( error, "Failed to Isend in send_recv_entities" );
    }

    //===========================================
    // Receive and unpack ents from received data
    //===========================================

    while( incoming )
    {

        MPI_Status status;
        int index_in_recv_requests;

        PRINT_DEBUG_WAITANY( recv_ent_reqs, MB_MESG_ENTS_SIZE, procConfig.proc_rank() );
        success = MPI_Waitany( 3 * buffProcs.size(), &recv_ent_reqs[0], &index_in_recv_requests, &status );
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "Failed in waitany in send_recv_entities" );
        }

        // Processor index in the list is divided by 3
        ind = index_in_recv_requests / 3;

        PRINT_DEBUG_RECD( status );

        // OK, received something; decrement incoming counter
        incoming--;

        bool done = false;

        error = recv_buffer( MB_MESG_ENTS_SIZE, status, remoteOwnedBuffs[ind],
                             recv_ent_reqs[3 * ind + 1],  // This is for receiving the second message
                             recv_ent_reqs[3 * ind + 2],  // This would be for ack, but it is not
                                                          // used; consider removing it
                             incoming, localOwnedBuffs[ind],
                             sendReqs[3 * ind + 1],  // Send request for sending the second message
                             sendReqs[3 * ind + 2],  // This is for sending the ack
                             done );MB_CHK_SET_ERR( error, "Failed to resize recv buffer" );

        if( done )
        {
            remoteOwnedBuffs[ind]->reset_ptr( sizeof( int ) );

            int from_proc = status.MPI_SOURCE;
            int idx       = std::find( send_procs.begin(), send_procs.end(), from_proc ) - send_procs.begin();

            int msg = msgsizes[idx].size();
            std::vector< int > recvmsg( msg );
            int ndata = senddata[idx].size();
            std::vector< EntityHandle > dum_vec( ndata );

            UNPACK_INTS( remoteOwnedBuffs[ind]->buff_ptr, &recvmsg[0], msg );
            UNPACK_EH( remoteOwnedBuffs[ind]->buff_ptr, &dum_vec[0], ndata );

            recvdata[idx].insert( recvdata[idx].end(), dum_vec.begin(), dum_vec.end() );
        }
    }

#ifdef USE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( ENTITIES_END, procConfig.proc_rank(), "Ending send_recv_entities." );
    }
#endif

    return MB_SUCCESS;
}

ErrorCode ParallelComm::update_remote_data( EntityHandle entity,
                                            std::vector< int >& procs,
                                            std::vector< EntityHandle >& handles )
{
    ErrorCode error;
    unsigned char pstatus = PSTATUS_INTERFACE;

    int procmin = *std::min_element( procs.begin(), procs.end() );

    if( (int)rank() > procmin )
        pstatus |= PSTATUS_NOT_OWNED;
    else
        procmin = rank();

    // DBG
    // std::cout<<"entity = "<<entity<<std::endl;
    // for (int j=0; j<procs.size(); j++)
    // std::cout<<"procs["<<j<<"] = "<<procs[j]<<", handles["<<j<<"] = "<<handles[j]<<std::endl;
    // DBG

    if( (int)procs.size() > 1 )
    {
        procs.push_back( rank() );
        handles.push_back( entity );

        int idx = std::find( procs.begin(), procs.end(), procmin ) - procs.begin();

        std::iter_swap( procs.begin(), procs.begin() + idx );
        std::iter_swap( handles.begin(), handles.begin() + idx );

        // DBG
        //  std::cout<<"entity = "<<entity<<std::endl;
        // for (int j=0; j<procs.size(); j++)
        // std::cout<<"procs["<<j<<"] = "<<procs[j]<<", handles["<<j<<"] = "<<handles[j]<<std::endl;
        // DBG
    }

    // if ((entity == 10388) && (rank()==1))
    //    std::cout<<"Here"<<std::endl;

    error = update_remote_data( entity, &procs[0], &handles[0], procs.size(), pstatus );MB_CHK_ERR( error );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_remote_handles( EntityHandle* local_vec, EntityHandle* rem_vec, int num_ents, int to_proc )
{
    ErrorCode error;
    std::vector< EntityHandle > newents;
    error = get_remote_handles( true, local_vec, rem_vec, num_ents, to_proc, newents );MB_CHK_ERR( error );

    return MB_SUCCESS;
}

//////////////////////////////////////////////////////////////////

ErrorCode ParallelComm::recv_entities( const int from_proc,<--- The function 'recv_entities' is never used.
                                       const bool store_remote_handles,
                                       const bool is_iface,
                                       Range& final_ents,
                                       int& incoming1,
                                       int& incoming2,
                                       std::vector< std::vector< EntityHandle > >& L1hloc,
                                       std::vector< std::vector< EntityHandle > >& L1hrem,
                                       std::vector< std::vector< int > >& L1p,
                                       std::vector< EntityHandle >& L2hloc,
                                       std::vector< EntityHandle >& L2hrem,
                                       std::vector< unsigned int >& L2p,
                                       std::vector< MPI_Request >& recv_remoteh_reqs,
                                       bool /*wait_all*/ )
{
#ifndef MOAB_HAVE_MPI
    return MB_FAILURE;
#else
    // Non-blocking receive for the first message (having size info)
    int ind1 = get_buffers( from_proc );
    incoming1++;
    PRINT_DEBUG_IRECV( procConfig.proc_rank(), from_proc, remoteOwnedBuffs[ind1]->mem_ptr, INITIAL_BUFF_SIZE,
                       MB_MESG_ENTS_SIZE, incoming1 );
    int success = MPI_Irecv( remoteOwnedBuffs[ind1]->mem_ptr, INITIAL_BUFF_SIZE, MPI_UNSIGNED_CHAR, from_proc,
                             MB_MESG_ENTS_SIZE, procConfig.proc_comm(), &recvReqs[2 * ind1] );
    if( success != MPI_SUCCESS )
    {
        MB_SET_ERR( MB_FAILURE, "Failed to post irecv in ghost exchange" );
    }

    // Receive messages in while loop
    return recv_messages( from_proc, store_remote_handles, is_iface, final_ents, incoming1, incoming2, L1hloc, L1hrem,
                          L1p, L2hloc, L2hrem, L2p, recv_remoteh_reqs );
#endif
}

ErrorCode ParallelComm::recv_entities( std::set< unsigned int >& recv_procs,
                                       int incoming1,
                                       int incoming2,
                                       const bool store_remote_handles,
                                       const bool migrate )
{
    //===========================================
    // Receive/unpack new entities
    //===========================================
    // Number of incoming messages is the number of procs we communicate with
    int success, ind, i;
    ErrorCode result;
    MPI_Status status;
    std::vector< std::vector< EntityHandle > > recd_ents( buffProcs.size() );<--- Variable 'recd_ents' is assigned a value that is never used.
    std::vector< std::vector< EntityHandle > > L1hloc( buffProcs.size() ), L1hrem( buffProcs.size() );
    std::vector< std::vector< int > > L1p( buffProcs.size() );
    std::vector< EntityHandle > L2hloc, L2hrem;
    std::vector< unsigned int > L2p;
    std::vector< EntityHandle > new_ents;

    while( incoming1 )
    {
        // Wait for all recvs of ents before proceeding to sending remote handles,
        // b/c some procs may have sent to a 3rd proc ents owned by me;
        PRINT_DEBUG_WAITANY( recvReqs, MB_MESG_ENTS_SIZE, procConfig.proc_rank() );

        success = MPI_Waitany( 2 * buffProcs.size(), &recvReqs[0], &ind, &status );
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "Failed in waitany in owned entity exchange" );
        }

        PRINT_DEBUG_RECD( status );

        // OK, received something; decrement incoming counter
        incoming1--;
        bool done = false;

        // In case ind is for ack, we need index of one before it
        unsigned int base_ind = 2 * ( ind / 2 );
        result = recv_buffer( MB_MESG_ENTS_SIZE, status, remoteOwnedBuffs[ind / 2], recvReqs[ind], recvReqs[ind + 1],
                              incoming1, localOwnedBuffs[ind / 2], sendReqs[base_ind], sendReqs[base_ind + 1], done,
                              ( store_remote_handles ? localOwnedBuffs[ind / 2] : NULL ), MB_MESG_REMOTEH_SIZE,
                              &recvRemotehReqs[base_ind], &incoming2 );MB_CHK_SET_ERR( result, "Failed to receive buffer" );

        if( done )
        {
            if( myDebug->get_verbosity() == 4 )
            {
                msgs.resize( msgs.size() + 1 );
                msgs.back() = new Buffer( *remoteOwnedBuffs[ind / 2] );
            }

            // Message completely received - process buffer that was sent
            remoteOwnedBuffs[ind / 2]->reset_ptr( sizeof( int ) );
            result = unpack_buffer( remoteOwnedBuffs[ind / 2]->buff_ptr, store_remote_handles, buffProcs[ind / 2],
                                    ind / 2, L1hloc, L1hrem, L1p, L2hloc, L2hrem, L2p, new_ents, true );
            if( MB_SUCCESS != result )
            {
                std::cout << "Failed to unpack entities. Buffer contents:" << std::endl;
                print_buffer( remoteOwnedBuffs[ind / 2]->mem_ptr, MB_MESG_ENTS_SIZE, buffProcs[ind / 2], false );
                return result;
            }

            if( recvReqs.size() != 2 * buffProcs.size() )
            {
                // Post irecv's for remote handles from new proc
                recvRemotehReqs.resize( 2 * buffProcs.size(), MPI_REQUEST_NULL );
                for( i = recvReqs.size(); i < (int)( 2 * buffProcs.size() ); i += 2 )
                {
                    localOwnedBuffs[i / 2]->reset_buffer();
                    incoming2++;
                    PRINT_DEBUG_IRECV( procConfig.proc_rank(), buffProcs[i / 2], localOwnedBuffs[i / 2]->mem_ptr,
                                       INITIAL_BUFF_SIZE, MB_MESG_REMOTEH_SIZE, incoming2 );
                    success = MPI_Irecv( localOwnedBuffs[i / 2]->mem_ptr, INITIAL_BUFF_SIZE, MPI_UNSIGNED_CHAR,
                                         buffProcs[i / 2], MB_MESG_REMOTEH_SIZE, procConfig.proc_comm(),
                                         &recvRemotehReqs[i] );
                    if( success != MPI_SUCCESS )
                    {
                        MB_SET_ERR( MB_FAILURE, "Failed to post irecv for remote handles in ghost exchange" );
                    }
                }
                recvReqs.resize( 2 * buffProcs.size(), MPI_REQUEST_NULL );
                sendReqs.resize( 2 * buffProcs.size(), MPI_REQUEST_NULL );
            }
        }
    }

    // Assign and remove newly created elements from/to receive processor
    result = assign_entities_part( new_ents, procConfig.proc_rank() );MB_CHK_SET_ERR( result, "Failed to assign entities to part" );
    if( migrate )
    {
        // result = remove_entities_part(allsent, procConfig.proc_rank());MB_CHK_SET_ERR(ressult,
        // "Failed to remove entities to part");
    }

    // Add requests for any new addl procs
    if( recvReqs.size() != 2 * buffProcs.size() )
    {
        // Shouldn't get here...
        MB_SET_ERR( MB_FAILURE, "Requests length doesn't match proc count in entity exchange" );
    }

#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( ENTITIES_END, procConfig.proc_rank(), "Ending recv entities." );
    }
#endif

    //===========================================
    // Send local handles for new entity to owner
    //===========================================
    std::set< unsigned int >::iterator it  = recv_procs.begin();
    std::set< unsigned int >::iterator eit = recv_procs.end();
    for( ; it != eit; ++it )
    {
        ind = get_buffers( *it );
        // Reserve space on front for size and for initial buff size
        remoteOwnedBuffs[ind]->reset_buffer( sizeof( int ) );

        result = pack_remote_handles( L1hloc[ind], L1hrem[ind], L1p[ind], buffProcs[ind], remoteOwnedBuffs[ind] );MB_CHK_SET_ERR( result, "Failed to pack remote handles" );
        remoteOwnedBuffs[ind]->set_stored_size();

        if( myDebug->get_verbosity() == 4 )
        {
            msgs.resize( msgs.size() + 1 );
            msgs.back() = new Buffer( *remoteOwnedBuffs[ind] );
        }
        result = send_buffer( buffProcs[ind], remoteOwnedBuffs[ind], MB_MESG_REMOTEH_SIZE, sendReqs[2 * ind],
                              recvRemotehReqs[2 * ind + 1], &ackbuff, incoming2 );MB_CHK_SET_ERR( result, "Failed to send remote handles" );
    }

    //===========================================
    // Process remote handles of my ghosteds
    //===========================================
    while( incoming2 )
    {
        PRINT_DEBUG_WAITANY( recvRemotehReqs, MB_MESG_REMOTEH_SIZE, procConfig.proc_rank() );
        success = MPI_Waitany( 2 * buffProcs.size(), &recvRemotehReqs[0], &ind, &status );
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "Failed in waitany in owned entity exchange" );
        }

        // OK, received something; decrement incoming counter
        incoming2--;

        PRINT_DEBUG_RECD( status );
        bool done             = false;
        unsigned int base_ind = 2 * ( ind / 2 );
        result = recv_buffer( MB_MESG_REMOTEH_SIZE, status, localOwnedBuffs[ind / 2], recvRemotehReqs[ind],
                              recvRemotehReqs[ind + 1], incoming2, remoteOwnedBuffs[ind / 2], sendReqs[base_ind],
                              sendReqs[base_ind + 1], done );MB_CHK_SET_ERR( result, "Failed to receive remote handles" );
        if( done )
        {
            // Incoming remote handles
            if( myDebug->get_verbosity() == 4 )
            {
                msgs.resize( msgs.size() + 1 );
                msgs.back() = new Buffer( *localOwnedBuffs[ind] );
            }

            localOwnedBuffs[ind / 2]->reset_ptr( sizeof( int ) );
            result =
                unpack_remote_handles( buffProcs[ind / 2], localOwnedBuffs[ind / 2]->buff_ptr, L2hloc, L2hrem, L2p );MB_CHK_SET_ERR( result, "Failed to unpack remote handles" );
        }
    }

#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( RHANDLES_END, procConfig.proc_rank(), "Ending remote handles." );
        MPE_Log_event( OWNED_END, procConfig.proc_rank(), "Ending recv entities (still doing checks)." );
    }
#endif
    myDebug->tprintf( 1, "Exiting recv_entities.\n" );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::recv_messages( const int from_proc,
                                       const bool store_remote_handles,
                                       const bool is_iface,
                                       Range& final_ents,
                                       int& incoming1,
                                       int& incoming2,
                                       std::vector< std::vector< EntityHandle > >& L1hloc,
                                       std::vector< std::vector< EntityHandle > >& L1hrem,
                                       std::vector< std::vector< int > >& L1p,
                                       std::vector< EntityHandle >& L2hloc,
                                       std::vector< EntityHandle >& L2hrem,
                                       std::vector< unsigned int >& L2p,
                                       std::vector< MPI_Request >& recv_remoteh_reqs )
{
#ifndef MOAB_HAVE_MPI
    return MB_FAILURE;
#else
    MPI_Status status;
    ErrorCode result;
    int ind1 = get_buffers( from_proc );
    int success, ind2;
    std::vector< EntityHandle > new_ents;

    // Wait and receive messages
    while( incoming1 )
    {
        PRINT_DEBUG_WAITANY( recvReqs, MB_MESG_TAGS_SIZE, procConfig.proc_rank() );
        success = MPI_Waitany( 2, &recvReqs[2 * ind1], &ind2, &status );
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "Failed in waitany in recv_messages" );
        }

        PRINT_DEBUG_RECD( status );

        // OK, received something; decrement incoming counter
        incoming1--;
        bool done = false;

        // In case ind is for ack, we need index of one before it
        ind2 += 2 * ind1;
        unsigned int base_ind = 2 * ( ind2 / 2 );

        result = recv_buffer( MB_MESG_ENTS_SIZE, status, remoteOwnedBuffs[ind2 / 2],
                              // recvbuff,
                              recvReqs[ind2], recvReqs[ind2 + 1], incoming1, localOwnedBuffs[ind2 / 2],
                              sendReqs[base_ind], sendReqs[base_ind + 1], done,
                              ( !is_iface && store_remote_handles ? localOwnedBuffs[ind2 / 2] : NULL ),
                              MB_MESG_REMOTEH_SIZE, &recv_remoteh_reqs[base_ind], &incoming2 );MB_CHK_SET_ERR( result, "Failed to receive buffer" );

        if( done )
        {
            // If it is done, unpack buffer
            remoteOwnedBuffs[ind2 / 2]->reset_ptr( sizeof( int ) );
            result = unpack_buffer( remoteOwnedBuffs[ind2 / 2]->buff_ptr, store_remote_handles, from_proc, ind2 / 2,
                                    L1hloc, L1hrem, L1p, L2hloc, L2hrem, L2p, new_ents );MB_CHK_SET_ERR( result, "Failed to unpack buffer in recev_messages" );

            std::copy( new_ents.begin(), new_ents.end(), range_inserter( final_ents ) );

            // Send local handles for new elements to owner
            // Reserve space on front for size and for initial buff size
            remoteOwnedBuffs[ind2 / 2]->reset_buffer( sizeof( int ) );

            result = pack_remote_handles( L1hloc[ind2 / 2], L1hrem[ind2 / 2], L1p[ind2 / 2], from_proc,
                                          remoteOwnedBuffs[ind2 / 2] );MB_CHK_SET_ERR( result, "Failed to pack remote handles" );
            remoteOwnedBuffs[ind2 / 2]->set_stored_size();

            result = send_buffer( buffProcs[ind2 / 2], remoteOwnedBuffs[ind2 / 2], MB_MESG_REMOTEH_SIZE, sendReqs[ind2],
                                  recv_remoteh_reqs[ind2 + 1], (int*)( localOwnedBuffs[ind2 / 2]->mem_ptr ),
                                  //&ackbuff,
                                  incoming2 );MB_CHK_SET_ERR( result, "Failed to send remote handles" );
        }
    }

    return MB_SUCCESS;
#endif
}

ErrorCode ParallelComm::recv_remote_handle_messages( const int from_proc,<--- The function 'recv_remote_handle_messages' is never used.
                                                     int& incoming2,
                                                     std::vector< EntityHandle >& L2hloc,
                                                     std::vector< EntityHandle >& L2hrem,
                                                     std::vector< unsigned int >& L2p,
                                                     std::vector< MPI_Request >& recv_remoteh_reqs )
{
#ifndef MOAB_HAVE_MPI
    return MB_FAILURE;
#else
    MPI_Status status;
    ErrorCode result;
    int ind1 = get_buffers( from_proc );
    int success, ind2;

    while( incoming2 )
    {
        PRINT_DEBUG_WAITANY( recv_remoteh_reqs, MB_MESG_REMOTEH_SIZE, procConfig.proc_rank() );
        success = MPI_Waitany( 2, &recv_remoteh_reqs[2 * ind1], &ind2, &status );
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "Failed in waitany in recv_remote_handle_messages" );
        }

        // OK, received something; decrement incoming counter
        incoming2--;

        PRINT_DEBUG_RECD( status );

        bool done = false;
        ind2 += 2 * ind1;
        unsigned int base_ind = 2 * ( ind2 / 2 );
        result = recv_buffer( MB_MESG_REMOTEH_SIZE, status, localOwnedBuffs[ind2 / 2], recv_remoteh_reqs[ind2],
                              recv_remoteh_reqs[ind2 + 1], incoming2, remoteOwnedBuffs[ind2 / 2], sendReqs[base_ind],
                              sendReqs[base_ind + 1], done );MB_CHK_SET_ERR( result, "Failed to receive remote handles" );
        if( done )
        {
            // Incoming remote handles
            localOwnedBuffs[ind2 / 2]->reset_ptr( sizeof( int ) );
            result =
                unpack_remote_handles( buffProcs[ind2 / 2], localOwnedBuffs[ind2 / 2]->buff_ptr, L2hloc, L2hrem, L2p );MB_CHK_SET_ERR( result, "Failed to unpack remote handles" );
        }
    }

    return MB_SUCCESS;
#endif
}

ErrorCode ParallelComm::pack_buffer( Range& orig_ents,
                                     const bool /*adjacencies*/,
                                     const bool tags,
                                     const bool store_remote_handles,
                                     const int to_proc,
                                     Buffer* buff,
                                     TupleList* entprocs,
                                     Range* allsent )
{
    // Pack the buffer with the entity ranges, adjacencies, and tags sections
    //
    // Note: new entities used in subsequent connectivity lists, sets, or tags,
    // are referred to as (MBMAXTYPE + index), where index is into vector
    // of new entities, 0-based
    ErrorCode result;

    Range set_range;
    std::vector< Tag > all_tags;
    std::vector< Range > tag_ranges;

    Range::const_iterator rit;

    // Entities
    result = pack_entities( orig_ents, buff, store_remote_handles, to_proc, false, entprocs, allsent );MB_CHK_SET_ERR( result, "Packing entities failed" );

    // Sets
    result = pack_sets( orig_ents, buff, store_remote_handles, to_proc );MB_CHK_SET_ERR( result, "Packing sets (count) failed" );

    // Tags
    Range final_ents;
    if( tags )
    {
        result = get_tag_send_list( orig_ents, all_tags, tag_ranges );MB_CHK_SET_ERR( result, "Failed to get tagged entities" );
        result = pack_tags( orig_ents, all_tags, all_tags, tag_ranges, buff, store_remote_handles, to_proc );MB_CHK_SET_ERR( result, "Packing tags (count) failed" );
    }
    else
    {  // Set tag size to 0
        buff->check_space( sizeof( int ) );
        PACK_INT( buff->buff_ptr, 0 );
        buff->set_stored_size();
    }

    return result;
}

ErrorCode ParallelComm::unpack_buffer( unsigned char* buff_ptr,
                                       const bool store_remote_handles,
                                       const int from_proc,
                                       const int ind,
                                       std::vector< std::vector< EntityHandle > >& L1hloc,
                                       std::vector< std::vector< EntityHandle > >& L1hrem,
                                       std::vector< std::vector< int > >& L1p,
                                       std::vector< EntityHandle >& L2hloc,
                                       std::vector< EntityHandle >& L2hrem,
                                       std::vector< unsigned int >& L2p,
                                       std::vector< EntityHandle >& new_ents,
                                       const bool created_iface )
{
    unsigned char* tmp_buff = buff_ptr;
    ErrorCode result;
    result = unpack_entities( buff_ptr, store_remote_handles, ind, false, L1hloc, L1hrem, L1p, L2hloc, L2hrem, L2p,
                              new_ents, created_iface );MB_CHK_SET_ERR( result, "Unpacking entities failed" );
    if( myDebug->get_verbosity() == 3 )
    {
        myDebug->tprintf( 4, "unpack_entities buffer space: %ld bytes.\n", (long int)( buff_ptr - tmp_buff ) );
        tmp_buff = buff_ptr;
    }
    result = unpack_sets( buff_ptr, new_ents, store_remote_handles, from_proc );MB_CHK_SET_ERR( result, "Unpacking sets failed" );
    if( myDebug->get_verbosity() == 3 )
    {
        myDebug->tprintf( 4, "unpack_sets buffer space: %ld bytes.\n", (long int)( buff_ptr - tmp_buff ) );
        tmp_buff = buff_ptr;
    }
    result = unpack_tags( buff_ptr, new_ents, store_remote_handles, from_proc );MB_CHK_SET_ERR( result, "Unpacking tags failed" );
    if( myDebug->get_verbosity() == 3 )
    {
        myDebug->tprintf( 4, "unpack_tags buffer space: %ld bytes.\n", (long int)( buff_ptr - tmp_buff ) );
        // tmp_buff = buff_ptr;
    }

    if( myDebug->get_verbosity() == 3 ) myDebug->print( 4, "\n" );

    return MB_SUCCESS;
}

int ParallelComm::estimate_ents_buffer_size( Range& entities, const bool store_remote_handles )
{
    int buff_size = 0;
    std::vector< EntityHandle > dum_connect_vec;
    const EntityHandle* connect;
    int num_connect;

    int num_verts = entities.num_of_type( MBVERTEX );
    // # verts + coords + handles
    buff_size += 2 * sizeof( int ) + 3 * sizeof( double ) * num_verts;
    if( store_remote_handles ) buff_size += sizeof( EntityHandle ) * num_verts;

    // Do a rough count by looking at first entity of each type
    for( EntityType t = MBEDGE; t < MBENTITYSET; t++ )
    {
        const Range::iterator rit = entities.lower_bound( t );
        if( TYPE_FROM_HANDLE( *rit ) != t ) continue;

        ErrorCode result = mbImpl->get_connectivity( *rit, connect, num_connect, false, &dum_connect_vec );MB_CHK_SET_ERR_RET_VAL( result, "Failed to get connectivity to estimate buffer size", -1 );

        // Number, type, nodes per entity
        buff_size += 3 * sizeof( int );
        int num_ents = entities.num_of_type( t );
        // Connectivity, handle for each ent
        buff_size += ( num_connect + 1 ) * sizeof( EntityHandle ) * num_ents;
    }

    // Extra entity type at end, passed as int
    buff_size += sizeof( int );

    return buff_size;
}

int ParallelComm::estimate_sets_buffer_size( Range& entities, const bool /*store_remote_handles*/ )
{
    // Number of sets
    int buff_size = sizeof( int );

    // Do a rough count by looking at first entity of each type
    Range::iterator rit = entities.lower_bound( MBENTITYSET );
    ErrorCode result;

    for( ; rit != entities.end(); ++rit )
    {
        unsigned int options;
        result = mbImpl->get_meshset_options( *rit, options );MB_CHK_SET_ERR_RET_VAL( result, "Failed to get meshset options", -1 );

        buff_size += sizeof( int );

        Range set_range;
        if( options & MESHSET_SET )
        {
            // Range-based set; count the subranges
            result = mbImpl->get_entities_by_handle( *rit, set_range );MB_CHK_SET_ERR_RET_VAL( result, "Failed to get set entities", -1 );

            // Set range
            buff_size += RANGE_SIZE( set_range );
        }
        else if( options & MESHSET_ORDERED )
        {
            // Just get the number of entities in the set
            int num_ents;
            result = mbImpl->get_number_entities_by_handle( *rit, num_ents );MB_CHK_SET_ERR_RET_VAL( result, "Failed to get number entities in ordered set", -1 );

            // Set vec
            buff_size += sizeof( EntityHandle ) * num_ents + sizeof( int );
        }

        // Get numbers of parents/children
        int num_par, num_ch;
        result = mbImpl->num_child_meshsets( *rit, &num_ch );MB_CHK_SET_ERR_RET_VAL( result, "Failed to get num children", -1 );
        result = mbImpl->num_parent_meshsets( *rit, &num_par );MB_CHK_SET_ERR_RET_VAL( result, "Failed to get num parents", -1 );

        buff_size += ( num_ch + num_par ) * sizeof( EntityHandle ) + 2 * sizeof( int );
    }

    return buff_size;
}

ErrorCode ParallelComm::pack_entities( Range& entities,
                                       Buffer* buff,
                                       const bool store_remote_handles,
                                       const int to_proc,
                                       const bool /*is_iface*/,
                                       TupleList* entprocs,
                                       Range* /*allsent*/ )
{
    // Packed information:
    // 1. # entities = E
    // 2. for e in E
    //   a. # procs sharing e, incl. sender and receiver = P
    //   b. for p in P (procs sharing e)
    //   c. for p in P (handle for e on p) (Note1)
    // 3. vertex/entity info

    // Get an estimate of the buffer size & pre-allocate buffer size
    int buff_size = estimate_ents_buffer_size( entities, store_remote_handles );
    if( buff_size < 0 ) MB_SET_ERR( MB_FAILURE, "Failed to estimate ents buffer size" );
    buff->check_space( buff_size );
    myDebug->tprintf( 3, "estimate buffer size for %d entities: %d \n", (int)entities.size(), buff_size );

    unsigned int num_ents;
    ErrorCode result;

    std::vector< EntityHandle > entities_vec( entities.size() );
    std::copy( entities.begin(), entities.end(), entities_vec.begin() );

    // First pack procs/handles sharing this ent, not including this dest but including
    // others (with zero handles)
    if( store_remote_handles )
    {
        // Buff space is at least proc + handle for each entity; use avg of 4 other procs
        // to estimate buff size, but check later
        buff->check_space( sizeof( int ) + ( 5 * sizeof( int ) + sizeof( EntityHandle ) ) * entities.size() );

        // 1. # entities = E
        PACK_INT( buff->buff_ptr, entities.size() );

        Range::iterator rit;

        // Pre-fetch sharedp and pstatus
        std::vector< int > sharedp_vals( entities.size() );
        result = mbImpl->tag_get_data( sharedp_tag(), entities, &sharedp_vals[0] );MB_CHK_SET_ERR( result, "Failed to get sharedp tag data" );
        std::vector< char > pstatus_vals( entities.size() );
        result = mbImpl->tag_get_data( pstatus_tag(), entities, &pstatus_vals[0] );MB_CHK_SET_ERR( result, "Failed to get pstatus tag data" );

        unsigned int i;
        int tmp_procs[MAX_SHARING_PROCS];
        EntityHandle tmp_handles[MAX_SHARING_PROCS];
        std::set< unsigned int > dumprocs;

        // 2. for e in E
        for( rit = entities.begin(), i = 0; rit != entities.end(); ++rit, i++ )
        {
            unsigned int ind =
                std::lower_bound( entprocs->vul_rd, entprocs->vul_rd + entprocs->get_n(), *rit ) - entprocs->vul_rd;
            assert( ind < entprocs->get_n() );

            while( ind < entprocs->get_n() && entprocs->vul_rd[ind] == *rit )
                dumprocs.insert( entprocs->vi_rd[ind++] );

            result = build_sharedhps_list( *rit, pstatus_vals[i], sharedp_vals[i], dumprocs, num_ents, tmp_procs,
                                           tmp_handles );MB_CHK_SET_ERR( result, "Failed to build sharedhps" );

            dumprocs.clear();

            // Now pack them
            buff->check_space( ( num_ents + 1 ) * sizeof( int ) + num_ents * sizeof( EntityHandle ) );
            PACK_INT( buff->buff_ptr, num_ents );
            PACK_INTS( buff->buff_ptr, tmp_procs, num_ents );
            PACK_EH( buff->buff_ptr, tmp_handles, num_ents );

#ifndef NDEBUG
            // Check for duplicates in proc list
            unsigned int dp = 0;
            for( ; dp < MAX_SHARING_PROCS && -1 != tmp_procs[dp]; dp++ )
                dumprocs.insert( tmp_procs[dp] );
            assert( dumprocs.size() == dp );
            dumprocs.clear();
#endif
        }
    }

    // Pack vertices
    Range these_ents = entities.subset_by_type( MBVERTEX );
    num_ents         = these_ents.size();

    if( num_ents )
    {
        buff_size = 2 * sizeof( int ) + 3 * num_ents * sizeof( double );
        buff->check_space( buff_size );

        // Type, # ents
        PACK_INT( buff->buff_ptr, ( (int)MBVERTEX ) );
        PACK_INT( buff->buff_ptr, ( (int)num_ents ) );

        std::vector< double > tmp_coords( 3 * num_ents );
        result = mbImpl->get_coords( these_ents, &tmp_coords[0] );MB_CHK_SET_ERR( result, "Failed to get vertex coordinates" );
        PACK_DBLS( buff->buff_ptr, &tmp_coords[0], 3 * num_ents );

        myDebug->tprintf( 4, "Packed %lu ents of type %s\n", (unsigned long)these_ents.size(),
                          CN::EntityTypeName( TYPE_FROM_HANDLE( *these_ents.begin() ) ) );
    }

    // Now entities; go through range, packing by type and equal # verts per element
    Range::iterator start_rit = entities.find( *these_ents.rbegin() );
    ++start_rit;
    int last_nodes       = -1;
    EntityType last_type = MBMAXTYPE;
    these_ents.clear();
    Range::iterator end_rit = start_rit;
    EntitySequence* seq;
    ElementSequence* eseq;

    while( start_rit != entities.end() || !these_ents.empty() )
    {
        // Cases:
        // A: !end, last_type == MBMAXTYPE, seq: save contig sequence in these_ents
        // B: !end, last type & nodes same, seq: save contig sequence in these_ents
        // C: !end, last type & nodes different: pack these_ents, then save contig sequence in
        // these_ents D: end: pack these_ents

        // Find the sequence holding current start entity, if we're not at end
        eseq = NULL;
        if( start_rit != entities.end() )
        {
            result = sequenceManager->find( *start_rit, seq );MB_CHK_SET_ERR( result, "Failed to find entity sequence" );
            if( NULL == seq ) return MB_FAILURE;
            eseq = dynamic_cast< ElementSequence* >( seq );
        }

        // Pack the last batch if at end or next one is different
        if( !these_ents.empty() &&
            ( !eseq || eseq->type() != last_type || last_nodes != (int)eseq->nodes_per_element() ) )
        {
            result = pack_entity_seq( last_nodes, store_remote_handles, to_proc, these_ents, entities_vec, buff );MB_CHK_SET_ERR( result, "Failed to pack entities from a sequence" );
            these_ents.clear();
        }

        if( eseq )
        {
            // Continuation of current range, just save these entities
            // Get position in entities list one past end of this sequence
            end_rit = entities.lower_bound( start_rit, entities.end(), eseq->end_handle() + 1 );

            // Put these entities in the range
            std::copy( start_rit, end_rit, range_inserter( these_ents ) );

            last_type  = eseq->type();
            last_nodes = eseq->nodes_per_element();
        }
        else if( start_rit != entities.end() && TYPE_FROM_HANDLE( *start_rit ) == MBENTITYSET )
            break;

        start_rit = end_rit;
    }

    // Pack MBMAXTYPE to indicate end of ranges
    buff->check_space( sizeof( int ) );
    PACK_INT( buff->buff_ptr, ( (int)MBMAXTYPE ) );

    buff->set_stored_size();
    return MB_SUCCESS;
}

ErrorCode ParallelComm::build_sharedhps_list( const EntityHandle entity,
                                              const unsigned char pstatus,
                                              const int
#ifndef NDEBUG
                                                  sharedp
#endif
                                              ,
                                              const std::set< unsigned int >& procs,
                                              unsigned int& num_ents,
                                              int* tmp_procs,
                                              EntityHandle* tmp_handles )
{
    num_ents = 0;
    unsigned char pstat;
    ErrorCode result = get_sharing_data( entity, tmp_procs, tmp_handles, pstat, num_ents );MB_CHK_SET_ERR( result, "Failed to get sharing data" );
    assert( pstat == pstatus );

    // Build shared proc/handle lists
    // Start with multi-shared, since if it is the owner will be first
    if( pstatus & PSTATUS_MULTISHARED )
    {
    }
    else if( pstatus & PSTATUS_NOT_OWNED )
    {
        // If not multishared and not owned, other sharing proc is owner, put that
        // one first
        assert( "If not owned, I should be shared too" && pstatus & PSTATUS_SHARED && 1 == num_ents );
        tmp_procs[1]   = procConfig.proc_rank();
        tmp_handles[1] = entity;
        num_ents       = 2;
    }
    else if( pstatus & PSTATUS_SHARED )
    {
        // If not multishared and owned, I'm owner
        assert( "shared and owned, should be only 1 sharing proc" && 1 == num_ents );
        tmp_procs[1]   = tmp_procs[0];
        tmp_procs[0]   = procConfig.proc_rank();
        tmp_handles[1] = tmp_handles[0];
        tmp_handles[0] = entity;
        num_ents       = 2;
    }
    else
    {
        // Not shared yet, just add owner (me)
        tmp_procs[0]   = procConfig.proc_rank();
        tmp_handles[0] = entity;
        num_ents       = 1;
    }

#ifndef NDEBUG
    int tmp_ps = num_ents;
#endif

    // Now add others, with zero handle for now
    for( std::set< unsigned int >::iterator sit = procs.begin(); sit != procs.end(); ++sit )
    {
#ifndef NDEBUG
        if( tmp_ps && std::find( tmp_procs, tmp_procs + tmp_ps, *sit ) != tmp_procs + tmp_ps )
        {
            std::cerr << "Trouble with something already in shared list on proc " << procConfig.proc_rank()
                      << ". Entity:" << std::endl;
            list_entities( &entity, 1 );
            std::cerr << "pstatus = " << (int)pstatus << ", sharedp = " << sharedp << std::endl;
            std::cerr << "tmp_ps = ";
            for( int i = 0; i < tmp_ps; i++ )
                std::cerr << tmp_procs[i] << " ";
            std::cerr << std::endl;
            std::cerr << "procs = ";
            for( std::set< unsigned int >::iterator sit2 = procs.begin(); sit2 != procs.end(); ++sit2 )
                std::cerr << *sit2 << " ";
            assert( false );
        }
#endif
        tmp_procs[num_ents]   = *sit;
        tmp_handles[num_ents] = 0;
        num_ents++;
    }

    // Put -1 after procs and 0 after handles
    if( MAX_SHARING_PROCS > num_ents )
    {
        tmp_procs[num_ents]   = -1;
        tmp_handles[num_ents] = 0;
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::pack_entity_seq( const int nodes_per_entity,
                                         const bool store_remote_handles,
                                         const int to_proc,
                                         Range& these_ents,
                                         std::vector< EntityHandle >& entities_vec,<--- Parameter 'entities_vec' can be declared with const
                                         Buffer* buff )
{
    int tmp_space = 3 * sizeof( int ) + nodes_per_entity * these_ents.size() * sizeof( EntityHandle );
    buff->check_space( tmp_space );

    // Pack the entity type
    PACK_INT( buff->buff_ptr, ( (int)TYPE_FROM_HANDLE( *these_ents.begin() ) ) );

    // Pack # ents
    PACK_INT( buff->buff_ptr, these_ents.size() );

    // Pack the nodes per entity
    PACK_INT( buff->buff_ptr, nodes_per_entity );
    myDebug->tprintf( 3, "after some pack int  %d \n", buff->get_current_size() );

    // Pack the connectivity
    std::vector< EntityHandle > connect;
    ErrorCode result = MB_SUCCESS;
    for( Range::const_iterator rit = these_ents.begin(); rit != these_ents.end(); ++rit )
    {
        connect.clear();
        result = mbImpl->get_connectivity( &( *rit ), 1, connect, false );MB_CHK_SET_ERR( result, "Failed to get connectivity" );
        assert( (int)connect.size() == nodes_per_entity );
        result =
            get_remote_handles( store_remote_handles, &connect[0], &connect[0], connect.size(), to_proc, entities_vec );MB_CHK_SET_ERR( result, "Failed in get_remote_handles" );
        PACK_EH( buff->buff_ptr, &connect[0], connect.size() );
    }

    myDebug->tprintf( 3, "Packed %lu ents of type %s\n", (unsigned long)these_ents.size(),
                      CN::EntityTypeName( TYPE_FROM_HANDLE( *these_ents.begin() ) ) );

    return result;
}

ErrorCode ParallelComm::get_remote_handles( const bool store_remote_handles,
                                            EntityHandle* from_vec,
                                            EntityHandle* to_vec_tmp,
                                            int num_ents,
                                            int to_proc,
                                            const std::vector< EntityHandle >& new_ents )
{
    // NOTE: THIS IMPLEMENTATION IS JUST LIKE THE RANGE-BASED VERSION, NO REUSE
    // AT THIS TIME, SO IF YOU FIX A BUG IN THIS VERSION, IT MAY BE IN THE
    // OTHER VERSION TOO!!!
    if( 0 == num_ents ) return MB_SUCCESS;

    // Use a local destination ptr in case we're doing an in-place copy
    std::vector< EntityHandle > tmp_vector;
    EntityHandle* to_vec = to_vec_tmp;
    if( to_vec == from_vec )
    {
        tmp_vector.resize( num_ents );
        to_vec = &tmp_vector[0];
    }

    if( !store_remote_handles )
    {
        int err;
        // In this case, substitute position in new_ents list
        for( int i = 0; i < num_ents; i++ )
        {
            int ind = std::lower_bound( new_ents.begin(), new_ents.end(), from_vec[i] ) - new_ents.begin();
            assert( new_ents[ind] == from_vec[i] );
            to_vec[i] = CREATE_HANDLE( MBMAXTYPE, ind, err );
            assert( to_vec[i] != 0 && !err && -1 != ind );
        }
    }
    else
    {
        Tag shp_tag, shps_tag, shh_tag, shhs_tag, pstat_tag;
        ErrorCode result = get_shared_proc_tags( shp_tag, shps_tag, shh_tag, shhs_tag, pstat_tag );MB_CHK_SET_ERR( result, "Failed to get shared proc tags" );

        // Get single-proc destination handles and shared procs
        std::vector< int > sharing_procs( num_ents );
        result = mbImpl->tag_get_data( shh_tag, from_vec, num_ents, to_vec );MB_CHK_SET_ERR( result, "Failed to get shared handle tag for remote_handles" );
        result = mbImpl->tag_get_data( shp_tag, from_vec, num_ents, &sharing_procs[0] );MB_CHK_SET_ERR( result, "Failed to get sharing proc tag in remote_handles" );
        for( int j = 0; j < num_ents; j++ )
        {
            if( to_vec[j] && sharing_procs[j] != to_proc ) to_vec[j] = 0;
        }

        EntityHandle tmp_handles[MAX_SHARING_PROCS];
        int tmp_procs[MAX_SHARING_PROCS];
        int i;
        // Go through results, and for 0-valued ones, look for multiple shared proc
        for( i = 0; i < num_ents; i++ )
        {
            if( !to_vec[i] )
            {
                result = mbImpl->tag_get_data( shps_tag, from_vec + i, 1, tmp_procs );
                if( MB_SUCCESS == result )
                {
                    for( int j = 0; j < MAX_SHARING_PROCS; j++ )
                    {
                        if( -1 == tmp_procs[j] )
                            break;
                        else if( tmp_procs[j] == to_proc )
                        {
                            result = mbImpl->tag_get_data( shhs_tag, from_vec + i, 1, tmp_handles );MB_CHK_SET_ERR( result, "Failed to get sharedhs tag data" );
                            to_vec[i] = tmp_handles[j];
                            assert( to_vec[i] );
                            break;
                        }
                    }
                }
                if( !to_vec[i] )
                {
                    int j = std::lower_bound( new_ents.begin(), new_ents.end(), from_vec[i] ) - new_ents.begin();
                    if( (int)new_ents.size() == j )
                    {
                        std::cout << "Failed to find new entity in send list, proc " << procConfig.proc_rank()
                                  << std::endl;
                        for( int k = 0; k <= num_ents; k++ )
                            std::cout << k << ": " << from_vec[k] << " " << to_vec[k] << std::endl;
                        MB_SET_ERR( MB_FAILURE, "Failed to find new entity in send list" );
                    }
                    int err;
                    to_vec[i] = CREATE_HANDLE( MBMAXTYPE, j, err );
                    if( err )
                    {
                        MB_SET_ERR( MB_FAILURE, "Failed to create handle in remote_handles" );
                    }
                }
            }
        }
    }

    // memcpy over results if from_vec and to_vec are the same
    if( to_vec_tmp == from_vec ) memcpy( from_vec, to_vec, num_ents * sizeof( EntityHandle ) );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_remote_handles( const bool store_remote_handles,
                                            const Range& from_range,
                                            EntityHandle* to_vec,
                                            int to_proc,
                                            const std::vector< EntityHandle >& new_ents )
{
    // NOTE: THIS IMPLEMENTATION IS JUST LIKE THE VECTOR-BASED VERSION, NO REUSE
    // AT THIS TIME, SO IF YOU FIX A BUG IN THIS VERSION, IT MAY BE IN THE
    // OTHER VERSION TOO!!!
    if( from_range.empty() ) return MB_SUCCESS;

    if( !store_remote_handles )
    {
        int err;
        // In this case, substitute position in new_ents list
        Range::iterator rit;
        unsigned int i;
        for( rit = from_range.begin(), i = 0; rit != from_range.end(); ++rit, i++ )
        {
            int ind = std::lower_bound( new_ents.begin(), new_ents.end(), *rit ) - new_ents.begin();
            assert( new_ents[ind] == *rit );
            to_vec[i] = CREATE_HANDLE( MBMAXTYPE, ind, err );
            assert( to_vec[i] != 0 && !err && -1 != ind );
        }
    }
    else
    {
        Tag shp_tag, shps_tag, shh_tag, shhs_tag, pstat_tag;
        ErrorCode result = get_shared_proc_tags( shp_tag, shps_tag, shh_tag, shhs_tag, pstat_tag );MB_CHK_SET_ERR( result, "Failed to get shared proc tags" );

        // Get single-proc destination handles and shared procs
        std::vector< int > sharing_procs( from_range.size() );
        result = mbImpl->tag_get_data( shh_tag, from_range, to_vec );MB_CHK_SET_ERR( result, "Failed to get shared handle tag for remote_handles" );
        result = mbImpl->tag_get_data( shp_tag, from_range, &sharing_procs[0] );MB_CHK_SET_ERR( result, "Failed to get sharing proc tag in remote_handles" );
        for( unsigned int j = 0; j < from_range.size(); j++ )
        {
            if( to_vec[j] && sharing_procs[j] != to_proc ) to_vec[j] = 0;
        }

        EntityHandle tmp_handles[MAX_SHARING_PROCS];
        int tmp_procs[MAX_SHARING_PROCS];
        // Go through results, and for 0-valued ones, look for multiple shared proc
        Range::iterator rit;
        unsigned int i;
        for( rit = from_range.begin(), i = 0; rit != from_range.end(); ++rit, i++ )
        {
            if( !to_vec[i] )
            {
                result = mbImpl->tag_get_data( shhs_tag, &( *rit ), 1, tmp_handles );
                if( MB_SUCCESS == result )
                {
                    result = mbImpl->tag_get_data( shps_tag, &( *rit ), 1, tmp_procs );MB_CHK_SET_ERR( result, "Failed to get sharedps tag data" );
                    for( int j = 0; j < MAX_SHARING_PROCS; j++ )
                        if( tmp_procs[j] == to_proc )
                        {
                            to_vec[i] = tmp_handles[j];
                            break;
                        }
                }

                if( !to_vec[i] )
                {
                    int j = std::lower_bound( new_ents.begin(), new_ents.end(), *rit ) - new_ents.begin();
                    if( (int)new_ents.size() == j )
                    {
                        MB_SET_ERR( MB_FAILURE, "Failed to find new entity in send list" );
                    }
                    int err;
                    to_vec[i] = CREATE_HANDLE( MBMAXTYPE, j, err );
                    if( err )
                    {
                        MB_SET_ERR( MB_FAILURE, "Failed to create handle in remote_handles" );
                    }
                }
            }
        }
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_remote_handles( const bool store_remote_handles,
                                            const Range& from_range,
                                            Range& to_range,
                                            int to_proc,
                                            const std::vector< EntityHandle >& new_ents )
{
    std::vector< EntityHandle > to_vector( from_range.size() );

    ErrorCode result = get_remote_handles( store_remote_handles, from_range, &to_vector[0], to_proc, new_ents );MB_CHK_SET_ERR( result, "Failed to get remote handles" );
    std::copy( to_vector.begin(), to_vector.end(), range_inserter( to_range ) );
    return result;
}

ErrorCode ParallelComm::unpack_entities( unsigned char*& buff_ptr,
                                         const bool store_remote_handles,
                                         const int /*from_ind*/,
                                         const bool is_iface,
                                         std::vector< std::vector< EntityHandle > >& L1hloc,
                                         std::vector< std::vector< EntityHandle > >& L1hrem,
                                         std::vector< std::vector< int > >& L1p,
                                         std::vector< EntityHandle >& L2hloc,
                                         std::vector< EntityHandle >& L2hrem,
                                         std::vector< unsigned int >& L2p,
                                         std::vector< EntityHandle >& new_ents,
                                         const bool created_iface )
{
    // General algorithm:
    // - unpack # entities
    // - save start of remote handle info, then scan forward to entity definition data
    // - for all vertices or entities w/ same # verts:
    //   . get entity type, num ents, and (if !vert) # verts
    //   . for each ent:
    //      o get # procs/handles in remote handle info
    //      o if # procs/handles > 2, check for already-created entity:
    //        x get index of owner proc (1st in proc list), resize L1 list if nec
    //        x look for already-arrived entity in L2 by owner handle
    //      o if no existing entity:
    //        x if iface, look for existing entity with same connect & type
    //        x if none found, create vertex or element
    //        x if !iface & multi-shared, save on L2
    //        x if !iface, put new entity on new_ents list
    //      o update proc/handle, pstatus tags, adjusting to put owner first if iface
    //      o if !iface, save new handle on L1 for all sharing procs

    // Lists of handles/procs to return to sending/other procs
    // L1hloc[p], L1hrem[p]: handle pairs [h, h'], where h is the local proc handle
    //         and h' is either the remote proc handle (if that is known) or
    //         the owner proc handle (otherwise);
    // L1p[p]: indicates whether h is remote handle (= -1) or owner (rank of owner)
    // L2hloc, L2hrem: local/remote handles for entities shared by > 2 procs;
    //         remote handles are on owning proc
    // L2p: owning procs for handles in L2hrem

    ErrorCode result;
    bool done         = false;<--- Assignment 'done=false', assigned value is 0
    ReadUtilIface* ru = NULL;

    result = mbImpl->query_interface( ru );MB_CHK_SET_ERR( result, "Failed to get ReadUtilIface" );

    // 1. # entities = E
    int num_ents             = 0;
    unsigned char* buff_save = buff_ptr;
    int i, j;

    if( store_remote_handles )
    {
        UNPACK_INT( buff_ptr, num_ents );

        buff_save = buff_ptr;

        // Save place where remote handle info starts, then scan forward to ents
        for( i = 0; i < num_ents; i++ )
        {
            UNPACK_INT( buff_ptr, j );
            if( j < 0 )
            {
                std::cout << "Should be non-negative # proc/handles.";
                return MB_FAILURE;
            }

            buff_ptr += j * ( sizeof( int ) + sizeof( EntityHandle ) );
        }
    }

    std::vector< EntityHandle > msg_ents;

    while( !done )<--- Condition '!done' is always true
    {
        EntityType this_type = MBMAXTYPE;
        UNPACK_TYPE( buff_ptr, this_type );
        assert( this_type != MBENTITYSET );

        // MBMAXTYPE signifies end of entities data
        if( MBMAXTYPE == this_type ) break;

        // Get the number of ents
        int num_ents2, verts_per_entity = 0;
        UNPACK_INT( buff_ptr, num_ents2 );

        // Unpack the nodes per entity
        if( MBVERTEX != this_type && num_ents2 )
        {
            UNPACK_INT( buff_ptr, verts_per_entity );
        }

        std::vector< int > ps( MAX_SHARING_PROCS, -1 );
        std::vector< EntityHandle > hs( MAX_SHARING_PROCS, 0 );
        for( int e = 0; e < num_ents2; e++ )
        {
            // Check for existing entity, otherwise make new one
            EntityHandle new_h = 0;
            EntityHandle connect[CN::MAX_NODES_PER_ELEMENT];
            double coords[3];
            int num_ps = -1;

            //=======================================
            // Unpack all the data at once, to make sure the buffer pointers
            // are tracked correctly
            //=======================================
            if( store_remote_handles )
            {
                // Pointers to other procs/handles
                UNPACK_INT( buff_save, num_ps );
                if( 0 >= num_ps )
                {
                    std::cout << "Shouldn't ever be fewer than 1 procs here." << std::endl;
                    return MB_FAILURE;
                }

                UNPACK_INTS( buff_save, &ps[0], num_ps );
                UNPACK_EH( buff_save, &hs[0], num_ps );
            }

            if( MBVERTEX == this_type )
            {
                UNPACK_DBLS( buff_ptr, coords, 3 );
            }
            else
            {
                assert( verts_per_entity <= CN::MAX_NODES_PER_ELEMENT );
                UNPACK_EH( buff_ptr, connect, verts_per_entity );

                // Update connectivity to local handles
                result = get_local_handles( connect, verts_per_entity, msg_ents );MB_CHK_SET_ERR( result, "Failed to get local handles" );
            }

            //=======================================
            // Now, process that data; begin by finding an identical
            // entity, if there is one
            //=======================================
            if( store_remote_handles )
            {
                result = find_existing_entity( is_iface, ps[0], hs[0], num_ps, connect, verts_per_entity, this_type,
                                               L2hloc, L2hrem, L2p, new_h );MB_CHK_SET_ERR( result, "Failed to get existing entity" );
            }

            //=======================================
            // If we didn't find one, we'll have to create one
            //=======================================
            bool created_here = false;
            if( !new_h && !is_iface )
            {
                if( MBVERTEX == this_type )
                {
                    // Create a vertex
                    result = mbImpl->create_vertex( coords, new_h );MB_CHK_SET_ERR( result, "Failed to make new vertex" );
                }
                else
                {
                    // Create the element
                    result = mbImpl->create_element( this_type, connect, verts_per_entity, new_h );MB_CHK_SET_ERR( result, "Failed to make new element" );

                    // Update adjacencies
                    result = ru->update_adjacencies( new_h, 1, verts_per_entity, connect );MB_CHK_SET_ERR( result, "Failed to update adjacencies" );
                }

                // Should have a new handle now
                assert( new_h );

                created_here = true;
            }

            //=======================================
            // Take care of sharing data
            //=======================================

            // Need to save entities found in order, for interpretation of
            // later parts of this message
            if( !is_iface )
            {
                assert( new_h );
                msg_ents.push_back( new_h );
            }

            if( created_here ) new_ents.push_back( new_h );

            if( new_h && store_remote_handles )<--- Assuming that condition 'store_remote_handles' is not redundant
            {
                unsigned char new_pstat = 0x0;
                if( is_iface )
                {
                    new_pstat = PSTATUS_INTERFACE;
                    // Here, lowest rank proc should be first
                    int idx = std::min_element( &ps[0], &ps[0] + num_ps ) - &ps[0];
                    if( idx )
                    {
                        std::swap( ps[0], ps[idx] );
                        std::swap( hs[0], hs[idx] );
                    }
                    // Set ownership based on lowest rank; can't be in update_remote_data, because
                    // there we don't know whether it resulted from ghosting or not
                    if( ( num_ps > 1 && ps[0] != (int)rank() ) ) new_pstat |= PSTATUS_NOT_OWNED;
                }
                else if( created_here )
                {
                    if( created_iface )
                        new_pstat = PSTATUS_NOT_OWNED;
                    else
                        new_pstat = PSTATUS_GHOST | PSTATUS_NOT_OWNED;
                }

                // Update sharing data and pstatus, adjusting order if iface
                result = update_remote_data( new_h, &ps[0], &hs[0], num_ps, new_pstat );MB_CHK_SET_ERR( result, "unpack_entities" );

                // If a new multi-shared entity, save owner for subsequent lookup in L2 lists
                if( store_remote_handles && !is_iface && num_ps > 2 )<--- Condition 'store_remote_handles' is always true
                {
                    L2hrem.push_back( hs[0] );
                    L2hloc.push_back( new_h );
                    L2p.push_back( ps[0] );
                }

                // Need to send this new handle to all sharing procs
                if( !is_iface )
                {
                    for( j = 0; j < num_ps; j++ )
                    {
                        if( ps[j] == (int)procConfig.proc_rank() ) continue;
                        int idx = get_buffers( ps[j] );
                        if( idx == (int)L1hloc.size() )
                        {
                            L1hloc.resize( idx + 1 );
                            L1hrem.resize( idx + 1 );
                            L1p.resize( idx + 1 );
                        }

                        // Don't bother adding if it's already in the list
                        std::vector< EntityHandle >::iterator vit =
                            std::find( L1hloc[idx].begin(), L1hloc[idx].end(), new_h );
                        if( vit != L1hloc[idx].end() )
                        {
                            // If it's in the list but remote handle isn't known but we know
                            // it, replace in the list
                            if( L1p[idx][vit - L1hloc[idx].begin()] != -1 && hs[j] )
                            {
                                L1hrem[idx][vit - L1hloc[idx].begin()] = hs[j];
                                L1p[idx][vit - L1hloc[idx].begin()]    = -1;
                            }
                            else
                                continue;
                        }
                        else
                        {
                            if( !hs[j] )
                            {
                                assert( -1 != ps[0] && num_ps > 2 );
                                L1p[idx].push_back( ps[0] );
                                L1hrem[idx].push_back( hs[0] );
                            }
                            else
                            {
                                assert(
                                    "either this remote handle isn't in the remote list, or "
                                    "it's for another proc" &&
                                    ( std::find( L1hrem[idx].begin(), L1hrem[idx].end(), hs[j] ) == L1hrem[idx].end() ||
                                      L1p[idx][std::find( L1hrem[idx].begin(), L1hrem[idx].end(), hs[j] ) -
                                               L1hrem[idx].begin()] != -1 ) );
                                L1p[idx].push_back( -1 );
                                L1hrem[idx].push_back( hs[j] );
                            }
                            L1hloc[idx].push_back( new_h );
                        }
                    }
                }

                assert( "Shouldn't be here for non-shared entities" && -1 != num_ps );
                std::fill( &ps[0], &ps[num_ps], -1 );
                std::fill( &hs[0], &hs[num_ps], 0 );
            }
        }

        myDebug->tprintf( 4, "Unpacked %d ents of type %s", num_ents2, CN::EntityTypeName( this_type ) );
    }

    myDebug->tprintf( 4, "Done unpacking entities.\n" );

    // Need to sort here, to enable searching
    std::sort( new_ents.begin(), new_ents.end() );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::print_buffer( unsigned char* buff_ptr, int mesg_tag, int from_proc, bool sent )
{
    std::cerr << procConfig.proc_rank();
    if( sent )
        std::cerr << " sent";
    else
        std::cerr << " received";
    std::cerr << " message type " << mesg_tag << " to/from proc " << from_proc << "; contents:" << std::endl;

    int msg_length, num_ents;
    unsigned char* orig_ptr = buff_ptr;
    UNPACK_INT( buff_ptr, msg_length );
    std::cerr << msg_length << " bytes..." << std::endl;

    if( MB_MESG_ENTS_SIZE == mesg_tag || MB_MESG_ENTS_LARGE == mesg_tag )
    {
        // 1. # entities = E
        int i, j, k;
        std::vector< int > ps;
        std::vector< EntityHandle > hs;

        UNPACK_INT( buff_ptr, num_ents );
        std::cerr << num_ents << " entities..." << std::endl;

        // Save place where remote handle info starts, then scan forward to ents
        for( i = 0; i < num_ents; i++ )
        {
            UNPACK_INT( buff_ptr, j );
            if( 0 > j ) return MB_FAILURE;
            ps.resize( j );
            hs.resize( j );
            std::cerr << "Entity " << i << ", # procs = " << j << std::endl;
            UNPACK_INTS( buff_ptr, &ps[0], j );
            UNPACK_EH( buff_ptr, &hs[0], j );
            std::cerr << "   Procs: ";
            for( k = 0; k < j; k++ )
                std::cerr << ps[k] << " ";
            std::cerr << std::endl;
            std::cerr << "   Handles: ";
            for( k = 0; k < j; k++ )
                std::cerr << hs[k] << " ";
            std::cerr << std::endl;

            if( buff_ptr - orig_ptr > msg_length )
            {
                std::cerr << "End of buffer..." << std::endl;
                std::cerr.flush();
                return MB_FAILURE;
            }
        }

        while( true )
        {
            EntityType this_type = MBMAXTYPE;
            UNPACK_TYPE( buff_ptr, this_type );
            assert( this_type != MBENTITYSET );

            // MBMAXTYPE signifies end of entities data
            if( MBMAXTYPE == this_type ) break;

            // Get the number of ents
            int num_ents2, verts_per_entity = 0;
            UNPACK_INT( buff_ptr, num_ents2 );

            // Unpack the nodes per entity
            if( MBVERTEX != this_type && num_ents2 )
            {
                UNPACK_INT( buff_ptr, verts_per_entity );
            }

            std::cerr << "Type: " << CN::EntityTypeName( this_type ) << "; num_ents = " << num_ents2;
            if( MBVERTEX != this_type ) std::cerr << "; verts_per_ent = " << verts_per_entity;
            std::cerr << std::endl;
            if( num_ents2 < 0 || num_ents2 > msg_length )
            {
                std::cerr << "Wrong number of entities, returning." << std::endl;
                return MB_FAILURE;
            }

            for( int e = 0; e < num_ents2; e++ )
            {
                // Check for existing entity, otherwise make new one
                if( MBVERTEX == this_type )
                {
                    double coords[3];
                    UNPACK_DBLS( buff_ptr, coords, 3 );
                    std::cerr << "xyz = " << coords[0] << ", " << coords[1] << ", " << coords[2] << std::endl;
                }
                else
                {
                    EntityHandle connect[CN::MAX_NODES_PER_ELEMENT];
                    assert( verts_per_entity <= CN::MAX_NODES_PER_ELEMENT );
                    UNPACK_EH( buff_ptr, connect, verts_per_entity );

                    // Update connectivity to local handles
                    std::cerr << "Connectivity: ";
                    for( k = 0; k < verts_per_entity; k++ )
                        std::cerr << connect[k] << " ";
                    std::cerr << std::endl;
                }

                if( buff_ptr - orig_ptr > msg_length )
                {
                    std::cerr << "End of buffer..." << std::endl;
                    std::cerr.flush();
                    return MB_FAILURE;
                }
            }
        }
    }
    else if( MB_MESG_REMOTEH_SIZE == mesg_tag || MB_MESG_REMOTEH_LARGE == mesg_tag )
    {
        UNPACK_INT( buff_ptr, num_ents );
        std::cerr << num_ents << " entities..." << std::endl;
        if( 0 > num_ents || num_ents > msg_length )
        {
            std::cerr << "Wrong number of entities, returning." << std::endl;
            return MB_FAILURE;
        }
        std::vector< EntityHandle > L1hloc( num_ents ), L1hrem( num_ents );
        std::vector< int > L1p( num_ents );
        UNPACK_INTS( buff_ptr, &L1p[0], num_ents );
        UNPACK_EH( buff_ptr, &L1hrem[0], num_ents );
        UNPACK_EH( buff_ptr, &L1hloc[0], num_ents );
        std::cerr << num_ents << " Entity pairs; hremote/hlocal/proc: " << std::endl;
        for( int i = 0; i < num_ents; i++ )
        {
            EntityType etype = TYPE_FROM_HANDLE( L1hloc[i] );
            std::cerr << CN::EntityTypeName( etype ) << ID_FROM_HANDLE( L1hrem[i] ) << ", "
                      << CN::EntityTypeName( etype ) << ID_FROM_HANDLE( L1hloc[i] ) << ", " << L1p[i] << std::endl;
        }

        if( buff_ptr - orig_ptr > msg_length )
        {
            std::cerr << "End of buffer..." << std::endl;
            std::cerr.flush();
            return MB_FAILURE;
        }
    }
    else if( mesg_tag == MB_MESG_TAGS_SIZE || mesg_tag == MB_MESG_TAGS_LARGE )
    {
        int num_tags, dum1, data_type, tag_size;
        UNPACK_INT( buff_ptr, num_tags );
        std::cerr << "Number of tags = " << num_tags << std::endl;
        for( int i = 0; i < num_tags; i++ )
        {
            std::cerr << "Tag " << i << ":" << std::endl;
            UNPACK_INT( buff_ptr, tag_size );
            UNPACK_INT( buff_ptr, dum1 );
            UNPACK_INT( buff_ptr, data_type );
            std::cerr << "Tag size, type, data type = " << tag_size << ", " << dum1 << ", " << data_type << std::endl;
            UNPACK_INT( buff_ptr, dum1 );
            std::cerr << "Default value size = " << dum1 << std::endl;
            buff_ptr += dum1;
            UNPACK_INT( buff_ptr, dum1 );
            std::string name( (char*)buff_ptr, dum1 );
            std::cerr << "Tag name = " << name.c_str() << std::endl;
            buff_ptr += dum1;
            UNPACK_INT( buff_ptr, num_ents );
            std::cerr << "Number of ents = " << num_ents << std::endl;
            std::vector< EntityHandle > tmp_buff( num_ents );
            UNPACK_EH( buff_ptr, &tmp_buff[0], num_ents );
            int tot_length = 0;
            for( int j = 0; j < num_ents; j++ )
            {
                EntityType etype = TYPE_FROM_HANDLE( tmp_buff[j] );
                std::cerr << CN::EntityTypeName( etype ) << " " << ID_FROM_HANDLE( tmp_buff[j] ) << ", tag = ";
                if( tag_size == MB_VARIABLE_LENGTH )
                {
                    UNPACK_INT( buff_ptr, dum1 );
                    tot_length += dum1;
                    std::cerr << "(variable, length = " << dum1 << ")" << std::endl;
                }
                else if( data_type == MB_TYPE_DOUBLE )
                {
                    double dum_dbl;
                    UNPACK_DBL( buff_ptr, dum_dbl );
                    std::cerr << dum_dbl << std::endl;
                }
                else if( data_type == MB_TYPE_INTEGER )
                {
                    int dum_int;
                    UNPACK_INT( buff_ptr, dum_int );
                    std::cerr << dum_int << std::endl;
                }
                else if( data_type == MB_TYPE_OPAQUE )
                {
                    std::cerr << "(opaque)" << std::endl;
                    buff_ptr += tag_size;
                }
                else if( data_type == MB_TYPE_HANDLE )
                {
                    EntityHandle dum_eh;
                    UNPACK_EH( buff_ptr, &dum_eh, 1 );
                    std::cerr << dum_eh << std::endl;
                }
                else if( data_type == MB_TYPE_BIT )
                {
                    std::cerr << "(bit)" << std::endl;
                    buff_ptr += tag_size;
                }
            }
            if( tag_size == MB_VARIABLE_LENGTH ) buff_ptr += tot_length;
        }
    }
    else
    {
        assert( false );
        return MB_FAILURE;
    }

    std::cerr.flush();

    return MB_SUCCESS;
}

ErrorCode ParallelComm::list_entities( const EntityHandle* ents, int num_ents )
{
    if( NULL == ents )
    {
        Range shared_ents;
        std::copy( sharedEnts.begin(), sharedEnts.end(), range_inserter( shared_ents ) );
        shared_ents.print( "Shared entities:\n" );
        return MB_SUCCESS;
    }

    unsigned char pstat;
    EntityHandle tmp_handles[MAX_SHARING_PROCS];
    int tmp_procs[MAX_SHARING_PROCS];
    unsigned int num_ps;
    ErrorCode result;

    for( int i = 0; i < num_ents; i++ )
    {
        result = mbImpl->list_entities( ents + i, 1 );MB_CHK_ERR( result );
        double coords[3];
        result = mbImpl->get_coords( ents + i, 1, coords );<--- result is assigned
        std::cout << " coords: " << coords[0] << " " << coords[1] << " " << coords[2] << "\n";

        result = get_sharing_data( ents[i], tmp_procs, tmp_handles, pstat, num_ps );MB_CHK_SET_ERR( result, "Failed to get sharing data" );<--- result is overwritten

        std::cout << "Pstatus: ";
        if( !num_ps )
            std::cout << "local " << std::endl;
        else
        {
            if( pstat & PSTATUS_NOT_OWNED ) std::cout << "NOT_OWNED; ";
            if( pstat & PSTATUS_SHARED ) std::cout << "SHARED; ";
            if( pstat & PSTATUS_MULTISHARED ) std::cout << "MULTISHARED; ";
            if( pstat & PSTATUS_INTERFACE ) std::cout << "INTERFACE; ";
            if( pstat & PSTATUS_GHOST ) std::cout << "GHOST; ";
            std::cout << std::endl;
            for( unsigned int j = 0; j < num_ps; j++ )
            {
                std::cout << "  proc " << tmp_procs[j] << " id (handle) " << mbImpl->id_from_handle( tmp_handles[j] )
                          << "(" << tmp_handles[j] << ")" << std::endl;
            }
        }
        std::cout << std::endl;
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::list_entities( const Range& ents )
{
    for( Range::iterator rit = ents.begin(); rit != ents.end(); ++rit )
        list_entities( &( *rit ), 1 );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::update_remote_data( Range& local_range,
                                            Range& remote_range,
                                            int other_proc,
                                            const unsigned char add_pstat )
{
    Range::iterator rit, rit2;
    ErrorCode result = MB_SUCCESS;<--- Variable 'result' is assigned a value that is never used.

    // For each pair of local/remote handles:
    for( rit = local_range.begin(), rit2 = remote_range.begin(); rit != local_range.end(); ++rit, ++rit2 )
    {
        result = update_remote_data( *rit, &other_proc, &( *rit2 ), 1, add_pstat );MB_CHK_ERR( result );
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::update_remote_data( const EntityHandle new_h,
                                            const int* ps,
                                            const EntityHandle* hs,
                                            const int num_ps,
                                            const unsigned char add_pstat
                                            // The following lines left in for future debugging, at least until I trust
                                            // this function; tjt, 10/4/2013
                                            //                                           , int *new_ps,
                                            //                                           EntityHandle *new_hs,
                                            //                                           int &new_numps,
                                            //                                           unsigned char &new_pstat
)
{
    // Get initial sharing data; tag_ps and tag_hs get terminated with -1 and 0
    // in this function, so no need to initialize; sharing data does not include
    // this proc if shared with only one other

    // Following variables declared here to avoid compiler errors
    int new_numps;
    unsigned char new_pstat;
    std::vector< int > new_ps( MAX_SHARING_PROCS, -1 );
    std::vector< EntityHandle > new_hs( MAX_SHARING_PROCS, 0 );

    new_numps        = 0;
    ErrorCode result = get_sharing_data( new_h, &new_ps[0], &new_hs[0], new_pstat, new_numps );MB_CHK_SET_ERR( result, "Failed to get sharing data in update_remote_data" );
    int num_exist = new_numps;

    // Add new pstat info to the flag
    new_pstat |= add_pstat;

    /*
    #define plist(str, lst, siz)                                          \
        std::cout << str << "(";                                          \
        for (int i = 0; i < (int)siz; i++) std::cout << lst[i] << " ";    \
        std::cout << ") ";                                                \

        std::cout << "update_remote_data: rank = " << rank() << ", new_h = " << new_h << std::endl;
        std::string ostr;
        plist("ps", ps, num_ps);
        plist("hs", hs, num_ps);
        print_pstatus(add_pstat, ostr);
        std::cout << ", add_pstat = " << ostr.c_str() << std::endl;
        plist("tag_ps", new_ps, new_numps);
        plist("tag_hs", new_hs, new_numps);
        assert(new_numps <= size());
        print_pstatus(new_pstat, ostr);
        std::cout << ", tag_pstat=" << ostr.c_str() << std::endl;
    */

#ifndef NDEBUG
    {
        // Check for duplicates in proc list
        std::set< unsigned int > dumprocs;
        unsigned int dp = 0;
        for( ; (int)dp < num_ps && -1 != ps[dp]; dp++ )
            dumprocs.insert( ps[dp] );
        assert( dp == dumprocs.size() );
    }
#endif

    // If only one sharer and I'm the owner, insert myself in the list;
    // otherwise, my data is checked at the end
    if( 1 == new_numps && !( new_pstat & PSTATUS_NOT_OWNED ) )
    {
        new_hs[1] = new_hs[0];
        new_ps[1] = new_ps[0];
        new_hs[0] = new_h;
        new_ps[0] = rank();
        new_numps = 2;
    }

    // Now put passed-in data onto lists
    int idx;
    for( int i = 0; i < num_ps; i++ )
    {
        idx = std::find( &new_ps[0], &new_ps[0] + new_numps, ps[i] ) - &new_ps[0];
        if( idx < new_numps )
        {
            if( !new_hs[idx] && hs[i] )
                // h on list is 0 and passed-in h is non-zero, replace it
                new_hs[idx] = hs[i];
            else
                assert( !hs[i] || new_hs[idx] == hs[i] );
        }
        else
        {
            if( new_numps + 1 == MAX_SHARING_PROCS )
            {
                MB_SET_ERR( MB_FAILURE, "Exceeded MAX_SHARING_PROCS for "
                                            << CN::EntityTypeName( TYPE_FROM_HANDLE( new_h ) ) << ' '
                                            << ID_FROM_HANDLE( new_h ) << " in process " << rank() );
            }
            new_ps[new_numps] = ps[i];
            new_hs[new_numps] = hs[i];
            new_numps++;
        }
    }

    // Add myself, if it isn't there already
    idx = std::find( &new_ps[0], &new_ps[0] + new_numps, rank() ) - &new_ps[0];
    if( idx == new_numps )
    {
        new_ps[new_numps] = rank();
        new_hs[new_numps] = new_h;
        new_numps++;
    }
    else if( !new_hs[idx] && new_numps > 2 )
        new_hs[idx] = new_h;

    // Proc list is complete; update for shared, multishared
    if( new_numps > 1 )
    {
        if( new_numps > 2 ) new_pstat |= PSTATUS_MULTISHARED;
        new_pstat |= PSTATUS_SHARED;
    }

    /*
        plist("new_ps", new_ps, new_numps);
        plist("new_hs", new_hs, new_numps);
        print_pstatus(new_pstat, ostr);
        std::cout << ", new_pstat=" << ostr.c_str() << std::endl;
        std::cout << std::endl;
    */

    result = set_sharing_data( new_h, new_pstat, num_exist, new_numps, &new_ps[0], &new_hs[0] );MB_CHK_SET_ERR( result, "Failed to set sharing data in update_remote_data" );

    if( new_pstat & PSTATUS_SHARED ) sharedEnts.insert( new_h );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::update_remote_data_old( const EntityHandle new_h,<--- The function 'update_remote_data_old' is never used.
                                                const int* ps,
                                                const EntityHandle* hs,
                                                const int num_ps,
                                                const unsigned char add_pstat )
{
    EntityHandle tag_hs[MAX_SHARING_PROCS];
    int tag_ps[MAX_SHARING_PROCS];
    unsigned char pstat;
    // Get initial sharing data; tag_ps and tag_hs get terminated with -1 and 0
    // in this function, so no need to initialize
    unsigned int num_exist;
    ErrorCode result = get_sharing_data( new_h, tag_ps, tag_hs, pstat, num_exist );MB_CHK_ERR( result );

#ifndef NDEBUG
    {
        // Check for duplicates in proc list
        std::set< unsigned int > dumprocs;
        unsigned int dp = 0;
        for( ; (int)dp < num_ps && -1 != ps[dp]; dp++ )
            dumprocs.insert( ps[dp] );
        assert( dp == dumprocs.size() );
    }
#endif

    // Add any new sharing data
    bool changed = false;
    int idx;
    if( !num_exist )
    {
        // Just take what caller passed
        memcpy( tag_ps, ps, num_ps * sizeof( int ) );
        memcpy( tag_hs, hs, num_ps * sizeof( EntityHandle ) );
        num_exist = num_ps;
        // If it's only one, hopefully I'm not there yet...
        assert( "I shouldn't be the only proc there." && ( 1 != num_exist || ps[0] != (int)procConfig.proc_rank() ) );
        changed = true;
    }
    else
    {
        for( int i = 0; i < num_ps; i++ )
        {
            idx = std::find( tag_ps, tag_ps + num_exist, ps[i] ) - tag_ps;
            if( idx == (int)num_exist )
            {
                if( num_exist == MAX_SHARING_PROCS )
                {
                    std::cerr << "Exceeded MAX_SHARING_PROCS for " << CN::EntityTypeName( TYPE_FROM_HANDLE( new_h ) )
                              << ' ' << ID_FROM_HANDLE( new_h ) << " in process " << proc_config().proc_rank()
                              << std::endl;
                    std::cerr.flush();
                    MPI_Abort( proc_config().proc_comm(), 66 );
                }

                // If there's only 1 sharing proc, and it's not me, then
                // we'll end up with 3; add me to the front
                if( !i && num_ps == 1 && num_exist == 1 && ps[0] != (int)procConfig.proc_rank() )
                {
                    int j = 1;
                    // If I own this entity, put me at front, otherwise after first
                    if( !( pstat & PSTATUS_NOT_OWNED ) )
                    {
                        tag_ps[1] = tag_ps[0];
                        tag_hs[1] = tag_hs[0];
                        j         = 0;
                    }
                    tag_ps[j] = procConfig.proc_rank();
                    tag_hs[j] = new_h;
                    num_exist++;
                }

                tag_ps[num_exist] = ps[i];
                tag_hs[num_exist] = hs[i];
                num_exist++;
                changed = true;
            }
            else if( 0 == tag_hs[idx] )
            {
                tag_hs[idx] = hs[i];
                changed     = true;
            }
            else if( 0 != hs[i] )
            {
                assert( hs[i] == tag_hs[idx] );
            }
        }
    }

    // Adjust for interface layer if necessary
    if( add_pstat & PSTATUS_INTERFACE )
    {
        idx = std::min_element( tag_ps, tag_ps + num_exist ) - tag_ps;
        if( idx )
        {
            int tag_proc       = tag_ps[idx];
            tag_ps[idx]        = tag_ps[0];
            tag_ps[0]          = tag_proc;
            EntityHandle tag_h = tag_hs[idx];
            tag_hs[idx]        = tag_hs[0];
            tag_hs[0]          = tag_h;
            changed            = true;
            if( tag_ps[0] != (int)procConfig.proc_rank() ) pstat |= PSTATUS_NOT_OWNED;
        }
    }

    if( !changed ) return MB_SUCCESS;

    assert( "interface entities should have > 1 proc" && ( !( add_pstat & PSTATUS_INTERFACE ) || num_exist > 1 ) );
    assert( "ghost entities should have > 1 proc" && ( !( add_pstat & PSTATUS_GHOST ) || num_exist > 1 ) );

    // If it's multi-shared and we created the entity in this unpack,
    // local handle probably isn't in handle list yet
    if( num_exist > 2 )
    {
        idx = std::find( tag_ps, tag_ps + num_exist, procConfig.proc_rank() ) - tag_ps;
        assert( idx < (int)num_exist );
        if( !tag_hs[idx] ) tag_hs[idx] = new_h;
    }

    int tag_p;
    EntityHandle tag_h;

    // Update pstat
    pstat |= add_pstat;

    if( num_exist > 2 )
        pstat |= ( PSTATUS_MULTISHARED | PSTATUS_SHARED );
    else if( num_exist > 0 )
        pstat |= PSTATUS_SHARED;

    //    compare_remote_data(new_h, num_ps, hs, ps, add_pstat,
    //                        num_exist, tag_hs, tag_ps, pstat);

    // Reset single shared proc/handle if was shared and moving to multi-shared
    if( num_exist > 2 && !( pstat & PSTATUS_MULTISHARED ) && ( pstat & PSTATUS_SHARED ) )
    {
        // Must remove sharedp/h first, which really means set to default value
        tag_p  = -1;
        result = mbImpl->tag_set_data( sharedp_tag(), &new_h, 1, &tag_p );MB_CHK_SET_ERR( result, "Failed to set sharedp tag data" );
        tag_h  = 0;
        result = mbImpl->tag_set_data( sharedh_tag(), &new_h, 1, &tag_h );MB_CHK_SET_ERR( result, "Failed to set sharedh tag data" );
    }

    // Set sharing tags
    if( num_exist > 2 )
    {
        std::fill( tag_ps + num_exist, tag_ps + MAX_SHARING_PROCS, -1 );
        std::fill( tag_hs + num_exist, tag_hs + MAX_SHARING_PROCS, 0 );
        result = mbImpl->tag_set_data( sharedps_tag(), &new_h, 1, tag_ps );MB_CHK_SET_ERR( result, "Failed to set sharedps tag data" );
        result = mbImpl->tag_set_data( sharedhs_tag(), &new_h, 1, tag_hs );MB_CHK_SET_ERR( result, "Failed to set sharedhs tag data" );

#ifndef NDEBUG
        {
            // Check for duplicates in proc list
            std::set< unsigned int > dumprocs;
            unsigned int dp = 0;
            for( ; dp < num_exist && -1 != tag_ps[dp]; dp++ )
                dumprocs.insert( tag_ps[dp] );
            assert( dp == dumprocs.size() );
        }
#endif
    }
    else if( num_exist == 2 || num_exist == 1 )
    {
        if( tag_ps[0] == (int)procConfig.proc_rank() )
        {
            assert( 2 == num_exist && tag_ps[1] != (int)procConfig.proc_rank() );
            tag_ps[0] = tag_ps[1];
            tag_hs[0] = tag_hs[1];
        }
        assert( tag_ps[0] != -1 && tag_hs[0] != 0 );
        result = mbImpl->tag_set_data( sharedp_tag(), &new_h, 1, tag_ps );MB_CHK_SET_ERR( result, "Failed to set sharedp tag data" );
        result = mbImpl->tag_set_data( sharedh_tag(), &new_h, 1, tag_hs );MB_CHK_SET_ERR( result, "Failed to set sharedh tag data" );
    }

    // Now set new pstatus
    result = mbImpl->tag_set_data( pstatus_tag(), &new_h, 1, &pstat );MB_CHK_SET_ERR( result, "Failed to set pstatus tag data" );

    if( pstat & PSTATUS_SHARED ) sharedEnts.insert( new_h );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_sharing_data( const Range& entities, std::set< int >& procs, int operation )
{
    // Get the union or intersection of sharing data for multiple entities
    ErrorCode result;
    int sp2[MAX_SHARING_PROCS];
    int num_ps;
    unsigned char pstat;
    std::set< int > tmp_procs;
    procs.clear();

    for( Range::const_iterator rit = entities.begin(); rit != entities.end(); ++rit )
    {
        // Get sharing procs
        result = get_sharing_data( *rit, sp2, NULL, pstat, num_ps );MB_CHK_SET_ERR( result, "Failed to get sharing data in get_sharing_data" );
        if( !( pstat & PSTATUS_SHARED ) && Interface::INTERSECT == operation )
        {
            procs.clear();
            return MB_SUCCESS;
        }

        if( rit == entities.begin() )
        {
            std::copy( sp2, sp2 + num_ps, std::inserter( procs, procs.begin() ) );
        }
        else
        {
            std::sort( sp2, sp2 + num_ps );
            tmp_procs.clear();
            if( Interface::UNION == operation )
                std::set_union( procs.begin(), procs.end(), sp2, sp2 + num_ps,
                                std::inserter( tmp_procs, tmp_procs.end() ) );
            else if( Interface::INTERSECT == operation )
                std::set_intersection( procs.begin(), procs.end(), sp2, sp2 + num_ps,
                                       std::inserter( tmp_procs, tmp_procs.end() ) );
            else
            {
                assert( "Unknown operation." && false );
                return MB_FAILURE;
            }
            procs.swap( tmp_procs );
        }
        if( Interface::INTERSECT == operation && procs.empty() ) return MB_SUCCESS;
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_sharing_data( const EntityHandle entity,
                                          int* ps,
                                          EntityHandle* hs,
                                          unsigned char& pstat,
                                          unsigned int& num_ps )
{
    ErrorCode result = mbImpl->tag_get_data( pstatus_tag(), &entity, 1, &pstat );MB_CHK_SET_ERR( result, "Failed to get pstatus tag data" );
    if( pstat & PSTATUS_MULTISHARED )
    {
        result = mbImpl->tag_get_data( sharedps_tag(), &entity, 1, ps );MB_CHK_SET_ERR( result, "Failed to get sharedps tag data" );
        if( hs )
        {
            result = mbImpl->tag_get_data( sharedhs_tag(), &entity, 1, hs );MB_CHK_SET_ERR( result, "Failed to get sharedhs tag data" );
        }
        num_ps = std::find( ps, ps + MAX_SHARING_PROCS, -1 ) - ps;
    }
    else if( pstat & PSTATUS_SHARED )
    {
        result = mbImpl->tag_get_data( sharedp_tag(), &entity, 1, ps );MB_CHK_SET_ERR( result, "Failed to get sharedp tag data" );
        if( hs )
        {
            result = mbImpl->tag_get_data( sharedh_tag(), &entity, 1, hs );MB_CHK_SET_ERR( result, "Failed to get sharedh tag data" );
            hs[1] = 0;
        }
        // Initialize past end of data
        ps[1]  = -1;
        num_ps = 1;
    }
    else
    {
        ps[0] = -1;
        if( hs ) hs[0] = 0;
        num_ps = 0;
    }

    assert( MAX_SHARING_PROCS >= num_ps );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::find_existing_entity( const bool is_iface,
                                              const int owner_p,
                                              const EntityHandle owner_h,
                                              const int num_ps,
                                              const EntityHandle* connect,
                                              const int num_connect,
                                              const EntityType this_type,
                                              std::vector< EntityHandle >& L2hloc,<--- Parameter 'L2hloc' can be declared with const
                                              std::vector< EntityHandle >& L2hrem,
                                              std::vector< unsigned int >& L2p,<--- Parameter 'L2p' can be declared with const
                                              EntityHandle& new_h )
{
    new_h = 0;
    if( !is_iface && num_ps > 2 )
    {
        for( unsigned int i = 0; i < L2hrem.size(); i++ )
        {
            if( L2hrem[i] == owner_h && owner_p == (int)L2p[i] )
            {
                new_h = L2hloc[i];
                return MB_SUCCESS;
            }
        }
    }

    // If we got here and it's a vertex, we don't need to look further
    if( MBVERTEX == this_type || !connect || !num_connect ) return MB_SUCCESS;

    Range tmp_range;
    ErrorCode result = mbImpl->get_adjacencies( connect, num_connect, CN::Dimension( this_type ), false, tmp_range );MB_CHK_SET_ERR( result, "Failed to get existing entity" );
    if( !tmp_range.empty() )
    {
        // Found a corresponding entity - return target
        new_h = *tmp_range.begin();
    }
    else
    {
        new_h = 0;
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_local_handles( const Range& remote_handles,
                                           Range& local_handles,
                                           const std::vector< EntityHandle >& new_ents )
{
    std::vector< EntityHandle > rh_vec;
    rh_vec.reserve( remote_handles.size() );
    std::copy( remote_handles.begin(), remote_handles.end(), std::back_inserter( rh_vec ) );
    ErrorCode result = get_local_handles( &rh_vec[0], remote_handles.size(), new_ents );
    std::copy( rh_vec.begin(), rh_vec.end(), range_inserter( local_handles ) );
    return result;
}

ErrorCode ParallelComm::get_local_handles( EntityHandle* from_vec, int num_ents, const Range& new_ents )
{
    std::vector< EntityHandle > tmp_ents;
    std::copy( new_ents.begin(), new_ents.end(), std::back_inserter( tmp_ents ) );
    return get_local_handles( from_vec, num_ents, tmp_ents );
}

ErrorCode ParallelComm::get_local_handles( EntityHandle* from_vec,
                                           int num_ents,
                                           const std::vector< EntityHandle >& new_ents )
{
    for( int i = 0; i < num_ents; i++ )
    {
        if( TYPE_FROM_HANDLE( from_vec[i] ) == MBMAXTYPE )
        {
            assert( ID_FROM_HANDLE( from_vec[i] ) < (int)new_ents.size() );
            from_vec[i] = new_ents[ID_FROM_HANDLE( from_vec[i] )];
        }
    }

    return MB_SUCCESS;
}

/*
template <typename T> void
insert_in_array(T* array, size_t array_size, size_t location, T value)
{
  assert(location + 1 < array_size);
  for (size_t i = array_size - 1; i > location; i--)
    array[i] = array[i - 1];
  array[location] = value;
}
*/

ErrorCode ParallelComm::pack_range_map( Range& key_range, EntityHandle val_start, HandleMap& handle_map )<--- The function 'pack_range_map' is never used.
{
    for( Range::const_pair_iterator key_it = key_range.const_pair_begin(); key_it != key_range.const_pair_end();
         ++key_it )
    {
        int tmp_num = ( *key_it ).second - ( *key_it ).first + 1;
        handle_map.insert( ( *key_it ).first, val_start, tmp_num );
        val_start += tmp_num;
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::pack_sets( Range& entities, Buffer* buff, const bool store_remote_handles, const int to_proc )
{
    // SETS:
    // . #sets
    // . for each set:
    //   - options[#sets] (unsigned int)
    //   - if (unordered) set range
    //   - else if ordered
    //     . #ents in set
    //     . handles[#ents]
    //   - #parents
    //   - if (#parents) handles[#parents]
    //   - #children
    //   - if (#children) handles[#children]

    // Now the sets; assume any sets the application wants to pass are in the entities list
    ErrorCode result;
    Range all_sets = entities.subset_by_type( MBENTITYSET );

    int buff_size = estimate_sets_buffer_size( all_sets, store_remote_handles );
    if( buff_size < 0 ) MB_SET_ERR( MB_FAILURE, "Failed to estimate sets buffer size" );
    buff->check_space( buff_size );

    // Number of sets
    PACK_INT( buff->buff_ptr, all_sets.size() );

    // Options for all sets
    std::vector< unsigned int > options( all_sets.size() );
    Range::iterator rit;
    std::vector< EntityHandle > members;
    int i;
    for( rit = all_sets.begin(), i = 0; rit != all_sets.end(); ++rit, i++ )
    {
        result = mbImpl->get_meshset_options( *rit, options[i] );MB_CHK_SET_ERR( result, "Failed to get meshset options" );
    }
    buff->check_space( all_sets.size() * sizeof( unsigned int ) );
    PACK_VOID( buff->buff_ptr, &options[0], all_sets.size() * sizeof( unsigned int ) );

    // Pack parallel geometry unique id
    if( !all_sets.empty() )
    {
        Tag uid_tag;
        int n_sets  = all_sets.size();
        bool b_pack = false;
        std::vector< int > id_data( n_sets );
        result =
            mbImpl->tag_get_handle( "PARALLEL_UNIQUE_ID", 1, MB_TYPE_INTEGER, uid_tag, MB_TAG_SPARSE | MB_TAG_CREAT );MB_CHK_SET_ERR( result, "Failed to create parallel geometry unique id tag" );

        result = mbImpl->tag_get_data( uid_tag, all_sets, &id_data[0] );
        if( MB_TAG_NOT_FOUND != result )
        {
            if( MB_SUCCESS != result ) MB_SET_ERR( result, "Failed to get parallel geometry unique ids" );
            for( i = 0; i < n_sets; i++ )
            {
                if( id_data[i] != 0 )
                {
                    b_pack = true;
                    break;
                }
            }
        }

        if( b_pack )
        {  // If you find
            buff->check_space( ( n_sets + 1 ) * sizeof( int ) );
            PACK_INT( buff->buff_ptr, n_sets );
            PACK_INTS( buff->buff_ptr, &id_data[0], n_sets );
        }
        else
        {
            buff->check_space( sizeof( int ) );
            PACK_INT( buff->buff_ptr, 0 );
        }
    }

    // Vectors/ranges
    std::vector< EntityHandle > entities_vec( entities.size() );
    std::copy( entities.begin(), entities.end(), entities_vec.begin() );
    for( rit = all_sets.begin(), i = 0; rit != all_sets.end(); ++rit, i++ )
    {
        members.clear();
        result = mbImpl->get_entities_by_handle( *rit, members );MB_CHK_SET_ERR( result, "Failed to get entities in ordered set" );
        result =
            get_remote_handles( store_remote_handles, &members[0], &members[0], members.size(), to_proc, entities_vec );MB_CHK_SET_ERR( result, "Failed in get_remote_handles" );
        buff->check_space( members.size() * sizeof( EntityHandle ) + sizeof( int ) );
        PACK_INT( buff->buff_ptr, members.size() );
        PACK_EH( buff->buff_ptr, &members[0], members.size() );
    }

    // Pack parent/child sets
    if( !store_remote_handles )
    {  // Only works not store remote handles
        // Pack numbers of parents/children
        unsigned int tot_pch = 0;
        int num_pch;
        buff->check_space( 2 * all_sets.size() * sizeof( int ) );
        for( rit = all_sets.begin(), i = 0; rit != all_sets.end(); ++rit, i++ )
        {
            // Pack parents
            result = mbImpl->num_parent_meshsets( *rit, &num_pch );MB_CHK_SET_ERR( result, "Failed to get num parents" );
            PACK_INT( buff->buff_ptr, num_pch );
            tot_pch += num_pch;
            result = mbImpl->num_child_meshsets( *rit, &num_pch );MB_CHK_SET_ERR( result, "Failed to get num children" );
            PACK_INT( buff->buff_ptr, num_pch );
            tot_pch += num_pch;
        }

        // Now pack actual parents/children
        members.clear();
        members.reserve( tot_pch );
        std::vector< EntityHandle > tmp_pch;
        for( rit = all_sets.begin(), i = 0; rit != all_sets.end(); ++rit, i++ )
        {
            result = mbImpl->get_parent_meshsets( *rit, tmp_pch );MB_CHK_SET_ERR( result, "Failed to get parents" );
            std::copy( tmp_pch.begin(), tmp_pch.end(), std::back_inserter( members ) );
            tmp_pch.clear();
            result = mbImpl->get_child_meshsets( *rit, tmp_pch );MB_CHK_SET_ERR( result, "Failed to get children" );
            std::copy( tmp_pch.begin(), tmp_pch.end(), std::back_inserter( members ) );
            tmp_pch.clear();
        }
        assert( members.size() == tot_pch );
        if( !members.empty() )
        {
            result = get_remote_handles( store_remote_handles, &members[0], &members[0], members.size(), to_proc,
                                         entities_vec );MB_CHK_SET_ERR( result, "Failed to get remote handles for set parent/child sets" );
#ifndef NDEBUG
            // Check that all handles are either sets or maxtype
            for( unsigned int __j = 0; __j < members.size(); __j++ )
                assert( ( TYPE_FROM_HANDLE( members[__j] ) == MBMAXTYPE &&
                          ID_FROM_HANDLE( members[__j] ) < (int)entities.size() ) ||
                        TYPE_FROM_HANDLE( members[__j] ) == MBENTITYSET );
#endif
            buff->check_space( members.size() * sizeof( EntityHandle ) );
            PACK_EH( buff->buff_ptr, &members[0], members.size() );
        }
    }
    else
    {
        buff->check_space( 2 * all_sets.size() * sizeof( int ) );
        for( rit = all_sets.begin(); rit != all_sets.end(); ++rit )
        {
            PACK_INT( buff->buff_ptr, 0 );
            PACK_INT( buff->buff_ptr, 0 );
        }
    }

    // Pack the handles
    if( store_remote_handles && !all_sets.empty() )
    {
        buff_size = RANGE_SIZE( all_sets );
        buff->check_space( buff_size );
        PACK_RANGE( buff->buff_ptr, all_sets );
    }

    myDebug->tprintf( 4, "Done packing sets.\n" );

    buff->set_stored_size();

    return MB_SUCCESS;
}

ErrorCode ParallelComm::unpack_sets( unsigned char*& buff_ptr,
                                     std::vector< EntityHandle >& entities,
                                     const bool store_remote_handles,
                                     const int from_proc )
{
    // Now the sets; assume any sets the application wants to pass are in the entities list
    ErrorCode result;

    bool no_sets = ( entities.empty() || ( mbImpl->type_from_handle( *entities.rbegin() ) == MBENTITYSET ) );

    Range new_sets;
    int num_sets;
    UNPACK_INT( buff_ptr, num_sets );

    if( !num_sets ) return MB_SUCCESS;

    int i;
    Range::const_iterator rit;
    std::vector< EntityHandle > members;
    int num_ents;
    std::vector< unsigned int > options_vec( num_sets );
    // Option value
    if( num_sets ) UNPACK_VOID( buff_ptr, &options_vec[0], num_sets * sizeof( unsigned int ) );

    // Unpack parallel geometry unique id
    int n_uid;
    UNPACK_INT( buff_ptr, n_uid );
    if( n_uid > 0 && n_uid != num_sets )
    {
        std::cerr << "The number of Parallel geometry unique ids should be same." << std::endl;
    }

    if( n_uid > 0 )
    {  // If parallel geometry unique id is packed
        std::vector< int > uids( n_uid );
        UNPACK_INTS( buff_ptr, &uids[0], n_uid );

        Tag uid_tag;
        result =
            mbImpl->tag_get_handle( "PARALLEL_UNIQUE_ID", 1, MB_TYPE_INTEGER, uid_tag, MB_TAG_SPARSE | MB_TAG_CREAT );MB_CHK_SET_ERR( result, "Failed to create parallel geometry unique id tag" );

        // Find existing sets
        for( i = 0; i < n_uid; i++ )
        {
            EntityHandle set_handle;
            Range temp_sets;
            void* tag_vals[] = { &uids[i] };
            if( uids[i] > 0 )
            {
                result = mbImpl->get_entities_by_type_and_tag( 0, MBENTITYSET, &uid_tag, tag_vals, 1, temp_sets );<--- result is assigned
            }
            if( !temp_sets.empty() )
            {  // Existing set
                set_handle = *temp_sets.begin();
            }
            else
            {  // Create a new set
                result = mbImpl->create_meshset( options_vec[i], set_handle );MB_CHK_SET_ERR( result, "Failed to create set in unpack" );
                result = mbImpl->tag_set_data( uid_tag, &set_handle, 1, &uids[i] );MB_CHK_SET_ERR( result, "Failed to set parallel geometry unique ids" );
            }
            new_sets.insert( set_handle );
        }
    }
    else
    {
        // Create sets
        for( i = 0; i < num_sets; i++ )
        {
            EntityHandle set_handle;
            result = mbImpl->create_meshset( options_vec[i], set_handle );MB_CHK_SET_ERR( result, "Failed to create set in unpack" );

            // Make sure new sets handles are monotonically increasing
            assert( set_handle > *new_sets.rbegin() );
            new_sets.insert( set_handle );
        }
    }

    std::copy( new_sets.begin(), new_sets.end(), std::back_inserter( entities ) );
    // Only need to sort if we came in with no sets on the end
    if( !no_sets ) std::sort( entities.begin(), entities.end() );

    for( rit = new_sets.begin(), i = 0; rit != new_sets.end(); ++rit, i++ )
    {
        // Unpack entities as vector, with length
        UNPACK_INT( buff_ptr, num_ents );
        members.resize( num_ents );
        if( num_ents ) UNPACK_EH( buff_ptr, &members[0], num_ents );
        result = get_local_handles( &members[0], num_ents, entities );MB_CHK_SET_ERR( result, "Failed to get local handles for ordered set contents" );
        result = mbImpl->add_entities( *rit, &members[0], num_ents );MB_CHK_SET_ERR( result, "Failed to add ents to ordered set in unpack" );
    }

    std::vector< int > num_pch( 2 * new_sets.size() );
    std::vector< int >::iterator vit;
    int tot_pch = 0;
    for( vit = num_pch.begin(); vit != num_pch.end(); ++vit )
    {
        UNPACK_INT( buff_ptr, *vit );
        tot_pch += *vit;
    }

    members.resize( tot_pch );
    UNPACK_EH( buff_ptr, &members[0], tot_pch );
    result = get_local_handles( &members[0], tot_pch, entities );MB_CHK_SET_ERR( result, "Failed to get local handle for parent/child sets" );<--- result is overwritten

    int num               = 0;
    EntityHandle* mem_ptr = &members[0];
    for( rit = new_sets.begin(); rit != new_sets.end(); ++rit )
    {
        // Unpack parents/children
        int num_par = num_pch[num++], num_child = num_pch[num++];
        if( num_par + num_child )
        {
            for( i = 0; i < num_par; i++ )
            {
                assert( 0 != mem_ptr[i] );
                result = mbImpl->add_parent_meshset( *rit, mem_ptr[i] );MB_CHK_SET_ERR( result, "Failed to add parent to set in unpack" );
            }
            mem_ptr += num_par;
            for( i = 0; i < num_child; i++ )
            {
                assert( 0 != mem_ptr[i] );
                result = mbImpl->add_child_meshset( *rit, mem_ptr[i] );MB_CHK_SET_ERR( result, "Failed to add child to set in unpack" );
            }
            mem_ptr += num_child;
        }
    }

    // Unpack source handles
    Range dum_range;
    if( store_remote_handles && !new_sets.empty() )
    {
        UNPACK_RANGE( buff_ptr, dum_range );
        result = update_remote_data( new_sets, dum_range, from_proc, 0 );MB_CHK_SET_ERR( result, "Failed to set sharing data for sets" );
    }

    myDebug->tprintf( 4, "Done unpacking sets." );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::pack_adjacencies( Range& /*entities*/,<--- The function 'pack_adjacencies' is never used.
                                          Range::const_iterator& /*start_rit*/,
                                          Range& /*whole_range*/,
                                          unsigned char*& /*buff_ptr*/,
                                          int& /*count*/,
                                          const bool /*just_count*/,
                                          const bool /*store_handles*/,
                                          const int /*to_proc*/ )
{
    return MB_FAILURE;
}

ErrorCode ParallelComm::unpack_adjacencies( unsigned char*& /*buff_ptr*/,<--- The function 'unpack_adjacencies' is never used.
                                            Range& /*entities*/,
                                            const bool /*store_handles*/,
                                            const int /*from_proc*/ )
{
    return MB_FAILURE;
}

ErrorCode ParallelComm::pack_tags( Range& entities,
                                   const std::vector< Tag >& src_tags,
                                   const std::vector< Tag >& dst_tags,
                                   const std::vector< Range >& tag_ranges,
                                   Buffer* buff,
                                   const bool store_remote_handles,
                                   const int to_proc )
{
    ErrorCode result;
    std::vector< Tag >::const_iterator tag_it, dst_it;
    std::vector< Range >::const_iterator rit;
    int count = 0;

    for( tag_it = src_tags.begin(), rit = tag_ranges.begin(); tag_it != src_tags.end(); ++tag_it, ++rit )
    {
        result = packed_tag_size( *tag_it, *rit, count );
        if( MB_SUCCESS != result ) return result;
    }

    // Number of tags
    count += sizeof( int );

    buff->check_space( count );

    PACK_INT( buff->buff_ptr, src_tags.size() );

    std::vector< EntityHandle > entities_vec( entities.size() );
    std::copy( entities.begin(), entities.end(), entities_vec.begin() );

    for( tag_it = src_tags.begin(), dst_it = dst_tags.begin(), rit = tag_ranges.begin(); tag_it != src_tags.end();
         ++tag_it, ++dst_it, ++rit )
    {
        result = pack_tag( *tag_it, *dst_it, *rit, entities_vec, buff, store_remote_handles, to_proc );
        if( MB_SUCCESS != result ) return result;
    }

    myDebug->tprintf( 4, "Done packing tags." );

    buff->set_stored_size();

    return MB_SUCCESS;
}

ErrorCode ParallelComm::packed_tag_size( Tag tag, const Range& tagged_entities, int& count )
{
    // For dense tags, compute size assuming all entities have that tag
    // For sparse tags, get number of entities w/ that tag to compute size

    std::vector< int > var_len_sizes;
    std::vector< const void* > var_len_values;

    // Default value
    count += sizeof( int );
    if( NULL != tag->get_default_value() ) count += tag->get_default_value_size();

    // Size, type, data type
    count += 3 * sizeof( int );

    // Name
    count += sizeof( int );
    count += tag->get_name().size();

    // Range of tag
    count += sizeof( int ) + tagged_entities.size() * sizeof( EntityHandle );

    if( tag->get_size() == MB_VARIABLE_LENGTH )
    {
        const int num_ent = tagged_entities.size();
        // Send a tag size for each entity
        count += num_ent * sizeof( int );
        // Send tag data for each entity
        var_len_sizes.resize( num_ent );
        var_len_values.resize( num_ent );
        ErrorCode result =
            tag->get_data( sequenceManager, errorHandler, tagged_entities, &var_len_values[0], &var_len_sizes[0] );MB_CHK_SET_ERR( result, "Failed to get lenghts of variable-length tag values" );
        count += std::accumulate( var_len_sizes.begin(), var_len_sizes.end(), 0 );
    }
    else
    {
        // Tag data values for range or vector
        count += tagged_entities.size() * tag->get_size();
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::pack_tag( Tag src_tag,
                                  Tag dst_tag,
                                  const Range& tagged_entities,
                                  const std::vector< EntityHandle >& whole_vec,
                                  Buffer* buff,
                                  const bool store_remote_handles,
                                  const int to_proc )
{
    ErrorCode result;
    std::vector< int > var_len_sizes;
    std::vector< const void* > var_len_values;

    if( src_tag != dst_tag )
    {
        if( dst_tag->get_size() != src_tag->get_size() ) return MB_TYPE_OUT_OF_RANGE;
        if( dst_tag->get_data_type() != src_tag->get_data_type() && dst_tag->get_data_type() != MB_TYPE_OPAQUE &&
            src_tag->get_data_type() != MB_TYPE_OPAQUE )
            return MB_TYPE_OUT_OF_RANGE;
    }

    // Size, type, data type
    buff->check_space( 3 * sizeof( int ) );
    PACK_INT( buff->buff_ptr, src_tag->get_size() );
    TagType this_type;
    result = mbImpl->tag_get_type( dst_tag, this_type );<--- result is assigned
    PACK_INT( buff->buff_ptr, (int)this_type );
    DataType data_type = src_tag->get_data_type();
    PACK_INT( buff->buff_ptr, (int)data_type );
    int type_size = TagInfo::size_from_data_type( data_type );

    // Default value
    if( NULL == src_tag->get_default_value() )
    {
        buff->check_space( sizeof( int ) );
        PACK_INT( buff->buff_ptr, 0 );
    }
    else
    {
        buff->check_space( src_tag->get_default_value_size() );
        PACK_BYTES( buff->buff_ptr, src_tag->get_default_value(), src_tag->get_default_value_size() );
    }

    // Name
    buff->check_space( src_tag->get_name().size() );
    PACK_BYTES( buff->buff_ptr, dst_tag->get_name().c_str(), dst_tag->get_name().size() );

    myDebug->tprintf( 4, "Packing tag \"%s\"", src_tag->get_name().c_str() );
    if( src_tag != dst_tag ) myDebug->tprintf( 4, " (as tag \"%s\")", dst_tag->get_name().c_str() );
    myDebug->tprintf( 4, "\n" );

    // Pack entities
    buff->check_space( tagged_entities.size() * sizeof( EntityHandle ) + sizeof( int ) );
    PACK_INT( buff->buff_ptr, tagged_entities.size() );
    std::vector< EntityHandle > dum_tagged_entities( tagged_entities.size() );
    result = get_remote_handles( store_remote_handles, tagged_entities, &dum_tagged_entities[0], to_proc, whole_vec );<--- result is overwritten
    if( MB_SUCCESS != result )
    {
        if( myDebug->get_verbosity() == 3 )
        {
            std::cerr << "Failed to get remote handles for tagged entities:" << std::endl;
            tagged_entities.print( "  " );
        }
        MB_SET_ERR( result, "Failed to get remote handles for tagged entities" );
    }

    PACK_EH( buff->buff_ptr, &dum_tagged_entities[0], dum_tagged_entities.size() );

    const size_t num_ent = tagged_entities.size();
    if( src_tag->get_size() == MB_VARIABLE_LENGTH )
    {
        var_len_sizes.resize( num_ent, 0 );
        var_len_values.resize( num_ent, 0 );
        result = mbImpl->tag_get_by_ptr( src_tag, tagged_entities, &var_len_values[0], &var_len_sizes[0] );MB_CHK_SET_ERR( result, "Failed to get variable-length tag data in pack_tags" );
        buff->check_space( num_ent * sizeof( int ) );
        PACK_INTS( buff->buff_ptr, &var_len_sizes[0], num_ent );
        for( unsigned int i = 0; i < num_ent; i++ )
        {
            buff->check_space( var_len_sizes[i] );
            PACK_VOID( buff->buff_ptr, var_len_values[i], type_size * var_len_sizes[i] );
        }
    }
    else
    {
        buff->check_space( num_ent * src_tag->get_size() );
        // Should be OK to read directly into buffer, since tags are untyped and
        // handled by memcpy
        result = mbImpl->tag_get_data( src_tag, tagged_entities, buff->buff_ptr );MB_CHK_SET_ERR( result, "Failed to get tag data in pack_tags" );
        buff->buff_ptr += num_ent * src_tag->get_size();
        PC( num_ent * src_tag->get_size(), " void" );
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_tag_send_list( const Range& whole_range,
                                           std::vector< Tag >& all_tags,
                                           std::vector< Range >& tag_ranges )
{
    std::vector< Tag > tmp_tags;
    ErrorCode result = mbImpl->tag_get_tags( tmp_tags );MB_CHK_SET_ERR( result, "Failed to get tags in pack_tags" );

    std::vector< Tag >::iterator tag_it;
    for( tag_it = tmp_tags.begin(); tag_it != tmp_tags.end(); ++tag_it )
    {
        std::string tag_name;
        result = mbImpl->tag_get_name( *tag_it, tag_name );
        if( tag_name.c_str()[0] == '_' && tag_name.c_str()[1] == '_' ) continue;

        Range tmp_range;
        result = ( *tag_it )->get_tagged_entities( sequenceManager, tmp_range );MB_CHK_SET_ERR( result, "Failed to get entities for tag in pack_tags" );
        tmp_range = intersect( tmp_range, whole_range );

        if( tmp_range.empty() ) continue;

        // OK, we'll be sending this tag
        all_tags.push_back( *tag_it );
        tag_ranges.push_back( Range() );
        tag_ranges.back().swap( tmp_range );
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::unpack_tags( unsigned char*& buff_ptr,
                                     std::vector< EntityHandle >& entities,
                                     const bool /*store_remote_handles*/,
                                     const int /*from_proc*/,
                                     const MPI_Op* const mpi_op )
{
    // Tags
    // Get all the tags
    // For dense tags, compute size assuming all entities have that tag
    // For sparse tags, get number of entities w/ that tag to compute size

    ErrorCode result;

    int num_tags;
    UNPACK_INT( buff_ptr, num_tags );
    std::vector< const void* > var_len_vals;
    std::vector< unsigned char > dum_vals;
    std::vector< EntityHandle > dum_ehvals;

    for( int i = 0; i < num_tags; i++ )
    {
        // Tag handle
        Tag tag_handle;

        // Size, data type
        int tag_size, tag_data_type, tag_type;
        UNPACK_INT( buff_ptr, tag_size );
        UNPACK_INT( buff_ptr, tag_type );
        UNPACK_INT( buff_ptr, tag_data_type );

        // Default value
        int def_val_size;
        UNPACK_INT( buff_ptr, def_val_size );
        void* def_val_ptr = NULL;
        if( def_val_size )
        {
            def_val_ptr = buff_ptr;
            buff_ptr += def_val_size;
            UPC( tag_size, " void" );
        }

        // Name
        int name_len;
        UNPACK_INT( buff_ptr, name_len );
        std::string tag_name( reinterpret_cast< char* >( buff_ptr ), name_len );
        buff_ptr += name_len;
        UPC( 64, " chars" );

        myDebug->tprintf( 4, "Unpacking tag %s\n", tag_name.c_str() );

        // Create the tag
        if( tag_size == MB_VARIABLE_LENGTH )
            result = mbImpl->tag_get_handle( tag_name.c_str(), def_val_size, (DataType)tag_data_type, tag_handle,
                                             MB_TAG_VARLEN | MB_TAG_CREAT | MB_TAG_BYTES | tag_type, def_val_ptr );
        else
            result = mbImpl->tag_get_handle( tag_name.c_str(), tag_size, (DataType)tag_data_type, tag_handle,
                                             MB_TAG_CREAT | MB_TAG_BYTES | tag_type, def_val_ptr );
        if( MB_SUCCESS != result ) return result;

        // Get handles and convert to local handles
        int num_ents;
        UNPACK_INT( buff_ptr, num_ents );
        std::vector< EntityHandle > dum_ents( num_ents );
        UNPACK_EH( buff_ptr, &dum_ents[0], num_ents );

        // In this case handles are indices into new entity range; need to convert
        // to local handles
        result = get_local_handles( &dum_ents[0], num_ents, entities );MB_CHK_SET_ERR( result, "Unable to convert to local handles" );

        // If it's a handle type, also convert tag vals in-place in buffer
        if( MB_TYPE_HANDLE == tag_type )
        {
            dum_ehvals.resize( num_ents );
            UNPACK_EH( buff_ptr, &dum_ehvals[0], num_ents );
            result = get_local_handles( &dum_ehvals[0], num_ents, entities );MB_CHK_SET_ERR( result, "Failed to get local handles for tag vals" );
        }

        DataType data_type;
        mbImpl->tag_get_data_type( tag_handle, data_type );
        int type_size = TagInfo::size_from_data_type( data_type );

        if( !dum_ents.empty() )
        {
            if( tag_size == MB_VARIABLE_LENGTH )
            {
                // Be careful of alignment here. If the integers are aligned
                // in the buffer, we can use them directly. Otherwise we must
                // copy them.
                std::vector< int > var_lengths( num_ents );
                UNPACK_INTS( buff_ptr, &var_lengths[0], num_ents );
                UPC( sizeof( int ) * num_ents, " void" );

                // Get pointers into buffer for each tag value
                var_len_vals.resize( num_ents );
                for( std::vector< EntityHandle >::size_type j = 0; j < (std::vector< EntityHandle >::size_type)num_ents;
                     j++ )
                {
                    var_len_vals[j] = buff_ptr;
                    buff_ptr += var_lengths[j] * type_size;
                    UPC( var_lengths[j], " void" );
                }
                result =
                    mbImpl->tag_set_by_ptr( tag_handle, &dum_ents[0], num_ents, &var_len_vals[0], &var_lengths[0] );MB_CHK_SET_ERR( result, "Failed to set tag data when unpacking variable-length tag" );
            }
            else
            {
                // Get existing values of dst tag
                dum_vals.resize( tag_size * num_ents );
                if( mpi_op )
                {
                    int tag_length;
                    result = mbImpl->tag_get_length( tag_handle, tag_length );MB_CHK_SET_ERR( result, "Failed to get tag length" );
                    result = mbImpl->tag_get_data( tag_handle, &dum_ents[0], num_ents, &dum_vals[0] );MB_CHK_SET_ERR( result, "Failed to get existing value of dst tag on entities" );
                    result = reduce_void( tag_data_type, *mpi_op, tag_length * num_ents, &dum_vals[0], buff_ptr );MB_CHK_SET_ERR( result, "Failed to perform mpi op on dst tags" );
                }
                result = mbImpl->tag_set_data( tag_handle, &dum_ents[0], num_ents, buff_ptr );MB_CHK_SET_ERR( result, "Failed to set range-based tag data when unpacking tag" );
                buff_ptr += num_ents * tag_size;
                UPC( num_ents * tag_size, " void" );
            }
        }
    }

    myDebug->tprintf( 4, "Done unpacking tags.\n" );

    return MB_SUCCESS;
}

template < class T >
T LAND( const T& arg1, const T& arg2 )
{
    return arg1 && arg2;
}
template < class T >
T LOR( const T& arg1, const T& arg2 )
{
    return arg1 || arg2;
}
template < class T >
T LXOR( const T& arg1, const T& arg2 )
{
    return ( ( arg1 && !arg2 ) || ( !arg1 && arg2 ) );
}
template < class T >
T MAX( const T& arg1, const T& arg2 )
{
    return ( arg1 > arg2 ? arg1 : arg2 );
}
template < class T >
T MIN( const T& arg1, const T& arg2 )
{
    return ( arg1 < arg2 ? arg1 : arg2 );
}
template < class T >
T ADD( const T& arg1, const T& arg2 )
{
    return arg1 + arg2;
}
template < class T >
T MULT( const T& arg1, const T& arg2 )
{
    return arg1 * arg2;
}

template < class T >
ErrorCode ParallelComm::reduce( const MPI_Op mpi_op, int num_ents, void* old_vals, void* new_vals )
{
    T* old_tmp = reinterpret_cast< T* >( old_vals );
    // T *new_tmp = reinterpret_cast<T*>(new_vals);
    // new vals pointer needs to be aligned , some compilers will optimize and will shift

    std::vector< T > new_values;
    new_values.resize( num_ents );
    memcpy( &new_values[0], new_vals, num_ents * sizeof( T ) );
    T* new_tmp = &new_values[0];

    if( mpi_op == MPI_SUM )
        std::transform( old_tmp, old_tmp + num_ents, new_tmp, new_tmp, ADD< T > );
    else if( mpi_op == MPI_PROD )
        std::transform( old_tmp, old_tmp + num_ents, new_tmp, new_tmp, MULT< T > );
    else if( mpi_op == MPI_MAX )
        std::transform( old_tmp, old_tmp + num_ents, new_tmp, new_tmp, MAX< T > );
    else if( mpi_op == MPI_MIN )
        std::transform( old_tmp, old_tmp + num_ents, new_tmp, new_tmp, MIN< T > );
    else if( mpi_op == MPI_LAND )
        std::transform( old_tmp, old_tmp + num_ents, new_tmp, new_tmp, LAND< T > );
    else if( mpi_op == MPI_LOR )
        std::transform( old_tmp, old_tmp + num_ents, new_tmp, new_tmp, LOR< T > );
    else if( mpi_op == MPI_LXOR )
        std::transform( old_tmp, old_tmp + num_ents, new_tmp, new_tmp, LXOR< T > );
    else if( mpi_op == MPI_BAND || mpi_op == MPI_BOR || mpi_op == MPI_BXOR )
    {
        std::cerr << "Bitwise operations not allowed in tag reductions." << std::endl;
        return MB_FAILURE;
    }
    else if( mpi_op != MPI_OP_NULL )
    {
        std::cerr << "Unknown MPI operation type." << std::endl;
        return MB_TYPE_OUT_OF_RANGE;
    }

    // copy now the result back where it should be
    memcpy( new_vals, new_tmp, num_ents * sizeof( T ) );
    std::vector< T >().swap( new_values );  // way to release allocated vector

    return MB_SUCCESS;
}

ErrorCode ParallelComm::reduce_void( int tag_data_type,
                                     const MPI_Op mpi_op,
                                     int num_ents,
                                     void* old_vals,
                                     void* new_vals )
{
    ErrorCode result;
    switch( tag_data_type )
    {
        case MB_TYPE_INTEGER:
            result = reduce< int >( mpi_op, num_ents, old_vals, new_vals );
            break;
        case MB_TYPE_DOUBLE:
            result = reduce< double >( mpi_op, num_ents, old_vals, new_vals );
            break;
        case MB_TYPE_BIT:
            result = reduce< unsigned char >( mpi_op, num_ents, old_vals, new_vals );
            break;
        default:
            result = MB_SUCCESS;
            break;
    }

    return result;
}

ErrorCode ParallelComm::resolve_shared_ents( EntityHandle this_set, int resolve_dim, int shared_dim, const Tag* id_tag )
{
    ErrorCode result;
    Range proc_ents;

    // Check for structured mesh, and do it differently if it is
    ScdInterface* scdi;
    result = mbImpl->query_interface( scdi );<--- Variable 'result' is assigned a value that is never used.
    if( scdi )
    {
        result = scdi->tag_shared_vertices( this, this_set );
        if( MB_SUCCESS == result )
        {
            myDebug->tprintf( 1, "Total number of shared entities = %lu.\n", (unsigned long)sharedEnts.size() );
            return result;
        }
    }

    if( 0 == this_set )
    {
        // Get the entities in the partition sets
        for( Range::iterator rit = partitionSets.begin(); rit != partitionSets.end(); ++rit )
        {
            Range tmp_ents;
            result = mbImpl->get_entities_by_handle( *rit, tmp_ents, true );
            if( MB_SUCCESS != result ) return result;
            proc_ents.merge( tmp_ents );
        }
    }
    else
    {
        result = mbImpl->get_entities_by_handle( this_set, proc_ents, true );
        if( MB_SUCCESS != result ) return result;
    }

    // Resolve dim is maximal dim of entities in proc_ents
    if( -1 == resolve_dim )
    {
        if( !proc_ents.empty() ) resolve_dim = mbImpl->dimension_from_handle( *proc_ents.rbegin() );
    }

    // proc_ents should all be of same dimension
    if( resolve_dim > shared_dim &&
        mbImpl->dimension_from_handle( *proc_ents.rbegin() ) != mbImpl->dimension_from_handle( *proc_ents.begin() ) )
    {
        Range::iterator lower = proc_ents.lower_bound( CN::TypeDimensionMap[0].first ),
                        upper = proc_ents.upper_bound( CN::TypeDimensionMap[resolve_dim - 1].second );
        proc_ents.erase( lower, upper );
    }

    // Must call even if we don't have any entities, to make sure
    // collective comm'n works
    return resolve_shared_ents( this_set, proc_ents, resolve_dim, shared_dim, NULL, id_tag );
}

ErrorCode ParallelComm::resolve_shared_ents( EntityHandle this_set,
                                             Range& proc_ents,
                                             int resolve_dim,
                                             int shared_dim,
                                             Range* skin_ents,
                                             const Tag* id_tag )
{
#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        define_mpe();
        MPE_Log_event( RESOLVE_START, procConfig.proc_rank(), "Entering resolve_shared_ents." );
    }
#endif

    ErrorCode result;
    myDebug->tprintf( 1, "Resolving shared entities.\n" );

    if( resolve_dim < shared_dim )
    {
        MB_SET_ERR( MB_FAILURE, "MOAB does not support vertex-based partitions, only element-based ones" );
    }

    if( -1 == shared_dim )
    {
        if( !proc_ents.empty() )
            shared_dim = mbImpl->dimension_from_handle( *proc_ents.begin() ) - 1;
        else if( resolve_dim == 3 )
            shared_dim = 2;
    }
    int max_global_resolve_dim = -1;
    int err = MPI_Allreduce( &resolve_dim, &max_global_resolve_dim, 1, MPI_INT, MPI_MAX, proc_config().proc_comm() );
    if( MPI_SUCCESS != err )
    {
        MB_SET_ERR( MB_FAILURE, "Unable to guess global resolve_dim" );
    }
    if( shared_dim < 0 || resolve_dim < 0 )
    {
        // MB_SET_ERR(MB_FAILURE, "Unable to guess shared_dim or resolve_dim");
        resolve_dim = max_global_resolve_dim;
        shared_dim  = resolve_dim - 1;
    }

    if( resolve_dim < 0 || shared_dim < 0 ) return MB_SUCCESS;
    // no task has any mesh, get out

    // Get the skin entities by dimension
    Range tmp_skin_ents[4];

    // Get the entities to be skinned
    // Find the skin
    int skin_dim = resolve_dim - 1;
    if( !skin_ents )
    {
        skin_ents              = tmp_skin_ents;
        skin_ents[resolve_dim] = proc_ents;
        Skinner skinner( mbImpl );
        result =
            skinner.find_skin( this_set, skin_ents[skin_dim + 1], false, skin_ents[skin_dim], NULL, true, true, true );MB_CHK_SET_ERR( result, "Failed to find skin" );
        myDebug->tprintf( 1, "Found skin:   skin_dim: %d resolve_dim: %d , now resolving.\n", skin_dim, resolve_dim );
        myDebug->tprintf( 3, "skin_ents[0].size(): %d skin_ents[1].size(): %d  \n", (int)skin_ents[0].size(),
                          (int)skin_ents[1].size() );
        // Get entities adjacent to skin ents from shared_dim down to zero
        for( int this_dim = skin_dim - 1; this_dim >= 0; this_dim-- )
        {
            result =
                mbImpl->get_adjacencies( skin_ents[skin_dim], this_dim, true, skin_ents[this_dim], Interface::UNION );MB_CHK_SET_ERR( result, "Failed to get skin adjacencies" );

            if( this_set && skin_dim == 2 && this_dim == 1 )
            {
                result = mbImpl->add_entities( this_set, skin_ents[this_dim] );MB_CHK_ERR( result );
            }
        }
    }
    else if( skin_ents[resolve_dim].empty() )
        skin_ents[resolve_dim] = proc_ents;

    // Global id tag
    Tag gid_tag;
    if( id_tag )
        gid_tag = *id_tag;
    else
    {
        bool tag_created = false;
        int def_val      = -1;
        result = mbImpl->tag_get_handle( GLOBAL_ID_TAG_NAME, 1, MB_TYPE_INTEGER, gid_tag, MB_TAG_DENSE | MB_TAG_CREAT,
                                         &def_val, &tag_created );
        if( MB_ALREADY_ALLOCATED != result && MB_SUCCESS != result )
        {
            MB_SET_ERR( result, "Failed to create/get gid tag handle" );
        }
        else if( tag_created )
        {
            // Just created it, so we need global ids
            result = assign_global_ids( this_set, skin_dim + 1, true, true, true );MB_CHK_SET_ERR( result, "Failed to assign global ids" );
        }
    }

    DataType tag_type;
    result = mbImpl->tag_get_data_type( gid_tag, tag_type );MB_CHK_SET_ERR( result, "Failed to get tag data type" );
    int bytes_per_tag;
    result = mbImpl->tag_get_bytes( gid_tag, bytes_per_tag );MB_CHK_SET_ERR( result, "Failed to get number of bytes per tag" );
    // On 64 bits, long and int are different
    // On 32 bits, they are not; if size of long is 8, it is a 64 bit machine (really?)

    // Get gids for skin ents in a vector, to pass to gs
    std::vector< long > lgid_data( skin_ents[0].size() );
    // Size is either long or int
    // On 64 bit is 8 or 4
    if( sizeof( long ) == bytes_per_tag && ( ( MB_TYPE_HANDLE == tag_type ) || ( MB_TYPE_OPAQUE == tag_type ) ) )
    {  // It is a special id tag
        result = mbImpl->tag_get_data( gid_tag, skin_ents[0], &lgid_data[0] );MB_CHK_SET_ERR( result, "Couldn't get gid tag for skin vertices" );
    }
    else if( 4 == bytes_per_tag )
    {  // Must be GLOBAL_ID tag or 32 bits ...
        std::vector< int > gid_data( lgid_data.size() );
        result = mbImpl->tag_get_data( gid_tag, skin_ents[0], &gid_data[0] );MB_CHK_SET_ERR( result, "Failed to get gid tag for skin vertices" );
        std::copy( gid_data.begin(), gid_data.end(), lgid_data.begin() );
    }
    else
    {
        // Not supported flag
        MB_SET_ERR( MB_FAILURE, "Unsupported id tag" );
    }

    // Put handles in vector for passing to gs setup
    std::vector< Ulong > handle_vec;  // Assumes that we can do conversion from Ulong to EntityHandle
    std::copy( skin_ents[0].begin(), skin_ents[0].end(), std::back_inserter( handle_vec ) );

#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( SHAREDV_START, procConfig.proc_rank(), "Creating crystal router." );
    }
#endif

    // Get a crystal router
    gs_data::crystal_data* cd = procConfig.crystal_router();

    /*
    // Get total number of entities; will overshoot highest global id, but
    // that's OK
    int num_total[2] = {0, 0}, num_local[2] = {0, 0};
    result = mbImpl->get_number_entities_by_dimension(this_set, 0, num_local);
    if (MB_SUCCESS != result)return result;
    int failure = MPI_Allreduce(num_local, num_total, 1,
    MPI_INT, MPI_SUM, procConfig.proc_comm());
    if (failure) {
      MB_SET_ERR(MB_FAILURE, "Allreduce for total number of shared ents failed");
    }
    */
    // Call gather-scatter to get shared ids & procs
    gs_data* gsd = new gs_data();
    // assert(sizeof(ulong_) == sizeof(EntityHandle));
    result = gsd->initialize( skin_ents[0].size(), &lgid_data[0], &handle_vec[0], 2, 1, 1, cd );MB_CHK_SET_ERR( result, "Failed to create gs data" );

    // Get shared proc tags
    Tag shp_tag, shps_tag, shh_tag, shhs_tag, pstat_tag;
    result = get_shared_proc_tags( shp_tag, shps_tag, shh_tag, shhs_tag, pstat_tag );MB_CHK_SET_ERR( result, "Failed to get shared proc tags" );

    // Load shared verts into a tuple, then sort by index
    TupleList shared_verts;
    shared_verts.initialize( 2, 0, 1, 0, skin_ents[0].size() * ( MAX_SHARING_PROCS + 1 ) );
    shared_verts.enableWriteAccess();

    unsigned int i = 0, j = 0;
    for( unsigned int p = 0; p < gsd->nlinfo->_np; p++ )
        for( unsigned int np = 0; np < gsd->nlinfo->_nshared[p]; np++ )
        {
            shared_verts.vi_wr[i++] = gsd->nlinfo->_sh_ind[j];
            shared_verts.vi_wr[i++] = gsd->nlinfo->_target[p];
            shared_verts.vul_wr[j]  = gsd->nlinfo->_ulabels[j];
            j++;
            shared_verts.inc_n();
        }

    myDebug->tprintf( 3, " shared verts size %d \n", (int)shared_verts.get_n() );

    int max_size = skin_ents[0].size() * ( MAX_SHARING_PROCS + 1 );
    moab::TupleList::buffer sort_buffer;
    sort_buffer.buffer_init( max_size );
    shared_verts.sort( 0, &sort_buffer );
    sort_buffer.reset();

    // Set sharing procs and handles tags on skin ents
    int maxp = -1;
    std::vector< int > sharing_procs( MAX_SHARING_PROCS );
    std::fill( sharing_procs.begin(), sharing_procs.end(), maxp );
    j = 0;<--- Variable 'j' is assigned a value that is never used.
    i = 0;<--- Variable 'i' is assigned a value that is never used.

    // Get ents shared by 1 or n procs
    std::map< std::vector< int >, std::vector< EntityHandle > > proc_nvecs;
    Range proc_verts;
    result = mbImpl->get_adjacencies( proc_ents, 0, false, proc_verts, Interface::UNION );MB_CHK_SET_ERR( result, "Failed to get proc_verts" );

    myDebug->print( 3, " resolve shared ents:  proc verts ", proc_verts );
    result = tag_shared_verts( shared_verts, skin_ents, proc_nvecs, proc_verts );MB_CHK_SET_ERR( result, "Failed to tag shared verts" );

#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( SHAREDV_END, procConfig.proc_rank(), "Finished tag_shared_verts." );
    }
#endif

    // Get entities shared by 1 or n procs
    result = get_proc_nvecs( resolve_dim, shared_dim, skin_ents, proc_nvecs );MB_CHK_SET_ERR( result, "Failed to tag shared entities" );

    shared_verts.reset();

    if( myDebug->get_verbosity() > 0 )
    {
        for( std::map< std::vector< int >, std::vector< EntityHandle > >::const_iterator mit = proc_nvecs.begin();
             mit != proc_nvecs.end(); ++mit )
        {
            myDebug->tprintf( 1, "Iface: " );
            for( std::vector< int >::const_iterator vit = ( mit->first ).begin(); vit != ( mit->first ).end(); ++vit )
                myDebug->printf( 1, " %d", *vit );
            myDebug->print( 1, "\n" );
        }
    }

    // Create the sets for each interface; store them as tags on
    // the interface instance
    Range iface_sets;
    result = create_interface_sets( proc_nvecs );MB_CHK_SET_ERR( result, "Failed to create interface sets" );

    // Establish comm procs and buffers for them
    std::set< unsigned int > procs;
    result = get_interface_procs( procs, true );MB_CHK_SET_ERR( result, "Failed to get interface procs" );

#ifndef NDEBUG
    result = check_all_shared_handles( true );MB_CHK_SET_ERR( result, "Shared handle check failed after interface vertex exchange" );
#endif

    // Resolve shared entity remote handles; implemented in ghost cell exchange
    // code because it's so similar
    result = exchange_ghost_cells( -1, -1, 0, 0, true, true );MB_CHK_SET_ERR( result, "Failed to resolve shared entity remote handles" );

    // Now build parent/child links for interface sets
    result = create_iface_pc_links();MB_CHK_SET_ERR( result, "Failed to create interface parent/child links" );

    gsd->reset();
    delete gsd;

#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( RESOLVE_END, procConfig.proc_rank(), "Exiting resolve_shared_ents." );
    }
#endif

    // std::ostringstream ent_str;
    // ent_str << "mesh." << procConfig.proc_rank() << ".h5m";
    // mbImpl->write_mesh(ent_str.str().c_str());

    // Done
    return result;
}

void ParallelComm::define_mpe()
{
#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        // Define mpe states used for logging
        int success;
        MPE_Log_get_state_eventIDs( &IFACE_START, &IFACE_END );
        MPE_Log_get_state_eventIDs( &GHOST_START, &GHOST_END );
        MPE_Log_get_state_eventIDs( &SHAREDV_START, &SHAREDV_END );
        MPE_Log_get_state_eventIDs( &RESOLVE_START, &RESOLVE_END );
        MPE_Log_get_state_eventIDs( &ENTITIES_START, &ENTITIES_END );
        MPE_Log_get_state_eventIDs( &RHANDLES_START, &RHANDLES_END );
        MPE_Log_get_state_eventIDs( &OWNED_START, &OWNED_END );
        success = MPE_Describe_state( IFACE_START, IFACE_END, "Resolve interface ents", "green" );
        assert( MPE_LOG_OK == success );
        success = MPE_Describe_state( GHOST_START, GHOST_END, "Exchange ghost ents", "red" );
        assert( MPE_LOG_OK == success );
        success = MPE_Describe_state( SHAREDV_START, SHAREDV_END, "Resolve interface vertices", "blue" );
        assert( MPE_LOG_OK == success );
        success = MPE_Describe_state( RESOLVE_START, RESOLVE_END, "Resolve shared ents", "purple" );
        assert( MPE_LOG_OK == success );
        success = MPE_Describe_state( ENTITIES_START, ENTITIES_END, "Exchange shared ents", "yellow" );
        assert( MPE_LOG_OK == success );
        success = MPE_Describe_state( RHANDLES_START, RHANDLES_END, "Remote handles", "cyan" );
        assert( MPE_LOG_OK == success );
        success = MPE_Describe_state( OWNED_START, OWNED_END, "Exchange owned ents", "black" );
        assert( MPE_LOG_OK == success );
    }
#endif
}

ErrorCode ParallelComm::resolve_shared_ents( ParallelComm** pc,
                                             const unsigned int np,
                                             EntityHandle this_set,
                                             const int part_dim )
{
    std::vector< Range > verts( np );
    int tot_verts = 0;
    unsigned int p, i, j, v;
    ErrorCode rval;
    for( p = 0; p < np; p++ )
    {
        Skinner skinner( pc[p]->get_moab() );
        Range part_ents, skin_ents;
        rval = pc[p]->get_moab()->get_entities_by_dimension( this_set, part_dim, part_ents );
        if( MB_SUCCESS != rval ) return rval;
        rval = skinner.find_skin( this_set, part_ents, false, skin_ents, 0, true, true, true );
        if( MB_SUCCESS != rval ) return rval;
        rval = pc[p]->get_moab()->get_adjacencies( skin_ents, 0, true, verts[p], Interface::UNION );
        if( MB_SUCCESS != rval ) return rval;
        tot_verts += verts[p].size();
    }

    TupleList shared_ents;
    shared_ents.initialize( 2, 0, 1, 0, tot_verts );
    shared_ents.enableWriteAccess();

    i = 0;
    j = 0;
    std::vector< int > gids;
    Range::iterator rit;
    Tag gid_tag;
    for( p = 0; p < np; p++ )
    {
        gid_tag = pc[p]->get_moab()->globalId_tag();

        gids.resize( verts[p].size() );
        rval = pc[p]->get_moab()->tag_get_data( gid_tag, verts[p], &gids[0] );
        if( MB_SUCCESS != rval ) return rval;

        for( v = 0, rit = verts[p].begin(); v < gids.size(); v++, ++rit )
        {
            shared_ents.vi_wr[i++] = gids[v];
            shared_ents.vi_wr[i++] = p;
            shared_ents.vul_wr[j]  = *rit;
            j++;
            shared_ents.inc_n();
        }
    }

    moab::TupleList::buffer sort_buffer;
    sort_buffer.buffer_init( tot_verts );
    shared_ents.sort( 0, &sort_buffer );
    sort_buffer.reset();

    j = 0;
    i = 0;
    std::vector< EntityHandle > handles;
    std::vector< int > procs;

    while( i < shared_ents.get_n() )
    {
        handles.clear();
        procs.clear();

        // Count & accumulate sharing procs
        int this_gid = shared_ents.vi_rd[j];
        while( i < shared_ents.get_n() && shared_ents.vi_rd[j] == this_gid )
        {
            j++;
            procs.push_back( shared_ents.vi_rd[j++] );
            handles.push_back( shared_ents.vul_rd[i++] );
        }
        if( 1 == procs.size() ) continue;

        for( v = 0; v < procs.size(); v++ )
        {
            rval = pc[procs[v]]->update_remote_data( handles[v], &procs[0], &handles[0], procs.size(),
                                                     ( procs[0] == (int)pc[procs[v]]->rank()
                                                           ? PSTATUS_INTERFACE
                                                           : ( PSTATUS_NOT_OWNED | PSTATUS_INTERFACE ) ) );
            if( MB_SUCCESS != rval ) return rval;
        }
    }

    std::set< unsigned int > psets;
    for( p = 0; p < np; p++ )
    {
        rval = pc[p]->create_interface_sets( this_set, part_dim, part_dim - 1 );
        if( MB_SUCCESS != rval ) return rval;
        // Establish comm procs and buffers for them
        psets.clear();
        rval = pc[p]->get_interface_procs( psets, true );
        if( MB_SUCCESS != rval ) return rval;
    }

    shared_ents.reset();

    return MB_SUCCESS;
}

ErrorCode ParallelComm::tag_iface_entities()
{
    ErrorCode result = MB_SUCCESS;<--- Variable 'result' is assigned a value that is never used.
    Range iface_ents, tmp_ents, rmv_ents;
    std::vector< unsigned char > pstat;
    unsigned char set_pstat;
    Range::iterator rit2;
    unsigned int i;

    for( Range::iterator rit = interfaceSets.begin(); rit != interfaceSets.end(); ++rit )
    {
        iface_ents.clear();

        result = mbImpl->get_entities_by_handle( *rit, iface_ents );MB_CHK_SET_ERR( result, "Failed to get interface set contents" );
        pstat.resize( iface_ents.size() );
        result = mbImpl->tag_get_data( pstatus_tag(), iface_ents, &pstat[0] );MB_CHK_SET_ERR( result, "Failed to get pstatus values for interface set entities" );
        result = mbImpl->tag_get_data( pstatus_tag(), &( *rit ), 1, &set_pstat );MB_CHK_SET_ERR( result, "Failed to get pstatus values for interface set" );
        rmv_ents.clear();
        for( rit2 = iface_ents.begin(), i = 0; rit2 != iface_ents.end(); ++rit2, i++ )
        {
            if( !( pstat[i] & PSTATUS_INTERFACE ) )
            {
                rmv_ents.insert( *rit2 );
                pstat[i] = 0x0;
            }
        }
        result = mbImpl->remove_entities( *rit, rmv_ents );MB_CHK_SET_ERR( result, "Failed to remove entities from interface set" );

        if( !( set_pstat & PSTATUS_NOT_OWNED ) ) continue;
        // If we're here, we need to set the notowned status on (remaining) set contents

        // Remove rmv_ents from the contents list
        iface_ents = subtract( iface_ents, rmv_ents );
        // Compress the pstat vector (removing 0x0's)
        std::remove_if( pstat.begin(), pstat.end(),<--- Return value of function std::remove_if() is not used.
                        std::bind( std::equal_to< unsigned char >(), std::placeholders::_1, 0x0 ) );
        // std::bind2nd(std::equal_to<unsigned char>(), 0x0));
        // https://stackoverflow.com/questions/32739018/a-replacement-for-stdbind2nd
        // Fold the not_owned bit into remaining values
        unsigned int sz = iface_ents.size();
        for( i = 0; i < sz; i++ )
            pstat[i] |= PSTATUS_NOT_OWNED;

        // Set the tag on the entities
        result = mbImpl->tag_set_data( pstatus_tag(), iface_ents, &pstat[0] );MB_CHK_SET_ERR( result, "Failed to set pstatus values for interface set entities" );
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::set_pstatus_entities( Range& pstatus_ents,
                                              unsigned char pstatus_val,
                                              bool lower_dim_ents,
                                              bool verts_too,
                                              int operation )
{
    std::vector< unsigned char > pstatus_vals( pstatus_ents.size() );
    Range all_ents, *range_ptr = &pstatus_ents;
    ErrorCode result;
    if( lower_dim_ents || verts_too )
    {
        all_ents      = pstatus_ents;
        range_ptr     = &all_ents;
        int start_dim = ( lower_dim_ents ? mbImpl->dimension_from_handle( *pstatus_ents.rbegin() ) - 1 : 0 );
        for( ; start_dim >= 0; start_dim-- )
        {
            result = mbImpl->get_adjacencies( all_ents, start_dim, true, all_ents, Interface::UNION );MB_CHK_SET_ERR( result, "Failed to get adjacencies for pstatus entities" );
        }
    }
    if( Interface::UNION == operation )
    {
        result = mbImpl->tag_get_data( pstatus_tag(), *range_ptr, &pstatus_vals[0] );MB_CHK_SET_ERR( result, "Failed to get pstatus tag data" );
        for( unsigned int i = 0; i < pstatus_vals.size(); i++ )
            pstatus_vals[i] |= pstatus_val;
    }
    else
    {
        for( unsigned int i = 0; i < pstatus_vals.size(); i++ )
            pstatus_vals[i] = pstatus_val;
    }
    result = mbImpl->tag_set_data( pstatus_tag(), *range_ptr, &pstatus_vals[0] );MB_CHK_SET_ERR( result, "Failed to set pstatus tag data" );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::set_pstatus_entities( EntityHandle* pstatus_ents,
                                              int num_ents,
                                              unsigned char pstatus_val,
                                              bool lower_dim_ents,
                                              bool verts_too,
                                              int operation )
{
    std::vector< unsigned char > pstatus_vals( num_ents );
    ErrorCode result;
    if( lower_dim_ents || verts_too )
    {
        // In this case, call the range-based version
        Range tmp_range;
        std::copy( pstatus_ents, pstatus_ents + num_ents, range_inserter( tmp_range ) );
        return set_pstatus_entities( tmp_range, pstatus_val, lower_dim_ents, verts_too, operation );
    }

    if( Interface::UNION == operation )
    {
        result = mbImpl->tag_get_data( pstatus_tag(), pstatus_ents, num_ents, &pstatus_vals[0] );MB_CHK_SET_ERR( result, "Failed to get pstatus tag data" );
        for( unsigned int i = 0; i < (unsigned int)num_ents; i++ )
            pstatus_vals[i] |= pstatus_val;
    }
    else
    {
        for( unsigned int i = 0; i < (unsigned int)num_ents; i++ )
            pstatus_vals[i] = pstatus_val;
    }
    result = mbImpl->tag_set_data( pstatus_tag(), pstatus_ents, num_ents, &pstatus_vals[0] );MB_CHK_SET_ERR( result, "Failed to set pstatus tag data" );

    return MB_SUCCESS;
}

static size_t choose_owner_idx( const std::vector< unsigned >& proc_list )
{
    // Try to assign owners randomly so we get a good distribution,
    // (note: specifying the same seed on all procs is essential)
    unsigned val = 0;
    for( size_t i = 0; i < proc_list.size(); i++ )
        val ^= proc_list[i];
    srand( (int)( val ) );
    return rand() % proc_list.size();
}

struct set_tuple
{
    unsigned idx;
    unsigned proc;
    EntityHandle handle;
    inline bool operator<( set_tuple other ) const
    {
        return ( idx == other.idx ) ? ( proc < other.proc ) : ( idx < other.idx );
    }
};

ErrorCode ParallelComm::resolve_shared_sets( EntityHandle file, const Tag* idtag )
{
    // Find all sets with any of the following tags:
    const char* const shared_set_tag_names[] = { GEOM_DIMENSION_TAG_NAME, MATERIAL_SET_TAG_NAME, DIRICHLET_SET_TAG_NAME,
                                                 NEUMANN_SET_TAG_NAME, PARALLEL_PARTITION_TAG_NAME };
    int num_tags                             = sizeof( shared_set_tag_names ) / sizeof( shared_set_tag_names[0] );
    Range candidate_sets;
    ErrorCode result = MB_FAILURE;

    // If we're not given an ID tag to use to globally identify sets,
    // then fall back to using known tag values
    if( !idtag )
    {
        Tag gid, tag;
        gid = mbImpl->globalId_tag();
        if( NULL != gid ) result = mbImpl->tag_get_handle( GEOM_DIMENSION_TAG_NAME, 1, MB_TYPE_INTEGER, tag );
        if( MB_SUCCESS == result )
        {
            for( int d = 0; d < 4; d++ )
            {
                candidate_sets.clear();
                const void* vals[] = { &d };
                result = mbImpl->get_entities_by_type_and_tag( file, MBENTITYSET, &tag, vals, 1, candidate_sets );
                if( MB_SUCCESS == result ) resolve_shared_sets( candidate_sets, gid );
            }
        }

        for( int i = 1; i < num_tags; i++ )
        {
            result = mbImpl->tag_get_handle( shared_set_tag_names[i], 1, MB_TYPE_INTEGER, tag );
            if( MB_SUCCESS == result )
            {
                candidate_sets.clear();
                result = mbImpl->get_entities_by_type_and_tag( file, MBENTITYSET, &tag, 0, 1, candidate_sets );
                if( MB_SUCCESS == result ) resolve_shared_sets( candidate_sets, tag );
            }
        }

        return MB_SUCCESS;
    }

    for( int i = 0; i < num_tags; i++ )
    {
        Tag tag;
        result = mbImpl->tag_get_handle( shared_set_tag_names[i], 1, MB_TYPE_INTEGER, tag, MB_TAG_ANY );
        if( MB_SUCCESS != result ) continue;

        mbImpl->get_entities_by_type_and_tag( file, MBENTITYSET, &tag, 0, 1, candidate_sets, Interface::UNION );
    }

    // Find any additional sets that contain shared entities
    Range::iterator hint = candidate_sets.begin();
    Range all_sets;
    mbImpl->get_entities_by_type( file, MBENTITYSET, all_sets );
    all_sets           = subtract( all_sets, candidate_sets );
    Range::iterator it = all_sets.begin();
    while( it != all_sets.end() )
    {
        Range contents;
        mbImpl->get_entities_by_handle( *it, contents );
        contents.erase( contents.lower_bound( MBENTITYSET ), contents.end() );
        filter_pstatus( contents, PSTATUS_SHARED, PSTATUS_OR );
        if( contents.empty() )
        {
            ++it;
        }
        else
        {
            hint = candidate_sets.insert( hint, *it );
            it   = all_sets.erase( it );
        }
    }

    // Find any additionl sets that contain or are parents of potential shared sets
    Range prev_list = candidate_sets;
    while( !prev_list.empty() )
    {
        it = all_sets.begin();
        Range new_list;
        hint = new_list.begin();
        while( it != all_sets.end() )
        {
            Range contents;
            mbImpl->get_entities_by_type( *it, MBENTITYSET, contents );
            if( !intersect( prev_list, contents ).empty() )
            {
                hint = new_list.insert( hint, *it );
                it   = all_sets.erase( it );
            }
            else
            {
                new_list.clear();
                mbImpl->get_child_meshsets( *it, contents );
                if( !intersect( prev_list, contents ).empty() )
                {
                    hint = new_list.insert( hint, *it );
                    it   = all_sets.erase( it );
                }
                else
                {
                    ++it;
                }
            }
        }

        candidate_sets.merge( new_list );
        prev_list.swap( new_list );
    }

    return resolve_shared_sets( candidate_sets, *idtag );
}

#ifndef NDEBUG
bool is_sorted_unique( std::vector< unsigned >& v )
{
    for( size_t i = 1; i < v.size(); i++ )
        if( v[i - 1] >= v[i] ) return false;
    return true;
}
#endif

ErrorCode ParallelComm::resolve_shared_sets( Range& sets, Tag idtag )
{
    ErrorCode result;
    const unsigned rk = proc_config().proc_rank();
    MPI_Comm cm       = proc_config().proc_comm();

    // Build sharing list for all sets

    // Get ids for sets in a vector, to pass to gs
    std::vector< long > larray;  // Allocate sufficient space for longs
    std::vector< Ulong > handles;
    Range tmp_sets;
    // The id tag can be size 4 or size 8
    // Based on that, convert to int or to long, similarly to what we do
    // for resolving shared vertices;
    // This code must work on 32 bit too, where long is 4 bytes, also
    // so test first size 4, then we should be fine
    DataType tag_type;
    result = mbImpl->tag_get_data_type( idtag, tag_type );MB_CHK_SET_ERR( result, "Failed getting tag data type" );
    int bytes_per_tag;
    result = mbImpl->tag_get_bytes( idtag, bytes_per_tag );MB_CHK_SET_ERR( result, "Failed getting number of bytes per tag" );
    // On 64 bits, long and int are different
    // On 32 bits, they are not; if size of long is 8, it is a 64 bit machine (really?)

    for( Range::iterator rit = sets.begin(); rit != sets.end(); ++rit )
    {
        if( sizeof( long ) == bytes_per_tag && ( ( MB_TYPE_HANDLE == tag_type ) || ( MB_TYPE_OPAQUE == tag_type ) ) )
        {  // It is a special id tag
            long dum;
            result = mbImpl->tag_get_data( idtag, &( *rit ), 1, &dum );
            if( MB_SUCCESS == result )
            {
                larray.push_back( dum );
                handles.push_back( *rit );
                tmp_sets.insert( tmp_sets.end(), *rit );
            }
        }
        else if( 4 == bytes_per_tag )
        {  // Must be GLOBAL_ID tag or MATERIAL_ID, etc
            int dum;
            result = mbImpl->tag_get_data( idtag, &( *rit ), 1, &dum );
            if( MB_SUCCESS == result )
            {
                larray.push_back( dum );
                handles.push_back( *rit );
                tmp_sets.insert( tmp_sets.end(), *rit );
            }
        }
    }

    const size_t nsets = handles.size();

    // Get handle array for sets
    // This is not true on windows machine, 64 bits: entity handle is 64 bit, long is 32
    // assert(sizeof(EntityHandle) <= sizeof(unsigned long));

    // Do communication of data
    gs_data::crystal_data* cd = procConfig.crystal_router();
    gs_data* gsd              = new gs_data();
    result                    = gsd->initialize( nsets, &larray[0], &handles[0], 2, 1, 1, cd );MB_CHK_SET_ERR( result, "Failed to create gs data" );

    // Convert from global IDs grouped by process rank to list
    // of <idx, rank> pairs so that we can sort primarily
    // by idx and secondarily by rank (we want lists of procs for each
    // idx, not lists if indices for each proc).
    size_t ntuple = 0;
    for( unsigned p = 0; p < gsd->nlinfo->_np; p++ )
        ntuple += gsd->nlinfo->_nshared[p];
    std::vector< set_tuple > tuples;
    tuples.reserve( ntuple );
    size_t j = 0;
    for( unsigned p = 0; p < gsd->nlinfo->_np; p++ )
    {
        for( unsigned np = 0; np < gsd->nlinfo->_nshared[p]; np++ )
        {
            set_tuple t;
            t.idx    = gsd->nlinfo->_sh_ind[j];
            t.proc   = gsd->nlinfo->_target[p];
            t.handle = gsd->nlinfo->_ulabels[j];
            tuples.push_back( t );
            j++;
        }
    }
    std::sort( tuples.begin(), tuples.end() );

    // Release crystal router stuff
    gsd->reset();
    delete gsd;

    // Storing sharing data for each set
    size_t ti    = 0;
    unsigned idx = 0;
    std::vector< unsigned > procs;
    Range::iterator si = tmp_sets.begin();
    while( si != tmp_sets.end() && ti < tuples.size() )
    {
        assert( idx <= tuples[ti].idx );
        if( idx < tuples[ti].idx ) si += ( tuples[ti].idx - idx );
        idx = tuples[ti].idx;

        procs.clear();
        size_t ti_init = ti;
        while( ti < tuples.size() && tuples[ti].idx == idx )
        {
            procs.push_back( tuples[ti].proc );
            ++ti;
        }
        assert( is_sorted_unique( procs ) );

        result = sharedSetData->set_sharing_procs( *si, procs );
        if( MB_SUCCESS != result )
        {
            std::cerr << "Failure at " __FILE__ ":" << __LINE__ << std::endl;
            std::cerr.flush();
            MPI_Abort( cm, 1 );
        }

        // Add this proc to list of sharing procs in correct position
        // so that all procs select owner based on same list
        std::vector< unsigned >::iterator it = std::lower_bound( procs.begin(), procs.end(), rk );
        assert( it == procs.end() || *it > rk );
        procs.insert( it, rk );
        size_t owner_idx = choose_owner_idx( procs );
        EntityHandle owner_handle;
        if( procs[owner_idx] == rk )
            owner_handle = *si;
        else if( procs[owner_idx] > rk )
            owner_handle = tuples[ti_init + owner_idx - 1].handle;
        else
            owner_handle = tuples[ti_init + owner_idx].handle;
        result = sharedSetData->set_owner( *si, procs[owner_idx], owner_handle );
        if( MB_SUCCESS != result )
        {
            std::cerr << "Failure at " __FILE__ ":" << __LINE__ << std::endl;
            std::cerr.flush();
            MPI_Abort( cm, 1 );
        }

        ++si;
        ++idx;
    }

    return MB_SUCCESS;
}
// populate sets with ghost entities, if necessary
ErrorCode ParallelComm::augment_default_sets_with_ghosts( EntityHandle file_set )
{
    // gather all default sets we are interested in, material, neumann, etc
    // we will skip geometry sets, because they are not uniquely identified with their tag value
    // maybe we will add another tag, like category

    if( procConfig.proc_size() < 2 ) return MB_SUCCESS;  // no reason to stop by
    const char* const shared_set_tag_names[] = { MATERIAL_SET_TAG_NAME, DIRICHLET_SET_TAG_NAME, NEUMANN_SET_TAG_NAME,
                                                 PARALLEL_PARTITION_TAG_NAME };

    int num_tags = sizeof( shared_set_tag_names ) / sizeof( shared_set_tag_names[0] );

    Range* rangeSets = new Range[num_tags];
    Tag* tags        = new Tag[num_tags + 1];  // one extra for global id tag, which is an int, so far

    int my_rank   = rank();
    int** tagVals = new int*[num_tags];
    for( int i = 0; i < num_tags; i++ )
        tagVals[i] = NULL;
    ErrorCode rval;

    // for each tag, we keep a local map, from the value to the actual set with that value
    // we assume that the tag values are unique, for a given set, otherwise we
    // do not know to which set to add the entity

    typedef std::map< int, EntityHandle > MVal;
    typedef std::map< int, EntityHandle >::iterator itMVal;
    MVal* localMaps = new MVal[num_tags];

    for( int i = 0; i < num_tags; i++ )
    {

        rval = mbImpl->tag_get_handle( shared_set_tag_names[i], 1, MB_TYPE_INTEGER, tags[i], MB_TAG_ANY );
        if( MB_SUCCESS != rval ) continue;
        rval = mbImpl->get_entities_by_type_and_tag( file_set, MBENTITYSET, &( tags[i] ), 0, 1, rangeSets[i],
                                                     Interface::UNION );MB_CHK_SET_ERR( rval, "can't get sets with a tag" );

        if( rangeSets[i].size() > 0 )
        {
            tagVals[i] = new int[rangeSets[i].size()];
            // fill up with the tag values
            rval = mbImpl->tag_get_data( tags[i], rangeSets[i], tagVals[i] );MB_CHK_SET_ERR( rval, "can't get set tag values" );
            // now for inverse mapping:
            for( int j = 0; j < (int)rangeSets[i].size(); j++ )
            {
                localMaps[i][tagVals[i][j]] = rangeSets[i][j];
            }
        }
    }
    // get the global id tag too
    tags[num_tags] = mbImpl->globalId_tag();

    TupleList remoteEnts;
    // processor to send to, type of tag (0-mat,) tag value,     remote handle
    //                         1-diri
    //                         2-neum
    //                         3-part
    //
    int initialSize = (int)sharedEnts.size();  // estimate that on average, each shared ent
    // will be sent to one processor, for one tag
    // we will actually send only entities that are owned locally, and from those
    // only those that do have a special tag (material, neumann, etc)
    // if we exceed the capacity, we resize the tuple
    remoteEnts.initialize( 3, 0, 1, 0, initialSize );
    remoteEnts.enableWriteAccess();

    // now, for each owned entity, get the remote handle(s) and Proc(s), and verify if it
    // belongs to one of the sets; if yes, create a tuple and append it

    std::set< EntityHandle > own_and_sha;
    int ir = 0, jr = 0;
    for( std::set< EntityHandle >::iterator vit = sharedEnts.begin(); vit != sharedEnts.end(); ++vit )
    {
        // ghosted eh
        EntityHandle geh = *vit;
        if( own_and_sha.find( geh ) != own_and_sha.end() )  // already encountered
            continue;
        int procs[MAX_SHARING_PROCS];
        EntityHandle handles[MAX_SHARING_PROCS];
        int nprocs;
        unsigned char pstat;
        rval = get_sharing_data( geh, procs, handles, pstat, nprocs );
        if( rval != MB_SUCCESS )
        {
            for( int i = 0; i < num_tags; i++ )
                delete[] tagVals[i];
            delete[] tagVals;

            MB_CHK_SET_ERR( rval, "Failed to get sharing data" );
        }
        if( pstat & PSTATUS_NOT_OWNED ) continue;  // we will send info only for entities that we own
        own_and_sha.insert( geh );
        for( int i = 0; i < num_tags; i++ )
        {
            for( int j = 0; j < (int)rangeSets[i].size(); j++ )
            {
                EntityHandle specialSet = rangeSets[i][j];  // this set has tag i, value tagVals[i][j];
                if( mbImpl->contains_entities( specialSet, &geh, 1 ) )
                {
                    // this ghosted entity is in a special set, so form the tuple
                    // to send to the processors that do not own this
                    for( int k = 0; k < nprocs; k++ )
                    {
                        if( procs[k] != my_rank )
                        {
                            if( remoteEnts.get_n() >= remoteEnts.get_max() - 1 )
                            {
                                // resize, so we do not overflow
                                int oldSize = remoteEnts.get_max();
                                // increase with 50% the capacity
                                remoteEnts.resize( oldSize + oldSize / 2 + 1 );
                            }
                            remoteEnts.vi_wr[ir++]  = procs[k];       // send to proc
                            remoteEnts.vi_wr[ir++]  = i;              // for the tags [i] (0-3)
                            remoteEnts.vi_wr[ir++]  = tagVals[i][j];  // actual value of the tag
                            remoteEnts.vul_wr[jr++] = handles[k];
                            remoteEnts.inc_n();
                        }
                    }
                }
            }
        }
        // if the local entity has a global id, send it too, so we avoid
        // another "exchange_tags" for global id
        int gid;
        rval = mbImpl->tag_get_data( tags[num_tags], &geh, 1, &gid );MB_CHK_SET_ERR( rval, "Failed to get global id" );
        if( gid != 0 )
        {
            for( int k = 0; k < nprocs; k++ )
            {
                if( procs[k] != my_rank )
                {
                    if( remoteEnts.get_n() >= remoteEnts.get_max() - 1 )
                    {
                        // resize, so we do not overflow
                        int oldSize = remoteEnts.get_max();
                        // increase with 50% the capacity
                        remoteEnts.resize( oldSize + oldSize / 2 + 1 );
                    }
                    remoteEnts.vi_wr[ir++]  = procs[k];  // send to proc
                    remoteEnts.vi_wr[ir++]  = num_tags;  // for the tags [j] (4)
                    remoteEnts.vi_wr[ir++]  = gid;       // actual value of the tag
                    remoteEnts.vul_wr[jr++] = handles[k];
                    remoteEnts.inc_n();
                }
            }
        }
    }

#ifndef NDEBUG
    if( my_rank == 1 && 1 == get_debug_verbosity() ) remoteEnts.print( " on rank 1, before augment routing" );
    MPI_Barrier( procConfig.proc_comm() );
    int sentEnts = remoteEnts.get_n();
    assert( ( sentEnts == jr ) && ( 3 * sentEnts == ir ) );
#endif
    // exchange the info now, and send to
    gs_data::crystal_data* cd = this->procConfig.crystal_router();
    // All communication happens here; no other mpi calls
    // Also, this is a collective call
    rval = cd->gs_transfer( 1, remoteEnts, 0 );MB_CHK_SET_ERR( rval, "Error in tuple transfer" );
#ifndef NDEBUG
    if( my_rank == 0 && 1 == get_debug_verbosity() ) remoteEnts.print( " on rank 0, after augment routing" );
    MPI_Barrier( procConfig.proc_comm() );
#endif

    // now process the data received from other processors
    int received = remoteEnts.get_n();
    for( int i = 0; i < received; i++ )
    {
        // int from = ents_to_delete.vi_rd[i];
        EntityHandle geh = (EntityHandle)remoteEnts.vul_rd[i];
        int from_proc    = remoteEnts.vi_rd[3 * i];
        if( my_rank == from_proc )
            std::cout << " unexpected receive from my rank " << my_rank << " during augmenting with ghosts\n ";
        int tag_type = remoteEnts.vi_rd[3 * i + 1];
        assert( ( 0 <= tag_type ) && ( tag_type <= num_tags ) );
        int value = remoteEnts.vi_rd[3 * i + 2];
        if( tag_type == num_tags )
        {
            // it is global id
            rval = mbImpl->tag_set_data( tags[num_tags], &geh, 1, &value );MB_CHK_SET_ERR( rval, "Error in setting gid tag" );
        }
        else
        {
            // now, based on value and tag type, see if we have that value in the map
            MVal& lmap = localMaps[tag_type];
            itMVal itm = lmap.find( value );
            if( itm == lmap.end() )
            {
                // the value was not found yet in the local map, so we have to create the set
                EntityHandle newSet;
                rval = mbImpl->create_meshset( MESHSET_SET, newSet );MB_CHK_SET_ERR( rval, "can't create new set" );
                lmap[value] = newSet;
                // set the tag value
                rval = mbImpl->tag_set_data( tags[tag_type], &newSet, 1, &value );MB_CHK_SET_ERR( rval, "can't set tag for new set" );

                // we also need to add the new created set to the file set, if not null
                if( file_set )
                {
                    rval = mbImpl->add_entities( file_set, &newSet, 1 );MB_CHK_SET_ERR( rval, "can't add new set to the file set" );
                }
            }
            // add the entity to the set pointed to by the map
            rval = mbImpl->add_entities( lmap[value], &geh, 1 );MB_CHK_SET_ERR( rval, "can't add ghost ent to the set" );
        }
    }

    for( int i = 0; i < num_tags; i++ )
        delete[] tagVals[i];
    delete[] tagVals;
    delete[] rangeSets;
    delete[] tags;
    delete[] localMaps;
    return MB_SUCCESS;
}
ErrorCode ParallelComm::create_interface_sets( EntityHandle this_set, int resolve_dim, int shared_dim )
{
    std::map< std::vector< int >, std::vector< EntityHandle > > proc_nvecs;

    // Build up the list of shared entities
    int procs[MAX_SHARING_PROCS];
    EntityHandle handles[MAX_SHARING_PROCS];
    ErrorCode result;
    int nprocs;
    unsigned char pstat;
    for( std::set< EntityHandle >::iterator vit = sharedEnts.begin(); vit != sharedEnts.end(); ++vit )
    {
        if( shared_dim != -1 && mbImpl->dimension_from_handle( *vit ) > shared_dim ) continue;
        result = get_sharing_data( *vit, procs, handles, pstat, nprocs );MB_CHK_SET_ERR( result, "Failed to get sharing data" );
        std::sort( procs, procs + nprocs );
        std::vector< int > tmp_procs( procs, procs + nprocs );
        assert( tmp_procs.size() != 2 );
        proc_nvecs[tmp_procs].push_back( *vit );
    }

    Skinner skinner( mbImpl );
    Range skin_ents[4];
    result = mbImpl->get_entities_by_dimension( this_set, resolve_dim, skin_ents[resolve_dim] );MB_CHK_SET_ERR( result, "Failed to get skin entities by dimension" );
    result =
        skinner.find_skin( this_set, skin_ents[resolve_dim], false, skin_ents[resolve_dim - 1], 0, true, true, true );MB_CHK_SET_ERR( result, "Failed to find skin" );
    if( shared_dim > 1 )
    {
        result = mbImpl->get_adjacencies( skin_ents[resolve_dim - 1], resolve_dim - 2, true, skin_ents[resolve_dim - 2],
                                          Interface::UNION );MB_CHK_SET_ERR( result, "Failed to get skin adjacencies" );
    }

    result = get_proc_nvecs( resolve_dim, shared_dim, skin_ents, proc_nvecs );

    return create_interface_sets( proc_nvecs );
}

ErrorCode ParallelComm::create_interface_sets( std::map< std::vector< int >, std::vector< EntityHandle > >& proc_nvecs )
{
    if( proc_nvecs.empty() ) return MB_SUCCESS;

    int proc_ids[MAX_SHARING_PROCS];
    EntityHandle proc_handles[MAX_SHARING_PROCS];
    Tag shp_tag, shps_tag, shh_tag, shhs_tag, pstat_tag;
    ErrorCode result = get_shared_proc_tags( shp_tag, shps_tag, shh_tag, shhs_tag, pstat_tag );MB_CHK_SET_ERR( result, "Failed to get shared proc tags in create_interface_sets" );
    Range::iterator rit;

    // Create interface sets, tag them, and tag their contents with iface set tag
    std::vector< unsigned char > pstatus;
    for( std::map< std::vector< int >, std::vector< EntityHandle > >::iterator vit = proc_nvecs.begin();
         vit != proc_nvecs.end(); ++vit )
    {
        // Create the set
        EntityHandle new_set;
        result = mbImpl->create_meshset( MESHSET_SET, new_set );MB_CHK_SET_ERR( result, "Failed to create interface set" );
        interfaceSets.insert( new_set );

        // Add entities
        assert( !vit->second.empty() );
        result = mbImpl->add_entities( new_set, &( vit->second )[0], ( vit->second ).size() );MB_CHK_SET_ERR( result, "Failed to add entities to interface set" );
        // Tag set with the proc rank(s)
        if( vit->first.size() == 1 )
        {
            assert( ( vit->first )[0] != (int)procConfig.proc_rank() );
            result = mbImpl->tag_set_data( shp_tag, &new_set, 1, &( vit->first )[0] );MB_CHK_SET_ERR( result, "Failed to tag interface set with procs" );
            proc_handles[0] = 0;
            result          = mbImpl->tag_set_data( shh_tag, &new_set, 1, proc_handles );MB_CHK_SET_ERR( result, "Failed to tag interface set with procs" );
        }
        else
        {
            // Pad tag data out to MAX_SHARING_PROCS with -1
            if( vit->first.size() > MAX_SHARING_PROCS )
            {
                std::cerr << "Exceeded MAX_SHARING_PROCS for " << CN::EntityTypeName( TYPE_FROM_HANDLE( new_set ) )
                          << ' ' << ID_FROM_HANDLE( new_set ) << " on process " << proc_config().proc_rank()
                          << std::endl;
                std::cerr.flush();
                MPI_Abort( proc_config().proc_comm(), 66 );
            }
            // assert(vit->first.size() <= MAX_SHARING_PROCS);
            std::copy( vit->first.begin(), vit->first.end(), proc_ids );
            std::fill( proc_ids + vit->first.size(), proc_ids + MAX_SHARING_PROCS, -1 );
            result = mbImpl->tag_set_data( shps_tag, &new_set, 1, proc_ids );MB_CHK_SET_ERR( result, "Failed to tag interface set with procs" );
            unsigned int ind = std::find( proc_ids, proc_ids + vit->first.size(), procConfig.proc_rank() ) - proc_ids;
            assert( ind < vit->first.size() );
            std::fill( proc_handles, proc_handles + MAX_SHARING_PROCS, 0 );
            proc_handles[ind] = new_set;
            result            = mbImpl->tag_set_data( shhs_tag, &new_set, 1, proc_handles );MB_CHK_SET_ERR( result, "Failed to tag interface set with procs" );
        }

        // Get the owning proc, then set the pstatus tag on iface set
        int min_proc       = ( vit->first )[0];
        unsigned char pval = ( PSTATUS_SHARED | PSTATUS_INTERFACE );
        if( min_proc < (int)procConfig.proc_rank() ) pval |= PSTATUS_NOT_OWNED;
        if( vit->first.size() > 1 ) pval |= PSTATUS_MULTISHARED;
        result = mbImpl->tag_set_data( pstat_tag, &new_set, 1, &pval );MB_CHK_SET_ERR( result, "Failed to tag interface set with pstatus" );

        // Tag the vertices with the same thing
        pstatus.clear();
        std::vector< EntityHandle > verts;
        for( std::vector< EntityHandle >::iterator v2it = ( vit->second ).begin(); v2it != ( vit->second ).end();
             ++v2it )
            if( mbImpl->type_from_handle( *v2it ) == MBVERTEX ) verts.push_back( *v2it );
        pstatus.resize( verts.size(), pval );
        if( !verts.empty() )
        {
            result = mbImpl->tag_set_data( pstat_tag, &verts[0], verts.size(), &pstatus[0] );MB_CHK_SET_ERR( result, "Failed to tag interface set vertices with pstatus" );
        }
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::create_iface_pc_links()
{
    // Now that we've resolved the entities in the iface sets,
    // set parent/child links between the iface sets

    // First tag all entities in the iface sets
    Tag tmp_iface_tag;
    EntityHandle tmp_iface_set = 0;
    ErrorCode result           = mbImpl->tag_get_handle( "__tmp_iface", 1, MB_TYPE_HANDLE, tmp_iface_tag,
                                                         MB_TAG_DENSE | MB_TAG_CREAT, &tmp_iface_set );MB_CHK_SET_ERR( result, "Failed to create temporary interface set tag" );

    Range iface_ents;
    std::vector< EntityHandle > tag_vals;
    Range::iterator rit;

    for( rit = interfaceSets.begin(); rit != interfaceSets.end(); ++rit )
    {
        // tag entities with interface set
        iface_ents.clear();
        result = mbImpl->get_entities_by_handle( *rit, iface_ents );MB_CHK_SET_ERR( result, "Failed to get entities in interface set" );

        if( iface_ents.empty() ) continue;

        tag_vals.resize( iface_ents.size() );
        std::fill( tag_vals.begin(), tag_vals.end(), *rit );
        result = mbImpl->tag_set_data( tmp_iface_tag, iface_ents, &tag_vals[0] );MB_CHK_SET_ERR( result, "Failed to tag iface entities with interface set" );
    }

    // Now go back through interface sets and add parent/child links
    Range tmp_ents2;
    for( int d = 2; d >= 0; d-- )
    {
        for( rit = interfaceSets.begin(); rit != interfaceSets.end(); ++rit )
        {
            // Get entities on this interface
            iface_ents.clear();
            result = mbImpl->get_entities_by_handle( *rit, iface_ents, true );MB_CHK_SET_ERR( result, "Failed to get entities by handle" );
            if( iface_ents.empty() || mbImpl->dimension_from_handle( *iface_ents.rbegin() ) != d ) continue;

            // Get higher-dimensional entities and their interface sets
            result = mbImpl->get_adjacencies( &( *iface_ents.begin() ), 1, d + 1, false, tmp_ents2 );MB_CHK_SET_ERR( result, "Failed to get adjacencies for interface sets" );
            tag_vals.resize( tmp_ents2.size() );
            result = mbImpl->tag_get_data( tmp_iface_tag, tmp_ents2, &tag_vals[0] );MB_CHK_SET_ERR( result, "Failed to get tmp iface tag for interface sets" );

            // Go through and for any on interface make it a parent
            EntityHandle last_set = 0;
            for( unsigned int i = 0; i < tag_vals.size(); i++ )
            {
                if( tag_vals[i] && tag_vals[i] != last_set )
                {
                    result = mbImpl->add_parent_child( tag_vals[i], *rit );MB_CHK_SET_ERR( result, "Failed to add parent/child link for interface set" );
                    last_set = tag_vals[i];
                }
            }
        }
    }

    // Delete the temporary tag
    result = mbImpl->tag_delete( tmp_iface_tag );MB_CHK_SET_ERR( result, "Failed to delete tmp iface tag" );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_proc_nvecs( int resolve_dim,
                                        int shared_dim,
                                        Range* skin_ents,
                                        std::map< std::vector< int >, std::vector< EntityHandle > >& proc_nvecs )
{
    // Set sharing procs tags on other skin ents
    ErrorCode result;
    const EntityHandle* connect;
    int num_connect;
    std::set< int > sharing_procs;
    std::vector< EntityHandle > dum_connect;
    std::vector< int > sp_vec;

    for( int d = 3; d > 0; d-- )
    {
        if( resolve_dim == d ) continue;

        for( Range::iterator rit = skin_ents[d].begin(); rit != skin_ents[d].end(); ++rit )
        {
            // Get connectivity
            result = mbImpl->get_connectivity( *rit, connect, num_connect, false, &dum_connect );MB_CHK_SET_ERR( result, "Failed to get connectivity on non-vertex skin entities" );

            int op = ( resolve_dim < shared_dim ? Interface::UNION : Interface::INTERSECT );
            result = get_sharing_data( connect, num_connect, sharing_procs, op );MB_CHK_SET_ERR( result, "Failed to get sharing data in get_proc_nvecs" );
            if( sharing_procs.empty() ||
                ( sharing_procs.size() == 1 && *sharing_procs.begin() == (int)procConfig.proc_rank() ) )
                continue;

            // Need to specify sharing data correctly for entities or they will
            // end up in a different interface set than corresponding vertices
            if( sharing_procs.size() == 2 )
            {
                std::set< int >::iterator it = sharing_procs.find( proc_config().proc_rank() );
                assert( it != sharing_procs.end() );
                sharing_procs.erase( it );
            }

            // Intersection is the owning proc(s) for this skin ent
            sp_vec.clear();
            std::copy( sharing_procs.begin(), sharing_procs.end(), std::back_inserter( sp_vec ) );
            assert( sp_vec.size() != 2 );
            proc_nvecs[sp_vec].push_back( *rit );
        }
    }

#ifndef NDEBUG
    // Shouldn't be any repeated entities in any of the vectors in proc_nvecs
    for( std::map< std::vector< int >, std::vector< EntityHandle > >::iterator mit = proc_nvecs.begin();
         mit != proc_nvecs.end(); ++mit )
    {
        std::vector< EntityHandle > tmp_vec = ( mit->second );
        std::sort( tmp_vec.begin(), tmp_vec.end() );
        std::vector< EntityHandle >::iterator vit = std::unique( tmp_vec.begin(), tmp_vec.end() );
        assert( vit == tmp_vec.end() );
    }
#endif

    return MB_SUCCESS;
}

// Overloaded form of tag_shared_verts
// Tuple coming in is of form (arbitrary value, remoteProc, localHandle, remoteHandle)
// Also will check for doubles in the list if the list is sorted
ErrorCode ParallelComm::tag_shared_verts( TupleList& shared_ents,
                                          std::map< std::vector< int >, std::vector< EntityHandle > >& proc_nvecs,
                                          Range& /*proc_verts*/,
                                          unsigned int i_extra )
{
    Tag shp_tag, shps_tag, shh_tag, shhs_tag, pstat_tag;
    ErrorCode result = get_shared_proc_tags( shp_tag, shps_tag, shh_tag, shhs_tag, pstat_tag );MB_CHK_SET_ERR( result, "Failed to get shared proc tags in tag_shared_verts" );

    unsigned int j = 0, i = 0;
    std::vector< int > sharing_procs, sharing_procs2, tag_procs;
    std::vector< EntityHandle > sharing_handles, sharing_handles2, tag_lhandles, tag_rhandles;
    std::vector< unsigned char > pstatus;

    // Were on tuple j/2
    if( i_extra ) i += i_extra;
    while( j < 2 * shared_ents.get_n() )
    {
        // Count & accumulate sharing procs
        EntityHandle this_ent = shared_ents.vul_rd[j], other_ent = 0;
        int other_proc = -1;
        while( j < 2 * shared_ents.get_n() && shared_ents.vul_rd[j] == this_ent )
        {
            j++;
            // Shouldn't have same proc
            assert( shared_ents.vi_rd[i] != (int)procConfig.proc_rank() );
            // Grab the remote data if its not a dublicate
            if( shared_ents.vul_rd[j] != other_ent || shared_ents.vi_rd[i] != other_proc )
            {
                assert( 0 != shared_ents.vul_rd[j] );
                sharing_procs.push_back( shared_ents.vi_rd[i] );
                sharing_handles.push_back( shared_ents.vul_rd[j] );
            }
            other_proc = shared_ents.vi_rd[i];
            other_ent  = shared_ents.vul_rd[j];
            j++;
            i += 1 + i_extra;
        }

        if( sharing_procs.size() > 1 )
        {
            // Add current proc/handle to list
            sharing_procs.push_back( procConfig.proc_rank() );
            sharing_handles.push_back( this_ent );

            // Sort sharing_procs and sharing_handles such that
            // sharing_procs is in ascending order. Use temporary
            // lists and binary search to re-order sharing_handles.
            sharing_procs2 = sharing_procs;
            std::sort( sharing_procs2.begin(), sharing_procs2.end() );
            sharing_handles2.resize( sharing_handles.size() );
            for( size_t k = 0; k < sharing_handles.size(); k++ )
            {
                size_t idx = std::lower_bound( sharing_procs2.begin(), sharing_procs2.end(), sharing_procs[k] ) -
                             sharing_procs2.begin();
                sharing_handles2[idx] = sharing_handles[k];
            }
            sharing_procs.swap( sharing_procs2 );
            sharing_handles.swap( sharing_handles2 );
        }

        assert( sharing_procs.size() != 2 );
        proc_nvecs[sharing_procs].push_back( this_ent );

        unsigned char share_flag = PSTATUS_SHARED, ms_flag = ( PSTATUS_SHARED | PSTATUS_MULTISHARED );
        if( sharing_procs.size() == 1 )
        {
            tag_procs.push_back( sharing_procs[0] );
            tag_lhandles.push_back( this_ent );
            tag_rhandles.push_back( sharing_handles[0] );
            pstatus.push_back( share_flag );
        }
        else
        {
            // Pad lists
            // assert(sharing_procs.size() <= MAX_SHARING_PROCS);
            if( sharing_procs.size() > MAX_SHARING_PROCS )
            {
                std::cerr << "MAX_SHARING_PROCS exceeded for vertex " << this_ent << " on process "
                          << proc_config().proc_rank() << std::endl;
                std::cerr.flush();
                MPI_Abort( proc_config().proc_comm(), 66 );
            }
            sharing_procs.resize( MAX_SHARING_PROCS, -1 );
            sharing_handles.resize( MAX_SHARING_PROCS, 0 );
            result = mbImpl->tag_set_data( shps_tag, &this_ent, 1, &sharing_procs[0] );MB_CHK_SET_ERR( result, "Failed to set sharedps tag on shared vertex" );
            result = mbImpl->tag_set_data( shhs_tag, &this_ent, 1, &sharing_handles[0] );MB_CHK_SET_ERR( result, "Failed to set sharedhs tag on shared vertex" );
            result = mbImpl->tag_set_data( pstat_tag, &this_ent, 1, &ms_flag );MB_CHK_SET_ERR( result, "Failed to set pstatus tag on shared vertex" );
            sharedEnts.insert( this_ent );
        }

        // Reset sharing proc(s) tags
        sharing_procs.clear();
        sharing_handles.clear();
    }

    if( !tag_procs.empty() )
    {
        result = mbImpl->tag_set_data( shp_tag, &tag_lhandles[0], tag_procs.size(), &tag_procs[0] );MB_CHK_SET_ERR( result, "Failed to set sharedp tag on shared vertex" );
        result = mbImpl->tag_set_data( shh_tag, &tag_lhandles[0], tag_procs.size(), &tag_rhandles[0] );MB_CHK_SET_ERR( result, "Failed to set sharedh tag on shared vertex" );
        result = mbImpl->tag_set_data( pstat_tag, &tag_lhandles[0], tag_procs.size(), &pstatus[0] );MB_CHK_SET_ERR( result, "Failed to set pstatus tag on shared vertex" );
        for( std::vector< EntityHandle >::iterator vvt = tag_lhandles.begin(); vvt != tag_lhandles.end(); vvt++ )
            sharedEnts.insert( *vvt );
    }

#ifndef NDEBUG
    // Shouldn't be any repeated entities in any of the vectors in proc_nvecs
    for( std::map< std::vector< int >, std::vector< EntityHandle > >::iterator mit = proc_nvecs.begin();
         mit != proc_nvecs.end(); ++mit )
    {
        std::vector< EntityHandle > tmp_vec = ( mit->second );
        std::sort( tmp_vec.begin(), tmp_vec.end() );
        std::vector< EntityHandle >::iterator vit = std::unique( tmp_vec.begin(), tmp_vec.end() );
        assert( vit == tmp_vec.end() );
    }
#endif

    return MB_SUCCESS;
}

ErrorCode ParallelComm::tag_shared_verts( TupleList& shared_ents,
                                          Range* skin_ents,
                                          std::map< std::vector< int >, std::vector< EntityHandle > >& proc_nvecs,
                                          Range& /*proc_verts*/ )
{
    Tag shp_tag, shps_tag, shh_tag, shhs_tag, pstat_tag;
    ErrorCode result = get_shared_proc_tags( shp_tag, shps_tag, shh_tag, shhs_tag, pstat_tag );MB_CHK_SET_ERR( result, "Failed to get shared proc tags in tag_shared_verts" );

    unsigned int j = 0, i = 0;
    std::vector< int > sharing_procs, sharing_procs2;
    std::vector< EntityHandle > sharing_handles, sharing_handles2, skin_verts( skin_ents[0].size() );
    for( Range::iterator rit = skin_ents[0].begin(); rit != skin_ents[0].end(); ++rit, i++ )
        skin_verts[i] = *rit;
    i = 0;

    while( j < 2 * shared_ents.get_n() )
    {
        // Count & accumulate sharing procs
        int this_idx          = shared_ents.vi_rd[j];
        EntityHandle this_ent = skin_verts[this_idx];
        while( j < 2 * shared_ents.get_n() && shared_ents.vi_rd[j] == this_idx )
        {
            j++;
            // Shouldn't have same proc
            assert( shared_ents.vi_rd[j] != (int)procConfig.proc_rank() );
            sharing_procs.push_back( shared_ents.vi_rd[j++] );
            sharing_handles.push_back( shared_ents.vul_rd[i++] );
        }

        if( sharing_procs.size() > 1 )
        {
            // Add current proc/handle to list
            sharing_procs.push_back( procConfig.proc_rank() );
            sharing_handles.push_back( this_ent );
        }

        // Sort sharing_procs and sharing_handles such that
        // sharing_procs is in ascending order. Use temporary
        // lists and binary search to re-order sharing_handles.
        sharing_procs2 = sharing_procs;
        std::sort( sharing_procs2.begin(), sharing_procs2.end() );
        sharing_handles2.resize( sharing_handles.size() );
        for( size_t k = 0; k < sharing_handles.size(); k++ )
        {
            size_t idx = std::lower_bound( sharing_procs2.begin(), sharing_procs2.end(), sharing_procs[k] ) -
                         sharing_procs2.begin();
            sharing_handles2[idx] = sharing_handles[k];
        }
        sharing_procs.swap( sharing_procs2 );
        sharing_handles.swap( sharing_handles2 );

        assert( sharing_procs.size() != 2 );
        proc_nvecs[sharing_procs].push_back( this_ent );

        unsigned char share_flag = PSTATUS_SHARED, ms_flag = ( PSTATUS_SHARED | PSTATUS_MULTISHARED );
        if( sharing_procs.size() == 1 )
        {
            result = mbImpl->tag_set_data( shp_tag, &this_ent, 1, &sharing_procs[0] );MB_CHK_SET_ERR( result, "Failed to set sharedp tag on shared vertex" );
            result = mbImpl->tag_set_data( shh_tag, &this_ent, 1, &sharing_handles[0] );MB_CHK_SET_ERR( result, "Failed to set sharedh tag on shared vertex" );
            result = mbImpl->tag_set_data( pstat_tag, &this_ent, 1, &share_flag );MB_CHK_SET_ERR( result, "Failed to set pstatus tag on shared vertex" );
            sharedEnts.insert( this_ent );
        }
        else
        {
            // Pad lists
            // assert(sharing_procs.size() <= MAX_SHARING_PROCS);
            if( sharing_procs.size() > MAX_SHARING_PROCS )
            {
                std::cerr << "MAX_SHARING_PROCS exceeded for vertex " << this_ent << " on process "
                          << proc_config().proc_rank() << std::endl;
                std::cerr.flush();
                MPI_Abort( proc_config().proc_comm(), 66 );
            }
            sharing_procs.resize( MAX_SHARING_PROCS, -1 );
            sharing_handles.resize( MAX_SHARING_PROCS, 0 );
            result = mbImpl->tag_set_data( shps_tag, &this_ent, 1, &sharing_procs[0] );MB_CHK_SET_ERR( result, "Failed to set sharedps tag on shared vertex" );
            result = mbImpl->tag_set_data( shhs_tag, &this_ent, 1, &sharing_handles[0] );MB_CHK_SET_ERR( result, "Failed to set sharedhs tag on shared vertex" );
            result = mbImpl->tag_set_data( pstat_tag, &this_ent, 1, &ms_flag );MB_CHK_SET_ERR( result, "Failed to set pstatus tag on shared vertex" );
            sharedEnts.insert( this_ent );
        }

        // Reset sharing proc(s) tags
        sharing_procs.clear();
        sharing_handles.clear();
    }

#ifndef NDEBUG
    // Shouldn't be any repeated entities in any of the vectors in proc_nvecs
    for( std::map< std::vector< int >, std::vector< EntityHandle > >::iterator mit = proc_nvecs.begin();
         mit != proc_nvecs.end(); ++mit )
    {
        std::vector< EntityHandle > tmp_vec = ( mit->second );
        std::sort( tmp_vec.begin(), tmp_vec.end() );
        std::vector< EntityHandle >::iterator vit = std::unique( tmp_vec.begin(), tmp_vec.end() );
        assert( vit == tmp_vec.end() );
    }
#endif

    return MB_SUCCESS;
}

//! Get processors with which this processor communicates; sets are sorted by processor
ErrorCode ParallelComm::get_interface_procs( std::set< unsigned int >& procs_set, bool get_buffs )
{
    // Make sure the sharing procs vector is empty
    procs_set.clear();

    // Pre-load vector of single-proc tag values
    unsigned int i, j;
    std::vector< int > iface_proc( interfaceSets.size() );
    ErrorCode result = mbImpl->tag_get_data( sharedp_tag(), interfaceSets, &iface_proc[0] );MB_CHK_SET_ERR( result, "Failed to get iface_proc for iface sets" );

    // Get sharing procs either from single-proc vector or by getting
    // multi-proc tag value
    int tmp_iface_procs[MAX_SHARING_PROCS];
    std::fill( tmp_iface_procs, tmp_iface_procs + MAX_SHARING_PROCS, -1 );
    Range::iterator rit;
    for( rit = interfaceSets.begin(), i = 0; rit != interfaceSets.end(); ++rit, i++ )
    {
        if( -1 != iface_proc[i] )
        {
            assert( iface_proc[i] != (int)procConfig.proc_rank() );
            procs_set.insert( (unsigned int)iface_proc[i] );
        }
        else
        {
            // Get the sharing_procs tag
            result = mbImpl->tag_get_data( sharedps_tag(), &( *rit ), 1, tmp_iface_procs );MB_CHK_SET_ERR( result, "Failed to get iface_procs for iface set" );
            for( j = 0; j < MAX_SHARING_PROCS; j++ )
            {
                if( -1 != tmp_iface_procs[j] && tmp_iface_procs[j] != (int)procConfig.proc_rank() )
                    procs_set.insert( (unsigned int)tmp_iface_procs[j] );
                else if( -1 == tmp_iface_procs[j] )
                {
                    std::fill( tmp_iface_procs, tmp_iface_procs + j, -1 );
                    break;
                }
            }
        }
    }

    if( get_buffs )
    {
        for( std::set< unsigned int >::iterator sit = procs_set.begin(); sit != procs_set.end(); ++sit )
            get_buffers( *sit );
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_pstatus( EntityHandle entity, unsigned char& pstatus_val )
{
    ErrorCode result = mbImpl->tag_get_data( pstatus_tag(), &entity, 1, &pstatus_val );MB_CHK_SET_ERR( result, "Failed to get pastatus tag data" );
    return result;
}

ErrorCode ParallelComm::get_pstatus_entities( int dim, unsigned char pstatus_val, Range& pstatus_ents )
{
    Range ents;
    ErrorCode result;

    if( -1 == dim )
    {
        result = mbImpl->get_entities_by_handle( 0, ents );MB_CHK_SET_ERR( result, "Failed to get all entities" );
    }
    else
    {
        result = mbImpl->get_entities_by_dimension( 0, dim, ents );MB_CHK_SET_ERR( result, "Failed to get entities of dimension " << dim );
    }

    std::vector< unsigned char > pstatus( ents.size() );
    result = mbImpl->tag_get_data( pstatus_tag(), ents, &pstatus[0] );MB_CHK_SET_ERR( result, "Failed to get pastatus tag data" );
    Range::iterator rit = ents.begin();
    int i               = 0;
    if( pstatus_val )
    {
        for( ; rit != ents.end(); i++, ++rit )
        {
            if( pstatus[i] & pstatus_val && ( -1 == dim || mbImpl->dimension_from_handle( *rit ) == dim ) )
                pstatus_ents.insert( *rit );
        }
    }
    else
    {
        for( ; rit != ents.end(); i++, ++rit )
        {
            if( !pstatus[i] && ( -1 == dim || mbImpl->dimension_from_handle( *rit ) == dim ) )
                pstatus_ents.insert( *rit );
        }
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::check_global_ids( EntityHandle this_set,
                                          const int dimension,
                                          const int start_id,
                                          const bool largest_dim_only,
                                          const bool parallel,
                                          const bool owned_only )
{
    // Global id tag
    Tag gid_tag = mbImpl->globalId_tag();
    int def_val = -1;
    Range dum_range;

    void* tag_ptr    = &def_val;
    ErrorCode result = mbImpl->get_entities_by_type_and_tag( this_set, MBVERTEX, &gid_tag, &tag_ptr, 1, dum_range );MB_CHK_SET_ERR( result, "Failed to get entities by MBVERTEX type and gid tag" );

    if( !dum_range.empty() )
    {
        // Just created it, so we need global ids
        result = assign_global_ids( this_set, dimension, start_id, largest_dim_only, parallel, owned_only );MB_CHK_SET_ERR( result, "Failed assigning global ids" );
    }

    return MB_SUCCESS;
}

bool ParallelComm::is_iface_proc( EntityHandle this_set, int to_proc )
{
    int sharing_procs[MAX_SHARING_PROCS];
    std::fill( sharing_procs, sharing_procs + MAX_SHARING_PROCS, -1 );
    ErrorCode result = mbImpl->tag_get_data( sharedp_tag(), &this_set, 1, sharing_procs );
    if( MB_SUCCESS == result && to_proc == sharing_procs[0] ) return true;

    result = mbImpl->tag_get_data( sharedps_tag(), &this_set, 1, sharing_procs );
    if( MB_SUCCESS != result ) return false;

    for( int i = 0; i < MAX_SHARING_PROCS; i++ )
    {
        if( to_proc == sharing_procs[i] )
            return true;
        else if( -1 == sharing_procs[i] )
            return false;
    }

    return false;
}

ErrorCode ParallelComm::filter_pstatus( Range& ents,
                                        unsigned char pstat,
                                        unsigned char op,
                                        int to_proc,
                                        Range* returned_ents )
{
    Range tmp_ents;

    // assert(!ents.empty());
    if( ents.empty() )
    {
        if( returned_ents ) returned_ents->clear();
        return MB_SUCCESS;
    }

    // Put into tmp_ents any entities which are not owned locally or
    // who are already shared with to_proc
    std::vector< unsigned char > shared_flags( ents.size() ), shared_flags2;
    ErrorCode result = mbImpl->tag_get_data( pstatus_tag(), ents, &shared_flags[0] );MB_CHK_SET_ERR( result, "Failed to get pstatus flag" );
    Range::const_iterator rit, hint = tmp_ents.begin();
    ;
    int i;
    if( op == PSTATUS_OR )
    {
        for( rit = ents.begin(), i = 0; rit != ents.end(); ++rit, i++ )
        {
            if( ( ( shared_flags[i] & ~pstat ) ^ shared_flags[i] ) & pstat )
            {
                hint = tmp_ents.insert( hint, *rit );
                if( -1 != to_proc ) shared_flags2.push_back( shared_flags[i] );
            }
        }
    }
    else if( op == PSTATUS_AND )
    {
        for( rit = ents.begin(), i = 0; rit != ents.end(); ++rit, i++ )
        {
            if( ( shared_flags[i] & pstat ) == pstat )
            {
                hint = tmp_ents.insert( hint, *rit );
                if( -1 != to_proc ) shared_flags2.push_back( shared_flags[i] );
            }
        }
    }
    else if( op == PSTATUS_NOT )
    {
        for( rit = ents.begin(), i = 0; rit != ents.end(); ++rit, i++ )
        {
            if( !( shared_flags[i] & pstat ) )
            {
                hint = tmp_ents.insert( hint, *rit );
                if( -1 != to_proc ) shared_flags2.push_back( shared_flags[i] );
            }
        }
    }
    else
    {
        assert( false );
        return MB_FAILURE;
    }

    if( -1 != to_proc )
    {
        int sharing_procs[MAX_SHARING_PROCS];
        std::fill( sharing_procs, sharing_procs + MAX_SHARING_PROCS, -1 );
        Range tmp_ents2;
        hint = tmp_ents2.begin();

        for( rit = tmp_ents.begin(), i = 0; rit != tmp_ents.end(); ++rit, i++ )
        {
            // We need to check sharing procs
            if( shared_flags2[i] & PSTATUS_MULTISHARED )
            {
                result = mbImpl->tag_get_data( sharedps_tag(), &( *rit ), 1, sharing_procs );MB_CHK_SET_ERR( result, "Failed to get sharedps tag" );
                assert( -1 != sharing_procs[0] );
                for( unsigned int j = 0; j < MAX_SHARING_PROCS; j++ )
                {
                    // If to_proc shares this entity, add it to list
                    if( sharing_procs[j] == to_proc )
                    {
                        hint = tmp_ents2.insert( hint, *rit );
                    }
                    else if( -1 == sharing_procs[j] )
                        break;

                    sharing_procs[j] = -1;
                }
            }
            else if( shared_flags2[i] & PSTATUS_SHARED )
            {
                result = mbImpl->tag_get_data( sharedp_tag(), &( *rit ), 1, sharing_procs );MB_CHK_SET_ERR( result, "Failed to get sharedp tag" );
                assert( -1 != sharing_procs[0] );
                if( sharing_procs[0] == to_proc ) hint = tmp_ents2.insert( hint, *rit );
                sharing_procs[0] = -1;
            }
            else
                assert( "should never get here" && false );
        }

        tmp_ents.swap( tmp_ents2 );
    }

    if( returned_ents )
        returned_ents->swap( tmp_ents );
    else
        ents.swap( tmp_ents );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::exchange_ghost_cells( int ghost_dim,
                                              int bridge_dim,
                                              int num_layers,
                                              int addl_ents,
                                              bool store_remote_handles,
                                              bool wait_all,
                                              EntityHandle* file_set )
{
#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        if( !num_layers )
            MPE_Log_event( IFACE_START, procConfig.proc_rank(), "Starting interface exchange." );
        else
            MPE_Log_event( GHOST_START, procConfig.proc_rank(), "Starting ghost exchange." );
    }
#endif

    myDebug->tprintf( 1, "Entering exchange_ghost_cells with num_layers = %d\n", num_layers );
    if( myDebug->get_verbosity() == 4 )
    {
        msgs.clear();
        msgs.reserve( MAX_SHARING_PROCS );
    }

    // If we're only finding out about existing ents, we have to be storing
    // remote handles too
    assert( num_layers > 0 || store_remote_handles );

    const bool is_iface = !num_layers;

    // Get the b-dimensional interface(s) with with_proc, where b = bridge_dim

    int success;
    ErrorCode result = MB_SUCCESS;
    int incoming1 = 0, incoming2 = 0;

    reset_all_buffers();

    // When this function is called, buffProcs should already have any
    // communicating procs

    //===========================================
    // Post ghost irecv's for ghost entities from all communicating procs
    //===========================================
#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( ENTITIES_START, procConfig.proc_rank(), "Starting entity exchange." );
    }
#endif

    // Index reqs the same as buffer/sharing procs indices
    std::vector< MPI_Request > recv_ent_reqs( 3 * buffProcs.size(), MPI_REQUEST_NULL ),
        recv_remoteh_reqs( 3 * buffProcs.size(), MPI_REQUEST_NULL );
    std::vector< unsigned int >::iterator proc_it;
    int ind, p;
    sendReqs.resize( 3 * buffProcs.size(), MPI_REQUEST_NULL );
    for( ind = 0, proc_it = buffProcs.begin(); proc_it != buffProcs.end(); ++proc_it, ind++ )
    {
        incoming1++;
        PRINT_DEBUG_IRECV( procConfig.proc_rank(), buffProcs[ind], remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE,
                           MB_MESG_ENTS_SIZE, incoming1 );
        success = MPI_Irecv( remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE, MPI_UNSIGNED_CHAR, buffProcs[ind],
                             MB_MESG_ENTS_SIZE, procConfig.proc_comm(), &recv_ent_reqs[3 * ind] );
        if( success != MPI_SUCCESS )
        {
            MB_SET_ERR( MB_FAILURE, "Failed to post irecv in ghost exchange" );
        }
    }

    //===========================================
    // Get entities to be sent to neighbors
    //===========================================
    Range sent_ents[MAX_SHARING_PROCS], allsent, tmp_range;
    TupleList entprocs;
    int dum_ack_buff;
    result = get_sent_ents( is_iface, bridge_dim, ghost_dim, num_layers, addl_ents, sent_ents, allsent, entprocs );MB_CHK_SET_ERR( result, "get_sent_ents failed" );

    // augment file set with the entities to be sent
    // we might have created new entities if addl_ents>0, edges and/or faces
    if( addl_ents > 0 && file_set && !allsent.empty() )
    {
        result = mbImpl->add_entities( *file_set, allsent );MB_CHK_SET_ERR( result, "Failed to add new sub-entities to set" );
    }
    myDebug->tprintf( 1, "allsent ents compactness (size) = %f (%lu)\n", allsent.compactness(),
                      (unsigned long)allsent.size() );

    //===========================================
    // Pack and send ents from this proc to others
    //===========================================
    for( p = 0, proc_it = buffProcs.begin(); proc_it != buffProcs.end(); ++proc_it, p++ )
    {
        myDebug->tprintf( 1, "Sent ents compactness (size) = %f (%lu)\n", sent_ents[p].compactness(),
                          (unsigned long)sent_ents[p].size() );

        // Reserve space on front for size and for initial buff size
        localOwnedBuffs[p]->reset_buffer( sizeof( int ) );

        // Entities
        result = pack_entities( sent_ents[p], localOwnedBuffs[p], store_remote_handles, buffProcs[p], is_iface,
                                &entprocs, &allsent );MB_CHK_SET_ERR( result, "Packing entities failed" );

        if( myDebug->get_verbosity() == 4 )
        {
            msgs.resize( msgs.size() + 1 );
            msgs.back() = new Buffer( *localOwnedBuffs[p] );
        }

        // Send the buffer (size stored in front in send_buffer)
        result = send_buffer( *proc_it, localOwnedBuffs[p], MB_MESG_ENTS_SIZE, sendReqs[3 * p],
                              recv_ent_reqs[3 * p + 2], &dum_ack_buff, incoming1, MB_MESG_REMOTEH_SIZE,
                              ( !is_iface && store_remote_handles ?  // this used for ghosting only
                                    localOwnedBuffs[p]
                                                                  : NULL ),
                              &recv_remoteh_reqs[3 * p], &incoming2 );MB_CHK_SET_ERR( result, "Failed to Isend in ghost exchange" );
    }

    entprocs.reset();

    //===========================================
    // Receive/unpack new entities
    //===========================================
    // Number of incoming messages for ghosts is the number of procs we
    // communicate with; for iface, it's the number of those with lower rank
    MPI_Status status;
    std::vector< std::vector< EntityHandle > > recd_ents( buffProcs.size() );<--- Variable 'recd_ents' is assigned a value that is never used.
    std::vector< std::vector< EntityHandle > > L1hloc( buffProcs.size() ), L1hrem( buffProcs.size() );
    std::vector< std::vector< int > > L1p( buffProcs.size() );
    std::vector< EntityHandle > L2hloc, L2hrem;
    std::vector< unsigned int > L2p;
    std::vector< EntityHandle > new_ents;

    while( incoming1 )
    {
        // Wait for all recvs of ghost ents before proceeding to sending remote handles,
        // b/c some procs may have sent to a 3rd proc ents owned by me;
        PRINT_DEBUG_WAITANY( recv_ent_reqs, MB_MESG_ENTS_SIZE, procConfig.proc_rank() );

        success = MPI_Waitany( 3 * buffProcs.size(), &recv_ent_reqs[0], &ind, &status );
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "Failed in waitany in ghost exchange" );
        }

        PRINT_DEBUG_RECD( status );

        // OK, received something; decrement incoming counter
        incoming1--;
        bool done = false;

        // In case ind is for ack, we need index of one before it
        unsigned int base_ind = 3 * ( ind / 3 );
        result = recv_buffer( MB_MESG_ENTS_SIZE, status, remoteOwnedBuffs[ind / 3], recv_ent_reqs[base_ind + 1],
                              recv_ent_reqs[base_ind + 2], incoming1, localOwnedBuffs[ind / 3], sendReqs[base_ind + 1],
                              sendReqs[base_ind + 2], done,
                              ( !is_iface && store_remote_handles ? localOwnedBuffs[ind / 3] : NULL ),
                              MB_MESG_REMOTEH_SIZE,  // maybe base_ind+1?
                              &recv_remoteh_reqs[base_ind + 1], &incoming2 );MB_CHK_SET_ERR( result, "Failed to receive buffer" );

        if( done )
        {
            if( myDebug->get_verbosity() == 4 )
            {
                msgs.resize( msgs.size() + 1 );
                msgs.back() = new Buffer( *remoteOwnedBuffs[ind / 3] );
            }

            // Message completely received - process buffer that was sent
            remoteOwnedBuffs[ind / 3]->reset_ptr( sizeof( int ) );
            result = unpack_entities( remoteOwnedBuffs[ind / 3]->buff_ptr, store_remote_handles, ind / 3, is_iface,
                                      L1hloc, L1hrem, L1p, L2hloc, L2hrem, L2p, new_ents );
            if( MB_SUCCESS != result )
            {
                std::cout << "Failed to unpack entities. Buffer contents:" << std::endl;
                print_buffer( remoteOwnedBuffs[ind / 3]->mem_ptr, MB_MESG_ENTS_SIZE, buffProcs[ind / 3], false );
                return result;
            }

            if( recv_ent_reqs.size() != 3 * buffProcs.size() )
            {
                // Post irecv's for remote handles from new proc; shouldn't be iface,
                // since we know about all procs we share with
                assert( !is_iface );
                recv_remoteh_reqs.resize( 3 * buffProcs.size(), MPI_REQUEST_NULL );
                for( unsigned int i = recv_ent_reqs.size(); i < 3 * buffProcs.size(); i += 3 )
                {
                    localOwnedBuffs[i / 3]->reset_buffer();
                    incoming2++;
                    PRINT_DEBUG_IRECV( procConfig.proc_rank(), buffProcs[i / 3], localOwnedBuffs[i / 3]->mem_ptr,
                                       INITIAL_BUFF_SIZE, MB_MESG_REMOTEH_SIZE, incoming2 );
                    success = MPI_Irecv( localOwnedBuffs[i / 3]->mem_ptr, INITIAL_BUFF_SIZE, MPI_UNSIGNED_CHAR,
                                         buffProcs[i / 3], MB_MESG_REMOTEH_SIZE, procConfig.proc_comm(),
                                         &recv_remoteh_reqs[i] );
                    if( success != MPI_SUCCESS )
                    {
                        MB_SET_ERR( MB_FAILURE, "Failed to post irecv for remote handles in ghost exchange" );
                    }
                }
                recv_ent_reqs.resize( 3 * buffProcs.size(), MPI_REQUEST_NULL );
                sendReqs.resize( 3 * buffProcs.size(), MPI_REQUEST_NULL );
            }
        }
    }

    // Add requests for any new addl procs
    if( recv_ent_reqs.size() != 3 * buffProcs.size() )
    {
        // Shouldn't get here...
        MB_SET_ERR( MB_FAILURE, "Requests length doesn't match proc count in ghost exchange" );
    }

#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( ENTITIES_END, procConfig.proc_rank(), "Ending entity exchange." );
    }
#endif

    if( is_iface )
    {
        // Need to check over entities I sent and make sure I received
        // handles for them from all expected procs; if not, need to clean
        // them up
        result = check_clean_iface( allsent );
        if( MB_SUCCESS != result ) std::cout << "Failed check." << std::endl;

        // Now set the shared/interface tag on non-vertex entities on interface
        result = tag_iface_entities();MB_CHK_SET_ERR( result, "Failed to tag iface entities" );

#ifndef NDEBUG
        result = check_sent_ents( allsent );
        if( MB_SUCCESS != result ) std::cout << "Failed check." << std::endl;
        result = check_all_shared_handles( true );
        if( MB_SUCCESS != result ) std::cout << "Failed check." << std::endl;
#endif

#ifdef MOAB_HAVE_MPE
        if( myDebug->get_verbosity() == 2 )
        {
            MPE_Log_event( IFACE_END, procConfig.proc_rank(), "Ending interface exchange." );
        }
#endif

        //===========================================
        // Wait if requested
        //===========================================
        if( wait_all )
        {
            if( myDebug->get_verbosity() == 5 )
            {
                success = MPI_Barrier( procConfig.proc_comm() );<--- Variable 'success' is assigned a value that is never used.
            }
            else
            {
                MPI_Status mult_status[3 * MAX_SHARING_PROCS];
                success = MPI_Waitall( 3 * buffProcs.size(), &recv_ent_reqs[0], mult_status );
                if( MPI_SUCCESS != success )
                {
                    MB_SET_ERR( MB_FAILURE, "Failed in waitall in ghost exchange" );
                }
                success = MPI_Waitall( 3 * buffProcs.size(), &sendReqs[0], mult_status );
                if( MPI_SUCCESS != success )
                {
                    MB_SET_ERR( MB_FAILURE, "Failed in waitall in ghost exchange" );
                }
                /*success = MPI_Waitall(3*buffProcs.size(), &recv_remoteh_reqs[0], mult_status);
                if (MPI_SUCCESS != success) {
                  MB_SET_ERR(MB_FAILURE, "Failed in waitall in ghost exchange");
                }*/
            }
        }

        myDebug->tprintf( 1, "Total number of shared entities = %lu.\n", (unsigned long)sharedEnts.size() );
        myDebug->tprintf( 1, "Exiting exchange_ghost_cells for is_iface==true \n" );

        return MB_SUCCESS;
    }

    // we still need to wait on sendReqs, if they are not fulfilled yet
    if( wait_all )
    {
        if( myDebug->get_verbosity() == 5 )
        {
            success = MPI_Barrier( procConfig.proc_comm() );<--- Variable 'success' is assigned a value that is never used.
        }
        else
        {
            MPI_Status mult_status[3 * MAX_SHARING_PROCS];
            success = MPI_Waitall( 3 * buffProcs.size(), &sendReqs[0], mult_status );
            if( MPI_SUCCESS != success )
            {
                MB_SET_ERR( MB_FAILURE, "Failed in waitall in ghost exchange" );
            }
        }
    }
    //===========================================
    // Send local handles for new ghosts to owner, then add
    // those to ghost list for that owner
    //===========================================
    for( p = 0, proc_it = buffProcs.begin(); proc_it != buffProcs.end(); ++proc_it, p++ )
    {

        // Reserve space on front for size and for initial buff size
        remoteOwnedBuffs[p]->reset_buffer( sizeof( int ) );

        result = pack_remote_handles( L1hloc[p], L1hrem[p], L1p[p], *proc_it, remoteOwnedBuffs[p] );MB_CHK_SET_ERR( result, "Failed to pack remote handles" );
        remoteOwnedBuffs[p]->set_stored_size();

        if( myDebug->get_verbosity() == 4 )
        {
            msgs.resize( msgs.size() + 1 );
            msgs.back() = new Buffer( *remoteOwnedBuffs[p] );
        }
        result = send_buffer( buffProcs[p], remoteOwnedBuffs[p], MB_MESG_REMOTEH_SIZE, sendReqs[3 * p],
                              recv_remoteh_reqs[3 * p + 2], &dum_ack_buff, incoming2 );MB_CHK_SET_ERR( result, "Failed to send remote handles" );
    }

    //===========================================
    // Process remote handles of my ghosteds
    //===========================================
    while( incoming2 )
    {
        PRINT_DEBUG_WAITANY( recv_remoteh_reqs, MB_MESG_REMOTEH_SIZE, procConfig.proc_rank() );
        success = MPI_Waitany( 3 * buffProcs.size(), &recv_remoteh_reqs[0], &ind, &status );
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "Failed in waitany in ghost exchange" );
        }

        // OK, received something; decrement incoming counter
        incoming2--;

        PRINT_DEBUG_RECD( status );

        bool done             = false;
        unsigned int base_ind = 3 * ( ind / 3 );
        result = recv_buffer( MB_MESG_REMOTEH_SIZE, status, localOwnedBuffs[ind / 3], recv_remoteh_reqs[base_ind + 1],
                              recv_remoteh_reqs[base_ind + 2], incoming2, remoteOwnedBuffs[ind / 3],
                              sendReqs[base_ind + 1], sendReqs[base_ind + 2], done );MB_CHK_SET_ERR( result, "Failed to receive remote handles" );
        if( done )
        {
            // Incoming remote handles
            if( myDebug->get_verbosity() == 4 )
            {
                msgs.resize( msgs.size() + 1 );
                msgs.back() = new Buffer( *localOwnedBuffs[ind / 3] );
            }
            localOwnedBuffs[ind / 3]->reset_ptr( sizeof( int ) );
            result =
                unpack_remote_handles( buffProcs[ind / 3], localOwnedBuffs[ind / 3]->buff_ptr, L2hloc, L2hrem, L2p );MB_CHK_SET_ERR( result, "Failed to unpack remote handles" );
        }
    }

#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( RHANDLES_END, procConfig.proc_rank(), "Ending remote handles." );
        MPE_Log_event( GHOST_END, procConfig.proc_rank(), "Ending ghost exchange (still doing checks)." );
    }
#endif

    //===========================================
    // Wait if requested
    //===========================================
    if( wait_all )
    {
        if( myDebug->get_verbosity() == 5 )
        {
            success = MPI_Barrier( procConfig.proc_comm() );
        }
        else
        {
            MPI_Status mult_status[3 * MAX_SHARING_PROCS];
            success = MPI_Waitall( 3 * buffProcs.size(), &recv_remoteh_reqs[0], mult_status );
            if( MPI_SUCCESS == success ) success = MPI_Waitall( 3 * buffProcs.size(), &sendReqs[0], mult_status );
        }
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "Failed in waitall in ghost exchange" );
        }
    }

#ifndef NDEBUG
    result = check_sent_ents( allsent );MB_CHK_SET_ERR( result, "Failed check on shared entities" );
    result = check_all_shared_handles( true );MB_CHK_SET_ERR( result, "Failed check on all shared handles" );
#endif

    if( file_set && !new_ents.empty() )
    {
        result = mbImpl->add_entities( *file_set, &new_ents[0], new_ents.size() );MB_CHK_SET_ERR( result, "Failed to add new entities to set" );
    }

    myDebug->tprintf( 1, "Total number of shared entities = %lu.\n", (unsigned long)sharedEnts.size() );
    myDebug->tprintf( 1, "Exiting exchange_ghost_cells for is_iface==false \n" );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::send_buffer( const unsigned int to_proc,
                                     Buffer* send_buff,
                                     int mesg_tag,
                                     MPI_Request& send_req,
                                     MPI_Request& ack_req,
                                     int* ack_buff,
                                     int& this_incoming,
                                     int next_mesg_tag,
                                     Buffer* next_recv_buff,
                                     MPI_Request* next_recv_req,
                                     int* next_incoming )
{
    ErrorCode result = MB_SUCCESS;
    int success;

    // If small message, post recv for remote handle message
    if( send_buff->get_stored_size() <= (int)INITIAL_BUFF_SIZE && next_recv_buff )
    {
        ( *next_incoming )++;
        PRINT_DEBUG_IRECV( procConfig.proc_rank(), to_proc, next_recv_buff->mem_ptr, INITIAL_BUFF_SIZE, next_mesg_tag,
                           *next_incoming );
        success = MPI_Irecv( next_recv_buff->mem_ptr, INITIAL_BUFF_SIZE, MPI_UNSIGNED_CHAR, to_proc, next_mesg_tag,
                             procConfig.proc_comm(), next_recv_req );
        if( success != MPI_SUCCESS )
        {
            MB_SET_ERR( MB_FAILURE, "Failed to post irecv for next message in ghost exchange" );
        }
    }
    // If large, we'll need an ack before sending the rest
    else if( send_buff->get_stored_size() > (int)INITIAL_BUFF_SIZE )
    {
        this_incoming++;
        PRINT_DEBUG_IRECV( procConfig.proc_rank(), to_proc, (unsigned char*)ack_buff, sizeof( int ), mesg_tag - 1,
                           this_incoming );
        success = MPI_Irecv( (void*)ack_buff, sizeof( int ), MPI_UNSIGNED_CHAR, to_proc, mesg_tag - 1,
                             procConfig.proc_comm(), &ack_req );
        if( success != MPI_SUCCESS )
        {
            MB_SET_ERR( MB_FAILURE, "Failed to post irecv for entity ack in ghost exchange" );
        }
    }

    // Send the buffer
    PRINT_DEBUG_ISEND( procConfig.proc_rank(), to_proc, send_buff->mem_ptr, mesg_tag,
                       std::min( send_buff->get_stored_size(), (int)INITIAL_BUFF_SIZE ) );
    assert( 0 <= send_buff->get_stored_size() && send_buff->get_stored_size() <= (int)send_buff->alloc_size );
    success = MPI_Isend( send_buff->mem_ptr, std::min( send_buff->get_stored_size(), (int)INITIAL_BUFF_SIZE ),
                         MPI_UNSIGNED_CHAR, to_proc, mesg_tag, procConfig.proc_comm(), &send_req );
    if( success != MPI_SUCCESS ) return MB_FAILURE;

    return result;
}

ErrorCode ParallelComm::recv_buffer( int mesg_tag_expected,
                                     const MPI_Status& mpi_status,
                                     Buffer* recv_buff,
                                     MPI_Request& recv_req,
                                     MPI_Request& /*ack_recvd_req*/,
                                     int& this_incoming,
                                     Buffer* send_buff,
                                     MPI_Request& send_req,
                                     MPI_Request& sent_ack_req,
                                     bool& done,
                                     Buffer* next_buff,
                                     int next_tag,
                                     MPI_Request* next_req,
                                     int* next_incoming )
{
    // Process a received message; if there will be more coming,
    // post a receive for 2nd part then send an ack message
    int from_proc = mpi_status.MPI_SOURCE;
    int success;

    // Set the buff_ptr on the recv_buffer; needs to point beyond any
    // valid data already in the buffer
    recv_buff->reset_ptr( std::min( recv_buff->get_stored_size(), (int)recv_buff->alloc_size ) );

    if( mpi_status.MPI_TAG == mesg_tag_expected && recv_buff->get_stored_size() > (int)INITIAL_BUFF_SIZE )
    {
        // 1st message & large - allocate buffer, post irecv for 2nd message,
        // then send ack
        recv_buff->reserve( recv_buff->get_stored_size() );
        assert( recv_buff->alloc_size > INITIAL_BUFF_SIZE );

        // Will expect a 2nd message
        this_incoming++;

        PRINT_DEBUG_IRECV( procConfig.proc_rank(), from_proc, recv_buff->mem_ptr + INITIAL_BUFF_SIZE,
                           recv_buff->get_stored_size() - INITIAL_BUFF_SIZE, mesg_tag_expected + 1, this_incoming );
        success = MPI_Irecv( recv_buff->mem_ptr + INITIAL_BUFF_SIZE, recv_buff->get_stored_size() - INITIAL_BUFF_SIZE,
                             MPI_UNSIGNED_CHAR, from_proc, mesg_tag_expected + 1, procConfig.proc_comm(), &recv_req );
        if( success != MPI_SUCCESS )
        {
            MB_SET_ERR( MB_FAILURE, "Failed to post 2nd iRecv in ghost exchange" );
        }

        // Send ack, doesn't matter what data actually is
        PRINT_DEBUG_ISEND( procConfig.proc_rank(), from_proc, recv_buff->mem_ptr, mesg_tag_expected - 1,
                           sizeof( int ) );
        success = MPI_Isend( recv_buff->mem_ptr, sizeof( int ), MPI_UNSIGNED_CHAR, from_proc, mesg_tag_expected - 1,
                             procConfig.proc_comm(), &sent_ack_req );
        if( success != MPI_SUCCESS )
        {
            MB_SET_ERR( MB_FAILURE, "Failed to send ack in ghost exchange" );
        }
    }
    else if( mpi_status.MPI_TAG == mesg_tag_expected - 1 )
    {
        // Got an ack back, send the 2nd half of message

        // Should be a large message if we got this
        assert( *( (size_t*)send_buff->mem_ptr ) > INITIAL_BUFF_SIZE );

        // Post irecv for next message, then send 2nd message
        if( next_buff )
        {
            // We'll expect a return message
            ( *next_incoming )++;
            PRINT_DEBUG_IRECV( procConfig.proc_rank(), from_proc, next_buff->mem_ptr, INITIAL_BUFF_SIZE, next_tag,
                               *next_incoming );

            success = MPI_Irecv( next_buff->mem_ptr, INITIAL_BUFF_SIZE, MPI_UNSIGNED_CHAR, from_proc, next_tag,
                                 procConfig.proc_comm(), next_req );
            if( success != MPI_SUCCESS )
            {
                MB_SET_ERR( MB_FAILURE, "Failed to post next irecv in ghost exchange" );
            }
        }

        // Send 2nd message
        PRINT_DEBUG_ISEND( procConfig.proc_rank(), from_proc, send_buff->mem_ptr + INITIAL_BUFF_SIZE,
                           mesg_tag_expected + 1, send_buff->get_stored_size() - INITIAL_BUFF_SIZE );

        assert( send_buff->get_stored_size() - INITIAL_BUFF_SIZE < send_buff->alloc_size &&
                0 <= send_buff->get_stored_size() );
        success = MPI_Isend( send_buff->mem_ptr + INITIAL_BUFF_SIZE, send_buff->get_stored_size() - INITIAL_BUFF_SIZE,
                             MPI_UNSIGNED_CHAR, from_proc, mesg_tag_expected + 1, procConfig.proc_comm(), &send_req );
        if( success != MPI_SUCCESS )
        {
            MB_SET_ERR( MB_FAILURE, "Failed to send 2nd message in ghost exchange" );
        }
    }
    else if( ( mpi_status.MPI_TAG == mesg_tag_expected && recv_buff->get_stored_size() <= (int)INITIAL_BUFF_SIZE ) ||
             mpi_status.MPI_TAG == mesg_tag_expected + 1 )
    {
        // Message completely received - signal that we're done
        done = true;
    }

    return MB_SUCCESS;
}

struct ProcList
{
    int procs[MAX_SHARING_PROCS];
};
static bool operator<( const ProcList& a, const ProcList& b )
{
    for( int i = 0; i < MAX_SHARING_PROCS; i++ )
    {
        if( a.procs[i] < b.procs[i] )
            return true;
        else if( b.procs[i] < a.procs[i] )
            return false;
        else if( a.procs[i] < 0 )
            return false;
    }
    return false;
}

ErrorCode ParallelComm::check_clean_iface( Range& allsent )
{
    // allsent is all entities I think are on interface; go over them, looking
    // for zero-valued handles, and fix any I find

    // Keep lists of entities for which teh sharing data changed, grouped
    // by set of sharing procs.
    typedef std::map< ProcList, Range > procmap_t;
    procmap_t old_procs, new_procs;

    ErrorCode result = MB_SUCCESS;<--- Variable 'result' is assigned a value that is never used.
    Range::iterator rit;
    Range::reverse_iterator rvit;
    unsigned char pstatus;
    int nump;
    ProcList sharedp;
    EntityHandle sharedh[MAX_SHARING_PROCS];
    for( rvit = allsent.rbegin(); rvit != allsent.rend(); ++rvit )
    {
        result = get_sharing_data( *rvit, sharedp.procs, sharedh, pstatus, nump );MB_CHK_SET_ERR( result, "Failed to get sharing data" );
        assert( "Should be shared with at least one other proc" &&
                ( nump > 1 || sharedp.procs[0] != (int)procConfig.proc_rank() ) );
        assert( nump == MAX_SHARING_PROCS || sharedp.procs[nump] == -1 );

        // Look for first null handle in list
        int idx = std::find( sharedh, sharedh + nump, (EntityHandle)0 ) - sharedh;
        if( idx == nump ) continue;  // All handles are valid

        ProcList old_list( sharedp );
        std::sort( old_list.procs, old_list.procs + nump );
        old_procs[old_list].insert( *rvit );

        // Remove null handles and corresponding proc ranks from lists
        int new_nump       = idx;
        bool removed_owner = !idx;
        for( ++idx; idx < nump; ++idx )
        {
            if( sharedh[idx] )
            {
                sharedh[new_nump]       = sharedh[idx];
                sharedp.procs[new_nump] = sharedp.procs[idx];
                ++new_nump;
            }
        }
        sharedp.procs[new_nump] = -1;

        if( removed_owner && new_nump > 1 )
        {
            // The proc that we choose as the entity owner isn't sharing the
            // entity (doesn't have a copy of it). We need to pick a different
            // owner. Choose the proc with lowest rank.
            idx = std::min_element( sharedp.procs, sharedp.procs + new_nump ) - sharedp.procs;
            std::swap( sharedp.procs[0], sharedp.procs[idx] );
            std::swap( sharedh[0], sharedh[idx] );
            if( sharedp.procs[0] == (int)proc_config().proc_rank() ) pstatus &= ~PSTATUS_NOT_OWNED;
        }

        result = set_sharing_data( *rvit, pstatus, nump, new_nump, sharedp.procs, sharedh );MB_CHK_SET_ERR( result, "Failed to set sharing data in check_clean_iface" );

        if( new_nump > 1 )
        {
            if( new_nump == 2 )
            {
                if( sharedp.procs[1] != (int)proc_config().proc_rank() )
                {
                    assert( sharedp.procs[0] == (int)proc_config().proc_rank() );
                    sharedp.procs[0] = sharedp.procs[1];
                }
                sharedp.procs[1] = -1;
            }
            else
            {
                std::sort( sharedp.procs, sharedp.procs + new_nump );
            }
            new_procs[sharedp].insert( *rvit );
        }
    }

    if( old_procs.empty() )
    {
        assert( new_procs.empty() );
        return MB_SUCCESS;
    }

    // Update interface sets
    procmap_t::iterator pmit;
    // std::vector<unsigned char> pstatus_list;
    rit = interface_sets().begin();
    while( rit != interface_sets().end() )
    {
        result = get_sharing_data( *rit, sharedp.procs, sharedh, pstatus, nump );MB_CHK_SET_ERR( result, "Failed to get sharing data for interface set" );
        assert( nump != 2 );
        std::sort( sharedp.procs, sharedp.procs + nump );
        assert( nump == MAX_SHARING_PROCS || sharedp.procs[nump] == -1 );

        pmit = old_procs.find( sharedp );
        if( pmit != old_procs.end() )
        {
            result = mbImpl->remove_entities( *rit, pmit->second );MB_CHK_SET_ERR( result, "Failed to remove entities from interface set" );
        }

        pmit = new_procs.find( sharedp );
        if( pmit == new_procs.end() )
        {
            int count;
            result = mbImpl->get_number_entities_by_handle( *rit, count );MB_CHK_SET_ERR( result, "Failed to get number of entities in interface set" );
            if( !count )
            {
                result = mbImpl->delete_entities( &*rit, 1 );MB_CHK_SET_ERR( result, "Failed to delete entities from interface set" );
                rit = interface_sets().erase( rit );
            }
            else
            {
                ++rit;
            }
        }
        else
        {
            result = mbImpl->add_entities( *rit, pmit->second );MB_CHK_SET_ERR( result, "Failed to add entities to interface set" );

            // Remove those that we've processed so that we know which ones
            // are new.
            new_procs.erase( pmit );
            ++rit;
        }
    }

    // Create interface sets for new proc id combinations
    std::fill( sharedh, sharedh + MAX_SHARING_PROCS, 0 );
    for( pmit = new_procs.begin(); pmit != new_procs.end(); ++pmit )
    {
        EntityHandle new_set;
        result = mbImpl->create_meshset( MESHSET_SET, new_set );MB_CHK_SET_ERR( result, "Failed to create interface set" );
        interfaceSets.insert( new_set );

        // Add entities
        result = mbImpl->add_entities( new_set, pmit->second );MB_CHK_SET_ERR( result, "Failed to add entities to interface set" );
        // Tag set with the proc rank(s)
        assert( pmit->first.procs[0] >= 0 );
        pstatus = PSTATUS_SHARED | PSTATUS_INTERFACE;
        if( pmit->first.procs[1] == -1 )
        {
            int other = pmit->first.procs[0];
            assert( other != (int)procConfig.proc_rank() );
            result = mbImpl->tag_set_data( sharedp_tag(), &new_set, 1, pmit->first.procs );MB_CHK_SET_ERR( result, "Failed to tag interface set with procs" );
            sharedh[0] = 0;
            result     = mbImpl->tag_set_data( sharedh_tag(), &new_set, 1, sharedh );MB_CHK_SET_ERR( result, "Failed to tag interface set with procs" );
            if( other < (int)proc_config().proc_rank() ) pstatus |= PSTATUS_NOT_OWNED;
        }
        else
        {
            result = mbImpl->tag_set_data( sharedps_tag(), &new_set, 1, pmit->first.procs );MB_CHK_SET_ERR( result, "Failed to tag interface set with procs" );
            result = mbImpl->tag_set_data( sharedhs_tag(), &new_set, 1, sharedh );MB_CHK_SET_ERR( result, "Failed to tag interface set with procs" );
            pstatus |= PSTATUS_MULTISHARED;
            if( pmit->first.procs[0] < (int)proc_config().proc_rank() ) pstatus |= PSTATUS_NOT_OWNED;
        }

        result = mbImpl->tag_set_data( pstatus_tag(), &new_set, 1, &pstatus );MB_CHK_SET_ERR( result, "Failed to tag interface set with pstatus" );

        // Set pstatus on all interface entities in set
        result = mbImpl->tag_clear_data( pstatus_tag(), pmit->second, &pstatus );MB_CHK_SET_ERR( result, "Failed to tag interface entities with pstatus" );
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::set_sharing_data( EntityHandle ent,
                                          unsigned char pstatus,
                                          int old_nump,
                                          int new_nump,
                                          int* ps,
                                          EntityHandle* hs )
{
    // If new nump is less than 3, the entity is no longer mutishared
    if( old_nump > 2 && ( pstatus & PSTATUS_MULTISHARED ) && new_nump < 3 )
    {
        // Unset multishared flag
        pstatus ^= PSTATUS_MULTISHARED;
    }

    // Check for consistency in input data
    // DBG
    /*  bool con1 = ((new_nump == 2 && pstatus&PSTATUS_SHARED && !(pstatus&PSTATUS_MULTISHARED)) ||
      (new_nump > 2 && pstatus&PSTATUS_SHARED && pstatus&PSTATUS_MULTISHARED)); bool con2 =
      (!(pstatus&PSTATUS_GHOST) || pstatus&PSTATUS_SHARED); bool con3 = (new_nump < 3 ||
      (pstatus&PSTATUS_NOT_OWNED && ps[0] != (int)rank()) || (!(pstatus&PSTATUS_NOT_OWNED) && ps[0]
      == (int)rank())); std::cout<<"current rank = "<<rank()<<std::endl; std::cout<<"condition
      1::"<<con1<<std::endl; std::cout<<"condition 2::"<<con2<<std::endl; std::cout<<"condition
      3::"<<con3<<std::endl;*/

    // DBG

    assert( new_nump > 1 &&
            ( ( new_nump == 2 && pstatus & PSTATUS_SHARED &&
                !( pstatus & PSTATUS_MULTISHARED ) ) ||  // If <= 2 must not be multishared
              ( new_nump > 2 && pstatus & PSTATUS_SHARED &&
                pstatus & PSTATUS_MULTISHARED ) ) &&                         // If > 2 procs, must be multishared
            ( !( pstatus & PSTATUS_GHOST ) || pstatus & PSTATUS_SHARED ) &&  // If ghost, it must also be shared
            ( new_nump < 3 ||
              ( pstatus & PSTATUS_NOT_OWNED && ps[0] != (int)rank() ) ||      // I'm not owner and first proc not me
              ( !( pstatus & PSTATUS_NOT_OWNED ) && ps[0] == (int)rank() ) )  // I'm owner and first proc is me
    );

#ifndef NDEBUG
    {
        // Check for duplicates in proc list
        std::set< unsigned int > dumprocs;
        int dp = 0;
        for( ; dp < old_nump && -1 != ps[dp]; dp++ )
            dumprocs.insert( ps[dp] );
        assert( dp == (int)dumprocs.size() );
    }
#endif

    ErrorCode result;
    // Reset any old data that needs to be
    if( old_nump > 2 && new_nump < 3 )
    {
        // Need to remove multishared tags
        result = mbImpl->tag_delete_data( sharedps_tag(), &ent, 1 );MB_CHK_SET_ERR( result, "set_sharing_data:1" );
        result = mbImpl->tag_delete_data( sharedhs_tag(), &ent, 1 );MB_CHK_SET_ERR( result, "set_sharing_data:2" );
        //    if (new_nump < 2)
        //      pstatus = 0x0;
        //    else if (ps[0] != (int)proc_config().proc_rank())
        //      pstatus |= PSTATUS_NOT_OWNED;
    }
    else if( ( old_nump < 3 && new_nump > 2 ) || ( old_nump > 1 && new_nump == 1 ) )
    {
        // Reset sharedp and sharedh tags
        int tmp_p          = -1;
        EntityHandle tmp_h = 0;
        result             = mbImpl->tag_set_data( sharedp_tag(), &ent, 1, &tmp_p );MB_CHK_SET_ERR( result, "set_sharing_data:3" );
        result = mbImpl->tag_set_data( sharedh_tag(), &ent, 1, &tmp_h );MB_CHK_SET_ERR( result, "set_sharing_data:4" );
    }

    assert( "check for multishared/owner I'm first proc" &&
            ( !( pstatus & PSTATUS_MULTISHARED ) || ( pstatus & ( PSTATUS_NOT_OWNED | PSTATUS_GHOST ) ) ||
              ( ps[0] == (int)rank() ) ) &&
            "interface entities should have > 1 proc" && ( !( pstatus & PSTATUS_INTERFACE ) || new_nump > 1 ) &&
            "ghost entities should have > 1 proc" && ( !( pstatus & PSTATUS_GHOST ) || new_nump > 1 ) );

    // Now set new data
    if( new_nump > 2 )
    {
        result = mbImpl->tag_set_data( sharedps_tag(), &ent, 1, ps );MB_CHK_SET_ERR( result, "set_sharing_data:5" );
        result = mbImpl->tag_set_data( sharedhs_tag(), &ent, 1, hs );MB_CHK_SET_ERR( result, "set_sharing_data:6" );
    }
    else
    {
        unsigned int j = ( ps[0] == (int)procConfig.proc_rank() ? 1 : 0 );
        assert( -1 != ps[j] );
        result = mbImpl->tag_set_data( sharedp_tag(), &ent, 1, ps + j );MB_CHK_SET_ERR( result, "set_sharing_data:7" );
        result = mbImpl->tag_set_data( sharedh_tag(), &ent, 1, hs + j );MB_CHK_SET_ERR( result, "set_sharing_data:8" );
    }

    result = mbImpl->tag_set_data( pstatus_tag(), &ent, 1, &pstatus );MB_CHK_SET_ERR( result, "set_sharing_data:9" );

    if( old_nump > 1 && new_nump < 2 ) sharedEnts.erase( ent );

    return result;
}

ErrorCode ParallelComm::get_sent_ents( const bool is_iface,
                                       const int bridge_dim,
                                       const int ghost_dim,
                                       const int num_layers,
                                       const int addl_ents,
                                       Range* sent_ents,
                                       Range& allsent,
                                       TupleList& entprocs )
{
    ErrorCode result;
    unsigned int ind;
    std::vector< unsigned int >::iterator proc_it;
    Range tmp_range;

    // Done in a separate loop over procs because sometimes later procs
    // need to add info to earlier procs' messages
    for( ind = 0, proc_it = buffProcs.begin(); proc_it != buffProcs.end(); ++proc_it, ind++ )
    {
        if( !is_iface )
        {
            result =
                get_ghosted_entities( bridge_dim, ghost_dim, buffProcs[ind], num_layers, addl_ents, sent_ents[ind] );MB_CHK_SET_ERR( result, "Failed to get ghost layers" );
        }
        else
        {
            result = get_iface_entities( buffProcs[ind], -1, sent_ents[ind] );MB_CHK_SET_ERR( result, "Failed to get interface layers" );
        }

        // Filter out entities already shared with destination
        tmp_range.clear();
        result = filter_pstatus( sent_ents[ind], PSTATUS_SHARED, PSTATUS_AND, buffProcs[ind], &tmp_range );MB_CHK_SET_ERR( result, "Failed to filter on owner" );
        if( !tmp_range.empty() ) sent_ents[ind] = subtract( sent_ents[ind], tmp_range );

        allsent.merge( sent_ents[ind] );
    }

    //===========================================
    // Need to get procs each entity is sent to
    //===========================================

    // Get the total # of proc/handle pairs
    int npairs = 0;
    for( ind = 0; ind < buffProcs.size(); ind++ )
        npairs += sent_ents[ind].size();

    // Allocate a TupleList of that size
    entprocs.initialize( 1, 0, 1, 0, npairs );
    entprocs.enableWriteAccess();

    // Put the proc/handle pairs in the list
    for( ind = 0, proc_it = buffProcs.begin(); proc_it != buffProcs.end(); ++proc_it, ind++ )
    {
        for( Range::iterator rit = sent_ents[ind].begin(); rit != sent_ents[ind].end(); ++rit )
        {
            entprocs.vi_wr[entprocs.get_n()]  = *proc_it;
            entprocs.vul_wr[entprocs.get_n()] = *rit;
            entprocs.inc_n();
        }
    }
    // Sort by handle
    moab::TupleList::buffer sort_buffer;
    sort_buffer.buffer_init( npairs );
    entprocs.sort( 1, &sort_buffer );

    entprocs.disableWriteAccess();
    sort_buffer.reset();

    return MB_SUCCESS;
}

ErrorCode ParallelComm::exchange_ghost_cells( ParallelComm** pcs,
                                              unsigned int num_procs,
                                              int ghost_dim,
                                              int bridge_dim,
                                              int num_layers,
                                              int addl_ents,
                                              bool store_remote_handles,
                                              EntityHandle* file_sets )
{
    // Static version of function, exchanging info through buffers rather
    // than through messages

    // If we're only finding out about existing ents, we have to be storing
    // remote handles too
    assert( num_layers > 0 || store_remote_handles );

    const bool is_iface = !num_layers;

    unsigned int ind;
    ParallelComm* pc;
    ErrorCode result = MB_SUCCESS;

    std::vector< Error* > ehs( num_procs );
    for( unsigned int i = 0; i < num_procs; i++ )
    {
        result = pcs[i]->get_moab()->query_interface( ehs[i] );
        assert( MB_SUCCESS == result );
    }

    // When this function is called, buffProcs should already have any
    // communicating procs

    //===========================================
    // Get entities to be sent to neighbors
    //===========================================

    // Done in a separate loop over procs because sometimes later procs
    // need to add info to earlier procs' messages
    Range sent_ents[MAX_SHARING_PROCS][MAX_SHARING_PROCS], allsent[MAX_SHARING_PROCS];

    //===========================================
    // Get entities to be sent to neighbors
    //===========================================
    TupleList entprocs[MAX_SHARING_PROCS];
    for( unsigned int p = 0; p < num_procs; p++ )
    {
        pc     = pcs[p];
        result = pc->get_sent_ents( is_iface, bridge_dim, ghost_dim, num_layers, addl_ents, sent_ents[p], allsent[p],
                                    entprocs[p] );MB_CHK_SET_ERR( result, "p = " << p << ", get_sent_ents failed" );

        //===========================================
        // Pack entities into buffers
        //===========================================
        for( ind = 0; ind < pc->buffProcs.size(); ind++ )
        {
            // Entities
            pc->localOwnedBuffs[ind]->reset_ptr( sizeof( int ) );
            result = pc->pack_entities( sent_ents[p][ind], pc->localOwnedBuffs[ind], store_remote_handles,
                                        pc->buffProcs[ind], is_iface, &entprocs[p], &allsent[p] );MB_CHK_SET_ERR( result, "p = " << p << ", packing entities failed" );
        }

        entprocs[p].reset();
    }

    //===========================================
    // Receive/unpack new entities
    //===========================================
    // Number of incoming messages for ghosts is the number of procs we
    // communicate with; for iface, it's the number of those with lower rank
    std::vector< std::vector< EntityHandle > > L1hloc[MAX_SHARING_PROCS], L1hrem[MAX_SHARING_PROCS];
    std::vector< std::vector< int > > L1p[MAX_SHARING_PROCS];
    std::vector< EntityHandle > L2hloc[MAX_SHARING_PROCS], L2hrem[MAX_SHARING_PROCS];
    std::vector< unsigned int > L2p[MAX_SHARING_PROCS];
    std::vector< EntityHandle > new_ents[MAX_SHARING_PROCS];

    for( unsigned int p = 0; p < num_procs; p++ )
    {
        L1hloc[p].resize( pcs[p]->buffProcs.size() );
        L1hrem[p].resize( pcs[p]->buffProcs.size() );
        L1p[p].resize( pcs[p]->buffProcs.size() );
    }

    for( unsigned int p = 0; p < num_procs; p++ )
    {
        pc = pcs[p];

        for( ind = 0; ind < pc->buffProcs.size(); ind++ )
        {
            // Incoming ghost entities; unpack; returns entities received
            // both from sending proc and from owning proc (which may be different)

            // Buffer could be empty, which means there isn't any message to
            // unpack (due to this comm proc getting added as a result of indirect
            // communication); just skip this unpack
            if( pc->localOwnedBuffs[ind]->get_stored_size() == 0 ) continue;

            unsigned int to_p = pc->buffProcs[ind];
            pc->localOwnedBuffs[ind]->reset_ptr( sizeof( int ) );
            result = pcs[to_p]->unpack_entities( pc->localOwnedBuffs[ind]->buff_ptr, store_remote_handles, ind,
                                                 is_iface, L1hloc[to_p], L1hrem[to_p], L1p[to_p], L2hloc[to_p],
                                                 L2hrem[to_p], L2p[to_p], new_ents[to_p] );MB_CHK_SET_ERR( result, "p = " << p << ", failed to unpack entities" );
        }
    }

    if( is_iface )
    {
        // Need to check over entities I sent and make sure I received
        // handles for them from all expected procs; if not, need to clean
        // them up
        for( unsigned int p = 0; p < num_procs; p++ )
        {
            result = pcs[p]->check_clean_iface( allsent[p] );MB_CHK_SET_ERR( result, "p = " << p << ", failed to check on shared entities" );
        }

#ifndef NDEBUG
        for( unsigned int p = 0; p < num_procs; p++ )
        {
            result = pcs[p]->check_sent_ents( allsent[p] );MB_CHK_SET_ERR( result, "p = " << p << ", failed to check on shared entities" );
        }
        result = check_all_shared_handles( pcs, num_procs );MB_CHK_SET_ERR( result, "Failed to check on all shared handles" );
#endif
        return MB_SUCCESS;
    }

    //===========================================
    // Send local handles for new ghosts to owner, then add
    // those to ghost list for that owner
    //===========================================
    std::vector< unsigned int >::iterator proc_it;
    for( unsigned int p = 0; p < num_procs; p++ )
    {
        pc = pcs[p];

        for( ind = 0, proc_it = pc->buffProcs.begin(); proc_it != pc->buffProcs.end(); ++proc_it, ind++ )
        {
            // Skip if iface layer and higher-rank proc
            pc->localOwnedBuffs[ind]->reset_ptr( sizeof( int ) );
            result = pc->pack_remote_handles( L1hloc[p][ind], L1hrem[p][ind], L1p[p][ind], *proc_it,
                                              pc->localOwnedBuffs[ind] );MB_CHK_SET_ERR( result, "p = " << p << ", failed to pack remote handles" );
        }
    }

    //===========================================
    // Process remote handles of my ghosteds
    //===========================================
    for( unsigned int p = 0; p < num_procs; p++ )
    {
        pc = pcs[p];

        for( ind = 0, proc_it = pc->buffProcs.begin(); proc_it != pc->buffProcs.end(); ++proc_it, ind++ )
        {
            // Incoming remote handles
            unsigned int to_p = pc->buffProcs[ind];
            pc->localOwnedBuffs[ind]->reset_ptr( sizeof( int ) );
            result = pcs[to_p]->unpack_remote_handles( p, pc->localOwnedBuffs[ind]->buff_ptr, L2hloc[to_p],
                                                       L2hrem[to_p], L2p[to_p] );MB_CHK_SET_ERR( result, "p = " << p << ", failed to unpack remote handles" );
        }
    }

#ifndef NDEBUG
    for( unsigned int p = 0; p < num_procs; p++ )
    {
        result = pcs[p]->check_sent_ents( allsent[p] );MB_CHK_SET_ERR( result, "p = " << p << ", failed to check on shared entities" );
    }

    result = ParallelComm::check_all_shared_handles( pcs, num_procs );MB_CHK_SET_ERR( result, "Failed to check on all shared handles" );
#endif

    if( file_sets )
    {
        for( unsigned int p = 0; p < num_procs; p++ )
        {
            if( new_ents[p].empty() ) continue;
            result = pcs[p]->get_moab()->add_entities( file_sets[p], &new_ents[p][0], new_ents[p].size() );MB_CHK_SET_ERR( result, "p = " << p << ", failed to add new entities to set" );
        }
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::post_irecv( std::vector< unsigned int >& exchange_procs )<--- The function 'post_irecv' is never used.
{
    // Set buffers
    int n_proc = exchange_procs.size();
    for( int i = 0; i < n_proc; i++ )
        get_buffers( exchange_procs[i] );
    reset_all_buffers();

    // Post ghost irecv's for entities from all communicating procs
    // Index requests the same as buffer/sharing procs indices
    int success;
    recvReqs.resize( 2 * buffProcs.size(), MPI_REQUEST_NULL );
    recvRemotehReqs.resize( 2 * buffProcs.size(), MPI_REQUEST_NULL );
    sendReqs.resize( 2 * buffProcs.size(), MPI_REQUEST_NULL );

    int incoming = 0;
    for( int i = 0; i < n_proc; i++ )
    {
        int ind = get_buffers( exchange_procs[i] );
        incoming++;
        PRINT_DEBUG_IRECV( procConfig.proc_rank(), buffProcs[ind], remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE,
                           MB_MESG_ENTS_SIZE, incoming );
        success = MPI_Irecv( remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE, MPI_UNSIGNED_CHAR, buffProcs[ind],
                             MB_MESG_ENTS_SIZE, procConfig.proc_comm(), &recvReqs[2 * ind] );
        if( success != MPI_SUCCESS )
        {
            MB_SET_ERR( MB_FAILURE, "Failed to post irecv in owned entity exchange" );
        }
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::post_irecv( std::vector< unsigned int >& shared_procs, std::set< unsigned int >& recv_procs )
{
    // Set buffers
    int num = shared_procs.size();
    for( int i = 0; i < num; i++ )
        get_buffers( shared_procs[i] );
    reset_all_buffers();
    num = remoteOwnedBuffs.size();
    for( int i = 0; i < num; i++ )
        remoteOwnedBuffs[i]->set_stored_size();
    num = localOwnedBuffs.size();
    for( int i = 0; i < num; i++ )
        localOwnedBuffs[i]->set_stored_size();

    // Post ghost irecv's for entities from all communicating procs
    // Index requests the same as buffer/sharing procs indices
    int success;
    recvReqs.resize( 2 * buffProcs.size(), MPI_REQUEST_NULL );
    recvRemotehReqs.resize( 2 * buffProcs.size(), MPI_REQUEST_NULL );
    sendReqs.resize( 2 * buffProcs.size(), MPI_REQUEST_NULL );

    int incoming                           = 0;
    std::set< unsigned int >::iterator it  = recv_procs.begin();
    std::set< unsigned int >::iterator eit = recv_procs.end();
    for( ; it != eit; ++it )
    {
        int ind = get_buffers( *it );
        incoming++;
        PRINT_DEBUG_IRECV( procConfig.proc_rank(), buffProcs[ind], remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE,
                           MB_MESG_ENTS_SIZE, incoming );
        success = MPI_Irecv( remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE, MPI_UNSIGNED_CHAR, buffProcs[ind],
                             MB_MESG_ENTS_SIZE, procConfig.proc_comm(), &recvReqs[2 * ind] );
        if( success != MPI_SUCCESS )
        {
            MB_SET_ERR( MB_FAILURE, "Failed to post irecv in owned entity exchange" );
        }
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::exchange_owned_meshs( std::vector< unsigned int >& exchange_procs,
                                              std::vector< Range* >& exchange_ents,
                                              std::vector< MPI_Request >& recv_ent_reqs,
                                              std::vector< MPI_Request >& recv_remoteh_reqs,
                                              bool store_remote_handles,
                                              bool wait_all,
                                              bool migrate,
                                              int dim )
{
    // Filter out entities already shared with destination
    // Exchange twice for entities and sets
    ErrorCode result;
    std::vector< unsigned int > exchange_procs_sets;
    std::vector< Range* > exchange_sets;
    int n_proc = exchange_procs.size();
    for( int i = 0; i < n_proc; i++ )
    {
        Range set_range   = exchange_ents[i]->subset_by_type( MBENTITYSET );
        *exchange_ents[i] = subtract( *exchange_ents[i], set_range );
        Range* tmp_range  = new Range( set_range );
        exchange_sets.push_back( tmp_range );
        exchange_procs_sets.push_back( exchange_procs[i] );
    }

    if( dim == 2 )
    {
        // Exchange entities first
        result = exchange_owned_mesh( exchange_procs, exchange_ents, recvReqs, recvRemotehReqs, true,
                                      store_remote_handles, wait_all, migrate );MB_CHK_SET_ERR( result, "Failed to exchange owned mesh entities" );

        // Exchange sets
        result = exchange_owned_mesh( exchange_procs_sets, exchange_sets, recvReqs, recvRemotehReqs, false,
                                      store_remote_handles, wait_all, migrate );
    }
    else
    {
        // Exchange entities first
        result = exchange_owned_mesh( exchange_procs, exchange_ents, recv_ent_reqs, recv_remoteh_reqs, false,
                                      store_remote_handles, wait_all, migrate );MB_CHK_SET_ERR( result, "Failed to exchange owned mesh entities" );

        // Exchange sets
        result = exchange_owned_mesh( exchange_procs_sets, exchange_sets, recv_ent_reqs, recv_remoteh_reqs, false,
                                      store_remote_handles, wait_all, migrate );MB_CHK_SET_ERR( result, "Failed to exchange owned mesh sets" );
    }

    for( int i = 0; i < n_proc; i++ )
        delete exchange_sets[i];

    // Build up the list of shared entities
    std::map< std::vector< int >, std::vector< EntityHandle > > proc_nvecs;
    int procs[MAX_SHARING_PROCS];
    EntityHandle handles[MAX_SHARING_PROCS];
    int nprocs;
    unsigned char pstat;
    for( std::set< EntityHandle >::iterator vit = sharedEnts.begin(); vit != sharedEnts.end(); ++vit )
    {
        if( mbImpl->dimension_from_handle( *vit ) > 2 ) continue;
        result = get_sharing_data( *vit, procs, handles, pstat, nprocs );MB_CHK_SET_ERR( result, "Failed to get sharing data in exchange_owned_meshs" );
        std::sort( procs, procs + nprocs );
        std::vector< int > tmp_procs( procs, procs + nprocs );
        assert( tmp_procs.size() != 2 );
        proc_nvecs[tmp_procs].push_back( *vit );
    }

    // Create interface sets from shared entities
    result = create_interface_sets( proc_nvecs );MB_CHK_SET_ERR( result, "Failed to create interface sets" );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::exchange_owned_mesh( std::vector< unsigned int >& exchange_procs,
                                             std::vector< Range* >& exchange_ents,
                                             std::vector< MPI_Request >& recv_ent_reqs,
                                             std::vector< MPI_Request >& recv_remoteh_reqs,
                                             const bool recv_posted,
                                             bool store_remote_handles,
                                             bool wait_all,
                                             bool migrate )
{
#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( OWNED_START, procConfig.proc_rank(), "Starting owned ents exchange." );
    }
#endif

    myDebug->tprintf( 1, "Entering exchange_owned_mesh\n" );
    if( myDebug->get_verbosity() == 4 )
    {
        msgs.clear();
        msgs.reserve( MAX_SHARING_PROCS );
    }
    unsigned int i;
    int ind, success;
    ErrorCode result = MB_SUCCESS;
    int incoming1 = 0, incoming2 = 0;

    // Set buffProcs with communicating procs
    unsigned int n_proc = exchange_procs.size();
    for( i = 0; i < n_proc; i++ )
    {
        ind    = get_buffers( exchange_procs[i] );
        result = add_verts( *exchange_ents[i] );MB_CHK_SET_ERR( result, "Failed to add verts" );

        // Filter out entities already shared with destination
        Range tmp_range;
        result = filter_pstatus( *exchange_ents[i], PSTATUS_SHARED, PSTATUS_AND, buffProcs[ind], &tmp_range );MB_CHK_SET_ERR( result, "Failed to filter on owner" );
        if( !tmp_range.empty() )
        {
            *exchange_ents[i] = subtract( *exchange_ents[i], tmp_range );
        }
    }

    //===========================================
    // Post ghost irecv's for entities from all communicating procs
    //===========================================
#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( ENTITIES_START, procConfig.proc_rank(), "Starting entity exchange." );
    }
#endif

    // Index reqs the same as buffer/sharing procs indices
    if( !recv_posted )
    {
        reset_all_buffers();
        recv_ent_reqs.resize( 3 * buffProcs.size(), MPI_REQUEST_NULL );
        recv_remoteh_reqs.resize( 3 * buffProcs.size(), MPI_REQUEST_NULL );
        sendReqs.resize( 3 * buffProcs.size(), MPI_REQUEST_NULL );

        for( i = 0; i < n_proc; i++ )
        {
            ind = get_buffers( exchange_procs[i] );
            incoming1++;
            PRINT_DEBUG_IRECV( procConfig.proc_rank(), buffProcs[ind], remoteOwnedBuffs[ind]->mem_ptr,
                               INITIAL_BUFF_SIZE, MB_MESG_ENTS_SIZE, incoming1 );
            success = MPI_Irecv( remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE, MPI_UNSIGNED_CHAR, buffProcs[ind],
                                 MB_MESG_ENTS_SIZE, procConfig.proc_comm(), &recv_ent_reqs[3 * ind] );
            if( success != MPI_SUCCESS )
            {
                MB_SET_ERR( MB_FAILURE, "Failed to post irecv in owned entity exchange" );
            }
        }
    }
    else
        incoming1 += n_proc;

    //===========================================
    // Get entities to be sent to neighbors
    // Need to get procs each entity is sent to
    //===========================================
    Range allsent, tmp_range;
    int dum_ack_buff;
    int npairs = 0;
    TupleList entprocs;
    for( i = 0; i < n_proc; i++ )
    {
        int n_ents = exchange_ents[i]->size();
        if( n_ents > 0 )
        {
            npairs += n_ents;  // Get the total # of proc/handle pairs
            allsent.merge( *exchange_ents[i] );
        }
    }

    // Allocate a TupleList of that size
    entprocs.initialize( 1, 0, 1, 0, npairs );
    entprocs.enableWriteAccess();

    // Put the proc/handle pairs in the list
    for( i = 0; i < n_proc; i++ )
    {
        for( Range::iterator rit = exchange_ents[i]->begin(); rit != exchange_ents[i]->end(); ++rit )
        {
            entprocs.vi_wr[entprocs.get_n()]  = exchange_procs[i];
            entprocs.vul_wr[entprocs.get_n()] = *rit;
            entprocs.inc_n();
        }
    }

    // Sort by handle
    moab::TupleList::buffer sort_buffer;
    sort_buffer.buffer_init( npairs );
    entprocs.sort( 1, &sort_buffer );
    sort_buffer.reset();

    myDebug->tprintf( 1, "allsent ents compactness (size) = %f (%lu)\n", allsent.compactness(),
                      (unsigned long)allsent.size() );

    //===========================================
    // Pack and send ents from this proc to others
    //===========================================
    for( i = 0; i < n_proc; i++ )
    {
        ind = get_buffers( exchange_procs[i] );
        myDebug->tprintf( 1, "Sent ents compactness (size) = %f (%lu)\n", exchange_ents[i]->compactness(),
                          (unsigned long)exchange_ents[i]->size() );
        // Reserve space on front for size and for initial buff size
        localOwnedBuffs[ind]->reset_buffer( sizeof( int ) );
        result = pack_buffer( *exchange_ents[i], false, true, store_remote_handles, buffProcs[ind],<--- result is assigned
                              localOwnedBuffs[ind], &entprocs, &allsent );

        if( myDebug->get_verbosity() == 4 )
        {
            msgs.resize( msgs.size() + 1 );
            msgs.back() = new Buffer( *localOwnedBuffs[ind] );
        }

        // Send the buffer (size stored in front in send_buffer)
        result = send_buffer( exchange_procs[i], localOwnedBuffs[ind], MB_MESG_ENTS_SIZE, sendReqs[3 * ind],<--- result is overwritten
                              recv_ent_reqs[3 * ind + 2], &dum_ack_buff, incoming1, MB_MESG_REMOTEH_SIZE,
                              ( store_remote_handles ? localOwnedBuffs[ind] : NULL ), &recv_remoteh_reqs[3 * ind],
                              &incoming2 );MB_CHK_SET_ERR( result, "Failed to Isend in ghost exchange" );
    }

    entprocs.reset();

    //===========================================
    // Receive/unpack new entities
    //===========================================
    // Number of incoming messages is the number of procs we communicate with
    MPI_Status status;
    std::vector< std::vector< EntityHandle > > recd_ents( buffProcs.size() );<--- Variable 'recd_ents' is assigned a value that is never used.
    std::vector< std::vector< EntityHandle > > L1hloc( buffProcs.size() ), L1hrem( buffProcs.size() );
    std::vector< std::vector< int > > L1p( buffProcs.size() );
    std::vector< EntityHandle > L2hloc, L2hrem;
    std::vector< unsigned int > L2p;
    std::vector< EntityHandle > new_ents;

    while( incoming1 )
    {
        // Wait for all recvs of ents before proceeding to sending remote handles,
        // b/c some procs may have sent to a 3rd proc ents owned by me;
        PRINT_DEBUG_WAITANY( recv_ent_reqs, MB_MESG_ENTS_SIZE, procConfig.proc_rank() );

        success = MPI_Waitany( 3 * buffProcs.size(), &recv_ent_reqs[0], &ind, &status );
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "Failed in waitany in owned entity exchange" );
        }

        PRINT_DEBUG_RECD( status );

        // OK, received something; decrement incoming counter
        incoming1--;
        bool done = false;

        // In case ind is for ack, we need index of one before it
        unsigned int base_ind = 3 * ( ind / 3 );
        result = recv_buffer( MB_MESG_ENTS_SIZE, status, remoteOwnedBuffs[ind / 3], recv_ent_reqs[base_ind + 1],
                              recv_ent_reqs[base_ind + 2], incoming1, localOwnedBuffs[ind / 3], sendReqs[base_ind + 1],
                              sendReqs[base_ind + 2], done, ( store_remote_handles ? localOwnedBuffs[ind / 3] : NULL ),
                              MB_MESG_REMOTEH_SIZE, &recv_remoteh_reqs[base_ind + 1], &incoming2 );MB_CHK_SET_ERR( result, "Failed to receive buffer" );

        if( done )
        {
            if( myDebug->get_verbosity() == 4 )
            {
                msgs.resize( msgs.size() + 1 );
                msgs.back() = new Buffer( *remoteOwnedBuffs[ind / 3] );
            }

            // Message completely received - process buffer that was sent
            remoteOwnedBuffs[ind / 3]->reset_ptr( sizeof( int ) );
            result = unpack_buffer( remoteOwnedBuffs[ind / 3]->buff_ptr, store_remote_handles, buffProcs[ind / 3],
                                    ind / 3, L1hloc, L1hrem, L1p, L2hloc, L2hrem, L2p, new_ents, true );
            if( MB_SUCCESS != result )
            {
                std::cout << "Failed to unpack entities. Buffer contents:" << std::endl;
                print_buffer( remoteOwnedBuffs[ind / 3]->mem_ptr, MB_MESG_ENTS_SIZE, buffProcs[ind / 3], false );
                return result;
            }

            if( recv_ent_reqs.size() != 3 * buffProcs.size() )
            {
                // Post irecv's for remote handles from new proc
                recv_remoteh_reqs.resize( 3 * buffProcs.size(), MPI_REQUEST_NULL );
                for( i = recv_ent_reqs.size(); i < 3 * buffProcs.size(); i += 3 )
                {
                    localOwnedBuffs[i / 3]->reset_buffer();
                    incoming2++;
                    PRINT_DEBUG_IRECV( procConfig.proc_rank(), buffProcs[i / 3], localOwnedBuffs[i / 3]->mem_ptr,
                                       INITIAL_BUFF_SIZE, MB_MESG_REMOTEH_SIZE, incoming2 );
                    success = MPI_Irecv( localOwnedBuffs[i / 3]->mem_ptr, INITIAL_BUFF_SIZE, MPI_UNSIGNED_CHAR,
                                         buffProcs[i / 3], MB_MESG_REMOTEH_SIZE, procConfig.proc_comm(),
                                         &recv_remoteh_reqs[i] );
                    if( success != MPI_SUCCESS )
                    {
                        MB_SET_ERR( MB_FAILURE, "Failed to post irecv for remote handles in ghost exchange" );
                    }
                }
                recv_ent_reqs.resize( 3 * buffProcs.size(), MPI_REQUEST_NULL );
                sendReqs.resize( 3 * buffProcs.size(), MPI_REQUEST_NULL );
            }
        }
    }

    // Assign and remove newly created elements from/to receive processor
    result = assign_entities_part( new_ents, procConfig.proc_rank() );MB_CHK_SET_ERR( result, "Failed to assign entities to part" );
    if( migrate )
    {
        result = remove_entities_part( allsent, procConfig.proc_rank() );MB_CHK_SET_ERR( result, "Failed to remove entities to part" );
    }

    // Add requests for any new addl procs
    if( recv_ent_reqs.size() != 3 * buffProcs.size() )
    {
        // Shouldn't get here...
        MB_SET_ERR( MB_FAILURE, "Requests length doesn't match proc count in entity exchange" );
    }

#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( ENTITIES_END, procConfig.proc_rank(), "Ending entity exchange." );
    }
#endif

    // we still need to wait on sendReqs, if they are not fulfilled yet
    if( wait_all )
    {
        if( myDebug->get_verbosity() == 5 )
        {
            success = MPI_Barrier( procConfig.proc_comm() );<--- Variable 'success' is assigned a value that is never used.
        }
        else
        {
            MPI_Status mult_status[3 * MAX_SHARING_PROCS];
            success = MPI_Waitall( 3 * buffProcs.size(), &sendReqs[0], mult_status );
            if( MPI_SUCCESS != success )
            {
                MB_SET_ERR( MB_FAILURE, "Failed in waitall in exchange owned mesh" );
            }
        }
    }

    //===========================================
    // Send local handles for new entity to owner
    //===========================================
    for( i = 0; i < n_proc; i++ )
    {
        ind = get_buffers( exchange_procs[i] );
        // Reserve space on front for size and for initial buff size
        remoteOwnedBuffs[ind]->reset_buffer( sizeof( int ) );

        result = pack_remote_handles( L1hloc[ind], L1hrem[ind], L1p[ind], buffProcs[ind], remoteOwnedBuffs[ind] );MB_CHK_SET_ERR( result, "Failed to pack remote handles" );
        remoteOwnedBuffs[ind]->set_stored_size();

        if( myDebug->get_verbosity() == 4 )
        {
            msgs.resize( msgs.size() + 1 );
            msgs.back() = new Buffer( *remoteOwnedBuffs[ind] );
        }
        result = send_buffer( buffProcs[ind], remoteOwnedBuffs[ind], MB_MESG_REMOTEH_SIZE, sendReqs[3 * ind],
                              recv_remoteh_reqs[3 * ind + 2], &dum_ack_buff, incoming2 );MB_CHK_SET_ERR( result, "Failed to send remote handles" );
    }

    //===========================================
    // Process remote handles of my ghosteds
    //===========================================
    while( incoming2 )
    {
        PRINT_DEBUG_WAITANY( recv_remoteh_reqs, MB_MESG_REMOTEH_SIZE, procConfig.proc_rank() );
        success = MPI_Waitany( 3 * buffProcs.size(), &recv_remoteh_reqs[0], &ind, &status );
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "Failed in waitany in owned entity exchange" );
        }

        // OK, received something; decrement incoming counter
        incoming2--;

        PRINT_DEBUG_RECD( status );

        bool done             = false;
        unsigned int base_ind = 3 * ( ind / 3 );
        result = recv_buffer( MB_MESG_REMOTEH_SIZE, status, localOwnedBuffs[ind / 3], recv_remoteh_reqs[base_ind + 1],
                              recv_remoteh_reqs[base_ind + 2], incoming2, remoteOwnedBuffs[ind / 3],
                              sendReqs[base_ind + 1], sendReqs[base_ind + 2], done );MB_CHK_SET_ERR( result, "Failed to receive remote handles" );

        if( done )
        {
            // Incoming remote handles
            if( myDebug->get_verbosity() == 4 )
            {
                msgs.resize( msgs.size() + 1 );
                msgs.back() = new Buffer( *localOwnedBuffs[ind / 3] );
            }

            localOwnedBuffs[ind / 3]->reset_ptr( sizeof( int ) );
            result =
                unpack_remote_handles( buffProcs[ind / 3], localOwnedBuffs[ind / 3]->buff_ptr, L2hloc, L2hrem, L2p );MB_CHK_SET_ERR( result, "Failed to unpack remote handles" );
        }
    }

#ifdef MOAB_HAVE_MPE
    if( myDebug->get_verbosity() == 2 )
    {
        MPE_Log_event( RHANDLES_END, procConfig.proc_rank(), "Ending remote handles." );
        MPE_Log_event( OWNED_END, procConfig.proc_rank(), "Ending ghost exchange (still doing checks)." );
    }
#endif

    //===========================================
    // Wait if requested
    //===========================================
    if( wait_all )
    {
        if( myDebug->get_verbosity() == 5 )
        {
            success = MPI_Barrier( procConfig.proc_comm() );
        }
        else
        {
            MPI_Status mult_status[3 * MAX_SHARING_PROCS];
            success = MPI_Waitall( 3 * buffProcs.size(), &recv_remoteh_reqs[0], mult_status );
            if( MPI_SUCCESS == success ) success = MPI_Waitall( 3 * buffProcs.size(), &sendReqs[0], mult_status );
        }
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "Failed in waitall in owned entity exchange" );
        }
    }

#ifndef NDEBUG
    result = check_sent_ents( allsent );MB_CHK_SET_ERR( result, "Failed check on shared entities" );
#endif
    myDebug->tprintf( 1, "Exiting exchange_owned_mesh\n" );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_iface_entities( int other_proc, int dim, Range& iface_ents )
{
    Range iface_sets;
    ErrorCode result = MB_SUCCESS;

    for( Range::iterator rit = interfaceSets.begin(); rit != interfaceSets.end(); ++rit )
    {
        if( -1 != other_proc && !is_iface_proc( *rit, other_proc ) ) continue;

        if( -1 == dim )
        {
            result = mbImpl->get_entities_by_handle( *rit, iface_ents );MB_CHK_SET_ERR( result, "Failed to get entities in iface set" );
        }
        else
        {
            result = mbImpl->get_entities_by_dimension( *rit, dim, iface_ents );MB_CHK_SET_ERR( result, "Failed to get entities in iface set" );
        }
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::assign_entities_part( std::vector< EntityHandle >& entities, const int proc )
{
    EntityHandle part_set;
    ErrorCode result = get_part_handle( proc, part_set );MB_CHK_SET_ERR( result, "Failed to get part handle" );

    if( part_set > 0 )
    {
        result = mbImpl->add_entities( part_set, &entities[0], entities.size() );MB_CHK_SET_ERR( result, "Failed to add entities to part set" );
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::remove_entities_part( Range& entities, const int proc )
{
    EntityHandle part_set;
    ErrorCode result = get_part_handle( proc, part_set );MB_CHK_SET_ERR( result, "Failed to get part handle" );

    if( part_set > 0 )
    {
        result = mbImpl->remove_entities( part_set, entities );MB_CHK_SET_ERR( result, "Failed to remove entities from part set" );
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::check_sent_ents( Range& allsent )
{
    // Check entities to make sure there are no zero-valued remote handles
    // where they shouldn't be
    std::vector< unsigned char > pstat( allsent.size() );
    ErrorCode result = mbImpl->tag_get_data( pstatus_tag(), allsent, &pstat[0] );MB_CHK_SET_ERR( result, "Failed to get pstatus tag data" );
    std::vector< EntityHandle > handles( allsent.size() );
    result = mbImpl->tag_get_data( sharedh_tag(), allsent, &handles[0] );MB_CHK_SET_ERR( result, "Failed to get sharedh tag data" );
    std::vector< int > procs( allsent.size() );
    result = mbImpl->tag_get_data( sharedp_tag(), allsent, &procs[0] );MB_CHK_SET_ERR( result, "Failed to get sharedp tag data" );

    Range bad_entities;

    Range::iterator rit;
    unsigned int i;
    EntityHandle dum_hs[MAX_SHARING_PROCS];
    int dum_ps[MAX_SHARING_PROCS];

    for( rit = allsent.begin(), i = 0; rit != allsent.end(); ++rit, i++ )
    {
        if( -1 != procs[i] && 0 == handles[i] )
            bad_entities.insert( *rit );
        else
        {
            // Might be multi-shared...
            result = mbImpl->tag_get_data( sharedps_tag(), &( *rit ), 1, dum_ps );
            if( MB_TAG_NOT_FOUND == result )
                continue;
            else if( MB_SUCCESS != result )
                MB_SET_ERR( result, "Failed to get sharedps tag data" );
            result = mbImpl->tag_get_data( sharedhs_tag(), &( *rit ), 1, dum_hs );MB_CHK_SET_ERR( result, "Failed to get sharedhs tag data" );

            // Find first non-set proc
            int* ns_proc  = std::find( dum_ps, dum_ps + MAX_SHARING_PROCS, -1 );
            int num_procs = ns_proc - dum_ps;
            assert( num_procs <= MAX_SHARING_PROCS );
            // Now look for zero handles in active part of dum_hs
            EntityHandle* ns_handle = std::find( dum_hs, dum_hs + num_procs, 0 );
            int num_handles         = ns_handle - dum_hs;
            assert( num_handles <= num_procs );
            if( num_handles != num_procs ) bad_entities.insert( *rit );
        }
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::pack_remote_handles( std::vector< EntityHandle >& L1hloc,
                                             std::vector< EntityHandle >& L1hrem,
                                             std::vector< int >& L1p,
                                             unsigned int /*to_proc*/,
                                             Buffer* buff )
{
    assert( std::find( L1hloc.begin(), L1hloc.end(), (EntityHandle)0 ) == L1hloc.end() );

    // 2 vectors of handles plus ints
    buff->check_space( ( ( L1p.size() + 1 ) * sizeof( int ) + ( L1hloc.size() + 1 ) * sizeof( EntityHandle ) +
                         ( L1hrem.size() + 1 ) * sizeof( EntityHandle ) ) );

    // Should be in pairs of handles
    PACK_INT( buff->buff_ptr, L1hloc.size() );
    PACK_INTS( buff->buff_ptr, &L1p[0], L1p.size() );
    // Pack handles in reverse order, (remote, local), so on destination they
    // are ordered (local, remote)
    PACK_EH( buff->buff_ptr, &L1hrem[0], L1hrem.size() );
    PACK_EH( buff->buff_ptr, &L1hloc[0], L1hloc.size() );

    buff->set_stored_size();

    return MB_SUCCESS;
}

ErrorCode ParallelComm::unpack_remote_handles( unsigned int from_proc,
                                               unsigned char*& buff_ptr,
                                               std::vector< EntityHandle >& L2hloc,
                                               std::vector< EntityHandle >& L2hrem,
                                               std::vector< unsigned int >& L2p )
{
    // Incoming remote handles; use to set remote handles
    int num_eh;
    UNPACK_INT( buff_ptr, num_eh );

    unsigned char* buff_proc = buff_ptr;
    buff_ptr += num_eh * sizeof( int );
    unsigned char* buff_rem = buff_ptr + num_eh * sizeof( EntityHandle );
    ErrorCode result;
    EntityHandle hpair[2], new_h;
    int proc;
    for( int i = 0; i < num_eh; i++ )
    {
        UNPACK_INT( buff_proc, proc );
        // Handles packed (local, remote), though here local is either on this
        // proc or owner proc, depending on value of proc (-1 = here, otherwise owner);
        // this is decoded in find_existing_entity
        UNPACK_EH( buff_ptr, hpair, 1 );
        UNPACK_EH( buff_rem, hpair + 1, 1 );

        if( -1 != proc )
        {
            result = find_existing_entity( false, proc, hpair[0], 3, NULL, 0, mbImpl->type_from_handle( hpair[1] ),
                                           L2hloc, L2hrem, L2p, new_h );MB_CHK_SET_ERR( result, "Didn't get existing entity" );
            if( new_h )
                hpair[0] = new_h;
            else
                hpair[0] = 0;
        }
        if( !( hpair[0] && hpair[1] ) ) return MB_FAILURE;
        int this_proc = from_proc;
        result        = update_remote_data( hpair[0], &this_proc, hpair + 1, 1, 0 );MB_CHK_SET_ERR( result, "Failed to set remote data range on sent entities in ghost exchange" );
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_ghosted_entities( int bridge_dim,
                                              int ghost_dim,
                                              int to_proc,
                                              int num_layers,
                                              int addl_ents,
                                              Range& ghosted_ents )
{
    // Get bridge ents on interface(s)
    Range from_ents;
    ErrorCode result = MB_SUCCESS;
    assert( 0 < num_layers );
    for( Range::iterator rit = interfaceSets.begin(); rit != interfaceSets.end(); ++rit )
    {
        if( !is_iface_proc( *rit, to_proc ) ) continue;

        // Get starting "from" entities
        if( bridge_dim == -1 )
        {
            result = mbImpl->get_entities_by_handle( *rit, from_ents );MB_CHK_SET_ERR( result, "Failed to get bridge ents in the set" );
        }
        else
        {
            result = mbImpl->get_entities_by_dimension( *rit, bridge_dim, from_ents );MB_CHK_SET_ERR( result, "Failed to get bridge ents in the set" );
        }

        // Need to get layers of bridge-adj entities
        if( from_ents.empty() ) continue;
        result =
            MeshTopoUtil( mbImpl ).get_bridge_adjacencies( from_ents, bridge_dim, ghost_dim, ghosted_ents, num_layers );MB_CHK_SET_ERR( result, "Failed to get bridge adjacencies" );
    }

    result = add_verts( ghosted_ents );MB_CHK_SET_ERR( result, "Failed to add verts" );

    if( addl_ents )
    {
        // First get the ents of ghost_dim
        Range tmp_ents, tmp_owned, tmp_notowned;
        tmp_owned = ghosted_ents.subset_by_dimension( ghost_dim );
        if( tmp_owned.empty() ) return result;

        tmp_notowned = tmp_owned;

        // Next, filter by pstatus; can only create adj entities for entities I own
        result = filter_pstatus( tmp_owned, PSTATUS_NOT_OWNED, PSTATUS_NOT, -1, &tmp_owned );MB_CHK_SET_ERR( result, "Failed to filter owned entities" );

        tmp_notowned -= tmp_owned;

        // Get edges first
        if( 1 == addl_ents || 3 == addl_ents )
        {
            result = mbImpl->get_adjacencies( tmp_owned, 1, true, tmp_ents, Interface::UNION );MB_CHK_SET_ERR( result, "Failed to get edge adjacencies for owned ghost entities" );
            result = mbImpl->get_adjacencies( tmp_notowned, 1, false, tmp_ents, Interface::UNION );MB_CHK_SET_ERR( result, "Failed to get edge adjacencies for notowned ghost entities" );
        }
        if( 2 == addl_ents || 3 == addl_ents )
        {
            result = mbImpl->get_adjacencies( tmp_owned, 2, true, tmp_ents, Interface::UNION );MB_CHK_SET_ERR( result, "Failed to get face adjacencies for owned ghost entities" );
            result = mbImpl->get_adjacencies( tmp_notowned, 2, false, tmp_ents, Interface::UNION );MB_CHK_SET_ERR( result, "Failed to get face adjacencies for notowned ghost entities" );
        }

        ghosted_ents.merge( tmp_ents );
    }

    return result;
}

ErrorCode ParallelComm::add_verts( Range& sent_ents )
{
    // Get the verts adj to these entities, since we'll have to send those too

    // First check sets
    std::pair< Range::const_iterator, Range::const_iterator > set_range = sent_ents.equal_range( MBENTITYSET );
    ErrorCode result                                                    = MB_SUCCESS, tmp_result;
    for( Range::const_iterator rit = set_range.first; rit != set_range.second; ++rit )
    {
        tmp_result = mbImpl->get_entities_by_type( *rit, MBVERTEX, sent_ents );MB_CHK_SET_ERR( tmp_result, "Failed to get contained verts" );
    }

    // Now non-sets
    Range tmp_ents;
    std::copy( sent_ents.begin(), set_range.first, range_inserter( tmp_ents ) );
    result = mbImpl->get_adjacencies( tmp_ents, 0, false, sent_ents, Interface::UNION );MB_CHK_SET_ERR( result, "Failed to get vertices adj to ghosted ents" );

    // if polyhedra, need to add all faces from there
    Range polyhedra = sent_ents.subset_by_type( MBPOLYHEDRON );
    // get all faces adjacent to every polyhedra
    result = mbImpl->get_connectivity( polyhedra, sent_ents );MB_CHK_SET_ERR( result, "Failed to get polyhedra faces" );
    return result;
}

ErrorCode ParallelComm::exchange_tags( const std::vector< Tag >& src_tags,
                                       const std::vector< Tag >& dst_tags,
                                       const Range& entities_in )
{
    ErrorCode result;
    int success;

    myDebug->tprintf( 1, "Entering exchange_tags\n" );

    // Get all procs interfacing to this proc
    std::set< unsigned int > exch_procs;
    result = get_comm_procs( exch_procs );<--- Variable 'result' is assigned a value that is never used.

    // Post ghost irecv's for all interface procs
    // Index requests the same as buffer/sharing procs indices
    std::vector< MPI_Request > recv_tag_reqs( 3 * buffProcs.size(), MPI_REQUEST_NULL );
    // sent_ack_reqs(buffProcs.size(), MPI_REQUEST_NULL);
    std::vector< unsigned int >::iterator sit;
    int ind;

    reset_all_buffers();
    int incoming = 0;

    for( ind = 0, sit = buffProcs.begin(); sit != buffProcs.end(); ++sit, ind++ )
    {
        incoming++;
        PRINT_DEBUG_IRECV( *sit, procConfig.proc_rank(), remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE,
                           MB_MESG_TAGS_SIZE, incoming );

        success = MPI_Irecv( remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE, MPI_UNSIGNED_CHAR, *sit,
                             MB_MESG_TAGS_SIZE, procConfig.proc_comm(), &recv_tag_reqs[3 * ind] );
        if( success != MPI_SUCCESS )
        {
            MB_SET_ERR( MB_FAILURE, "Failed to post irecv in ghost exchange" );
        }
    }

    // Pack and send tags from this proc to others
    // Make sendReqs vector to simplify initialization
    sendReqs.resize( 3 * buffProcs.size(), MPI_REQUEST_NULL );

    // Take all shared entities if incoming list is empty
    Range entities;
    if( entities_in.empty() )
        std::copy( sharedEnts.begin(), sharedEnts.end(), range_inserter( entities ) );
    else
        entities = entities_in;

    int dum_ack_buff;

    for( ind = 0, sit = buffProcs.begin(); sit != buffProcs.end(); ++sit, ind++ )
    {
        Range tag_ents = entities;

        // Get ents shared by proc *sit
        result = filter_pstatus( tag_ents, PSTATUS_SHARED, PSTATUS_AND, *sit );MB_CHK_SET_ERR( result, "Failed pstatus AND check" );

        // Remote nonowned entities
        if( !tag_ents.empty() )
        {
            result = filter_pstatus( tag_ents, PSTATUS_NOT_OWNED, PSTATUS_NOT );MB_CHK_SET_ERR( result, "Failed pstatus NOT check" );
        }

        // Pack-send; this also posts receives if store_remote_handles is true
        std::vector< Range > tag_ranges;
        for( std::vector< Tag >::const_iterator vit = src_tags.begin(); vit != src_tags.end(); ++vit )
        {
            const void* ptr;
            int sz;
            if( mbImpl->tag_get_default_value( *vit, ptr, sz ) != MB_SUCCESS )
            {
                Range tagged_ents;
                mbImpl->get_entities_by_type_and_tag( 0, MBMAXTYPE, &*vit, 0, 1, tagged_ents );
                tag_ranges.push_back( intersect( tag_ents, tagged_ents ) );
            }
            else
            {
                tag_ranges.push_back( tag_ents );
            }
        }

        // Pack the data
        // Reserve space on front for size and for initial buff size
        localOwnedBuffs[ind]->reset_ptr( sizeof( int ) );

        result = pack_tags( tag_ents, src_tags, dst_tags, tag_ranges, localOwnedBuffs[ind], true, *sit );MB_CHK_SET_ERR( result, "Failed to count buffer in pack_send_tag" );

        // Now send it
        result = send_buffer( *sit, localOwnedBuffs[ind], MB_MESG_TAGS_SIZE, sendReqs[3 * ind],
                              recv_tag_reqs[3 * ind + 2], &dum_ack_buff, incoming );MB_CHK_SET_ERR( result, "Failed to send buffer" );
    }

    // Receive/unpack tags
    while( incoming )
    {
        MPI_Status status;
        int index_in_recv_requests;
        PRINT_DEBUG_WAITANY( recv_tag_reqs, MB_MESG_TAGS_SIZE, procConfig.proc_rank() );
        success = MPI_Waitany( 3 * buffProcs.size(), &recv_tag_reqs[0], &index_in_recv_requests, &status );
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "Failed in waitany in tag exchange" );
        }
        // Processor index in the list is divided by 3
        ind = index_in_recv_requests / 3;

        PRINT_DEBUG_RECD( status );

        // OK, received something; decrement incoming counter
        incoming--;

        bool done = false;
        std::vector< EntityHandle > dum_vec;
        result = recv_buffer( MB_MESG_TAGS_SIZE, status, remoteOwnedBuffs[ind],
                              recv_tag_reqs[3 * ind + 1],  // This is for receiving the second message
                              recv_tag_reqs[3 * ind + 2],  // This would be for ack, but it is not
                                                           // used; consider removing it
                              incoming, localOwnedBuffs[ind],
                              sendReqs[3 * ind + 1],  // Send request for sending the second message
                              sendReqs[3 * ind + 2],  // This is for sending the ack
                              done );MB_CHK_SET_ERR( result, "Failed to resize recv buffer" );
        if( done )
        {
            remoteOwnedBuffs[ind]->reset_ptr( sizeof( int ) );
            result = unpack_tags( remoteOwnedBuffs[ind]->buff_ptr, dum_vec, true, buffProcs[ind] );MB_CHK_SET_ERR( result, "Failed to recv-unpack-tag message" );
        }
    }

    // OK, now wait
    if( myDebug->get_verbosity() == 5 )
    {
        success = MPI_Barrier( procConfig.proc_comm() );
    }
    else
    {
        MPI_Status status[3 * MAX_SHARING_PROCS];
        success = MPI_Waitall( 3 * buffProcs.size(), &sendReqs[0], status );
    }
    if( MPI_SUCCESS != success )
    {
        MB_SET_ERR( MB_FAILURE, "Failure in waitall in tag exchange" );
    }

    // If source tag is not equal to destination tag, then
    // do local copy for owned entities (communicate w/ self)
    assert( src_tags.size() == dst_tags.size() );
    if( src_tags != dst_tags )
    {
        std::vector< unsigned char > data;
        Range owned_ents;
        if( entities_in.empty() )
            std::copy( sharedEnts.begin(), sharedEnts.end(), range_inserter( entities ) );
        else
            owned_ents = entities_in;
        result = filter_pstatus( owned_ents, PSTATUS_NOT_OWNED, PSTATUS_NOT );MB_CHK_SET_ERR( result, "Failure to get subset of owned entities" );

        if( !owned_ents.empty() )
        {  // Check this here, otherwise we get
            // Unexpected results from get_entities_by_type_and_tag w/ Interface::INTERSECT
            for( size_t i = 0; i < src_tags.size(); i++ )
            {
                if( src_tags[i] == dst_tags[i] ) continue;

                Range tagged_ents( owned_ents );
                result = mbImpl->get_entities_by_type_and_tag( 0, MBMAXTYPE, &src_tags[0], 0, 1, tagged_ents,
                                                               Interface::INTERSECT );MB_CHK_SET_ERR( result, "get_entities_by_type_and_tag(type == MBMAXTYPE) failed" );

                int sz, size2;
                result = mbImpl->tag_get_bytes( src_tags[i], sz );MB_CHK_SET_ERR( result, "tag_get_size failed" );
                result = mbImpl->tag_get_bytes( dst_tags[i], size2 );MB_CHK_SET_ERR( result, "tag_get_size failed" );
                if( sz != size2 )
                {
                    MB_SET_ERR( MB_FAILURE, "tag sizes don't match" );
                }

                data.resize( sz * tagged_ents.size() );
                result = mbImpl->tag_get_data( src_tags[i], tagged_ents, &data[0] );MB_CHK_SET_ERR( result, "tag_get_data failed" );
                result = mbImpl->tag_set_data( dst_tags[i], tagged_ents, &data[0] );MB_CHK_SET_ERR( result, "tag_set_data failed" );
            }
        }
    }

    myDebug->tprintf( 1, "Exiting exchange_tags" );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::reduce_tags( const std::vector< Tag >& src_tags,
                                     const std::vector< Tag >& dst_tags,
                                     const MPI_Op mpi_op,
                                     const Range& entities_in )
{
    ErrorCode result;
    int success;

    myDebug->tprintf( 1, "Entering reduce_tags\n" );

    // Check that restrictions are met: number of source/dst tags...
    if( src_tags.size() != dst_tags.size() )
    {
        MB_SET_ERR( MB_FAILURE, "Source and destination tag handles must be specified for reduce_tags" );
    }

    // ... tag data types
    std::vector< Tag >::const_iterator vits, vitd;
    int tags_size, tagd_size;
    DataType tags_type, tagd_type;
    std::vector< unsigned char > vals;
    std::vector< int > tags_sizes;
    for( vits = src_tags.begin(), vitd = dst_tags.begin(); vits != src_tags.end(); ++vits, ++vitd )
    {
        // Checks on tag characteristics
        result = mbImpl->tag_get_data_type( *vits, tags_type );MB_CHK_SET_ERR( result, "Failed to get src tag data type" );
        if( tags_type != MB_TYPE_INTEGER && tags_type != MB_TYPE_DOUBLE && tags_type != MB_TYPE_BIT )
        {
            MB_SET_ERR( MB_FAILURE, "Src/dst tags must have integer, double, or bit data type" );
        }

        result = mbImpl->tag_get_bytes( *vits, tags_size );MB_CHK_SET_ERR( result, "Failed to get src tag bytes" );
        vals.resize( tags_size );
        result = mbImpl->tag_get_default_value( *vits, &vals[0] );MB_CHK_SET_ERR( result, "Src tag must have default value" );

        tags_sizes.push_back( tags_size );

        // OK, those passed; now check whether dest tags, if specified, agree with src tags
        if( *vits == *vitd ) continue;

        result = mbImpl->tag_get_bytes( *vitd, tagd_size );MB_CHK_SET_ERR( result, "Coudln't get dst tag bytes" );
        if( tags_size != tagd_size )
        {
            MB_SET_ERR( MB_FAILURE, "Sizes between src and dst tags don't match" );
        }
        result = mbImpl->tag_get_data_type( *vitd, tagd_type );MB_CHK_SET_ERR( result, "Coudln't get dst tag data type" );
        if( tags_type != tagd_type )
        {
            MB_SET_ERR( MB_FAILURE, "Src and dst tags must be of same data type" );
        }
    }

    // Get all procs interfacing to this proc
    std::set< unsigned int > exch_procs;
    result = get_comm_procs( exch_procs );

    // Post ghost irecv's for all interface procs
    // Index requests the same as buffer/sharing procs indices
    std::vector< MPI_Request > recv_tag_reqs( 3 * buffProcs.size(), MPI_REQUEST_NULL );

    std::vector< unsigned int >::iterator sit;
    int ind;

    reset_all_buffers();
    int incoming = 0;

    for( ind = 0, sit = buffProcs.begin(); sit != buffProcs.end(); ++sit, ind++ )
    {
        incoming++;
        PRINT_DEBUG_IRECV( *sit, procConfig.proc_rank(), remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE,
                           MB_MESG_TAGS_SIZE, incoming );

        success = MPI_Irecv( remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE, MPI_UNSIGNED_CHAR, *sit,
                             MB_MESG_TAGS_SIZE, procConfig.proc_comm(), &recv_tag_reqs[3 * ind] );
        if( success != MPI_SUCCESS )
        {
            MB_SET_ERR( MB_FAILURE, "Failed to post irecv in ghost exchange" );
        }
    }

    // Pack and send tags from this proc to others
    // Make sendReqs vector to simplify initialization
    sendReqs.resize( 3 * buffProcs.size(), MPI_REQUEST_NULL );

    // Take all shared entities if incoming list is empty
    Range entities;
    if( entities_in.empty() )
        std::copy( sharedEnts.begin(), sharedEnts.end(), range_inserter( entities ) );
    else
        entities = entities_in;

    // If the tags are different, copy the source to the dest tag locally
    std::vector< Tag >::const_iterator vit = src_tags.begin(), vit2 = dst_tags.begin();
    std::vector< int >::const_iterator vsizes = tags_sizes.begin();
    for( ; vit != src_tags.end(); ++vit, ++vit2, ++vsizes )
    {
        if( *vit == *vit2 ) continue;
        vals.resize( entities.size() * ( *vsizes ) );
        result = mbImpl->tag_get_data( *vit, entities, &vals[0] );MB_CHK_SET_ERR( result, "Didn't get data properly" );
        result = mbImpl->tag_set_data( *vit2, entities, &vals[0] );MB_CHK_SET_ERR( result, "Didn't set data properly" );
    }

    int dum_ack_buff;

    for( ind = 0, sit = buffProcs.begin(); sit != buffProcs.end(); ++sit, ind++ )
    {
        Range tag_ents = entities;

        // Get ents shared by proc *sit
        result = filter_pstatus( tag_ents, PSTATUS_SHARED, PSTATUS_AND, *sit );MB_CHK_SET_ERR( result, "Failed pstatus AND check" );

        // Pack-send
        std::vector< Range > tag_ranges;
        for( vit = src_tags.begin(); vit != src_tags.end(); ++vit )
        {
            const void* ptr;
            int sz;
            if( mbImpl->tag_get_default_value( *vit, ptr, sz ) != MB_SUCCESS )
            {
                Range tagged_ents;
                mbImpl->get_entities_by_type_and_tag( 0, MBMAXTYPE, &*vit, 0, 1, tagged_ents );
                tag_ranges.push_back( intersect( tag_ents, tagged_ents ) );
            }
            else
                tag_ranges.push_back( tag_ents );
        }

        // Pack the data
        // Reserve space on front for size and for initial buff size
        localOwnedBuffs[ind]->reset_ptr( sizeof( int ) );

        result = pack_tags( tag_ents, src_tags, dst_tags, tag_ranges, localOwnedBuffs[ind], true, *sit );MB_CHK_SET_ERR( result, "Failed to count buffer in pack_send_tag" );

        // Now send it
        result = send_buffer( *sit, localOwnedBuffs[ind], MB_MESG_TAGS_SIZE, sendReqs[3 * ind],
                              recv_tag_reqs[3 * ind + 2], &dum_ack_buff, incoming );MB_CHK_SET_ERR( result, "Failed to send buffer" );
    }

    // Receive/unpack tags
    while( incoming )
    {
        MPI_Status status;
        int index_in_recv_requests;
        PRINT_DEBUG_WAITANY( recv_tag_reqs, MB_MESG_TAGS_SIZE, procConfig.proc_rank() );
        success = MPI_Waitany( 3 * buffProcs.size(), &recv_tag_reqs[0], &index_in_recv_requests, &status );
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "Failed in waitany in ghost exchange" );
        }
        ind = index_in_recv_requests / 3;

        PRINT_DEBUG_RECD( status );

        // OK, received something; decrement incoming counter
        incoming--;

        bool done = false;
        std::vector< EntityHandle > dum_vec;
        result = recv_buffer( MB_MESG_TAGS_SIZE, status, remoteOwnedBuffs[ind],
                              recv_tag_reqs[3 * ind + 1],  // This is for receiving the second message
                              recv_tag_reqs[3 * ind + 2],  // This would be for ack, but it is not
                                                           // used; consider removing it
                              incoming, localOwnedBuffs[ind],
                              sendReqs[3 * ind + 1],  // Send request for sending the second message
                              sendReqs[3 * ind + 2],  // This is for sending the ack
                              done );MB_CHK_SET_ERR( result, "Failed to resize recv buffer" );
        if( done )
        {
            remoteOwnedBuffs[ind]->reset_ptr( sizeof( int ) );
            result = unpack_tags( remoteOwnedBuffs[ind]->buff_ptr, dum_vec, true, buffProcs[ind], &mpi_op );MB_CHK_SET_ERR( result, "Failed to recv-unpack-tag message" );
        }
    }

    // OK, now wait
    if( myDebug->get_verbosity() == 5 )
    {
        success = MPI_Barrier( procConfig.proc_comm() );
    }
    else
    {
        MPI_Status status[3 * MAX_SHARING_PROCS];
        success = MPI_Waitall( 3 * buffProcs.size(), &sendReqs[0], status );
    }
    if( MPI_SUCCESS != success )
    {
        MB_SET_ERR( MB_FAILURE, "Failure in waitall in tag exchange" );
    }

    myDebug->tprintf( 1, "Exiting reduce_tags" );

    return MB_SUCCESS;
}

//! return sharedp tag
Tag ParallelComm::sharedp_tag()
{
    if( !sharedpTag )
    {
        int def_val      = -1;
        ErrorCode result = mbImpl->tag_get_handle( PARALLEL_SHARED_PROC_TAG_NAME, 1, MB_TYPE_INTEGER, sharedpTag,
                                                   MB_TAG_DENSE | MB_TAG_CREAT, &def_val );
        if( MB_SUCCESS != result ) return 0;
    }

    return sharedpTag;
}

//! return sharedps tag
Tag ParallelComm::sharedps_tag()
{
    if( !sharedpsTag )
    {
        ErrorCode result = mbImpl->tag_get_handle( PARALLEL_SHARED_PROCS_TAG_NAME, MAX_SHARING_PROCS, MB_TYPE_INTEGER,
                                                   sharedpsTag, MB_TAG_SPARSE | MB_TAG_CREAT );
        if( MB_SUCCESS != result ) return 0;
    }

    return sharedpsTag;
}

//! return sharedh tag
Tag ParallelComm::sharedh_tag()
{
    if( !sharedhTag )
    {
        EntityHandle def_val = 0;
        ErrorCode result     = mbImpl->tag_get_handle( PARALLEL_SHARED_HANDLE_TAG_NAME, 1, MB_TYPE_HANDLE, sharedhTag,
                                                       MB_TAG_DENSE | MB_TAG_CREAT, &def_val );
        if( MB_SUCCESS != result ) return 0;
    }

    return sharedhTag;
}

//! return sharedhs tag
Tag ParallelComm::sharedhs_tag()
{
    if( !sharedhsTag )
    {
        ErrorCode result = mbImpl->tag_get_handle( PARALLEL_SHARED_HANDLES_TAG_NAME, MAX_SHARING_PROCS, MB_TYPE_HANDLE,
                                                   sharedhsTag, MB_TAG_SPARSE | MB_TAG_CREAT );
        if( MB_SUCCESS != result ) return 0;
    }

    return sharedhsTag;
}

//! return pstatus tag
Tag ParallelComm::pstatus_tag()
{
    if( !pstatusTag )
    {
        unsigned char tmp_pstatus = 0;
        ErrorCode result          = mbImpl->tag_get_handle( PARALLEL_STATUS_TAG_NAME, 1, MB_TYPE_OPAQUE, pstatusTag,
                                                            MB_TAG_DENSE | MB_TAG_CREAT, &tmp_pstatus );
        if( MB_SUCCESS != result ) return 0;
    }

    return pstatusTag;
}

//! return partition set tag
Tag ParallelComm::partition_tag()
{
    if( !partitionTag )
    {
        int dum_id       = -1;
        ErrorCode result = mbImpl->tag_get_handle( PARALLEL_PARTITION_TAG_NAME, 1, MB_TYPE_INTEGER, partitionTag,
                                                   MB_TAG_SPARSE | MB_TAG_CREAT, &dum_id );
        if( MB_SUCCESS != result ) return 0;
    }

    return partitionTag;
}

//! return pcomm tag; passes in impl 'cuz this is a static function
Tag ParallelComm::pcomm_tag( Interface* impl, bool create_if_missing )
{
    Tag this_tag = 0;
    ErrorCode result;
    if( create_if_missing )
    {
        result = impl->tag_get_handle( PARALLEL_COMM_TAG_NAME, MAX_SHARING_PROCS * sizeof( ParallelComm* ),
                                       MB_TYPE_OPAQUE, this_tag, MB_TAG_SPARSE | MB_TAG_CREAT );
    }
    else
    {
        result = impl->tag_get_handle( PARALLEL_COMM_TAG_NAME, MAX_SHARING_PROCS * sizeof( ParallelComm* ),
                                       MB_TYPE_OPAQUE, this_tag, MB_TAG_SPARSE );
    }

    if( MB_SUCCESS != result ) return 0;

    return this_tag;
}

//! get the indexed pcomm object from the interface
ParallelComm* ParallelComm::get_pcomm( Interface* impl, const int index )
{
    Tag pc_tag = pcomm_tag( impl, false );
    if( 0 == pc_tag ) return NULL;

    const EntityHandle root = 0;
    ParallelComm* pc_array[MAX_SHARING_PROCS];
    ErrorCode result = impl->tag_get_data( pc_tag, &root, 1, (void*)pc_array );
    if( MB_SUCCESS != result ) return NULL;

    return pc_array[index];
}

ErrorCode ParallelComm::get_all_pcomm( Interface* impl, std::vector< ParallelComm* >& list )
{
    Tag pc_tag = pcomm_tag( impl, false );
    if( 0 == pc_tag ) return MB_TAG_NOT_FOUND;

    const EntityHandle root = 0;
    ParallelComm* pc_array[MAX_SHARING_PROCS];
    ErrorCode rval = impl->tag_get_data( pc_tag, &root, 1, pc_array );
    if( MB_SUCCESS != rval ) return rval;

    for( int i = 0; i < MAX_SHARING_PROCS; i++ )
    {
        if( pc_array[i] ) list.push_back( pc_array[i] );
    }

    return MB_SUCCESS;
}

//! get the indexed pcomm object from the interface
ParallelComm* ParallelComm::get_pcomm( Interface* impl, EntityHandle prtn, const MPI_Comm* comm )
{
    ErrorCode rval;
    ParallelComm* result = 0;

    Tag prtn_tag;
    rval =
        impl->tag_get_handle( PARTITIONING_PCOMM_TAG_NAME, 1, MB_TYPE_INTEGER, prtn_tag, MB_TAG_SPARSE | MB_TAG_CREAT );
    if( MB_SUCCESS != rval ) return 0;

    int pcomm_id;
    rval = impl->tag_get_data( prtn_tag, &prtn, 1, &pcomm_id );
    if( MB_SUCCESS == rval )
    {
        result = get_pcomm( impl, pcomm_id );
    }
    else if( MB_TAG_NOT_FOUND == rval && comm )
    {
        result = new ParallelComm( impl, *comm, &pcomm_id );
        if( !result ) return 0;
        result->set_partitioning( prtn );

        rval = impl->tag_set_data( prtn_tag, &prtn, 1, &pcomm_id );
        if( MB_SUCCESS != rval )
        {
            delete result;
            result = 0;
        }
    }

    return result;
}

ErrorCode ParallelComm::set_partitioning( EntityHandle set )
{
    ErrorCode rval;
    Tag prtn_tag;
    rval = mbImpl->tag_get_handle( PARTITIONING_PCOMM_TAG_NAME, 1, MB_TYPE_INTEGER, prtn_tag,
                                   MB_TAG_SPARSE | MB_TAG_CREAT );
    if( MB_SUCCESS != rval ) return rval;

    // Get my id
    ParallelComm* pcomm_arr[MAX_SHARING_PROCS];
    Tag pc_tag = pcomm_tag( mbImpl, false );
    if( 0 == pc_tag ) return MB_FAILURE;
    const EntityHandle root = 0;
    ErrorCode result        = mbImpl->tag_get_data( pc_tag, &root, 1, pcomm_arr );
    if( MB_SUCCESS != result ) return MB_FAILURE;
    int id = std::find( pcomm_arr, pcomm_arr + MAX_SHARING_PROCS, this ) - pcomm_arr;
    if( id == MAX_SHARING_PROCS ) return MB_FAILURE;

    EntityHandle old = partitioningSet;
    if( old )
    {
        rval = mbImpl->tag_delete_data( prtn_tag, &old, 1 );
        if( MB_SUCCESS != rval ) return rval;
        partitioningSet = 0;
    }

    if( !set ) return MB_SUCCESS;

    Range contents;
    if( old )
    {
        rval = mbImpl->get_entities_by_handle( old, contents );
        if( MB_SUCCESS != rval ) return rval;
    }
    else
    {
        contents = partition_sets();
    }

    rval = mbImpl->add_entities( set, contents );
    if( MB_SUCCESS != rval ) return rval;

    // Store pcomm id on new partition set
    rval = mbImpl->tag_set_data( prtn_tag, &set, 1, &id );
    if( MB_SUCCESS != rval ) return rval;

    partitioningSet = set;
    return MB_SUCCESS;
}

//! return all the entities in parts owned locally
ErrorCode ParallelComm::get_part_entities( Range& ents, int dim )
{
    ErrorCode result;

    for( Range::iterator rit = partitionSets.begin(); rit != partitionSets.end(); ++rit )
    {
        Range tmp_ents;
        if( -1 == dim )
            result = mbImpl->get_entities_by_handle( *rit, tmp_ents, true );
        else
            result = mbImpl->get_entities_by_dimension( *rit, dim, tmp_ents, true );

        if( MB_SUCCESS != result ) return result;
        ents.merge( tmp_ents );
    }

    return MB_SUCCESS;
}

/** \brief Return the rank of the entity owner
 */
ErrorCode ParallelComm::get_owner_handle( EntityHandle entity, int& owner, EntityHandle& handle )
{
    unsigned char pstat;
    int sharing_procs[MAX_SHARING_PROCS];
    EntityHandle sharing_handles[MAX_SHARING_PROCS];

    ErrorCode result = mbImpl->tag_get_data( pstatus_tag(), &entity, 1, &pstat );MB_CHK_SET_ERR( result, "Failed to get pstatus tag data" );
    if( !( pstat & PSTATUS_NOT_OWNED ) )
    {
        owner  = proc_config().proc_rank();
        handle = entity;
    }
    else if( pstat & PSTATUS_MULTISHARED )
    {
        result = mbImpl->tag_get_data( sharedps_tag(), &entity, 1, sharing_procs );MB_CHK_SET_ERR( result, "Failed to get sharedps tag data" );
        owner  = sharing_procs[0];
        result = mbImpl->tag_get_data( sharedhs_tag(), &entity, 1, sharing_handles );MB_CHK_SET_ERR( result, "Failed to get sharedhs tag data" );
        handle = sharing_handles[0];
    }
    else if( pstat & PSTATUS_SHARED )
    {
        result = mbImpl->tag_get_data( sharedp_tag(), &entity, 1, sharing_procs );MB_CHK_SET_ERR( result, "Failed to get sharedp tag data" );
        owner  = sharing_procs[0];
        result = mbImpl->tag_get_data( sharedh_tag(), &entity, 1, sharing_handles );MB_CHK_SET_ERR( result, "Failed to get sharedh tag data" );
        handle = sharing_handles[0];
    }
    else
    {
        owner  = -1;
        handle = 0;
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_global_part_count( int& count_out ) const
{
    count_out = globalPartCount;
    return count_out < 0 ? MB_FAILURE : MB_SUCCESS;
}

ErrorCode ParallelComm::get_part_owner( int part_id, int& owner ) const
{
    // FIXME: assumes only 1 local part
    owner = part_id;
    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_part_id( EntityHandle /*part*/, int& id_out ) const
{
    // FIXME: assumes only 1 local part
    id_out = proc_config().proc_rank();
    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_part_handle( int id, EntityHandle& handle_out ) const
{
    // FIXME: assumes only 1 local part
    if( (unsigned)id != proc_config().proc_rank() ) return MB_ENTITY_NOT_FOUND;
    handle_out = partition_sets().front();
    return MB_SUCCESS;
}

ErrorCode ParallelComm::create_part( EntityHandle& set_out )
{
    // Mark as invalid so we know that it needs to be updated
    globalPartCount = -1;

    // Create set representing part
    ErrorCode rval = mbImpl->create_meshset( MESHSET_SET, set_out );
    if( MB_SUCCESS != rval ) return rval;

    // Set tag on set
    int val = proc_config().proc_rank();
    rval    = mbImpl->tag_set_data( part_tag(), &set_out, 1, &val );

    if( MB_SUCCESS != rval )
    {
        mbImpl->delete_entities( &set_out, 1 );
        return rval;
    }

    if( get_partitioning() )
    {
        rval = mbImpl->add_entities( get_partitioning(), &set_out, 1 );
        if( MB_SUCCESS != rval )
        {
            mbImpl->delete_entities( &set_out, 1 );
            return rval;
        }
    }

    moab::Range& pSets = this->partition_sets();
    if( pSets.index( set_out ) < 0 )
    {
        pSets.insert( set_out );
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::destroy_part( EntityHandle part_id )
{
    // Mark as invalid so we know that it needs to be updated
    globalPartCount = -1;

    ErrorCode rval;
    if( get_partitioning() )
    {
        rval = mbImpl->remove_entities( get_partitioning(), &part_id, 1 );
        if( MB_SUCCESS != rval ) return rval;
    }

    moab::Range& pSets = this->partition_sets();
    if( pSets.index( part_id ) >= 0 )
    {
        pSets.erase( part_id );
    }
    return mbImpl->delete_entities( &part_id, 1 );
}

ErrorCode ParallelComm::collective_sync_partition()
{
    int count       = partition_sets().size();
    globalPartCount = 0;
    int err         = MPI_Allreduce( &count, &globalPartCount, 1, MPI_INT, MPI_SUM, proc_config().proc_comm() );
    return err ? MB_FAILURE : MB_SUCCESS;
}

ErrorCode ParallelComm::get_part_neighbor_ids( EntityHandle part,
                                               int neighbors_out[MAX_SHARING_PROCS],
                                               int& num_neighbors_out )
{
    ErrorCode rval;
    Range iface;
    rval = get_interface_sets( part, iface );
    if( MB_SUCCESS != rval ) return rval;

    num_neighbors_out = 0;
    int n, j = 0;
    int tmp[MAX_SHARING_PROCS] = { 0 }, curr[MAX_SHARING_PROCS] = { 0 };
    int* parts[2] = { neighbors_out, tmp };
    for( Range::iterator i = iface.begin(); i != iface.end(); ++i )
    {
        unsigned char pstat;
        rval = get_sharing_data( *i, curr, NULL, pstat, n );
        if( MB_SUCCESS != rval ) return rval;
        std::sort( curr, curr + n );
        assert( num_neighbors_out < MAX_SHARING_PROCS );
        int* k            = std::set_union( parts[j], parts[j] + num_neighbors_out, curr, curr + n, parts[1 - j] );
        j                 = 1 - j;
        num_neighbors_out = k - parts[j];
    }
    if( parts[j] != neighbors_out ) std::copy( parts[j], parts[j] + num_neighbors_out, neighbors_out );

    // Remove input part from list
    int id;
    rval = get_part_id( part, id );
    if( MB_SUCCESS == rval )
        num_neighbors_out = std::remove( neighbors_out, neighbors_out + num_neighbors_out, id ) - neighbors_out;
    return rval;
}

ErrorCode ParallelComm::get_interface_sets( EntityHandle, Range& iface_sets_out, int* adj_part_id )
{
    // FIXME : assumes one part per processor.
    // Need to store part iface sets as children to implement
    // this correctly.
    iface_sets_out = interface_sets();

    if( adj_part_id )
    {
        int part_ids[MAX_SHARING_PROCS], num_parts;
        Range::iterator i = iface_sets_out.begin();
        while( i != iface_sets_out.end() )
        {
            unsigned char pstat;
            ErrorCode rval = get_sharing_data( *i, part_ids, NULL, pstat, num_parts );
            if( MB_SUCCESS != rval ) return rval;

            if( std::find( part_ids, part_ids + num_parts, *adj_part_id ) - part_ids != num_parts )
                ++i;
            else
                i = iface_sets_out.erase( i );
        }
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_owning_part( EntityHandle handle, int& owning_part_id, EntityHandle* remote_handle )
{
    // FIXME : assumes one part per proc, and therefore part_id == rank

    // If entity is not shared, then we're the owner.
    unsigned char pstat;
    ErrorCode result = mbImpl->tag_get_data( pstatus_tag(), &handle, 1, &pstat );MB_CHK_SET_ERR( result, "Failed to get pstatus tag data" );
    if( !( pstat & PSTATUS_NOT_OWNED ) )
    {
        owning_part_id = proc_config().proc_rank();
        if( remote_handle ) *remote_handle = handle;
        return MB_SUCCESS;
    }

    // If entity is shared with one other proc, then
    // sharedp_tag will contain a positive value.
    result = mbImpl->tag_get_data( sharedp_tag(), &handle, 1, &owning_part_id );MB_CHK_SET_ERR( result, "Failed to get sharedp tag data" );
    if( owning_part_id != -1 )
    {
        // Done?
        if( !remote_handle ) return MB_SUCCESS;

        // Get handles on remote processors (and this one)
        return mbImpl->tag_get_data( sharedh_tag(), &handle, 1, remote_handle );
    }

    // If here, then the entity is shared with at least two other processors.
    // Get the list from the sharedps_tag
    const void* part_id_list = 0;
    result                   = mbImpl->tag_get_by_ptr( sharedps_tag(), &handle, 1, &part_id_list );
    if( MB_SUCCESS != result ) return result;
    owning_part_id = ( (const int*)part_id_list )[0];

    // Done?
    if( !remote_handle ) return MB_SUCCESS;

    // Get remote handles
    const void* handle_list = 0;
    result                  = mbImpl->tag_get_by_ptr( sharedhs_tag(), &handle, 1, &handle_list );
    if( MB_SUCCESS != result ) return result;

    *remote_handle = ( (const EntityHandle*)handle_list )[0];
    return MB_SUCCESS;
}

ErrorCode ParallelComm::get_sharing_parts( EntityHandle entity,
                                           int part_ids_out[MAX_SHARING_PROCS],
                                           int& num_part_ids_out,
                                           EntityHandle remote_handles[MAX_SHARING_PROCS] )
{
    // FIXME : assumes one part per proc, and therefore part_id == rank

    // If entity is not shared, then we're the owner.
    unsigned char pstat;
    ErrorCode result = mbImpl->tag_get_data( pstatus_tag(), &entity, 1, &pstat );MB_CHK_SET_ERR( result, "Failed to get pstatus tag data" );
    if( !( pstat & PSTATUS_SHARED ) )
    {
        part_ids_out[0] = proc_config().proc_rank();
        if( remote_handles ) remote_handles[0] = entity;
        num_part_ids_out = 1;
        return MB_SUCCESS;
    }

    // If entity is shared with one other proc, then
    // sharedp_tag will contain a positive value.
    result = mbImpl->tag_get_data( sharedp_tag(), &entity, 1, part_ids_out );MB_CHK_SET_ERR( result, "Failed to get sharedp tag data" );
    if( part_ids_out[0] != -1 )
    {
        num_part_ids_out = 2;
        part_ids_out[1]  = proc_config().proc_rank();

        // Done?
        if( !remote_handles ) return MB_SUCCESS;

        // Get handles on remote processors (and this one)
        remote_handles[1] = entity;
        return mbImpl->tag_get_data( sharedh_tag(), &entity, 1, remote_handles );
    }

    // If here, then the entity is shared with at least two other processors.
    // Get the list from the sharedps_tag
    result = mbImpl->tag_get_data( sharedps_tag(), &entity, 1, part_ids_out );
    if( MB_SUCCESS != result ) return result;
    // Count number of valid (positive) entries in sharedps_tag
    for( num_part_ids_out = 0; num_part_ids_out < MAX_SHARING_PROCS && part_ids_out[num_part_ids_out] >= 0;
         num_part_ids_out++ )
        ;
        // part_ids_out[num_part_ids_out++] = proc_config().proc_rank();
#ifndef NDEBUG
    int my_idx = std::find( part_ids_out, part_ids_out + num_part_ids_out, proc_config().proc_rank() ) - part_ids_out;
    assert( my_idx < num_part_ids_out );
#endif

    // Done?
    if( !remote_handles ) return MB_SUCCESS;

    // Get remote handles
    result = mbImpl->tag_get_data( sharedhs_tag(), &entity, 1, remote_handles );
    // remote_handles[num_part_ids_out - 1] = entity;
    assert( remote_handles[my_idx] == entity );

    return result;
}

ErrorCode ParallelComm::pack_shared_handles( std::vector< std::vector< SharedEntityData > >& send_data )
{
    // Build up send buffers
    ErrorCode rval = MB_SUCCESS;<--- Variable 'rval' is assigned a value that is never used.
    int ent_procs[MAX_SHARING_PROCS];
    EntityHandle handles[MAX_SHARING_PROCS];
    int num_sharing, tmp_int;
    SharedEntityData tmp;
    send_data.resize( buffProcs.size() );
    for( std::set< EntityHandle >::iterator i = sharedEnts.begin(); i != sharedEnts.end(); ++i )
    {
        tmp.remote = *i;  // Swap local/remote so they're correct on the remote proc.
        rval       = get_owner( *i, tmp_int );
        tmp.owner  = tmp_int;
        if( MB_SUCCESS != rval ) return rval;

        unsigned char pstat;
        rval = get_sharing_data( *i, ent_procs, handles, pstat, num_sharing );
        if( MB_SUCCESS != rval ) return rval;
        for( int j = 0; j < num_sharing; j++ )
        {
            if( ent_procs[j] == (int)proc_config().proc_rank() ) continue;
            tmp.local = handles[j];
            int ind   = get_buffers( ent_procs[j] );
            assert( -1 != ind );
            if( (int)send_data.size() < ind + 1 ) send_data.resize( ind + 1 );
            send_data[ind].push_back( tmp );
        }
    }

    return MB_SUCCESS;
}

ErrorCode ParallelComm::exchange_all_shared_handles( std::vector< std::vector< SharedEntityData > >& send_data,
                                                     std::vector< std::vector< SharedEntityData > >& result )
{
    int ierr;
    const int tag      = 0;
    const MPI_Comm cm  = procConfig.proc_comm();
    const int num_proc = buffProcs.size();
    const std::vector< int > procs( buffProcs.begin(), buffProcs.end() );
    std::vector< MPI_Request > recv_req( buffProcs.size(), MPI_REQUEST_NULL );
    std::vector< MPI_Request > send_req( buffProcs.size(), MPI_REQUEST_NULL );

    // Set up to receive sizes
    std::vector< int > sizes_send( num_proc ), sizes_recv( num_proc );
    for( int i = 0; i < num_proc; i++ )
    {
        ierr = MPI_Irecv( &sizes_recv[i], 1, MPI_INT, procs[i], tag, cm, &recv_req[i] );
        if( ierr ) return MB_FILE_WRITE_ERROR;
    }

    // Send sizes
    assert( num_proc == (int)send_data.size() );

    result.resize( num_proc );
    for( int i = 0; i < num_proc; i++ )
    {
        sizes_send[i] = send_data[i].size();
        ierr          = MPI_Isend( &sizes_send[i], 1, MPI_INT, buffProcs[i], tag, cm, &send_req[i] );
        if( ierr ) return MB_FILE_WRITE_ERROR;
    }

    // Receive sizes
    std::vector< MPI_Status > stat( num_proc );
    ierr = MPI_Waitall( num_proc, &recv_req[0], &stat[0] );
    if( ierr ) return MB_FILE_WRITE_ERROR;

    // Wait until all sizes are sent (clean up pending req's)
    ierr = MPI_Waitall( num_proc, &send_req[0], &stat[0] );
    if( ierr ) return MB_FILE_WRITE_ERROR;

    // Set up to receive data
    for( int i = 0; i < num_proc; i++ )
    {
        result[i].resize( sizes_recv[i] );
        ierr = MPI_Irecv( (void*)( &( result[i][0] ) ), sizeof( SharedEntityData ) * sizes_recv[i], MPI_UNSIGNED_CHAR,
                          buffProcs[i], tag, cm, &recv_req[i] );
        if( ierr ) return MB_FILE_WRITE_ERROR;
    }

    // Send data
    for( int i = 0; i < num_proc; i++ )
    {
        ierr = MPI_Isend( (void*)( &( send_data[i][0] ) ), sizeof( SharedEntityData ) * sizes_send[i],
                          MPI_UNSIGNED_CHAR, buffProcs[i], tag, cm, &send_req[i] );
        if( ierr ) return MB_FILE_WRITE_ERROR;
    }

    // Receive data
    ierr = MPI_Waitall( num_proc, &recv_req[0], &stat[0] );
    if( ierr ) return MB_FILE_WRITE_ERROR;

    // Wait until everything is sent to release send buffers
    ierr = MPI_Waitall( num_proc, &send_req[0], &stat[0] );
    if( ierr ) return MB_FILE_WRITE_ERROR;

    return MB_SUCCESS;
}

ErrorCode ParallelComm::check_all_shared_handles( bool print_em )
{
    // Get all shared ent data from other procs
    std::vector< std::vector< SharedEntityData > > shents( buffProcs.size() ), send_data( buffProcs.size() );

    ErrorCode result;
    bool done = false;

    while( !done )
    {
        result = check_local_shared();
        if( MB_SUCCESS != result )
        {
            done = true;
            continue;
        }

        result = pack_shared_handles( send_data );
        if( MB_SUCCESS != result )
        {
            done = true;
            continue;
        }

        result = exchange_all_shared_handles( send_data, shents );
        if( MB_SUCCESS != result )
        {
            done = true;
            continue;
        }

        if( !shents.empty() ) result = check_my_shared_handles( shents );
        done = true;
    }

    if( MB_SUCCESS != result && print_em )
    {
#ifdef MOAB_HAVE_HDF5
        std::ostringstream ent_str;
        ent_str << "mesh." << procConfig.proc_rank() << ".h5m";
        mbImpl->write_mesh( ent_str.str().c_str() );
#endif
    }

    return result;
}

ErrorCode ParallelComm::check_local_shared()
{
    // Do some checks on shared entities to make sure things look
    // consistent

    // Check that non-vertex shared entities are shared by same procs as all
    // their vertices
    // std::pair<Range::const_iterator,Range::const_iterator> vert_it =
    //    sharedEnts.equal_range(MBVERTEX);
    std::vector< EntityHandle > dum_connect;
    const EntityHandle* connect;
    int num_connect;
    int tmp_procs[MAX_SHARING_PROCS];
    EntityHandle tmp_hs[MAX_SHARING_PROCS];
    std::set< int > tmp_set, vset;
    int num_ps;
    ErrorCode result;
    unsigned char pstat;
    std::vector< EntityHandle > bad_ents;
    std::vector< std::string > errors;

    std::set< EntityHandle >::iterator vit;
    for( vit = sharedEnts.begin(); vit != sharedEnts.end(); ++vit )
    {
        // Get sharing procs for this ent
        result = get_sharing_data( *vit, tmp_procs, tmp_hs, pstat, num_ps );
        if( MB_SUCCESS != result )
        {
            bad_ents.push_back( *vit );
            errors.push_back( std::string( "Failure getting sharing data." ) );
            continue;
        }

        bool bad = false;
        // Entity must be shared
        if( !( pstat & PSTATUS_SHARED ) )
            errors.push_back( std::string( "Entity should be shared but isn't." ) ), bad = true;

        // If entity is not owned this must not be first proc
        if( pstat & PSTATUS_NOT_OWNED && tmp_procs[0] == (int)procConfig.proc_rank() )
            errors.push_back( std::string( "Entity not owned but is first proc." ) ), bad = true;

        // If entity is owned and multishared, this must be first proc
        if( !( pstat & PSTATUS_NOT_OWNED ) && pstat & PSTATUS_MULTISHARED &&
            ( tmp_procs[0] != (int)procConfig.proc_rank() || tmp_hs[0] != *vit ) )
            errors.push_back( std::string( "Entity owned and multishared but not first proc or not first handle." ) ),
                bad = true;

        if( bad )
        {
            bad_ents.push_back( *vit );
            continue;
        }

        EntityType type = mbImpl->type_from_handle( *vit );
        if( type == MBVERTEX || type == MBENTITYSET ) continue;

        // Copy element's procs to vset and save size
        int orig_ps = num_ps;
        vset.clear();
        std::copy( tmp_procs, tmp_procs + num_ps, std::inserter( vset, vset.begin() ) );

        // Get vertices for this ent and intersection of sharing procs
        result = mbImpl->get_connectivity( *vit, connect, num_connect, false, &dum_connect );
        if( MB_SUCCESS != result )
        {
            bad_ents.push_back( *vit );
            errors.push_back( std::string( "Failed to get connectivity." ) );
            continue;
        }

        for( int i = 0; i < num_connect; i++ )
        {
            result = get_sharing_data( connect[i], tmp_procs, NULL, pstat, num_ps );
            if( MB_SUCCESS != result )
            {
                bad_ents.push_back( *vit );
                continue;
            }
            if( !num_ps )
            {
                vset.clear();
                break;
            }
            std::sort( tmp_procs, tmp_procs + num_ps );
            tmp_set.clear();
            std::set_intersection( tmp_procs, tmp_procs + num_ps, vset.begin(), vset.end(),
                                   std::inserter( tmp_set, tmp_set.end() ) );
            vset.swap( tmp_set );
            if( vset.empty() ) break;
        }

        // Intersect them; should be the same size as orig_ps
        tmp_set.clear();
        std::set_intersection( tmp_procs, tmp_procs + num_ps, vset.begin(), vset.end(),
                               std::inserter( tmp_set, tmp_set.end() ) );
        if( orig_ps != (int)tmp_set.size() )
        {
            errors.push_back( std::string( "Vertex proc set not same size as entity proc set." ) );
            bad_ents.push_back( *vit );
            for( int i = 0; i < num_connect; i++ )
            {
                bad_ents.push_back( connect[i] );
                errors.push_back( std::string( "vertex in connect" ) );
            }
        }
    }

    if( !bad_ents.empty() )
    {
        std::cout << "Found bad entities in check_local_shared, proc rank " << procConfig.proc_rank() << ","
                  << std::endl;
        std::vector< std::string >::iterator sit;
        std::vector< EntityHandle >::iterator rit;
        for( rit = bad_ents.begin(), sit = errors.begin(); rit != bad_ents.end(); ++rit, ++sit )
        {
            list_entities( &( *rit ), 1 );
            std::cout << "Reason: " << *sit << std::endl;
        }
        return MB_FAILURE;
    }

    // To do: check interface sets

    return MB_SUCCESS;
}

ErrorCode ParallelComm::check_all_shared_handles( ParallelComm** pcs, int num_pcs )
{
    std::vector< std::vector< std::vector< SharedEntityData > > > shents, send_data;
    ErrorCode result = MB_SUCCESS, tmp_result;

    // Get all shared ent data from each proc to all other procs
    send_data.resize( num_pcs );
    for( int p = 0; p < num_pcs; p++ )
    {
        tmp_result = pcs[p]->pack_shared_handles( send_data[p] );
        if( MB_SUCCESS != tmp_result ) result = tmp_result;
    }
    if( MB_SUCCESS != result ) return result;

    // Move the data sorted by sending proc to data sorted by receiving proc
    shents.resize( num_pcs );
    for( int p = 0; p < num_pcs; p++ )
        shents[p].resize( pcs[p]->buffProcs.size() );

    for( int p = 0; p < num_pcs; p++ )
    {
        for( unsigned int idx_p = 0; idx_p < pcs[p]->buffProcs.size(); idx_p++ )
        {
            // Move send_data[p][to_p] to shents[to_p][idx_p]
            int to_p      = pcs[p]->buffProcs[idx_p];
            int top_idx_p = pcs[to_p]->get_buffers( p );
            assert( -1 != top_idx_p );
            shents[to_p][top_idx_p] = send_data[p][idx_p];
        }
    }

    for( int p = 0; p < num_pcs; p++ )
    {
        std::ostringstream ostr;
        ostr << "Processor " << p << " bad entities:";
        tmp_result = pcs[p]->check_my_shared_handles( shents[p], ostr.str().c_str() );
        if( MB_SUCCESS != tmp_result ) result = tmp_result;
    }

    return result;
}

ErrorCode ParallelComm::check_my_shared_handles( std::vector< std::vector< SharedEntityData > >& shents,
                                                 const char* prefix )
{
    // Now check against what I think data should be
    // Get all shared entities
    ErrorCode result;
    Range all_shared;
    std::copy( sharedEnts.begin(), sharedEnts.end(), range_inserter( all_shared ) );
    std::vector< EntityHandle > dum_vec;
    all_shared.erase( all_shared.upper_bound( MBPOLYHEDRON ), all_shared.end() );

    Range bad_ents, local_shared;
    std::vector< SharedEntityData >::iterator vit;
    unsigned char tmp_pstat;
    for( unsigned int i = 0; i < shents.size(); i++ )
    {
        int other_proc = buffProcs[i];
        result         = get_shared_entities( other_proc, local_shared );
        if( MB_SUCCESS != result ) return result;
        for( vit = shents[i].begin(); vit != shents[i].end(); ++vit )
        {
            EntityHandle localh = vit->local, remoteh = vit->remote, dumh;
            local_shared.erase( localh );
            result = get_remote_handles( true, &localh, &dumh, 1, other_proc, dum_vec );
            if( MB_SUCCESS != result || dumh != remoteh ) bad_ents.insert( localh );
            result = get_pstatus( localh, tmp_pstat );
            if( MB_SUCCESS != result || ( !( tmp_pstat & PSTATUS_NOT_OWNED ) && (unsigned)vit->owner != rank() ) ||
                ( tmp_pstat & PSTATUS_NOT_OWNED && (unsigned)vit->owner == rank() ) )
                bad_ents.insert( localh );
        }

        if( !local_shared.empty() ) bad_ents.merge( local_shared );
    }

    if( !bad_ents.empty() )
    {
        if( prefix ) std::cout << prefix << std::endl;
        list_entities( bad_ents );
        return MB_FAILURE;
    }
    else
        return MB_SUCCESS;
}

ErrorCode ParallelComm::get_shared_entities( int other_proc,
                                             Range& shared_ents,
                                             int dim,
                                             const bool iface,
                                             const bool owned_filter )
{
    shared_ents.clear();
    ErrorCode result = MB_SUCCESS;

    // Dimension
    if( -1 != dim )
    {
        DimensionPair dp = CN::TypeDimensionMap[dim];
        Range dum_range;
        std::copy( sharedEnts.begin(), sharedEnts.end(), range_inserter( dum_range ) );
        shared_ents.merge( dum_range.lower_bound( dp.first ), dum_range.upper_bound( dp.second ) );
    }
    else
        std::copy( sharedEnts.begin(), sharedEnts.end(), range_inserter( shared_ents ) );

    // Filter by iface
    if( iface )
    {
        result = filter_pstatus( shared_ents, PSTATUS_INTERFACE, PSTATUS_AND );MB_CHK_SET_ERR( result, "Failed to filter by iface" );
    }

    // Filter by owned
    if( owned_filter )
    {
        result = filter_pstatus( shared_ents, PSTATUS_NOT_OWNED, PSTATUS_NOT );MB_CHK_SET_ERR( result, "Failed to filter by owned" );
    }

    // Filter by proc
    if( -1 != other_proc )
    {
        result = filter_pstatus( shared_ents, PSTATUS_SHARED, PSTATUS_AND, other_proc );MB_CHK_SET_ERR( result, "Failed to filter by proc" );
    }

    return result;
}

ErrorCode ParallelComm::clean_shared_tags( std::vector< Range* >& exchange_ents )<--- The function 'clean_shared_tags' is never used.
{
    for( unsigned int i = 0; i < exchange_ents.size(); i++ )
    {
        Range* ents        = exchange_ents[i];
        int num_ents       = ents->size();
        Range::iterator it = ents->begin();

        for( int n = 0; n < num_ents; n++ )
        {
            int sharing_proc;
            ErrorCode result = mbImpl->tag_get_data( sharedp_tag(), &( *ents->begin() ), 1, &sharing_proc );
            if( result != MB_TAG_NOT_FOUND && sharing_proc == -1 )
            {
                result = mbImpl->tag_delete_data( sharedp_tag(), &( *it ), 1 );MB_CHK_SET_ERR( result, "Failed to delete sharedp tag data" );
                result = mbImpl->tag_delete_data( sharedh_tag(), &( *it ), 1 );MB_CHK_SET_ERR( result, "Failed to delete sharedh tag data" );
                result = mbImpl->tag_delete_data( pstatus_tag(), &( *it ), 1 );MB_CHK_SET_ERR( result, "Failed to delete pstatus tag data" );
            }
            ++it;
        }
    }

    return MB_SUCCESS;
}

void ParallelComm::set_debug_verbosity( int verb )
{
    myDebug->set_verbosity( verb );
}

int ParallelComm::get_debug_verbosity()
{
    return myDebug->get_verbosity();
}

ErrorCode ParallelComm::get_entityset_procs( EntityHandle set, std::vector< unsigned >& ranks ) const
{
    return sharedSetData->get_sharing_procs( set, ranks );
}

ErrorCode ParallelComm::get_entityset_owner( EntityHandle entity_set,
                                             unsigned& owner_rank,
                                             EntityHandle* remote_handle ) const
{
    if( remote_handle )
        return sharedSetData->get_owner( entity_set, owner_rank, *remote_handle );
    else
        return sharedSetData->get_owner( entity_set, owner_rank );
}

ErrorCode ParallelComm::get_entityset_local_handle( unsigned owning_rank,
                                                    EntityHandle remote_handle,
                                                    EntityHandle& local_handle ) const
{
    return sharedSetData->get_local_handle( owning_rank, remote_handle, local_handle );
}

ErrorCode ParallelComm::get_shared_sets( Range& result ) const
{
    return sharedSetData->get_shared_sets( result );
}

ErrorCode ParallelComm::get_entityset_owners( std::vector< unsigned >& ranks ) const
{
    return sharedSetData->get_owning_procs( ranks );
}

ErrorCode ParallelComm::get_owned_sets( unsigned owning_rank, Range& sets_out ) const
{
    return sharedSetData->get_shared_sets( owning_rank, sets_out );
}

ErrorCode ParallelComm::gather_data( Range& gather_ents,
                                     Tag& tag_handle,
                                     Tag id_tag,
                                     EntityHandle gather_set,
                                     int root_proc_rank )
{
    int dim           = mbImpl->dimension_from_handle( *gather_ents.begin() );
    int bytes_per_tag = 0;
    ErrorCode rval    = mbImpl->tag_get_bytes( tag_handle, bytes_per_tag );
    if( rval != MB_SUCCESS ) return rval;

    int sz_buffer         = sizeof( int ) + gather_ents.size() * ( sizeof( int ) + bytes_per_tag );
    void* senddata        = malloc( sz_buffer );
    ( (int*)senddata )[0] = (int)gather_ents.size();
    int* ptr_int          = (int*)senddata + 1;
    rval                  = mbImpl->tag_get_data( id_tag, gather_ents, (void*)ptr_int );
    if( rval != MB_SUCCESS ) return rval;<--- Memory leak: senddata
    ptr_int = (int*)( senddata ) + 1 + gather_ents.size();
    rval    = mbImpl->tag_get_data( tag_handle, gather_ents, (void*)ptr_int );
    if( rval != MB_SUCCESS ) return rval;<--- Memory leak: senddata
    std::vector< int > displs( proc_config().proc_size(), 0 );
    MPI_Gather( &sz_buffer, 1, MPI_INT, &displs[0], 1, MPI_INT, root_proc_rank, comm() );
    std::vector< int > recvcnts( proc_config().proc_size(), 0 );
    std::copy( displs.begin(), displs.end(), recvcnts.begin() );
    std::partial_sum( displs.begin(), displs.end(), displs.begin() );
    std::vector< int >::iterator lastM1 = displs.end() - 1;
    std::copy_backward( displs.begin(), lastM1, displs.end() );
    // std::copy_backward(displs.begin(), --displs.end(), displs.end());
    displs[0] = 0;

    if( (int)rank() != root_proc_rank )
        MPI_Gatherv( senddata, sz_buffer, MPI_BYTE, NULL, NULL, NULL, MPI_BYTE, root_proc_rank, comm() );
    else
    {
        Range gents;
        mbImpl->get_entities_by_dimension( gather_set, dim, gents );
        int recvbuffsz = gents.size() * ( bytes_per_tag + sizeof( int ) ) + proc_config().proc_size() * sizeof( int );
        void* recvbuf  = malloc( recvbuffsz );
        MPI_Gatherv( senddata, sz_buffer, MPI_BYTE, recvbuf, &recvcnts[0], &displs[0], MPI_BYTE, root_proc_rank,
                     comm() );

        void* gvals = NULL;

        // Test whether gents has multiple sequences
        bool multiple_sequences = false;
        if( gents.psize() > 1 )
            multiple_sequences = true;
        else
        {
            int count;
            rval = mbImpl->tag_iterate( tag_handle, gents.begin(), gents.end(), count, gvals );<--- Variable 'rval' is assigned a value that is never used.
            assert( NULL != gvals );
            assert( count > 0 );
            if( (size_t)count != gents.size() )
            {
                multiple_sequences = true;
                gvals              = NULL;
            }
        }

        // If gents has multiple sequences, create a temp buffer for gathered values
        if( multiple_sequences )
        {
            gvals = malloc( gents.size() * bytes_per_tag );
            assert( NULL != gvals );
        }

        for( int i = 0; i != (int)size(); i++ )
        {
            int numents   = *(int*)( ( (char*)recvbuf ) + displs[i] );
            int* id_ptr   = (int*)( ( (char*)recvbuf ) + displs[i] + sizeof( int ) );
            char* val_ptr = (char*)( id_ptr + numents );
            for( int j = 0; j != numents; j++ )
            {
                int idx = id_ptr[j];
                memcpy( (char*)gvals + ( idx - 1 ) * bytes_per_tag, val_ptr + j * bytes_per_tag, bytes_per_tag );
            }
        }

        // Free the receive buffer
        free( recvbuf );

        // If gents has multiple sequences, copy tag data (stored in the temp buffer) to each
        // sequence separately
        if( multiple_sequences )
        {
            Range::iterator iter = gents.begin();
            size_t start_idx     = 0;
            while( iter != gents.end() )
            {
                int count;
                void* ptr;
                rval = mbImpl->tag_iterate( tag_handle, iter, gents.end(), count, ptr );<--- Variable 'rval' is assigned a value that is never used.
                assert( NULL != ptr );
                assert( count > 0 );
                memcpy( (char*)ptr, (char*)gvals + start_idx * bytes_per_tag, bytes_per_tag * count );

                iter += count;
                start_idx += count;
            }
            assert( start_idx == gents.size() );

            // Free the temp buffer
            free( gvals );
        }
    }

    // Free the send data
    free( senddata );

    return MB_SUCCESS;
}

/*
 * This call is collective, so we will use the message ids for tag communications;
 * they are similar, but simpler
 * Pack the number of edges, the remote edge handles, then for each edge, the number
 *    of intersection points, and then 3 doubles for each intersection point
 * On average, there is one intx point per edge, in some cases 2, in some cases 0
 *   so on average, the message size is num_edges * (sizeof(eh) + sizeof(int) + 1*3*sizeof(double))
 *          = num_edges * (8 + 4 + 24)
 */
ErrorCode ParallelComm::settle_intersection_points( Range& edges,<--- The function 'settle_intersection_points' is never used.
                                                    Range& shared_edges_owned,<--- Parameter 'shared_edges_owned' can be declared with const
                                                    std::vector< std::vector< EntityHandle >* >& extraNodesVec,
                                                    double tolerance )
{
    // The index of an edge in the edges Range will give the index for extraNodesVec
    // the strategy of this follows exchange tags strategy:
    ErrorCode result;
    int success;

    myDebug->tprintf( 1, "Entering settle_intersection_points\n" );

    // Get all procs interfacing to this proc
    std::set< unsigned int > exch_procs;
    result = get_comm_procs( exch_procs );<--- Variable 'result' is assigned a value that is never used.

    // Post ghost irecv's for all interface procs
    // Index requests the same as buffer/sharing procs indices
    std::vector< MPI_Request > recv_intx_reqs( 3 * buffProcs.size(), MPI_REQUEST_NULL );
    std::vector< unsigned int >::iterator sit;
    int ind;

    reset_all_buffers();
    int incoming = 0;

    for( ind = 0, sit = buffProcs.begin(); sit != buffProcs.end(); ++sit, ind++ )
    {
        incoming++;
        PRINT_DEBUG_IRECV( *sit, procConfig.proc_rank(), remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE,
                           MB_MESG_TAGS_SIZE, incoming );

        success = MPI_Irecv( remoteOwnedBuffs[ind]->mem_ptr, INITIAL_BUFF_SIZE, MPI_UNSIGNED_CHAR, *sit,
                             MB_MESG_TAGS_SIZE, procConfig.proc_comm(), &recv_intx_reqs[3 * ind] );
        if( success != MPI_SUCCESS )
        {
            MB_SET_ERR( MB_FAILURE, "Failed to post irecv in settle intersection point" );
        }
    }

    // Pack and send intersection points from this proc to others
    // Make sendReqs vector to simplify initialization
    sendReqs.resize( 3 * buffProcs.size(), MPI_REQUEST_NULL );

    // Take all shared entities if incoming list is empty
    Range& entities = shared_edges_owned;<--- Variable 'entities' can be declared with const

    int dum_ack_buff;

    for( ind = 0, sit = buffProcs.begin(); sit != buffProcs.end(); ++sit, ind++ )
    {
        Range edges_to_send = entities;

        // Get ents shared by proc *sit
        result = filter_pstatus( edges_to_send, PSTATUS_SHARED, PSTATUS_AND, *sit );MB_CHK_SET_ERR( result, "Failed pstatus AND check" );

        // Remote nonowned entities; not needed, edges are already owned by this proc

        // Pack the data
        // Reserve space on front for size and for initial buff size
        Buffer* buff = localOwnedBuffs[ind];
        buff->reset_ptr( sizeof( int ) );

        /*result = pack_intx_points(edges_to_send, edges, extraNodesVec,
            localOwnedBuffs[ind], *sit);*/

        // Count first data, and see if it is enough room?
        // Send the remote handles
        std::vector< EntityHandle > dum_remote_edges( edges_to_send.size() );
        /*
         *  get_remote_handles(const bool store_remote_handles,
                                   EntityHandle *from_vec,
                                   EntityHandle *to_vec_tmp,
                                   int num_ents, int to_proc,
                                   const std::vector<EntityHandle> &new_ents);
         */
        // We are sending count, num edges, remote edges handles, and then, for each edge:
        //          -- nb intx points, 3*nbintPointsforEdge "doubles"
        std::vector< EntityHandle > dum_vec;
        result = get_remote_handles( true, edges_to_send, &dum_remote_edges[0], *sit, dum_vec );MB_CHK_SET_ERR( result, "Failed to get remote handles" );
        int count = 4;  // Size of data
        count += sizeof( int ) * (int)edges_to_send.size();
        count += sizeof( EntityHandle ) * (int)edges_to_send.size();  // We will send the remote handles
        for( Range::iterator eit = edges_to_send.begin(); eit != edges_to_send.end(); ++eit )
        {
            EntityHandle edge                       = *eit;
            unsigned int indx                       = edges.find( edge ) - edges.begin();
            std::vector< EntityHandle >& intx_nodes = *( extraNodesVec[indx] );
            count += (int)intx_nodes.size() * 3 * sizeof( double );  // 3 integer for each entity handle
        }
        //
        buff->check_space( count );
        PACK_INT( buff->buff_ptr, edges_to_send.size() );
        PACK_EH( buff->buff_ptr, &dum_remote_edges[0], dum_remote_edges.size() );
        for( Range::iterator eit = edges_to_send.begin(); eit != edges_to_send.end(); ++eit )
        {
            EntityHandle edge = *eit;
            // Pack the remote edge
            unsigned int indx                       = edges.find( edge ) - edges.begin();
            std::vector< EntityHandle >& intx_nodes = *( extraNodesVec[indx] );
            PACK_INT( buff->buff_ptr, intx_nodes.size() );

            result = mbImpl->get_coords( &intx_nodes[0], intx_nodes.size(), (double*)buff->buff_ptr );MB_CHK_SET_ERR( result, "Failed to get coords" );<--- Casting between unsigned char * and double * which have an incompatible binary data representation.
            buff->buff_ptr += 3 * sizeof( double ) * intx_nodes.size();
        }

        // Done packing the intx points and remote edges
        buff->set_stored_size();

        // Now send it
        result = send_buffer( *sit, localOwnedBuffs[ind], MB_MESG_TAGS_SIZE, sendReqs[3 * ind],
                              recv_intx_reqs[3 * ind + 2], &dum_ack_buff, incoming );MB_CHK_SET_ERR( result, "Failed to send buffer" );
    }

    // Receive/unpack intx points
    while( incoming )
    {
        MPI_Status status;
        int index_in_recv_requests;
        PRINT_DEBUG_WAITANY( recv_intx_reqs, MB_MESG_TAGS_SIZE, procConfig.proc_rank() );
        success = MPI_Waitany( 3 * buffProcs.size(), &recv_intx_reqs[0], &index_in_recv_requests, &status );
        if( MPI_SUCCESS != success )
        {
            MB_SET_ERR( MB_FAILURE, "Failed in waitany in ghost exchange" );
        }
        // Processor index in the list is divided by 3
        ind = index_in_recv_requests / 3;

        PRINT_DEBUG_RECD( status );

        // OK, received something; decrement incoming counter
        incoming--;

        bool done = false;
        result    = recv_buffer( MB_MESG_TAGS_SIZE, status, remoteOwnedBuffs[ind],
                                 recv_intx_reqs[3 * ind + 1],  // This is for receiving the second message
                                 recv_intx_reqs[3 * ind + 2],  // This would be for ack, but it is not
                                                               // used; consider removing it
                                 incoming, localOwnedBuffs[ind],
                                 sendReqs[3 * ind + 1],  // Send request for sending the second message
                                 sendReqs[3 * ind + 2],  // This is for sending the ack
                                 done );MB_CHK_SET_ERR( result, "Failed to resize recv buffer" );
        if( done )
        {
            Buffer* buff = remoteOwnedBuffs[ind];
            buff->reset_ptr( sizeof( int ) );
            /*result = unpack_tags(remoteOwnedBuffs[ind/2]->buff_ptr, dum_vec, true,
                buffProcs[ind/2]);*/
            // Unpack now the edges and vertex info; compare with the existing vertex positions

            int num_edges;

            UNPACK_INT( buff->buff_ptr, num_edges );
            std::vector< EntityHandle > rec_edges;
            rec_edges.resize( num_edges );
            UNPACK_EH( buff->buff_ptr, &rec_edges[0], num_edges );
            for( int i = 0; i < num_edges; i++ )
            {
                EntityHandle edge                       = rec_edges[i];
                unsigned int indx                       = edges.find( edge ) - edges.begin();
                std::vector< EntityHandle >& intx_nodes = *( extraNodesVec[indx] );
                // Now get the number of nodes on this (now local) edge
                int nverts;
                UNPACK_INT( buff->buff_ptr, nverts );
                std::vector< double > pos_from_owner;
                pos_from_owner.resize( 3 * nverts );
                UNPACK_DBLS( buff->buff_ptr, &pos_from_owner[0], 3 * nverts );
                std::vector< double > current_positions( 3 * intx_nodes.size() );
                result = mbImpl->get_coords( &intx_nodes[0], intx_nodes.size(), &current_positions[0] );MB_CHK_SET_ERR( result, "Failed to get current positions" );
                // Now, look at what we have in current pos, compare to pos from owner, and reset
                for( int k = 0; k < (int)intx_nodes.size(); k++ )
                {
                    double* pk = &current_positions[3 * k];
                    // Take the current pos k, and settle among the ones from owner:
                    bool found = false;
                    for( int j = 0; j < nverts && !found; j++ )
                    {
                        double* pj   = &pos_from_owner[3 * j];
                        double dist2 = ( pk[0] - pj[0] ) * ( pk[0] - pj[0] ) + ( pk[1] - pj[1] ) * ( pk[1] - pj[1] ) +
                                       ( pk[2] - pj[2] ) * ( pk[2] - pj[2] );
                        if( dist2 < tolerance )
                        {
                            pk[0] = pj[0];
                            pk[1] = pj[1];
                            pk[2] = pj[2];  // Correct it!
                            found = true;
                            break;
                        }
                    }
                    if( !found )
                    {
#ifndef NDEBUG
                        std::cout << " pk:" << pk[0] << " " << pk[1] << " " << pk[2] << " not found \n";
#endif
                        result = MB_FAILURE;<--- result is assigned
                    }
                }
                // After we are done resetting, we can set the new positions of nodes:
                result = mbImpl->set_coords( &intx_nodes[0], (int)intx_nodes.size(), &current_positions[0] );MB_CHK_SET_ERR( result, "Failed to set new current positions" );<--- result is overwritten
            }
        }
    }

    // OK, now wait
    if( myDebug->get_verbosity() == 5 )
    {
        success = MPI_Barrier( procConfig.proc_comm() );
    }
    else
    {
        MPI_Status status[3 * MAX_SHARING_PROCS];
        success = MPI_Waitall( 3 * buffProcs.size(), &sendReqs[0], status );
    }
    if( MPI_SUCCESS != success )
    {
        MB_SET_ERR( MB_FAILURE, "Failure in waitall in tag exchange" );
    }

    myDebug->tprintf( 1, "Exiting settle_intersection_points" );

    return MB_SUCCESS;
}

ErrorCode ParallelComm::delete_entities( Range& to_delete )
{
    // Will not look at shared sets yet, but maybe we should
    // First, see if any of the entities to delete is shared; then inform the other processors
    // about their fate (to be deleted), using a crystal router transfer
    ErrorCode rval = MB_SUCCESS;
    unsigned char pstat;
    EntityHandle tmp_handles[MAX_SHARING_PROCS];
    int tmp_procs[MAX_SHARING_PROCS];
    unsigned int num_ps;
    TupleList ents_to_delete;
    ents_to_delete.initialize( 1, 0, 1, 0, to_delete.size() * ( MAX_SHARING_PROCS + 1 ) );  // A little bit of overkill
    ents_to_delete.enableWriteAccess();
    unsigned int i = 0;
    for( Range::iterator it = to_delete.begin(); it != to_delete.end(); ++it )
    {
        EntityHandle eh = *it;  // Entity to be deleted

        rval = get_sharing_data( eh, tmp_procs, tmp_handles, pstat, num_ps );
        if( rval != MB_SUCCESS || num_ps == 0 ) continue;
        // Add to the tuple list the information to be sent (to the remote procs)
        for( unsigned int p = 0; p < num_ps; p++ )
        {
            ents_to_delete.vi_wr[i]  = tmp_procs[p];
            ents_to_delete.vul_wr[i] = (unsigned long)tmp_handles[p];
            i++;
            ents_to_delete.inc_n();
        }
    }

    gs_data::crystal_data* cd = this->procConfig.crystal_router();
    // All communication happens here; no other mpi calls
    // Also, this is a collective call
    rval = cd->gs_transfer( 1, ents_to_delete, 0 );MB_CHK_SET_ERR( rval, "Error in tuple transfer" );

    // Add to the range of ents to delete the new ones that were sent from other procs
    unsigned int received = ents_to_delete.get_n();
    for( i = 0; i < received; i++ )
    {
        // int from = ents_to_delete.vi_rd[i];
        unsigned long valrec = ents_to_delete.vul_rd[i];
        to_delete.insert( (EntityHandle)valrec );
    }
    rval = mbImpl->delete_entities( to_delete );MB_CHK_SET_ERR( rval, "Error in deleting actual entities" );

    std::set< EntityHandle > good_ents;
    for( std::set< EntityHandle >::iterator sst = sharedEnts.begin(); sst != sharedEnts.end(); sst++ )
    {
        EntityHandle eh = *sst;
        int index       = to_delete.index( eh );
        if( -1 == index ) good_ents.insert( eh );
    }
    sharedEnts = good_ents;

    // What about shared sets? Who is updating them?
    return MB_SUCCESS;
}

void ParallelComm::print_pstatus( unsigned char pstat, std::string& ostr )
{
    std::ostringstream str;
    int num = 0;
#define ppstat( a, b )             \
    {                              \
        if( pstat & ( a ) )        \
        {                          \
            if( num ) str << ", "; \
            str << ( b );          \
            num++;                 \
        }                          \
    }

    ppstat( PSTATUS_NOT_OWNED, "NOT_OWNED" );
    ppstat( PSTATUS_SHARED, "SHARED" );
    ppstat( PSTATUS_MULTISHARED, "MULTISHARED" );
    ppstat( PSTATUS_INTERFACE, "INTERFACE" );
    ppstat( PSTATUS_GHOST, "GHOST" );<--- Variable 'num' is assigned a value that is never used.

    ostr = str.str();
}

void ParallelComm::print_pstatus( unsigned char pstat )
{
    std::string str;
    print_pstatus( pstat, str );
    std::cout << str.c_str() << std::endl;
}

ErrorCode ParallelComm::correct_thin_ghost_layers()
{

    // Get all shared ent data from other procs
    std::vector< std::vector< SharedEntityData > > shents( buffProcs.size() ), send_data( buffProcs.size() );

    // will work only on multi-shared tags  sharedps_tag(), sharedhs_tag();

    /*
     *   domain0 | domain1 | domain2 | domain3
     *   vertices from domain 1 and 2 are visible from both 0 and 3, but
     *   domain 0 might not have info about multi-sharing from domain 3
     *   so we will force that domain 0 vertices owned by 1 and 2 have information
     *   about the domain 3 sharing
     *
     *   SharedEntityData will have :
     *    struct SharedEntityData {
            EntityHandle local;  // this is same meaning, for the proc we sent to, it is local
            EntityHandle remote; // this will be the far away handle that will need to be added
            EntityID owner;      // this will be the remote proc
          };
          // so we need to add data like this:
           a multishared entity owned by proc x will have data like
             multishared procs:  proc x, a, b, c
             multishared handles:     h1, h2, h3, h4
             we will need to send data from proc x like this:
               to proc a we will send
                 (h2, h3, b), (h2, h4, c)
               to proc b we will send
                  (h3, h2, a), (h3, h4, c)
               to proc c we will send
                  (h4, h2, a), (h4, h3, b)
     *
     */

    ErrorCode result = MB_SUCCESS;
    int ent_procs[MAX_SHARING_PROCS + 1];
    EntityHandle handles[MAX_SHARING_PROCS + 1];
    int num_sharing;
    SharedEntityData tmp;

    for( std::set< EntityHandle >::iterator i = sharedEnts.begin(); i != sharedEnts.end(); ++i )
    {

        unsigned char pstat;
        result = get_sharing_data( *i, ent_procs, handles, pstat, num_sharing );MB_CHK_SET_ERR( result, "can't get sharing data" );
        if( !( pstat & PSTATUS_MULTISHARED ) ||
            num_sharing <= 2 )  // if not multishared, skip, it should have no problems
            continue;
        // we should skip the ones that are not owned locally
        // the owned ones will have the most multi-shared info, because the info comes from other
        // remote processors
        if( pstat & PSTATUS_NOT_OWNED ) continue;
        for( int j = 1; j < num_sharing; j++ )
        {
            // we will send to proc
            int send_to_proc = ent_procs[j];  //
            tmp.local        = handles[j];
            int ind          = get_buffers( send_to_proc );
            assert( -1 != ind );  // THIS SHOULD NEVER HAPPEN
            for( int k = 1; k < num_sharing; k++ )
            {
                // do not send to self proc
                if( j == k ) continue;
                tmp.remote = handles[k];  // this will be the handle of entity on proc
                tmp.owner  = ent_procs[k];
                send_data[ind].push_back( tmp );
            }
        }
    }

    result = exchange_all_shared_handles( send_data, shents );MB_CHK_ERR( result );

    // loop over all shents and add if vertex type, add if missing
    for( size_t i = 0; i < shents.size(); i++ )
    {
        std::vector< SharedEntityData >& shEnts = shents[i];
        for( size_t j = 0; j < shEnts.size(); j++ )
        {
            tmp = shEnts[j];
            // basically, check the shared data for tmp.local entity
            // it should have inside the tmp.owner and tmp.remote
            EntityHandle eh = tmp.local;
            unsigned char pstat;
            result = get_sharing_data( eh, ent_procs, handles, pstat, num_sharing );MB_CHK_SET_ERR( result, "can't get sharing data" );
            // see if the proc tmp.owner is in the list of ent_procs; if not, we have to increase
            // handles, and ent_procs; and set

            int proc_remote = tmp.owner;  //
            if( std::find( ent_procs, ent_procs + num_sharing, proc_remote ) == ent_procs + num_sharing )
            {
                // so we did not find on proc
#ifndef NDEBUG
                std::cout << "THIN GHOST: we did not find on proc " << rank() << " for shared ent " << eh
                          << " the proc " << proc_remote << "\n";
#endif
                // increase num_sharing, and set the multi-shared tags
                if( num_sharing >= MAX_SHARING_PROCS ) return MB_FAILURE;
                handles[num_sharing]       = tmp.remote;
                handles[num_sharing + 1]   = 0;  // end of list
                ent_procs[num_sharing]     = tmp.owner;
                ent_procs[num_sharing + 1] = -1;  // this should be already set
                result                     = mbImpl->tag_set_data( sharedps_tag(), &eh, 1, ent_procs );MB_CHK_SET_ERR( result, "Failed to set sharedps tag data" );
                result = mbImpl->tag_set_data( sharedhs_tag(), &eh, 1, handles );MB_CHK_SET_ERR( result, "Failed to set sharedhs tag data" );
                if( 2 == num_sharing )  // it means the sharedp and sharedh tags were set with a
                                        // value non default
                {
                    // so entity eh was simple shared before, we need to set those dense tags back
                    // to default
                    //  values
                    EntityHandle zero = 0;
                    int no_proc       = -1;
                    result            = mbImpl->tag_set_data( sharedp_tag(), &eh, 1, &no_proc );MB_CHK_SET_ERR( result, "Failed to set sharedp tag data" );
                    result = mbImpl->tag_set_data( sharedh_tag(), &eh, 1, &zero );MB_CHK_SET_ERR( result, "Failed to set sharedh tag data" );
                    // also, add multishared pstatus tag
                    // also add multishared status to pstatus
                    pstat  = pstat | PSTATUS_MULTISHARED;
                    result = mbImpl->tag_set_data( pstatus_tag(), &eh, 1, &pstat );MB_CHK_SET_ERR( result, "Failed to set pstatus tag data" );
                }
            }
        }
    }
    return MB_SUCCESS;
}
}  // namespace moab