This file is indexed.

/usr/include/trilinos/Zoltan2_AlgMultiJagged.hpp is in libtrilinos-zoltan2-dev 12.10.1-3.

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

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
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
// @HEADER
//
// ***********************************************************************
//
//   Zoltan2: A package of combinatorial algorithms for scientific computing
//                  Copyright 2012 Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Karen Devine      (kddevin@sandia.gov)
//                    Erik Boman        (egboman@sandia.gov)
//                    Siva Rajamanickam (srajama@sandia.gov)
//
// ***********************************************************************
//
// @HEADER
/*! \file Zoltan2_AlgMultiJagged.hpp
  \brief Contains the Multi-jagged algorthm.
 */

#ifndef _ZOLTAN2_ALGMultiJagged_HPP_
#define _ZOLTAN2_ALGMultiJagged_HPP_

#include <Zoltan2_MultiJagged_ReductionOps.hpp>
#include <Zoltan2_CoordinateModel.hpp>
#include <Zoltan2_Parameters.hpp>
#include <Zoltan2_Algorithm.hpp>
#include <Zoltan2_IntegerRangeList.hpp>
#include <Teuchos_StandardParameterEntryValidators.hpp>

#include <Tpetra_Distributor.hpp>
#include <Teuchos_ParameterList.hpp>
#include <Zoltan2_CoordinatePartitioningGraph.hpp>
#include <new>          // ::operator new[]
#include <algorithm>    // std::sort
#include <Zoltan2_Util.hpp>
#include <vector>

#if defined(__cplusplus) && __cplusplus >= 201103L
#include <unordered_map>
#else
#include <Teuchos_Hashtable.hpp>
#endif // C++11 is enabled

#ifdef ZOLTAN2_USEZOLTANCOMM
#ifdef HAVE_ZOLTAN2_MPI
#define ENABLE_ZOLTAN_MIGRATION
#include "zoltan_comm_cpp.h"
#include "zoltan_types.h" // for error codes
#endif
#endif

#ifdef HAVE_ZOLTAN2_OMP
#include <omp.h>
#endif

#define LEAST_SIGNIFICANCE 0.0001
#define SIGNIFICANCE_MUL 1000

//if the (last dimension reduce all count) x the mpi world size
//estimated to be bigger than this number then migration will be forced
//in earlier iterations.
#define FUTURE_REDUCEALL_CUTOFF 1500000
//if parts right before last dimension are estimated to have less than
//MIN_WORK_LAST_DIM many coords, migration will be forced in earlier iterations.
#define MIN_WORK_LAST_DIM 1000




#define ZOLTAN2_ABS(x) ((x) >= 0 ? (x) : -(x))
//imbalance calculation. Wreal / Wexpected - 1
#define imbalanceOf(Wachieved, totalW, expectedRatio) \
        (Wachieved) / ((totalW) * (expectedRatio)) - 1
#define imbalanceOf2(Wachieved, wExpected) \
        (Wachieved) / (wExpected) - 1


#define ZOLTAN2_ALGMULTIJAGGED_SWAP(a,b,temp) temp=(a);(a)=(b);(b)=temp;


namespace Teuchos{

/*! \brief Zoltan2_BoxBoundaries is a reduction operation
 * to all reduce the all box boundaries.
*/

template <typename Ordinal, typename T>
class Zoltan2_BoxBoundaries  : public ValueTypeReductionOp<Ordinal,T>
{
private:
    Ordinal size;
    T _EPSILON;

public:
    /*! \brief Default Constructor
     */
    Zoltan2_BoxBoundaries ():size(0), _EPSILON (std::numeric_limits<T>::epsilon()){}

    /*! \brief Constructor
     *   \param nsum  the count of how many sums will be computed at the
     *             start of the list.
     *   \param nmin  following the sums, this many minimums will be computed.
     *   \param nmax  following the minimums, this many maximums will be computed.
     */
    Zoltan2_BoxBoundaries (Ordinal s_):
        size(s_), _EPSILON (std::numeric_limits<T>::epsilon()){}

    /*! \brief Implement Teuchos::ValueTypeReductionOp interface
     */
    void reduce( const Ordinal count, const T inBuffer[], T inoutBuffer[]) const
    {
        for (Ordinal i=0; i < count; i++){
            if (Z2_ABS(inBuffer[i]) >  _EPSILON){
                inoutBuffer[i] = inBuffer[i];
            }
        }
    }
};
} // namespace Teuchos

namespace Zoltan2{

/*! \brief Allocates memory for the given size.
 *
 */
template <typename T>
T *allocMemory(size_t size){
    if (size > 0){
        T * a = new T[size];
        if (a == NULL) {
            throw  "cannot allocate memory";
        }
        return a;
    }
    else {
        return NULL;
    }
}

/*! \brief Frees the given array.
 *
 */
template <typename T>
void freeArray(T *&array){
    if(array != NULL){
        delete [] array;
        array = NULL;
    }
}


/*! \brief Class for sorting items with multiple values.
 * First sorting with respect to val[0], then val[1] then ... val[count-1].
 * The last tie breaking is done with index values.
 * Used for task mapping partitioning where the points on a cut line needs to be
 * distributed consistently.
 *
 */
template <typename IT, typename CT, typename WT>
class uMultiSortItem
{
public:
    IT index;
    CT count;
    //unsigned int val;
    WT *val;
    WT _EPSILON;

    uMultiSortItem(){
        this->index = 0;
        this->count = 0;
        this->val = NULL;
        this->_EPSILON = std::numeric_limits<WT>::epsilon() * 100;
    }


    uMultiSortItem(IT index_ ,CT count_, WT *vals_){
        this->index = index_;
        this->count = count_;
        this->val = vals_;
        this->_EPSILON = std::numeric_limits<WT>::epsilon() * 100;
    }

    uMultiSortItem( const uMultiSortItem<IT,CT,WT>& other ){
        this->index = other.index;
        this->count = other.count;
        this->val = other.val;
        this->_EPSILON = other._EPSILON;
    }

    ~uMultiSortItem(){
        //freeArray<WT>(this->val);
    }

    void set(IT index_ ,CT count_, WT *vals_){
        this->index = index_;
        this->count = count_;
        this->val = vals_;
    }


    uMultiSortItem<IT,CT,WT> operator=(const uMultiSortItem<IT,CT,WT>& other){
        this->index = other.index;
        this->count = other.count;
        this->val = other.val;
        return *(this);
    }

    bool operator<(const uMultiSortItem<IT,CT,WT>& other) const{
        assert (this->count == other.count);
        for(CT i = 0; i < this->count; ++i){
            //if the values are equal go to next one.
            if (ZOLTAN2_ABS(this->val[i] - other.val[i]) < this->_EPSILON){
                continue;
            }
            //if next value is smaller return true;
            if(this->val[i] < other.val[i]){
                return true;
            }
            //if next value is bigger return false;
            else {
                return false;
            }
        }
        //if they are totally equal.
        return this->index < other.index;
    }
    bool operator>(const uMultiSortItem<IT,CT,WT>& other) const{
        assert (this->count == other.count);
        for(CT i = 0; i < this->count; ++i){
            //if the values are equal go to next one.
            if (ZOLTAN2_ABS(this->val[i] - other.val[i]) < this->_EPSILON){
                continue;
            }
            //if next value is bigger return true;
            if(this->val[i] > other.val[i]){
                return true;
            }
            //if next value is smaller return false;
            else //(this->val[i] > other.val[i])
            {
                return false;
            }
        }
        //if they are totally equal.
        return this->index > other.index;
    }
};// uSortItem;

/*! \brief Sort items for quick sort function.
 *
 */
template <class IT, class WT>
struct uSortItem
{
    IT id;
    //unsigned int val;
    WT val;
};// uSortItem;

/*! \brief Quick sort function.
 *      Sorts the arr of uSortItems, with respect to increasing vals.
 */
template <class IT, class WT>
void uqsort(IT n, uSortItem<IT, WT> * arr)
{

    int NSTACK = 50;
    int M = 7;
    IT         i, ir=n, j, k, l=1;
    IT         jstack=0, istack[50];
    WT aval;
    uSortItem<IT,WT>    a, temp;

    --arr;
    for (;;)
    {
        if (ir-l < M)
        {
            for (j=l+1;j<=ir;j++)
            {
                a=arr[j];
                aval = a.val;
                for (i=j-1;i>=1;i--)
                {
                    if (arr[i].val <= aval)
                        break;
                    arr[i+1] = arr[i];
                }
                arr[i+1]=a;
            }
            if (jstack == 0)
                break;
            ir=istack[jstack--];
            l=istack[jstack--];
        }
        else
        {
            k=(l+ir) >> 1;

            ZOLTAN2_ALGMULTIJAGGED_SWAP(arr[k],arr[l+1], temp)
            if (arr[l+1].val > arr[ir].val)
            {
                ZOLTAN2_ALGMULTIJAGGED_SWAP(arr[l+1],arr[ir],temp)
            }
            if (arr[l].val > arr[ir].val)
            {
                ZOLTAN2_ALGMULTIJAGGED_SWAP(arr[l],arr[ir],temp)
            }
            if (arr[l+1].val > arr[l].val)
            {
                ZOLTAN2_ALGMULTIJAGGED_SWAP(arr[l+1],arr[l],temp)
            }
            i=l+1;
            j=ir;
            a=arr[l];
            aval = a.val;
            for (;;)
            {
                do i++; while (arr[i].val < aval);
                do j--; while (arr[j].val > aval);
                if (j < i) break;
                ZOLTAN2_ALGMULTIJAGGED_SWAP(arr[i],arr[j],temp);
            }
            arr[l]=arr[j];
            arr[j]=a;
            jstack += 2;
            if (jstack > NSTACK){
                std::cout << "uqsort: NSTACK too small in sort." << std::endl;
                exit(1);
            }
            if (ir-i+1 >= j-l)
            {
                istack[jstack]=ir;
                istack[jstack-1]=i;
                ir=j-1;
            }
            else
            {
                istack[jstack]=j-1;
                istack[jstack-1]=l;
                l=i;
            }
        }
    }
}

template <class IT, class WT, class SIGN>
struct uSignedSortItem
{
    IT id;
    //unsigned int val;
    WT val;
    SIGN signbit; // 1 means positive, 0 means negative.
    bool operator<(const uSignedSortItem<IT, WT, SIGN>& rhs) const {
      /*if I am negative, the other is positive*/
      if (this->signbit < rhs.signbit){
        return true;
      }
      /*if both has the same sign*/
      else if (this->signbit == rhs.signbit){

        if (this->val < rhs.val){//if my value is smaller,
          return this->signbit;//then if we both are positive return true.
                              //if we both are negative, return false.
        }
        else if (this->val > rhs.val){//if my value is larger,
          return !this->signbit; //then if we both are positive return false.
                                //if we both are negative, return true.
        }
        else { //if both are equal.
          return false;
        }
      }
      else {
        /*if I am positive, the other is negative*/
        return false;
      }

    }
    bool operator>(const uSignedSortItem<IT, WT, SIGN>& rhs) const {
      /*if I am positive, the other is negative*/
      if (this->signbit > rhs.signbit){
        return true;
      }
      /*if both has the same sign*/
      else if (this->signbit == rhs.signbit){

        if (this->val < rhs.val){//if my value is smaller,
          return !this->signbit;//then if we both are positive return false.
                              //if we both are negative, return true.
        }
        else if (this->val > rhs.val){//if my value is larger,
          return this->signbit; //then if we both are positive return true.
                                //if we both are negative, return false.
        }
        else { // if they are equal
          return false;
        }
      }
      else {
        /*if I am negative, the other is positive*/
        return false;
      }
    }
    bool operator<=(const uSignedSortItem<IT, WT, SIGN>& rhs){
      return !(*this > rhs);}
    bool operator>=(const uSignedSortItem<IT, WT, SIGN>& rhs){
      return !(*this  < rhs);}
};

/*! \brief Quick sort function.
 *      Sorts the arr of uSignedSortItems, with respect to increasing vals.
 */
template <class IT, class WT, class SIGN>
void uqSignsort(IT n, uSignedSortItem<IT, WT, SIGN> * arr){

    IT NSTACK = 50;
    IT M = 7;
    IT         i, ir=n, j, k, l=1;
    IT         jstack=0, istack[50];
    uSignedSortItem<IT,WT,SIGN>    a, temp;

    --arr;
    for (;;)
    {
        if (ir < M + l)
        {
            for (j=l+1;j<=ir;j++)
            {
                a=arr[j];
                for (i=j-1;i>=1;i--)
                {
                    if (arr[i] <= a)
                    {
                        break;
                    }
                    arr[i+1] = arr[i];
                }
                arr[i+1]=a;
            }
            if (jstack == 0)
                break;
            ir=istack[jstack--];
            l=istack[jstack--];
        }
        else
        {
            k=(l+ir) >> 1;
            ZOLTAN2_ALGMULTIJAGGED_SWAP(arr[k],arr[l+1], temp)
            if (arr[l+1] > arr[ir])
            {
                ZOLTAN2_ALGMULTIJAGGED_SWAP(arr[l+1],arr[ir],temp)
            }
            if (arr[l] > arr[ir])
            {
                ZOLTAN2_ALGMULTIJAGGED_SWAP(arr[l],arr[ir],temp)
            }
            if (arr[l+1] > arr[l])
            {
                ZOLTAN2_ALGMULTIJAGGED_SWAP(arr[l+1],arr[l],temp)
            }
            i=l+1;
            j=ir;
            a=arr[l];
            for (;;)
            {
                do i++; while (arr[i] < a);
                do j--; while (arr[j] > a);
                if (j < i) break;
                ZOLTAN2_ALGMULTIJAGGED_SWAP(arr[i],arr[j],temp);
            }
            arr[l]=arr[j];
            arr[j]=a;
            jstack += 2;
            if (jstack > NSTACK){
                std::cout << "uqsort: NSTACK too small in sort." << std::endl;
                exit(1);
            }
            if (ir+l+1 >= j+i)
            {
                istack[jstack]=ir;
                istack[jstack-1]=i;
                ir=j-1;
            }
            else
            {
                istack[jstack]=j-1;
                istack[jstack-1]=l;
                l=i;
            }
        }
    }
}

/*! \brief Multi Jagged coordinate partitioning algorithm.
 *
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
class AlgMJ
{
private:
    typedef coordinateModelPartBox<mj_scalar_t, mj_part_t> mj_partBox_t;
    typedef std::vector<mj_partBox_t> mj_partBoxVector_t;

    RCP<const Environment> mj_env; //the environment object
    RCP<const Comm<int> > mj_problemComm; //initial comm object

    double imbalance_tolerance; //input imbalance tolerance.
    mj_part_t *part_no_array; //input part array specifying num part to divide along each dim.
    int recursion_depth; //the number of steps that partitioning will be solved in.
    int coord_dim, num_weights_per_coord; //coordinate dim and # of weights per coord

    size_t initial_num_loc_coords; //initial num local coords.
    global_size_t initial_num_glob_coords; //initial num global coords.

    mj_lno_t num_local_coords; //number of local coords.
    mj_gno_t num_global_coords; //number of global coords.

    mj_scalar_t **mj_coordinates; //two dimension coordinate array
    mj_scalar_t **mj_weights; //two dimension weight array
    bool *mj_uniform_parts; //if the target parts are uniform
    mj_scalar_t **mj_part_sizes; //target part weight sizes.
    bool *mj_uniform_weights; //if the coordinates have uniform weights.

    ArrayView<const mj_gno_t> mj_gnos; //global ids of the coordinates, comes from the input
    size_t num_global_parts; //the targeted number of parts

    mj_gno_t *initial_mj_gnos; //initial global ids of the coordinates.
    mj_gno_t *current_mj_gnos; //current global ids of the coordinates, might change during migration.
    int *owner_of_coordinate; //the actual processor owner of the coordinate, to track after migrations.

    mj_lno_t *coordinate_permutations; //permutation of coordinates, for partitioning.
    mj_lno_t *new_coordinate_permutations; //permutation work array.
    mj_part_t *assigned_part_ids; //the part ids assigned to coordinates.

    mj_lno_t *part_xadj; //beginning and end of each part.
    mj_lno_t *new_part_xadj; // work array for beginning and end of each part.

    //get mj specific parameters.
    bool distribute_points_on_cut_lines; //if partitioning can distribute points on same coordiante to different parts.
    mj_part_t max_concurrent_part_calculation; // how many parts we can calculate concurrently.

    bool mj_run_as_rcb; //if this is set, then recursion depth is adjusted to its maximum value.
    int mj_user_recursion_depth; //the recursion depth value provided by user.
    bool mj_keep_part_boxes; //if the boxes need to be kept.

    int check_migrate_avoid_migration_option; //whether to migrate=1, avoid migrate=2, or leave decision to MJ=0
    mj_scalar_t minimum_migration_imbalance; //when MJ decides whether to migrate, the minimum imbalance for migration.
    int num_threads; //num threads

    mj_part_t total_num_cut ; //how many cuts will be totally
    mj_part_t total_num_part;    //how many parts will be totally

    mj_part_t max_num_part_along_dim ;         //maximum part count along a dimension.
    mj_part_t max_num_cut_along_dim; //maximum cut count along a dimension.
    size_t max_num_total_part_along_dim; //maximum part+cut count along a dimension.

    mj_part_t total_dim_num_reduce_all;    //estimate on #reduceAlls can be done.
    mj_part_t last_dim_num_part; //max no of parts that might occur
                                //during the partition before the
                                //last partitioning dimension.

    RCP<Comm<int> > comm; //comm object than can be altered during execution
    float fEpsilon; //epsilon for float
    mj_scalar_t sEpsilon; //epsilon for mj_scalar_t

    mj_scalar_t maxScalar_t; //max possible scalar
    mj_scalar_t minScalar_t; //min scalar

    mj_scalar_t *all_cut_coordinates;
    mj_scalar_t *max_min_coords;
    mj_scalar_t *process_cut_line_weight_to_put_left; //how much weight should a MPI put left side of the each cutline
    mj_scalar_t **thread_cut_line_weight_to_put_left; //how much weight percentage should each thread in MPI put left side of the each outline

    // work array to manipulate coordinate of cutlines in different iterations.
    //necessary because previous cut line information is used for determining
    //the next cutline information. therefore, cannot update the cut work array
    //until all cutlines are determined.
    mj_scalar_t *cut_coordinates_work_array;

    //cumulative part weight array.
    mj_scalar_t *target_part_weights;

    mj_scalar_t *cut_upper_bound_coordinates ;  //upper bound coordinate of a cut line
    mj_scalar_t *cut_lower_bound_coordinates ;  //lower bound coordinate of a cut line
    mj_scalar_t *cut_lower_bound_weights ;  //lower bound weight of a cut line
    mj_scalar_t *cut_upper_bound_weights ;  //upper bound weight of a cut line

    mj_scalar_t *process_local_min_max_coord_total_weight ; //combined array to exchange the min and max coordinate, and total weight of part.
    mj_scalar_t *global_min_max_coord_total_weight ;//global combined array with the results for min, max and total weight.

    //isDone is used to determine if a cutline is determined already.
    //If a cut line is already determined, the next iterations will skip this cut line.
    bool *is_cut_line_determined;
    //my_incomplete_cut_count count holds the number of cutlines that have not been finalized for each part
    //when concurrentPartCount>1, using this information, if my_incomplete_cut_count[x]==0, then no work is done for this part.
    mj_part_t *my_incomplete_cut_count;
    //local part weights of each thread.
    double **thread_part_weights;
    //the work manupulation array for partweights.
    double **thread_part_weight_work;

    //thread_cut_left_closest_point to hold the closest coordinate to a cutline from left (for each thread).
    mj_scalar_t **thread_cut_left_closest_point;
    //thread_cut_right_closest_point to hold the closest coordinate to a cutline from right (for each thread)
    mj_scalar_t **thread_cut_right_closest_point;

    //to store how many points in each part a thread has.
    mj_lno_t **thread_point_counts;

    mj_scalar_t *process_rectilinear_cut_weight;
    mj_scalar_t *global_rectilinear_cut_weight;

    //for faster communication, concatanation of
    //totalPartWeights sized 2P-1, since there are P parts and P-1 cut lines
    //leftClosest distances sized P-1, since P-1 cut lines
    //rightClosest distances size P-1, since P-1 cut lines.
    mj_scalar_t *total_part_weight_left_right_closests ;
    mj_scalar_t *global_total_part_weight_left_right_closests;

    RCP<mj_partBoxVector_t> kept_boxes;  // vector of all boxes for all parts;
                                         // constructed only if
                                         // mj_keep_part_boxes == true
    RCP<mj_partBox_t> global_box;
    int myRank, myActualRank; //processor rank, and initial rank

    /* \brief Either the mj array (part_no_array) or num_global_parts should be provided in
     * the input. part_no_array takes
     * precedence if both are provided.
     * Depending on these parameters, total cut/part number,
     * maximum part/cut number along a dimension, estimated number of reduceAlls,
     * and the number of parts before the last dimension is calculated.
     * */
    void set_part_specifications();

    /* \brief Tries to determine the part number for current dimension,
     * by trying to make the partitioning as square as possible.
     * \param num_total_future how many more partitionings are required.
     * \param root how many more recursion depth is left.
     */
    inline mj_part_t get_part_count(
                mj_part_t num_total_future,
                double root);

    /* \brief Allocates the all required memory for the mj partitioning algorithm.
     *
     */
    void allocate_set_work_memory();

    /* \brief for part communication we keep track of the box boundaries.
     * This is performed when either asked specifically, or when geometric mapping is performed afterwards.
     * This function initializes a single box with all global min and max coordinates.
     * \param initial_partitioning_boxes the input and output vector for boxes.
     */
    void init_part_boxes(RCP<mj_partBoxVector_t> & outPartBoxes);

    /* \brief compute global bounding box:  min/max coords of global domain */
    void compute_global_box();

    /* \brief Function returns how many parts that will be obtained after this dimension partitioning.
     * It sets how many parts each current part will be partitioned into in this dimension to num_partitioning_in_current_dim vector,
     * sets how many total future parts each obtained part will be partitioned into in next_future_num_parts_in_parts vector,
     * If part boxes are kept, then sets initializes the output_part_boxes as its ancestor.
     *
     *  \param num_partitioning_in_current_dim: output. How many parts each current part will be partitioned into.
     *  \param future_num_part_in_parts: input, how many future parts each current part will be partitioned into.
     *  \param next_future_num_parts_in_parts: output, how many future parts each obtained part will be partitioned into.
     *  \param future_num_parts: output, max number of future parts that will be obtained from a single
     *  \param current_num_parts: input, how many parts are there currently.
     *  \param current_iteration: input, current dimension iteration number.
     *  \param input_part_boxes: input, if boxes are kept, current boxes.
     *  \param output_part_boxes: output, if boxes are kept, the initial box boundaries for obtained parts.
     */
    mj_part_t update_part_num_arrays(
                std::vector<mj_part_t> &num_partitioning_in_current_dim, //assumes this vector is empty.
                std::vector<mj_part_t> *future_num_part_in_parts,
                std::vector<mj_part_t> *next_future_num_parts_in_parts, //assumes this vector is empty.
                mj_part_t &future_num_parts,
                mj_part_t current_num_parts,
                int current_iteration,
                RCP<mj_partBoxVector_t> input_part_boxes,
                RCP<mj_partBoxVector_t> output_part_boxes);

    /*! \brief Function to determine the local minimum and maximum coordinate, and local total weight
     * in the given set of local points.
     * \param coordinate_begin_index is the start index of the given partition on partitionedPointPermutations.
     * \param coordinate_end_index is the end index of the given partition on partitionedPointPermutations.
     * \param mj_current_coordinate_permutations is the permutation array that point to the actual coordinate index. Sized as numLocalCoords.
     * \param mj_current_dim_coords float-like array representing the coordinates in a single dimension. Sized as numLocalCoords.
     * \param min_coordinate is the output to represent the local minimumCoordinate in  given range of coordinates.
     * \param max_coordinate is the output to represent the local maximum coordinate in the given range of coordinates.
     * \param total_weight is the output to represent the local total weight in the coordinate in the given range of coordinates.
     *
     */
    void mj_get_local_min_max_coord_totW(
                mj_lno_t coordinate_begin_index,
                mj_lno_t coordinate_end_index,
                mj_lno_t *mj_current_coordinate_permutations,
                mj_scalar_t *mj_current_dim_coords,
                mj_scalar_t &min_coordinate,
                mj_scalar_t &max_coordinate,
                mj_scalar_t &total_weight);

    /*! \brief Function that reduces global minimum and maximum coordinates with global total weight from given local arrays.
     * \param current_concurrent_num_parts is the number of parts whose cut lines will be calculated concurrently.
     * \param local_min_max_total is the array holding local min and max coordinate values with local total weight.
     * First current_concurrent_num_parts entries are minimums of the parts, next current_concurrent_num_parts entries are max, and then the total weights.
     * \param global_min_max_total is the output array holding global min and global coordinate values with global total weight.
     * The structure is same as local_min_max_total.
     */
    void mj_get_global_min_max_coord_totW(
        mj_part_t current_concurrent_num_parts,
        mj_scalar_t *local_min_max_total,
        mj_scalar_t *global_min_max_total);

    /*! \brief Function that calculates the new coordinates for the cut lines. Function is called inside the parallel region.
     * \param min_coord minimum coordinate in the range.
     * \param max_coord maximum coordinate in the range.
     *
     * \param num_cuts holds the number of cuts in the current partitioning dimension.
     * \param global_weight holds the global total weight in the current part.
     *
     * \param initial_cut_coords is the output array for the initial cut lines.
     * \param target_part_weights is the output array holding the cumulative ratios of parts in current partitioning.
     * For partitioning to 4 uniformly, target_part_weights will be (0.25 * globalTotalWeight, 0.5 *globalTotalWeight , 0.75 * globalTotalWeight, globalTotalWeight).
     *
     * \param future_num_part_in_parts is the vector that holds how many more parts each part will be divided into more
     * for the parts at the beginning of this coordinate partitioning
     * \param next_future_num_parts_in_parts is the vector that holds how many more parts each part will be divided into more
     * for the parts that will be obtained at the end of this coordinate partitioning.
     * \param concurrent_current_part is the index of the part in the future_num_part_in_parts vector.
     * \param obtained_part_index holds the amount of shift in the next_future_num_parts_in_parts for the output parts.
     */
    void mj_get_initial_cut_coords_target_weights(
        mj_scalar_t min_coord,
        mj_scalar_t max_coord,
        mj_part_t num_cuts/*p-1*/ ,
        mj_scalar_t global_weight,
        mj_scalar_t *initial_cut_coords /*p - 1 sized, coordinate of each cut line*/,
        mj_scalar_t *target_part_weights /*cumulative weights, at left side of each cut line. p-1 sized*/,

        std::vector <mj_part_t> *future_num_part_in_parts, //the vecto
        std::vector <mj_part_t> *next_future_num_parts_in_parts,
        mj_part_t concurrent_current_part,
        mj_part_t obtained_part_index);

    /*! \brief Function that calculates the new coordinates for the cut lines. Function is called inside the parallel region.
     * \param max_coordinate maximum coordinate in the range.
     * \param min_coordinate minimum coordinate in the range.
     *
     * \param concurrent_current_part_index is the index of the part in the inTotalCounts vector.
     * \param coordinate_begin_index holds the beginning of the coordinates in current part.
     * \param coordinate_end_index holds end of the coordinates in current part.
     * \param mj_current_coordinate_permutations is the permutation array, holds the real indices of coordinates on mj_current_dim_coords array.
     * \param mj_current_dim_coords is the 1D array holding the coordinates.
     * \param mj_part_ids is the array holding the partIds of each coordinate.
     * \param partition_count is the number of parts that the current part will be partitioned into.
     */
    void set_initial_coordinate_parts(
        mj_scalar_t &max_coordinate,
        mj_scalar_t &min_coordinate,
        mj_part_t &concurrent_current_part_index,
        mj_lno_t coordinate_begin_index,
        mj_lno_t coordinate_end_index,
        mj_lno_t *mj_current_coordinate_permutations,
        mj_scalar_t *mj_current_dim_coords,
        mj_part_t *mj_part_ids,
        mj_part_t &partition_count);

    /*! \brief Function that is responsible from 1D partitioning of the given range of coordinates.
     * \param mj_current_dim_coords is 1 dimensional array holding coordinate values.
     * \param imbalanceTolerance is the maximum allowed imbalance ratio.
     * \param current_work_part is the beginning index of concurrentPartCount parts.
     * \param current_concurrent_num_parts is the number of parts whose cut lines will be calculated concurrently.
     * \param current_cut_coordinates is the array holding the coordinates of the cut.
     * \param total_incomplete_cut_count is the number of cut lines whose positions should be calculated.
     * \param num_partitioning_in_current_dim is the vector that holds how many parts each part will be divided into.
     *
     */
    void mj_1D_part(
        mj_scalar_t *mj_current_dim_coords,
        mj_scalar_t imbalanceTolerance,
        mj_part_t current_work_part,
        mj_part_t current_concurrent_num_parts,
        mj_scalar_t *current_cut_coordinates,
        mj_part_t total_incomplete_cut_count,
        std::vector <mj_part_t> &num_partitioning_in_current_dim);

    /*! \brief Function that calculates the weights of each part according to given part cut coordinates.
     * Function is called inside the parallel region. Thread specific work arrays are provided
     * as function parameter.
     *
     * \param total_part_count is the sum of number of cutlines and number of parts. Simply it is 2*P - 1.
     * \param num_cuts is the number of cut lines. P - 1.
     * \param max_coord is the maximum coordinate in the part.
     * \param min_coord is the min coordinate in the part.
     * \param coordinate_begin_index is the index of the first coordinate in current part.
     * \param coordinate_end_index is the index of the last coordinate in current part.
     * \param mj_current_dim_coords is 1 dimensional array holding coordinate values.
     *
     * \param temp_current_cut_coords is the array holding the coordinates of each cut line. Sized P - 1.
     * \param current_cut_status is the boolean array to determine if the correct position for a cut line is found.
     * \param my_current_part_weights is the array holding the part weights for the calling thread.
     * \param my_current_left_closest is the array holding the coordinate of the closest points to the cut lines from left for the calling thread..
     * \param my_current_right_closest is the array holding the coordinate of the closest points to the cut lines from right for the calling thread.
     * \param partIds is the array that holds the part ids of the coordinates
     */
    void mj_1D_part_get_thread_part_weights(
        size_t total_part_count,
        mj_part_t num_cuts,
        mj_scalar_t max_coord,
        mj_scalar_t min_coord,
        mj_lno_t coordinate_begin_index,
        mj_lno_t coordinate_end_index,
        mj_scalar_t *mj_current_dim_coords,
        mj_scalar_t *temp_current_cut_coords,
        bool *current_cut_status,
        double *my_current_part_weights,
        mj_scalar_t *my_current_left_closest,
        mj_scalar_t *my_current_right_closest);

    /*! \brief Function that reduces the result of multiple threads
     * for left and right closest points and part weights in a single mpi process.
     *
     * \param num_partitioning_in_current_dim is the vector that holds the number of cut lines in current dimension for each part.
     * \param current_work_part holds the index of the first part (important when concurrent parts are used.)
     * \param current_concurrent_num_parts is the number of parts whose cut lines will be calculated concurrently.
     */
    void mj_accumulate_thread_results(
        const std::vector <mj_part_t> &num_partitioning_in_current_dim,
        mj_part_t current_work_part,
        mj_part_t current_concurrent_num_parts);

    /*! \brief Function that calculates the new coordinates for the cut lines.
     * Function is called inside the parallel region. Write the new cut coordinates
     * to new_current_cut_coordinates, and determines if the final position of a cut is found.
     *
     * \param num_total_part is the sum of number of cutlines and number of parts. Simply it is 2*P - 1.
     * \param num_cuts is the number of cut lines. P - 1.
     * \param max_coordinate is the maximum coordinate in the current range of coordinates and in the current dimension.
     * \param min_coordinate is the maximum coordinate in the current range of coordinates and in the current dimension.
     * \param global_total_weight is the global total weight in the current range of coordinates.
     * \param used_imbalance_tolerance is the maximum allowed imbalance ratio.
     *
     *
     * \param current_global_part_weights is the array holding the weight of parts. Assumes there are 2*P - 1 parts (cut lines are seperate parts).
     * \param current_local_part_weights is the local totalweight of the processor.
     * \param current_part_target_weights are the desired cumulative part ratios, sized P.
     * \param current_cut_line_determined is the boolean array to determine if the correct position for a cut line is found.
     *
     * \param current_cut_coordinates is the array holding the coordinates of each cut line. Sized P - 1.
     * \param current_cut_upper_bounds is the array holding the upper bound coordinate for each cut line. Sized P - 1.
     * \param current_cut_lower_bounds is the array holding the lower bound coordinate for each cut line. Sized P - 1.
     * \param current_global_left_closest_points is the array holding the closest points to the cut lines from left.
     * \param current_global_right_closest_points is the array holding the closest points to the cut lines from right.
     * \param current_cut_lower_bound_weights is the array holding the weight of the parts at the left of lower bound coordinates.
     * \param current_cut_upper_weights is the array holding the weight of the parts at the left of upper bound coordinates.
     * \param new_current_cut_coordinates is the work array, sized P - 1.
     *
     * \param current_part_cut_line_weight_ratio holds how much weight of the coordinates on the cutline should be put on left side.
     * \param rectilinear_cut_count is the count of cut lines whose balance can be achived via distributing the points in same coordinate to different parts.
     * \param my_num_incomplete_cut is the number of cutlines whose position has not been determined yet. For K > 1 it is the count in a single part (whose cut lines are determined).
     */
    void mj_get_new_cut_coordinates(
        const size_t &num_total_part,
        const mj_part_t &num_cuts,
        const mj_scalar_t &max_coordinate,
        const mj_scalar_t &min_coordinate,
        const mj_scalar_t &global_total_weight,
        const mj_scalar_t &used_imbalance_tolerance,
        mj_scalar_t * current_global_part_weights,
        const mj_scalar_t * current_local_part_weights,
        const mj_scalar_t *current_part_target_weights,
        bool *current_cut_line_determined,
        mj_scalar_t *current_cut_coordinates,
        mj_scalar_t *current_cut_upper_bounds,
        mj_scalar_t *current_cut_lower_bounds,
        mj_scalar_t *current_global_left_closest_points,
        mj_scalar_t *current_global_right_closest_points,
        mj_scalar_t * current_cut_lower_bound_weights,
        mj_scalar_t * current_cut_upper_weights,
        mj_scalar_t *new_current_cut_coordinates,
        mj_scalar_t *current_part_cut_line_weight_to_put_left,
        mj_part_t *rectilinear_cut_count,
        mj_part_t &my_num_incomplete_cut);

    /*! \brief
     * Function that calculates the next pivot position,
     * according to given coordinates of upper bound and lower bound, the weights at upper and lower bounds, and the expected weight.
     * \param cut_upper_bound is the upper bound coordinate of the cut.
     * \param cut_lower_bound is the lower bound coordinate of the cut.
     * \param cut_upper_weight is the weights at the upper bound of the cut.
     * \param cut_lower_weight is the weights at the lower bound of the cut.
     * \param expected_weight is the expected weight that should be placed on the left of the cut line.
     */
    void mj_calculate_new_cut_position (
        mj_scalar_t cut_upper_bound,
        mj_scalar_t cut_lower_bound,
        mj_scalar_t cut_upper_weight,
        mj_scalar_t cut_lower_weight,
        mj_scalar_t expected_weight,
        mj_scalar_t &new_cut_position);

    /*! \brief Function that determines the permutation indices of the coordinates.
     * \param num_parts is the number of parts.
     * \param mj_current_dim_coords is 1 dimensional array holding the coordinate values.
     * \param current_concurrent_cut_coordinate is 1 dimensional array holding the cut coordinates.
     * \param coordinate_begin is the start index of the given partition on partitionedPointPermutations.
     * \param coordinate_end is the end index of the given partition on partitionedPointPermutations.
     * \param used_local_cut_line_weight_to_left holds how much weight of the coordinates on the cutline should be put on left side.
     * \param used_thread_part_weight_work is the two dimensional array holding the weight of parts for each thread. Assumes there are 2*P - 1 parts (cut lines are seperate parts).
     * \param out_part_xadj is the indices of coordinates calculated for the partition on next dimension.
     */
    void mj_create_new_partitions(
        mj_part_t num_parts,
        mj_scalar_t *mj_current_dim_coords,
        mj_scalar_t *current_concurrent_cut_coordinate,
        mj_lno_t coordinate_begin,
        mj_lno_t coordinate_end,
        mj_scalar_t *used_local_cut_line_weight_to_left,
        double **used_thread_part_weight_work,
        mj_lno_t *out_part_xadj);

    /*! \brief Function checks if should do migration or not.
     * It returns true to point that migration should be done when
     * -migration_reduce_all_population are higher than a predetermined value
     * -num_coords_for_last_dim_part that left for the last dimension partitioning is less than a predetermined value
     * -the imbalance of the processors on the parts are higher than given threshold.

     * \param input_num_parts is the number of parts when migration is called.
     * \param output_num_parts is the output number of parts after migration.
     * \param next_future_num_parts_in_parts is the number of total future parts each
     * part is partitioned into. This will be updated when migration is performed.
     * \param output_part_begin_index is the number that will be used as beginning part number
     * when final solution part numbers are assigned.
     * \param migration_reduce_all_population is the estimated total number of reduceall operations
     * multiplied with number of processors to be used for determining migration.
     *
     * \param num_coords_for_last_dim_part is the estimated number of points in each part,
     * when last dimension partitioning is performed.
     * \param iteration is the string that gives information about the dimension for printing purposes.
     * \param input_part_boxes is the array that holds the part boxes after the migration. (swapped)
     * \param output_part_boxes is the array that holds the part boxes before the migration. (swapped)
     *
     */
    bool mj_perform_migration(
        mj_part_t in_num_parts, //current umb parts
        mj_part_t &out_num_parts, //output umb parts.
        std::vector<mj_part_t> *next_future_num_parts_in_parts,
        mj_part_t &output_part_begin_index,
        size_t migration_reduce_all_population,
        mj_lno_t num_coords_for_last_dim_part,
        std::string iteration,
        RCP<mj_partBoxVector_t> &input_part_boxes,
        RCP<mj_partBoxVector_t> &output_part_boxes);

    /*! \brief Function fills up the num_points_in_all_processor_parts, so that
     * it has the number of coordinates in each processor of each part.
     * to access how many points processor i has on part j, num_points_in_all_processor_parts[i * num_parts + j].
     *
     * \param num_procs is the number of processor attending to migration operation.
     * \param num_parts is the number of parts that exist in the current partitioning.
     * \param num_points_in_all_processor_parts is the output array that holds
     * the number of coordinates in each part in each processor.
     */
    void get_processor_num_points_in_parts(
                mj_part_t num_procs,
                mj_part_t num_parts,
                mj_gno_t *&num_points_in_all_processor_parts);

    /*! \brief Function checks if should do migration or not.
     * It returns true to point that migration should be done when
     * -migration_reduce_all_population are higher than a predetermined value
     * -num_coords_for_last_dim_part that left for the last dimension partitioning is less than a predetermined value
     * -the imbalance of the processors on the parts are higher than given threshold.
     * \param migration_reduce_all_population is the multiplication of the number of reduceall operations estimated and the number of processors.
     * \param num_coords_for_last_dim_part is the estimated number of coordinates in a part per processor in the last dimension partitioning.
     * \param num_procs is the number of processor attending to migration operation.
     * \param num_parts is the number of parts that exist in the current partitioning.
     * \param num_points_in_all_processor_parts is the input array that holds
     * the number of coordinates in each part in each processor.
     */
    bool mj_check_to_migrate(
                size_t migration_reduce_all_population,
                mj_lno_t num_coords_for_last_dim_part,
                mj_part_t num_procs,
                mj_part_t num_parts,
                mj_gno_t *num_points_in_all_processor_parts);


    /*! \brief Function fills up coordinate_destinations is the output array
     * that holds which part each coordinate should be sent. In addition it calculates
     * the shift amount (output_part_numbering_begin_index) to be done when
     * final numberings of the parts are performed.
     *
     * \param num_points_in_all_processor_parts is the array holding the num points in each part in each proc.
     * \param num_parts is the number of parts that exist in the current partitioning.
     * \param num_procs is the number of processor attending to migration operation.

     * \param send_count_to_each_proc array array storing the number of points to be sent to each part.
     * \param processor_ranks_for_subcomm is the ranks of the processors that will be in the subcommunicator with me.
     * \param next_future_num_parts_in_parts is the vector, how many more parts each part will be divided into in the future.
     * \param out_num_part is the number of parts assigned to the process.
     * \param out_part_indices is the indices of the part to which the processor is assigned.
     * \param output_part_numbering_begin_index is how much the numbers should be shifted when numbering the result parts.
     * \param coordinate_destinations is the output array that holds which part each coordinate should be sent.
     */
    void mj_migration_part_proc_assignment(
                mj_gno_t * num_points_in_all_processor_parts,
                mj_part_t num_parts,
                mj_part_t num_procs,
                mj_lno_t *send_count_to_each_proc,
                std::vector<mj_part_t> &processor_ranks_for_subcomm,
                std::vector<mj_part_t> *next_future_num_parts_in_parts,
                mj_part_t &out_num_part,
                std::vector<mj_part_t> &out_part_indices,
                mj_part_t &output_part_numbering_begin_index,
                int *coordinate_destinations);

    /*! \brief Function that assigned the processors to parts, when there are more processors then parts.
     *  sets the destination of each coordinate in coordinate_destinations, also edits output_part_numbering_begin_index,
     *  and out_part_index, and returns the processor_ranks_for_subcomm which represents the ranks of the processors
     *  that will be used for creating the subcommunicator.
     *
     * \param num_points_in_all_processor_parts is the array holding the num points in each part in each proc.
     * \param num_parts is the number of parts that exist in the current partitioning.
     * \param num_procs is the number of processor attending to migration operation.

     * \param send_count_to_each_proc array array storing the number of points to be sent to each part.
     * \param processor_ranks_for_subcomm is the ranks of the processors that will be in the subcommunicator with me.
     * \param next_future_num_parts_in_parts is the vector, how many more parts each part will be divided into in the future.
     * \param out_part_index is the index of the part to which the processor is assigned.
     * \param output_part_numbering_begin_index is how much the numbers should be shifted when numbering the result parts.
     * \param coordinate_destinations is the output array that holds which part each coordinate should be sent.
     */
    void mj_assign_proc_to_parts(
                mj_gno_t * num_points_in_all_processor_parts,
                mj_part_t num_parts,
                mj_part_t num_procs,
                mj_lno_t *send_count_to_each_proc,
                std::vector<mj_part_t> &processor_ranks_for_subcomm,
                std::vector<mj_part_t> *next_future_num_parts_in_parts,
                mj_part_t &out_part_index,
                mj_part_t &output_part_numbering_begin_index,
                int *coordinate_destinations);

    /*! \brief Function fills up coordinate_destinations is the output array
     * that holds which part each coordinate should be sent.
     *
     * \param num_parts is the number of parts that exist in the current partitioning.
     * \param num_procs is the number of processor attending to migration operation.
     * \param part_assignment_proc_begin_indices ([i]) points to the first processor index that part i will be sent to.
     * \param processor_chains_in_parts the array that holds the linked list structure, started from part_assignment_proc_begin_indices ([i]).
     * \param send_count_to_each_proc array array storing the number of points to be sent to each part.
     * \param coordinate_destinations is the output array that holds which part each coordinate should be sent.
     */
    void assign_send_destinations(
                mj_part_t num_parts,
                mj_part_t *part_assignment_proc_begin_indices,
                mj_part_t *processor_chains_in_parts,
                mj_lno_t *send_count_to_each_proc,
                int *coordinate_destinations);

    /*! \brief Function fills up coordinate_destinations is the output array
     * that holds which part each coordinate should be sent. In addition it calculates
     * the shift amount (output_part_numbering_begin_index) to be done when
     * final numberings of the parts are performed.
     *
     * \param num_parts is the number of parts that exist in the current partitioning.
     * \param sort_item_part_to_proc_assignment is the sorted parts with respect to the assigned processors.
     * \param coordinate_destinations is the output array that holds which part each coordinate should be sent.
     * \param output_part_numbering_begin_index is how much the numbers should be shifted when numbering the result parts.
     * \param next_future_num_parts_in_parts is the vector, how many more parts each part will be divided into in the future.
     *
     */
    void assign_send_destinations2(
        mj_part_t num_parts,
        uSortItem<mj_part_t, mj_part_t> * sort_item_part_to_proc_assignment, //input sorted wrt processors
        int *coordinate_destinations,
        mj_part_t &output_part_numbering_begin_index,
        std::vector<mj_part_t> *next_future_num_parts_in_parts);

    /*! \brief Function fills up coordinate_destinations is the output array
     * that holds which part each coordinate should be sent. In addition it calculates
     * the shift amount (output_part_numbering_begin_index) to be done when
     * final numberings of the parts are performed.
     *
     * \param num_points_in_all_processor_parts is the array holding the num points in each part in each proc.
     * \param num_parts is the number of parts that exist in the current partitioning.
     * \param num_procs is the number of processor attending to migration operation.

     * \param send_count_to_each_proc array array storing the number of points to be sent to each part.
     * \param next_future_num_parts_in_parts is the vector, how many more parts each part will be divided into in the future.
     * \param out_num_part is the number of parts assigned to the process.
     * \param out_part_indices is the indices of the part to which the processor is assigned.
     * \param output_part_numbering_begin_index is how much the numbers should be shifted when numbering the result parts.
     * \param coordinate_destinations is the output array that holds which part each coordinate should be sent.
     */
    void mj_assign_parts_to_procs(
        mj_gno_t * num_points_in_all_processor_parts,
        mj_part_t num_parts,
        mj_part_t num_procs,
        mj_lno_t *send_count_to_each_proc, //output: sized nprocs, show the number of send point counts to each proc.
        std::vector<mj_part_t> *next_future_num_parts_in_parts,//input how many more partitions the part will be partitioned into.
        mj_part_t &out_num_part, //output, how many parts the processor will have. this is always 1 for this function.
        std::vector<mj_part_t> &out_part_indices, //output: the part indices which the processor is assigned to.
        mj_part_t &output_part_numbering_begin_index, //output: how much the part number should be shifted when setting the solution
        int *coordinate_destinations);

    /*! \brief Function fills up coordinate_destinations is the output array
     * that holds which part each coordinate should be sent. In addition it calculates
     * the shift amount (output_part_numbering_begin_index) to be done when
     * final numberings of the parts are performed.
     *
     *
     * \param num_procs is the number of processor attending to migration operation.
     * \param num_new_local_points is the output to represent the new number of local points.
     * \param iteration is the string for the current iteration.
     * \param coordinate_destinations is the output array that holds which part each coordinate should be sent.
     * \param num_parts is the number of parts that exist in the current partitioning.
     */
    void mj_migrate_coords(
        mj_part_t num_procs,
        mj_lno_t &num_new_local_points,
        std::string iteration,
        int *coordinate_destinations,
        mj_part_t num_parts);

    /*! \brief Function creates the new subcomminicator for the processors
     * given in processor_ranks_for_subcomm.
     *
     * \param processor_ranks_for_subcomm is the vector that has the ranks of
     * the processors that will be in the same group.
     */
    void create_sub_communicator(std::vector<mj_part_t> &processor_ranks_for_subcomm);


    /*! \brief Function writes the new permutation arrays after the migration.
     *
     * \param output_num_parts is the number of parts that is assigned to the processor.
     * \param num_parts is the number of parts right before migration.
     */
    void fill_permutation_array(
        mj_part_t output_num_parts,
        mj_part_t num_parts);

    /*! \brief Function checks if should do migration or not.
     * \param current_num_parts is the number of parts in the process.
     * \param output_part_begin_index is the number that will be used as beginning part number
     * \param output_part_boxes is the array that holds the part boxes
     * \param is_data_ever_migrated is the boolean value which is true
     * if the data is ever migrated during the partitioning.
     *
     */
    void set_final_parts(
                mj_part_t current_num_parts,
                mj_part_t output_part_begin_index,
                RCP<mj_partBoxVector_t> &output_part_boxes,
                bool is_data_ever_migrated);
    /*! \brief Function frees all allocated work memory.
     */
    void free_work_memory();
    /*! \brief Function creates consistent chunks for task partitioning. Used only in the case of
     * sequential task partitioning, where consistent handle of the points on the cuts are required.
     *
     * \param num_parts is the number of parts.
     * \param mj_current_dim_coords is 1 dimensional array holding the coordinate values.
     * \param current_concurrent_cut_coordinate is 1 dimensional array holding the cut coordinates.
     * \param coordinate_begin is the start index of the given partition on partitionedPointPermutations.
     * \param coordinate_end is the end index of the given partition on partitionedPointPermutations.
     * \param used_local_cut_line_weight_to_left holds how much weight of the coordinates on the cutline should be put on left side.
     *
     * \param out_part_xadj is the indices of begginning and end of the parts in the output partition.
     * \param coordInd is the index according to which the partitioning is done.
     */
    void create_consistent_chunks(
        mj_part_t num_parts,
        mj_scalar_t *mj_current_dim_coords,
        mj_scalar_t *current_concurrent_cut_coordinate,
        mj_lno_t coordinate_begin,
        mj_lno_t coordinate_end,
        mj_scalar_t *used_local_cut_line_weight_to_left,
        mj_lno_t *out_part_xadj,
        int coordInd);
public:
    AlgMJ();

    /*! \brief Multi Jagged  coordinate partitioning algorithm.
     *
     *  \param env   library configuration and problem parameters
     *  \param problemComm the communicator for the problem
     *  \param imbalance_tolerance : the input provided imbalance tolerance.
     *  \param num_global_parts: number of target global parts.
     *  \param part_no_array: part no array, if provided this will be used for partitioning.
     *  \param recursion_depth: if part no array is provided, it is the length of part no array,
     *                                                  if part no is not provided than it is the number of steps that algorithm will divide into num_global_parts parts.
     *
     *  \param coord_dim: coordinate dimension
     *  \param num_local_coords: number of local coordinates
     *  \param num_global_coords: number of global coordinates
     *  \param initial_mj_gnos: the list of initial global id's
     *  \param mj_coordinates: the two dimensional coordinate array.
     *
     *  \param num_weights_per_coord: number of weights per coordinate
     *  \param mj_uniform_weights: if weight index [i] has uniform weight or not.
     *  \param mj_weights: the two dimensional array for weights
     *  \param mj_uniform_parts: if the target partitioning aims uniform parts
     *  \param mj_part_sizes: if the target partitioning does not aim uniform parts, then weight of each part.
     *
     *  \param result_assigned_part_ids: Output - 1D pointer, should be provided as null.
     *                          the result partids corresponding to the coordinates given in result_mj_gnos.
     *  \param result_mj_gnos: Output - 1D pointer, should be provided as null.
     *                          the result coordinate global id's corresponding to the part_ids array.
     *
     */
    void multi_jagged_part(
                const RCP<const Environment> &env,
                RCP<const Comm<int> > &problemComm,

                double imbalance_tolerance,
                size_t num_global_parts,
                mj_part_t *part_no_array,
                int recursion_depth,

                int coord_dim,
                mj_lno_t num_local_coords,
                mj_gno_t num_global_coords,
                const mj_gno_t *initial_mj_gnos,
                mj_scalar_t **mj_coordinates,

                int num_weights_per_coord,
                bool *mj_uniform_weights,
                mj_scalar_t **mj_weights,
                bool *mj_uniform_parts,
                mj_scalar_t **mj_part_sizes,

                mj_part_t *&result_assigned_part_ids,
                mj_gno_t *&result_mj_gnos

                );
    /*! \brief Multi Jagged  coordinate partitioning algorithm.
     *
     *  \param distribute_points_on_cut_lines_ :  if partitioning can distribute points on same coordinate to different parts.
     *  \param max_concurrent_part_calculation_ : how many parts we can calculate concurrently.
     *  \param check_migrate_avoid_migration_option_ : whether to migrate=1, avoid migrate=2, or leave decision to MJ=0
     *  \param minimum_migration_imbalance_  : when MJ decides whether to migrate, the minimum imbalance for migration.
     */
    void set_partitioning_parameters(
                bool distribute_points_on_cut_lines_,
                int max_concurrent_part_calculation_,
                int check_migrate_avoid_migration_option_,
                mj_scalar_t minimum_migration_imbalance_);
    /*! \brief Function call, if the part boxes are intended to be kept.
     *
     */
    void set_to_keep_part_boxes();

    /*! \brief Return the global bounding box: min/max coords of global domain
     */
    RCP<mj_partBox_t> get_global_box() const;

    RCP<mj_partBoxVector_t> get_kept_boxes() const;

    RCP<mj_partBoxVector_t> compute_global_box_boundaries(
        RCP<mj_partBoxVector_t> &localPartBoxes) const;

    /*! \brief Special function for partitioning for task mapping.
     * Runs sequential, and performs deterministic partitioning for the
     * partitioning the points along a cutline.
     *
     *  \param env library configuration and problem parameters
     *  \param num_total_coords number of total coordinates
     *  \param num_selected_coords : the number of selected coordinates. This is to set,
     *                                                          if there are n processors, but only m<n processors
     *                                                          are selected for mapping.
     *
     *  \param num_target_part: number of target global parts.
     *  \param coord_dim_: coordinate dimension for coordinates
     *  \param mj_coordinates_: the coordinates
     *
     *  \param inital_adjList_output_adjlist: Array allocated by caller, in the size of num_total_coords,
     *                                                  first num_selected_coords elements should list the indices of the selected processors.
     *                                                  This is output for output permutation array.
     *  \param output_xadj: The output part xadj array, pointing beginning and end of each part on
     *          output permutation array (inital_adjList_output_adjlist).
     *          Returned in CSR format: part i's info in output_xadj[i] : output_xadj[i+1]
     *
     *  \param rd: recursion depth
     *  \param part_no_array_: possibly null part_no_array, specifying how many parts each should be divided during partitioning.
     */
    void sequential_task_partitioning(
        const RCP<const Environment> &env,
        mj_lno_t num_total_coords,
        mj_lno_t num_selected_coords,
        size_t num_target_part,
        int coord_dim,
        mj_scalar_t **mj_coordinates,
        mj_lno_t *initial_selected_coords_output_permutation,
        mj_lno_t *output_xadj,
        int recursion_depth,
        const mj_part_t *part_no_array,
        bool partition_along_longest_dim);

};

/*! \brief Special function for partitioning for task mapping.
 * Runs sequential, and performs deterministic partitioning for the
 * partitioning the points along a cutline.
 *
 *  \param env library configuration and problem parameters
 *  \param num_total_coords number of total coordinates
 *  \param num_selected_coords : the number of selected coordinates. This is to set,
 *                                                      if there are n processors, but only m<n processors
 *                                                      are selected for mapping.
 *
 *  \param num_target_part: number of target global parts.
 *  \param coord_dim_: coordinate dimension for coordinates
 *  \param mj_coordinates_: the coordinates
 *
 *  \param inital_adjList_output_adjlist: Array allocated by caller, in the size of num_total_coords,
 *                                              first num_selected_coords elements should list the indices of the selected processors.
 *                                              This is output for output permutation array.
 *  \param output_xadj: The output part xadj array, pointing beginning and end of each part on
 *      output permutation array (inital_adjList_output_adjlist).
 *      Returned in CSR format: part i's info in output_xadj[i] : output_xadj[i+1]
 *
 *  \param rd: recursion depth
 *  \param part_no_array_: possibly null part_no_array, specifying how many parts each should be divided during partitioning.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::sequential_task_partitioning(
    const RCP<const Environment> &env,
    mj_lno_t num_total_coords,
    mj_lno_t num_selected_coords,
    size_t num_target_part,
    int coord_dim_,
    mj_scalar_t **mj_coordinates_,
    mj_lno_t *inital_adjList_output_adjlist,
    mj_lno_t *output_xadj,
    int rd,
    const mj_part_t *part_no_array_,
    bool partition_along_longest_dim
){

        this->mj_env = env;
        const RCP<Comm<int> > commN;
        this->mj_problemComm = 
              Teuchos::DefaultComm<int>::getDefaultSerialComm(commN);
        this->comm = 
              Teuchos::rcp_const_cast<Comm<int> >(this->mj_problemComm);
        this->myActualRank = this->myRank = 1;

#ifdef HAVE_ZOLTAN2_OMP
        int actual_num_threads = omp_get_num_threads();
        omp_set_num_threads(1);
#endif

    //weights are uniform for task mapping

    //parts are uniform for task mapping
    //as input indices.

    this->imbalance_tolerance = 0;
    this->num_global_parts = num_target_part;
    this->part_no_array = (mj_part_t *)part_no_array_;
    this->recursion_depth = rd;

    this->coord_dim = coord_dim_;
    this->num_local_coords = num_total_coords;
    this->num_global_coords = num_total_coords;
    this->mj_coordinates = mj_coordinates_;  //will copy the memory to this->mj_coordinates.

    ////temporary memory. It is not used here, but the functions require these to be allocated.
    ////will copy the memory to this->current_mj_gnos[j].
    this->initial_mj_gnos = allocMemory<mj_gno_t>(this->num_local_coords);

    this->num_weights_per_coord = 0;
    bool *tmp_mj_uniform_weights = new bool[1];
    this->mj_uniform_weights = tmp_mj_uniform_weights ;
    this->mj_uniform_weights[0] = true;

    mj_scalar_t **tmp_mj_weights = new mj_scalar_t *[1];
    this->mj_weights = tmp_mj_weights; //will copy the memory to this->mj_weights

    bool *tmp_mj_uniform_parts = new bool[1];
    this->mj_uniform_parts = tmp_mj_uniform_parts;
    this->mj_uniform_parts[0] = true;

    mj_scalar_t **tmp_mj_part_sizes = new mj_scalar_t * [1];
    this->mj_part_sizes = tmp_mj_part_sizes;
    this->mj_part_sizes[0] = NULL;

    this->num_threads = 1;
    this->set_part_specifications();

    this->allocate_set_work_memory();
    //the end of the initial partition is the end of coordinates.
    this->part_xadj[0] = static_cast<mj_lno_t>(num_selected_coords);
    for(size_t i = 0; i < static_cast<size_t>(num_total_coords); ++i){
        this->coordinate_permutations[i] = inital_adjList_output_adjlist[i];
    }

    mj_part_t current_num_parts = 1;

    mj_scalar_t *current_cut_coordinates =  this->all_cut_coordinates;

    mj_part_t future_num_parts = this->total_num_part;

    std::vector<mj_part_t> *future_num_part_in_parts = new std::vector<mj_part_t> ();
    std::vector<mj_part_t> *next_future_num_parts_in_parts = new std::vector<mj_part_t> ();
    next_future_num_parts_in_parts->push_back(this->num_global_parts);
    RCP<mj_partBoxVector_t> t1;
    RCP<mj_partBoxVector_t> t2;


    std::vector <uSignedSortItem<int, mj_scalar_t, char> > coord_dimension_range_sorted(this->coord_dim);
    uSignedSortItem<int, mj_scalar_t, char> *p_coord_dimension_range_sorted = &(coord_dimension_range_sorted[0]);
    std::vector <mj_scalar_t> coord_dim_mins(this->coord_dim);
    std::vector <mj_scalar_t> coord_dim_maxs(this->coord_dim);

    for (int i = 0; i < this->recursion_depth; ++i){

        //partitioning array. size will be as the number of current partitions and this
        //holds how many parts that each part will be in the current dimension partitioning.
        std::vector <mj_part_t> num_partitioning_in_current_dim;

        //number of parts that will be obtained at the end of this partitioning.
        //future_num_part_in_parts is as the size of current number of parts.
        //holds how many more parts each should be divided in the further
        //iterations. this will be used to calculate num_partitioning_in_current_dim,
        //as the number of parts that the part will be partitioned
        //in the current dimension partitioning.

        //next_future_num_parts_in_parts will be as the size of outnumParts,
        //and this will hold how many more parts that each output part
        //should be divided. this array will also be used to determine the weight ratios
        //of the parts.
        //swap the arrays to use iteratively..
        std::vector<mj_part_t> *tmpPartVect= future_num_part_in_parts;
        future_num_part_in_parts = next_future_num_parts_in_parts;
        next_future_num_parts_in_parts = tmpPartVect;

        //clear next_future_num_parts_in_parts array as
        //getPartitionArrays expects it to be empty.
        //it also expects num_partitioning_in_current_dim to be empty as well.
        next_future_num_parts_in_parts->clear();


        //returns the total number of output parts for this dimension partitioning.
        mj_part_t output_part_count_in_dimension =
                        this->update_part_num_arrays(
                                        num_partitioning_in_current_dim,
                                        future_num_part_in_parts,
                                        next_future_num_parts_in_parts,
                                        future_num_parts,
                                        current_num_parts,
                                        i,
                                        t1,
                                        t2);

        //if the number of obtained parts equal to current number of parts,
        //skip this dimension. For example, this happens when 1 is given in the input
        //part array is given. P=4,5,1,2
        if(output_part_count_in_dimension == current_num_parts) {
            tmpPartVect= future_num_part_in_parts;
            future_num_part_in_parts = next_future_num_parts_in_parts;
            next_future_num_parts_in_parts = tmpPartVect;
            continue;
        }

        //convert i to string to be used for debugging purposes.
        std::string istring = Teuchos::toString<int>(i);

        //alloc Memory to point the indices
        //of the parts in the permutation array.
        this->new_part_xadj = allocMemory<mj_lno_t>(output_part_count_in_dimension);

        //the index where in the outtotalCounts will be written.
        mj_part_t output_part_index = 0;
        //whatever is written to outTotalCounts will be added with previousEnd
        //so that the points will be shifted.
        mj_part_t output_coordinate_end_index = 0;

        mj_part_t current_work_part = 0;
        mj_part_t current_concurrent_num_parts = 1;

        mj_part_t obtained_part_index = 0;

        //get the coordinate axis along which the partitioning will be done.
        int coordInd = i % this->coord_dim;
        mj_scalar_t * mj_current_dim_coords = this->mj_coordinates[coordInd];


        //run for all available parts.
        for (; current_work_part < current_num_parts;
                     current_work_part += current_concurrent_num_parts){


            //current_concurrent_num_parts = std::min(current_num_parts - current_work_part,
            //this->max_concurrent_part_calculation);

            mj_part_t actual_work_part_count = 0;
            //initialization for 1D partitioning.
            //get the min and max coordinates of each part
            //together with the part weights of each part.
            for(int kk = 0; kk < current_concurrent_num_parts; ++kk){
                mj_part_t current_work_part_in_concurrent_parts = current_work_part + kk;

                //if this part wont be partitioned any further
                //dont do any work for this part.
                if (num_partitioning_in_current_dim[current_work_part_in_concurrent_parts] == 1){
                    continue;
                }
                ++actual_work_part_count;
                mj_lno_t coordinate_end_index= this->part_xadj[current_work_part_in_concurrent_parts];
                mj_lno_t coordinate_begin_index = current_work_part_in_concurrent_parts==0 ? 0: this->part_xadj[current_work_part_in_concurrent_parts -1];

                /*
                std::cout << "i:" << i << " j:" << current_work_part + kk
                                << " coordinate_begin_index:" << coordinate_begin_index
                                << " coordinate_end_index:" << coordinate_end_index
                                << " total:" << coordinate_end_index - coordinate_begin_index<< std::endl;
                                */


                if(partition_along_longest_dim){

                  mj_scalar_t best_weight_coord = 0;
                  for (int coord_traverse_ind = 0; coord_traverse_ind < this->coord_dim; ++coord_traverse_ind){
                    mj_scalar_t best_min_coord = 0;
                    mj_scalar_t best_max_coord = 0;
                    //MD:same for all coordinates, but I will still use this for now.

                    this->mj_get_local_min_max_coord_totW(
                        coordinate_begin_index,
                        coordinate_end_index,
                        this->coordinate_permutations,
                        this->mj_coordinates[coord_traverse_ind],
                        best_min_coord, //min coordinate
                        best_max_coord, //max coordinate
                        best_weight_coord //total weight);
                    );

                    coord_dim_mins[coord_traverse_ind] = best_min_coord;
                    coord_dim_maxs[coord_traverse_ind] = best_max_coord;
                    mj_scalar_t best_range = best_max_coord - best_min_coord;
                    coord_dimension_range_sorted[coord_traverse_ind].id = coord_traverse_ind;
                    coord_dimension_range_sorted[coord_traverse_ind].val = best_range;
                    coord_dimension_range_sorted[coord_traverse_ind].signbit = 1;
                  }


                  uqSignsort(this->coord_dim, p_coord_dimension_range_sorted);
                  coordInd = p_coord_dimension_range_sorted[this->coord_dim - 1].id;
                  /*
                  for (int coord_traverse_ind = 0; coord_traverse_ind < this->coord_dim; ++coord_traverse_ind){
                    std::cout << "i:" << p_coord_dimension_range_sorted[coord_traverse_ind].id << " range:" << p_coord_dimension_range_sorted[coord_traverse_ind].val << std::endl;
                    std::cout << "i:" << p_coord_dimension_range_sorted[coord_traverse_ind].id << " coord_dim_mins:" << coord_dim_mins[p_coord_dimension_range_sorted[coord_traverse_ind].id]<< std::endl;
                    std::cout << "i:" << p_coord_dimension_range_sorted[coord_traverse_ind].id << " coord_dim_maxs:" << coord_dim_maxs[p_coord_dimension_range_sorted[coord_traverse_ind].id] << std::endl;

                  }
                  */
                  mj_current_dim_coords = this->mj_coordinates[coordInd];

                  this->process_local_min_max_coord_total_weight[kk] = coord_dim_mins[coordInd];
                  this->process_local_min_max_coord_total_weight[kk+ current_concurrent_num_parts] = coord_dim_maxs[coordInd];
                  this->process_local_min_max_coord_total_weight[kk + 2*current_concurrent_num_parts] = best_weight_coord;

                }
                else{
                  this->mj_get_local_min_max_coord_totW(
                                  coordinate_begin_index,
                                  coordinate_end_index,
                                  this->coordinate_permutations,
                                  mj_current_dim_coords,
                                  this->process_local_min_max_coord_total_weight[kk], //min coordinate
                          this->process_local_min_max_coord_total_weight[kk + current_concurrent_num_parts], //max coordinate
                          this->process_local_min_max_coord_total_weight[kk + 2*current_concurrent_num_parts] //total weight);
                  );
                }
            }

            //1D partitioning
            if (actual_work_part_count > 0){
                //obtain global Min max of the part.
                this->mj_get_global_min_max_coord_totW(
                                current_concurrent_num_parts,
                                this->process_local_min_max_coord_total_weight,
                                this->global_min_max_coord_total_weight);

                //represents the total number of cutlines
                //whose coordinate should be determined.
                mj_part_t total_incomplete_cut_count = 0;

                //Compute weight ratios for parts & cuts:
                //e.g., 0.25  0.25  0.5    0.5  0.75 0.75  1
                //part0  cut0  part1 cut1 part2 cut2 part3
                mj_part_t concurrent_part_cut_shift = 0;
                mj_part_t concurrent_part_part_shift = 0;
                for(int kk = 0; kk < current_concurrent_num_parts; ++kk){
                    mj_scalar_t min_coordinate = this->global_min_max_coord_total_weight[kk];
                    mj_scalar_t max_coordinate = this->global_min_max_coord_total_weight[kk +
                                                     current_concurrent_num_parts];
                    mj_scalar_t global_total_weight =
                                                        this->global_min_max_coord_total_weight[kk +
                                                     2 * current_concurrent_num_parts];

                    mj_part_t concurrent_current_part_index = current_work_part + kk;

                    mj_part_t partition_count = num_partitioning_in_current_dim[concurrent_current_part_index];

                    mj_scalar_t *usedCutCoordinate = current_cut_coordinates + concurrent_part_cut_shift;
                    mj_scalar_t *current_target_part_weights = this->target_part_weights +
                                                                     concurrent_part_part_shift;
                    //shift the usedCutCoordinate array as noCuts.
                    concurrent_part_cut_shift += partition_count - 1;
                    //shift the partRatio array as noParts.
                    concurrent_part_part_shift += partition_count;

                    //calculate only if part is not empty,
                    //and part will be further partitioend.
                    if(partition_count > 1 && min_coordinate <= max_coordinate){

                        //increase allDone by the number of cuts of the current
                        //part's cut line number.
                        total_incomplete_cut_count += partition_count - 1;
                        //set the number of cut lines that should be determined
                        //for this part.
                        this->my_incomplete_cut_count[kk] = partition_count - 1;

                        //get the target weights of the parts.
                        this->mj_get_initial_cut_coords_target_weights(
                            min_coordinate,
                            max_coordinate,
                            partition_count - 1,
                            global_total_weight,
                            usedCutCoordinate,
                            current_target_part_weights,
                            future_num_part_in_parts,
                            next_future_num_parts_in_parts,
                            concurrent_current_part_index,
                            obtained_part_index);

                        mj_lno_t coordinate_end_index= this->part_xadj[concurrent_current_part_index];
                        mj_lno_t coordinate_begin_index = concurrent_current_part_index==0 ? 0: this->part_xadj[concurrent_current_part_index -1];

                        //get the initial estimated part assignments of the coordinates.
                        this->set_initial_coordinate_parts(
                            max_coordinate,
                            min_coordinate,
                            concurrent_current_part_index,
                            coordinate_begin_index, coordinate_end_index,
                            this->coordinate_permutations,
                            mj_current_dim_coords,
                            this->assigned_part_ids,
                            partition_count);
                    }
                    else {
                        // e.g., if have fewer coordinates than parts, don't need to do next dim.
                        this->my_incomplete_cut_count[kk] = 0;
                    }
                    obtained_part_index += partition_count;
                }

                //used imbalance, it is always 0, as it is difficult to estimate a range.
                mj_scalar_t used_imbalance = 0;

                // Determine cut lines for k parts here.
                this->mj_1D_part(
                    mj_current_dim_coords,
                    used_imbalance,
                    current_work_part,
                    current_concurrent_num_parts,
                    current_cut_coordinates,
                    total_incomplete_cut_count,
                    num_partitioning_in_current_dim);
            }

            //create part chunks
            {

                mj_part_t output_array_shift = 0;
                mj_part_t cut_shift = 0;
                size_t tlr_shift = 0;
                size_t partweight_array_shift = 0;

                for(int kk = 0; kk < current_concurrent_num_parts; ++kk){
                    mj_part_t current_concurrent_work_part = current_work_part + kk;
                    mj_part_t num_parts = num_partitioning_in_current_dim[current_concurrent_work_part];

                    //if the part is empty, skip the part.
                    if((num_parts != 1  ) && this->global_min_max_coord_total_weight[kk] >
                             this->global_min_max_coord_total_weight[kk + current_concurrent_num_parts]) {

                        for(mj_part_t jj = 0; jj < num_parts; ++jj){
                            this->new_part_xadj[output_part_index + output_array_shift + jj] = 0;
                        }
                        cut_shift += num_parts - 1;
                        tlr_shift += (4 *(num_parts - 1) + 1);
                        output_array_shift += num_parts;
                        partweight_array_shift += (2 * (num_parts - 1) + 1);
                        continue;
                    }

                    mj_lno_t coordinate_end = this->part_xadj[current_concurrent_work_part];
                    mj_lno_t coordinate_begin = current_concurrent_work_part==0 ? 0: this->part_xadj[current_concurrent_work_part
                                                             -1];
                    mj_scalar_t *current_concurrent_cut_coordinate = current_cut_coordinates + cut_shift;
                    mj_scalar_t *used_local_cut_line_weight_to_left = this->process_cut_line_weight_to_put_left +
                                                         cut_shift;

                    for(int ii = 0; ii < this->num_threads; ++ii){
                        this->thread_part_weight_work[ii] = this->thread_part_weights[ii] +  partweight_array_shift;
                    }

                    if(num_parts > 1){
                        // Rewrite the indices based on the computed cuts.
                        this->create_consistent_chunks(
                            num_parts,
                            mj_current_dim_coords,
                            current_concurrent_cut_coordinate,
                            coordinate_begin,
                            coordinate_end,
                            used_local_cut_line_weight_to_left,
                            this->new_part_xadj + output_part_index + output_array_shift,
                            coordInd );
                    }
                    else {
                        //if this part is partitioned into 1 then just copy
                        //the old values.
                        mj_lno_t part_size = coordinate_end - coordinate_begin;
                        *(this->new_part_xadj + output_part_index + output_array_shift) = part_size;
                        memcpy(this->new_coordinate_permutations + coordinate_begin,
                        this->coordinate_permutations + coordinate_begin,
                        part_size * sizeof(mj_lno_t));
                    }



                    cut_shift += num_parts - 1;
                    tlr_shift += (4 *(num_parts - 1) + 1);
                    output_array_shift += num_parts;
                    partweight_array_shift += (2 * (num_parts - 1) + 1);
                }

                //shift cut coordinates so that all cut coordinates are stored.
                //current_cut_coordinates += cutShift;

                //getChunks from coordinates partitioned the parts and
                //wrote the indices as if there were a single part.
                //now we need to shift the beginning indices.
                for(mj_part_t kk = 0; kk < current_concurrent_num_parts; ++kk){
                    mj_part_t num_parts = num_partitioning_in_current_dim[ current_work_part + kk];
                    for (mj_part_t ii = 0;ii < num_parts ; ++ii){
                        //shift it by previousCount
                        this->new_part_xadj[output_part_index+ii] += output_coordinate_end_index;
                        if (ii % 2 == 1){
                          mj_lno_t coordinate_end = this->new_part_xadj[output_part_index+ii];
                          mj_lno_t coordinate_begin = this->new_part_xadj[output_part_index];

                          for (mj_lno_t task_traverse = coordinate_begin; task_traverse < coordinate_end; ++task_traverse){
                            mj_lno_t l = this->new_coordinate_permutations[task_traverse];
                            mj_current_dim_coords[l] = -mj_current_dim_coords[l];
                          }
                        }
                    }
                    //increase the previous count by current end.
                    output_coordinate_end_index = this->new_part_xadj[output_part_index + num_parts - 1];
                    //increase the current out.
                    output_part_index += num_parts ;
                }
            }
        }
        // end of this partitioning dimension

        //set the current num parts for next dim partitioning
        current_num_parts = output_part_count_in_dimension;

        //swap the coordinate permutations for the next dimension.
        mj_lno_t * tmp = this->coordinate_permutations;
        this->coordinate_permutations = this->new_coordinate_permutations;
        this->new_coordinate_permutations = tmp;

        freeArray<mj_lno_t>(this->part_xadj);
        this->part_xadj = this->new_part_xadj;
        this->new_part_xadj = NULL;
    }

    for(mj_lno_t i = 0; i < num_total_coords; ++i){
        inital_adjList_output_adjlist[i] = this->coordinate_permutations[i];
    }

    // Return output_xadj in CSR format
    output_xadj[0] = 0;
    for(size_t i = 0; i < this->num_global_parts ; ++i){
        output_xadj[i+1] = this->part_xadj[i];
    }

    delete future_num_part_in_parts;
    delete next_future_num_parts_in_parts;

    //free the extra memory that we allocated.
    freeArray<mj_part_t>(this->assigned_part_ids);
    freeArray<mj_gno_t>(this->initial_mj_gnos);
    freeArray<mj_gno_t>(this->current_mj_gnos);
    freeArray<bool>(tmp_mj_uniform_weights);
    freeArray<bool>(tmp_mj_uniform_parts);
    freeArray<mj_scalar_t *>(tmp_mj_weights);
    freeArray<mj_scalar_t *>(tmp_mj_part_sizes);

    this->free_work_memory();

#ifdef HAVE_ZOLTAN2_OMP
    omp_set_num_threads(actual_num_threads);
#endif
}

/*! \brief Multi Jagged  coordinate partitioning algorithm default constructor.
 *
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::AlgMJ():
        mj_env(), mj_problemComm(), imbalance_tolerance(0),
        part_no_array(NULL), recursion_depth(0), coord_dim(0),
        num_weights_per_coord(0), initial_num_loc_coords(0),
        initial_num_glob_coords(0),
        num_local_coords(0), num_global_coords(0), mj_coordinates(NULL),
        mj_weights(NULL), mj_uniform_parts(NULL), mj_part_sizes(NULL),
        mj_uniform_weights(NULL), mj_gnos(), num_global_parts(1),
        initial_mj_gnos(NULL), current_mj_gnos(NULL), owner_of_coordinate(NULL),
        coordinate_permutations(NULL), new_coordinate_permutations(NULL),
        assigned_part_ids(NULL), part_xadj(NULL), new_part_xadj(NULL),
        distribute_points_on_cut_lines(true), max_concurrent_part_calculation(1),
        mj_run_as_rcb(false), mj_user_recursion_depth(0), mj_keep_part_boxes(false),
        check_migrate_avoid_migration_option(0), minimum_migration_imbalance(0.30),
        num_threads(1), total_num_cut(0), total_num_part(0), max_num_part_along_dim(0),
        max_num_cut_along_dim(0), max_num_total_part_along_dim(0), total_dim_num_reduce_all(0),
        last_dim_num_part(0), comm(), fEpsilon(0), sEpsilon(0), maxScalar_t(0), minScalar_t(0),
        all_cut_coordinates(NULL), max_min_coords(NULL), process_cut_line_weight_to_put_left(NULL),
        thread_cut_line_weight_to_put_left(NULL), cut_coordinates_work_array(NULL),
        target_part_weights(NULL), cut_upper_bound_coordinates(NULL), cut_lower_bound_coordinates(NULL),
        cut_lower_bound_weights(NULL), cut_upper_bound_weights(NULL),
        process_local_min_max_coord_total_weight(NULL), global_min_max_coord_total_weight(NULL),
        is_cut_line_determined(NULL), my_incomplete_cut_count(NULL),
        thread_part_weights(NULL), thread_part_weight_work(NULL),
        thread_cut_left_closest_point(NULL), thread_cut_right_closest_point(NULL),
        thread_point_counts(NULL), process_rectilinear_cut_weight(NULL),
        global_rectilinear_cut_weight(NULL),total_part_weight_left_right_closests(NULL),
        global_total_part_weight_left_right_closests(NULL),
        kept_boxes(),global_box(),
        myRank(0), myActualRank(0)
{
    this->fEpsilon = std::numeric_limits<float>::epsilon();
    this->sEpsilon = std::numeric_limits<mj_scalar_t>::epsilon() * 100;

    this->maxScalar_t = std::numeric_limits<mj_scalar_t>::max();
    this->minScalar_t = -std::numeric_limits<mj_scalar_t>::max();

}


/*! \brief Function returns the part boxes stored
 * returns null if boxes are not stored, and prints warning mesage.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
RCP<typename AlgMJ<mj_scalar_t,mj_lno_t,mj_gno_t,mj_part_t>::mj_partBox_t>
AlgMJ<mj_scalar_t,mj_lno_t,mj_gno_t,mj_part_t>::get_global_box() const
{
  return this->global_box;
}

/*! \brief Function call, if the part boxes are intended to be kept.
 *
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::set_to_keep_part_boxes(){
  this->mj_keep_part_boxes = true;
}


/* \brief Either the mj array (part_no_array) or num_global_parts should be provided in
 * the input. part_no_array takes
 * precedence if both are provided.
 * Depending on these parameters, total cut/part number,
 * maximum part/cut number along a dimension, estimated number of reduceAlls,
 * and the number of parts before the last dimension is calculated.
 * */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::set_part_specifications(){

        this->total_num_cut = 0; //how many cuts will be totally
        this->total_num_part = 1;    //how many parts will be totally
        this->max_num_part_along_dim = 0;         //maximum part count along a dimension.
        this->total_dim_num_reduce_all = 0;    //estimate on #reduceAlls can be done.
        this->last_dim_num_part = 1; //max no of parts that might occur
        //during the partition before the
        //last partitioning dimension.
        this->max_num_cut_along_dim = 0;
        this->max_num_total_part_along_dim = 0;

        if (this->part_no_array){
                //if user provided part array, traverse the array and set variables.
                for (int i = 0; i < this->recursion_depth; ++i){
                        this->total_dim_num_reduce_all += this->total_num_part;
                        this->total_num_part *= this->part_no_array[i];
                        if(this->part_no_array[i] > this->max_num_part_along_dim) {
                                this->max_num_part_along_dim = this->part_no_array[i];
                        }
                }
                this->last_dim_num_part = this->total_num_part / this->part_no_array[recursion_depth-1];
                this->num_global_parts = this->total_num_part;
        } else {
                mj_part_t future_num_parts = this->num_global_parts;

                //we need to calculate the part numbers now, to determine the maximum along the dimensions.
                for (int i = 0; i < this->recursion_depth; ++i){

                        mj_part_t maxNoPartAlongI = this->get_part_count(
                                        future_num_parts, 1.0f / (this->recursion_depth - i));

                        if (maxNoPartAlongI > this->max_num_part_along_dim){
                                this->max_num_part_along_dim = maxNoPartAlongI;
                        }

                        mj_part_t nfutureNumParts = future_num_parts / maxNoPartAlongI;
                        if (future_num_parts % maxNoPartAlongI){
                                ++nfutureNumParts;
                        }
                        future_num_parts = nfutureNumParts;
                }
                this->total_num_part = this->num_global_parts;
                //estimate reduceAll Count here.
                //we find the upperbound instead.
                mj_part_t p = 1;
                for (int i = 0; i < this->recursion_depth; ++i){
                        this->total_dim_num_reduce_all += p;
                        p *= this->max_num_part_along_dim;
                }

                this->last_dim_num_part  = p / this->max_num_part_along_dim;
        }

        this->total_num_cut = this->total_num_part - 1;
        this->max_num_cut_along_dim = this->max_num_part_along_dim - 1;
        this->max_num_total_part_along_dim = this->max_num_part_along_dim + size_t(this->max_num_cut_along_dim);
        //maxPartNo is P, maxCutNo = P-1, matTotalPartcount = 2P-1

        //refine the concurrent part count, if it is given bigger than the maximum possible part count.
    if(this->max_concurrent_part_calculation > this->last_dim_num_part){
        if(this->mj_problemComm->getRank() == 0){
            std::cerr << "Warning: Concurrent part count ("<< this->max_concurrent_part_calculation <<
            ") has been set bigger than maximum amount that can be used." <<
            " Setting to:" << this->last_dim_num_part << "." << std::endl;
        }
        this->max_concurrent_part_calculation = this->last_dim_num_part;
    }

}
/* \brief Tries to determine the part number for current dimension,
 * by trying to make the partitioning as square as possible.
 * \param num_total_future how many more partitionings are required.
 * \param root how many more recursion depth is left.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
inline mj_part_t AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::get_part_count(
                mj_part_t num_total_future,
                double root)
{
        double fp = pow(num_total_future, root);
        mj_part_t ip = mj_part_t (fp);
        if (fp - ip < this->fEpsilon * 100){
                return ip;
        }
        else {
                return ip  + 1;
        }
}

/* \brief Function returns how many parts that will be obtained after this dimension partitioning.
 * It sets how many parts each current part will be partitioned into in this dimension to num_partitioning_in_current_dim vector,
 * sets how many total future parts each obtained part will be partitioned into in next_future_num_parts_in_parts vector,
 * If part boxes are kept, then sets initializes the output_part_boxes as its ancestor.
 *
 *  \param num_partitioning_in_current_dim: output. How many parts each current part will be partitioned into.
 *  \param future_num_part_in_parts: input, how many future parts each current part will be partitioned into.
 *  \param next_future_num_parts_in_parts: output, how many future parts each obtained part will be partitioned into.
 *  \param future_num_parts: output, max number of future parts that will be obtained from a single
 *  \param current_num_parts: input, how many parts are there currently.
 *  \param current_iteration: input, current dimension iteration number.
 *  \param input_part_boxes: input, if boxes are kept, current boxes.
 *  \param output_part_boxes: output, if boxes are kept, the initial box boundaries for obtained parts.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
mj_part_t AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::update_part_num_arrays(
        std::vector <mj_part_t> &num_partitioning_in_current_dim, //assumes this vector is empty.
    std::vector<mj_part_t> *future_num_part_in_parts,
    std::vector<mj_part_t> *next_future_num_parts_in_parts, //assumes this vector is empty.
    mj_part_t &future_num_parts,
    mj_part_t current_num_parts,
    int current_iteration,
    RCP<mj_partBoxVector_t> input_part_boxes,
    RCP<mj_partBoxVector_t> output_part_boxes
){
        //how many parts that will be obtained after this dimension.
    mj_part_t output_num_parts = 0;
    if(this->part_no_array){
        //when the partNo array is provided as input,
        //each current partition will be partition to the same number of parts.
        //we dont need to use the future_num_part_in_parts vector in this case.

        mj_part_t p = this->part_no_array[current_iteration];
        if (p < 1){
            std::cout << "i:" << current_iteration << " p is given as:" << p << std::endl;
            exit(1);
        }
        if (p == 1){
            return current_num_parts;
        }

        for (mj_part_t ii = 0; ii < current_num_parts; ++ii){
            num_partitioning_in_current_dim.push_back(p);

        }
        //cout << "me:" << this->myRank << " current_iteration" << current_iteration <<
        //" current_num_parts:" << current_num_parts << std::endl;
        //cout << "num_partitioning_in_current_dim[0]:" << num_partitioning_in_current_dim[0] << std::endl;
        //set the new value of future_num_parts.

        /*
        cout << "\tfuture_num_parts:" << future_num_parts
                        << " num_partitioning_in_current_dim[0]:" << num_partitioning_in_current_dim[0]
                        << future_num_parts/ num_partitioning_in_current_dim[0] << std::endl;
        */

        future_num_parts /= num_partitioning_in_current_dim[0];
        output_num_parts = current_num_parts * num_partitioning_in_current_dim[0];

        if (this->mj_keep_part_boxes){
            for (mj_part_t k = 0; k < current_num_parts; ++k){
                //initialized the output boxes as its ancestor.
                for (mj_part_t j = 0; j < num_partitioning_in_current_dim[0]; ++j){
                    output_part_boxes->push_back((*input_part_boxes)[k]);
                }
            }
        }

        //set the how many more parts each part will be divided.
        //this is obvious when partNo array is provided as input.
        //however, fill this so that weights will be calculated according to this array.
        for (mj_part_t ii = 0; ii < output_num_parts; ++ii){
            next_future_num_parts_in_parts->push_back(future_num_parts);
        }
    }
    else {
        //if partNo array is not provided as input,
        //future_num_part_in_parts  holds how many parts each part should be divided.
        //initially it holds a single number equal to the total number of global parts.

        //calculate the future_num_parts from beginning,
        //since each part might be divided into different number of parts.
        future_num_parts = 1;

        //cout << "i:" << i << std::endl;

        for (mj_part_t ii = 0; ii < current_num_parts; ++ii){
            //get how many parts a part should be divided.
            mj_part_t future_num_parts_of_part_ii = (*future_num_part_in_parts)[ii];

            //get the ideal number of parts that is close to the
            //(recursion_depth - i) root of the future_num_parts_of_part_ii.
            mj_part_t num_partitions_in_current_dim =
                                                this->get_part_count(
                                                                future_num_parts_of_part_ii,
                                                                1.0 / (this->recursion_depth - current_iteration)
                                        );

            if (num_partitions_in_current_dim > this->max_num_part_along_dim){
                std::cerr << "ERROR: maxPartNo calculation is wrong." << std::endl;
                exit(1);
            }
            //add this number to num_partitioning_in_current_dim vector.
            num_partitioning_in_current_dim.push_back(num_partitions_in_current_dim);


            //increase the output number of parts.
            output_num_parts += num_partitions_in_current_dim;

            //ideal number of future partitions for each part.
            mj_part_t ideal_num_future_parts_in_part = future_num_parts_of_part_ii / num_partitions_in_current_dim;
            for (mj_part_t iii = 0; iii < num_partitions_in_current_dim; ++iii){
                mj_part_t num_future_parts_for_part_iii = ideal_num_future_parts_in_part;

                //if there is a remainder in the part increase the part weight.
                if (iii < future_num_parts_of_part_ii % num_partitions_in_current_dim){
                    //if not uniform, add 1 for the extra parts.
                    ++num_future_parts_for_part_iii;
                }
                next_future_num_parts_in_parts->push_back(num_future_parts_for_part_iii);

                //if part boxes are stored, initialize the box of the parts as the ancestor.
                if (this->mj_keep_part_boxes){
                    output_part_boxes->push_back((*input_part_boxes)[ii]);
                }

                //set num future_num_parts to maximum in this part.
                if (num_future_parts_for_part_iii > future_num_parts) future_num_parts = num_future_parts_for_part_iii;
            }
        }
    }
    return output_num_parts;
}


/* \brief Allocates and initializes the work memory that will be used by MJ.
 *
 * */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::allocate_set_work_memory(){

        //points to process that initially owns the coordinate.
        this->owner_of_coordinate  = NULL;

        //Throughout the partitioning execution,
        //instead of the moving the coordinates, hold a permutation array for parts.
        //coordinate_permutations holds the current permutation.
        this->coordinate_permutations =  allocMemory< mj_lno_t>(this->num_local_coords);
        //initial configuration, set each pointer-i to i.
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp parallel for
#endif
        for(mj_lno_t i = 0; i < this->num_local_coords; ++i){
                this->coordinate_permutations[i] = i;
        }

        //new_coordinate_permutations holds the current permutation.
        this->new_coordinate_permutations = allocMemory< mj_lno_t>(this->num_local_coords);

        this->assigned_part_ids = NULL;
        if(this->num_local_coords > 0){
                this->assigned_part_ids = allocMemory<mj_part_t>(this->num_local_coords);
        }

        //single partition starts at index-0, and ends at numLocalCoords
        //inTotalCounts array holds the end points in coordinate_permutations array
        //for each partition. Initially sized 1, and single element is set to numLocalCoords.
        this->part_xadj = allocMemory<mj_lno_t>(1);
        this->part_xadj[0] = static_cast<mj_lno_t>(this->num_local_coords);//the end of the initial partition is the end of coordinates.
        //the ends points of the output, this is allocated later.
        this->new_part_xadj = NULL;

        // only store this much if cuts are needed to be stored.
        //this->all_cut_coordinates = allocMemory< mj_scalar_t>(this->total_num_cut);


        this->all_cut_coordinates  = allocMemory< mj_scalar_t>(this->max_num_cut_along_dim * this->max_concurrent_part_calculation);

        this->max_min_coords =  allocMemory< mj_scalar_t>(this->num_threads * 2);

        this->process_cut_line_weight_to_put_left = NULL; //how much weight percentage should a MPI put left side of the each cutline
        this->thread_cut_line_weight_to_put_left = NULL; //how much weight percentage should each thread in MPI put left side of the each outline
        //distribute_points_on_cut_lines = false;
        if(this->distribute_points_on_cut_lines){
                this->process_cut_line_weight_to_put_left = allocMemory<mj_scalar_t>(this->max_num_cut_along_dim * this->max_concurrent_part_calculation);
                this->thread_cut_line_weight_to_put_left = allocMemory<mj_scalar_t *>(this->num_threads);
                for(int i = 0; i < this->num_threads; ++i){
                        this->thread_cut_line_weight_to_put_left[i] = allocMemory<mj_scalar_t>(this->max_num_cut_along_dim);
                }
            this->process_rectilinear_cut_weight = allocMemory<mj_scalar_t>(this->max_num_cut_along_dim);
            this->global_rectilinear_cut_weight = allocMemory<mj_scalar_t>(this->max_num_cut_along_dim);
        }


        // work array to manipulate coordinate of cutlines in different iterations.
        //necessary because previous cut line information is used for determining
        //the next cutline information. therefore, cannot update the cut work array
        //until all cutlines are determined.
        this->cut_coordinates_work_array = allocMemory<mj_scalar_t>(this->max_num_cut_along_dim *
                        this->max_concurrent_part_calculation);


        //cumulative part weight array.
        this->target_part_weights = allocMemory<mj_scalar_t>(
                                        this->max_num_part_along_dim * this->max_concurrent_part_calculation);
        // the weight from left to write.

    this->cut_upper_bound_coordinates = allocMemory<mj_scalar_t>(this->max_num_cut_along_dim * this->max_concurrent_part_calculation);  //upper bound coordinate of a cut line
    this->cut_lower_bound_coordinates = allocMemory<mj_scalar_t>(this->max_num_cut_along_dim* this->max_concurrent_part_calculation);  //lower bound coordinate of a cut line
    this->cut_lower_bound_weights = allocMemory<mj_scalar_t>(this->max_num_cut_along_dim* this->max_concurrent_part_calculation);  //lower bound weight of a cut line
    this->cut_upper_bound_weights = allocMemory<mj_scalar_t>(this->max_num_cut_along_dim* this->max_concurrent_part_calculation);  //upper bound weight of a cut line

    this->process_local_min_max_coord_total_weight = allocMemory<mj_scalar_t>(3 * this->max_concurrent_part_calculation); //combined array to exchange the min and max coordinate, and total weight of part.
    this->global_min_max_coord_total_weight = allocMemory<mj_scalar_t>(3 * this->max_concurrent_part_calculation);//global combined array with the results for min, max and total weight.

    //is_cut_line_determined is used to determine if a cutline is determined already.
    //If a cut line is already determined, the next iterations will skip this cut line.
    this->is_cut_line_determined = allocMemory<bool>(this->max_num_cut_along_dim * this->max_concurrent_part_calculation);
    //my_incomplete_cut_count count holds the number of cutlines that have not been finalized for each part
    //when concurrentPartCount>1, using this information, if my_incomplete_cut_count[x]==0, then no work is done for this part.
    this->my_incomplete_cut_count =  allocMemory<mj_part_t>(this->max_concurrent_part_calculation);
    //local part weights of each thread.
    this->thread_part_weights = allocMemory<double *>(this->num_threads);
    //the work manupulation array for partweights.
    this->thread_part_weight_work = allocMemory<double *>(this->num_threads);

    //thread_cut_left_closest_point to hold the closest coordinate to a cutline from left (for each thread).
    this->thread_cut_left_closest_point = allocMemory<mj_scalar_t *>(this->num_threads);
    //thread_cut_right_closest_point to hold the closest coordinate to a cutline from right (for each thread)
    this->thread_cut_right_closest_point = allocMemory<mj_scalar_t *>(this->num_threads);

    //to store how many points in each part a thread has.
    this->thread_point_counts = allocMemory<mj_lno_t *>(this->num_threads);

    for(int i = 0; i < this->num_threads; ++i){
        //partWeights[i] = allocMemory<mj_scalar_t>(maxTotalPartCount);
        this->thread_part_weights[i] = allocMemory < double >(this->max_num_total_part_along_dim * this->max_concurrent_part_calculation);
        this->thread_cut_right_closest_point[i] = allocMemory<mj_scalar_t>(this->max_num_cut_along_dim * this->max_concurrent_part_calculation);
        this->thread_cut_left_closest_point[i] = allocMemory<mj_scalar_t>(this->max_num_cut_along_dim * this->max_concurrent_part_calculation);
        this->thread_point_counts[i] =  allocMemory<mj_lno_t>(this->max_num_part_along_dim);
    }
    //for faster communication, concatanation of
    //totalPartWeights sized 2P-1, since there are P parts and P-1 cut lines
    //leftClosest distances sized P-1, since P-1 cut lines
    //rightClosest distances size P-1, since P-1 cut lines.
    this->total_part_weight_left_right_closests = allocMemory<mj_scalar_t>((this->max_num_total_part_along_dim + this->max_num_cut_along_dim * 2) * this->max_concurrent_part_calculation);
    this->global_total_part_weight_left_right_closests = allocMemory<mj_scalar_t>((this->max_num_total_part_along_dim + this->max_num_cut_along_dim * 2) * this->max_concurrent_part_calculation);


    mj_scalar_t **coord = allocMemory<mj_scalar_t *>(this->coord_dim);
    for (int i=0; i < this->coord_dim; i++){
        coord[i] = allocMemory<mj_scalar_t>(this->num_local_coords);
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp parallel for
#endif
        for (mj_lno_t j=0; j < this->num_local_coords; j++)
                coord[i][j] = this->mj_coordinates[i][j];
    }
    this->mj_coordinates = coord;


    int criteria_dim = (this->num_weights_per_coord ? this->num_weights_per_coord : 1);
    mj_scalar_t **weights = allocMemory<mj_scalar_t *>(criteria_dim);

    for (int i=0; i < criteria_dim; i++){
        weights[i] = NULL;
    }
    for (int i=0; i < this->num_weights_per_coord; i++){
        weights[i] = allocMemory<mj_scalar_t>(this->num_local_coords);
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp parallel for
#endif
        for (mj_lno_t j=0; j < this->num_local_coords; j++)
                weights[i][j] = this->mj_weights[i][j];

    }
        this->mj_weights = weights;
    this->current_mj_gnos = allocMemory<mj_gno_t>(this->num_local_coords);
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp parallel for
#endif
    for (mj_lno_t j=0; j < this->num_local_coords; j++)
        this->current_mj_gnos[j] = this->initial_mj_gnos[j];

    this->owner_of_coordinate = allocMemory<int>(this->num_local_coords);

#ifdef HAVE_ZOLTAN2_OMP
#pragma omp parallel for
#endif
    for (mj_lno_t j=0; j < this->num_local_coords; j++)
        this->owner_of_coordinate[j] = this->myActualRank;
}

/* \brief compute the global bounding box
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t,mj_lno_t,mj_gno_t,mj_part_t>::compute_global_box()
{
    //local min coords
    mj_scalar_t *mins = allocMemory<mj_scalar_t>(this->coord_dim);
    //global min coords
    mj_scalar_t *gmins = allocMemory<mj_scalar_t>(this->coord_dim);
    //local max coords
    mj_scalar_t *maxs = allocMemory<mj_scalar_t>(this->coord_dim);
    //global max coords
    mj_scalar_t *gmaxs = allocMemory<mj_scalar_t>(this->coord_dim);

    for (int i = 0; i < this->coord_dim; ++i){
        mj_scalar_t localMin = std::numeric_limits<mj_scalar_t>::max();
        mj_scalar_t localMax = -localMin;
        if (localMax > 0) localMax = 0;


        for (mj_lno_t j = 0; j < this->num_local_coords; ++j){
            if (this->mj_coordinates[i][j] < localMin){
                localMin = this->mj_coordinates[i][j];
            }
            if (this->mj_coordinates[i][j] > localMax){
                localMax = this->mj_coordinates[i][j];
            }
        }
        //cout << " localMin:" << localMin << endl;
        //cout << " localMax:" << localMax << endl;
        mins[i] = localMin;
        maxs[i] = localMax;

    }
    reduceAll<int, mj_scalar_t>(*this->comm, Teuchos::REDUCE_MIN,
            this->coord_dim, mins, gmins
    );


    reduceAll<int, mj_scalar_t>(*this->comm, Teuchos::REDUCE_MAX,
            this->coord_dim, maxs, gmaxs
    );



    //create single box with all areas.
    global_box = rcp(new mj_partBox_t(0,this->coord_dim,gmins,gmaxs));
    //coordinateModelPartBox <mj_scalar_t, mj_part_t> tmpBox (0, coordDim);
    freeArray<mj_scalar_t>(mins);
    freeArray<mj_scalar_t>(gmins);
    freeArray<mj_scalar_t>(maxs);
    freeArray<mj_scalar_t>(gmaxs);
}

/* \brief for part communication we keep track of the box boundaries.
 * This is performed when either asked specifically, or when geometric mapping is performed afterwards.
 * This function initializes a single box with all global min and max coordinates.
 * \param initial_partitioning_boxes the input and output vector for boxes.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::init_part_boxes(
                RCP<mj_partBoxVector_t> & initial_partitioning_boxes
)
{
    mj_partBox_t tmp_box(*global_box);
    initial_partitioning_boxes->push_back(tmp_box);
}

/*! \brief Function to determine the local minimum and maximum coordinate, and local total weight
 *  in the given set of local points.
 * \param coordinate_begin_index is the start index of the given partition on partitionedPointPermutations.
 * \param coordinate_end_index is the end index of the given partition on partitionedPointPermutations.
 * \param mj_current_coordinate_permutations is the permutation array that point to the actual coordinate index. Sized as numLocalCoords.
 * \param mj_current_dim_coords float-like array representing the coordinates in a single dimension. Sized as numLocalCoords.
 * \param min_coordinate is the output to represent the local minimumCoordinate in  given range of coordinates.
 * \param max_coordinate is the output to represent the local maximum coordinate in the given range of coordinates.
 * \param total_weight is the output to represent the local total weight in the coordinate in the given range of coordinates.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_get_local_min_max_coord_totW(
                mj_lno_t coordinate_begin_index,
                mj_lno_t coordinate_end_index,
                mj_lno_t *mj_current_coordinate_permutations,
                mj_scalar_t *mj_current_dim_coords,
                mj_scalar_t &min_coordinate,
                mj_scalar_t &max_coordinate,
                mj_scalar_t &total_weight){

    //if the part is empty.
    //set the min and max coordinates as reverse.
    if(coordinate_begin_index >= coordinate_end_index)
    {
        min_coordinate = this->maxScalar_t;
        max_coordinate = this->minScalar_t;
        total_weight = 0;
    }
    else {
        mj_scalar_t my_total_weight = 0;
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp parallel
#endif
        {
            //if uniform weights are used, then weight is equal to count.
            if (this->mj_uniform_weights[0]) {
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp single
#endif
                {
                    my_total_weight = coordinate_end_index - coordinate_begin_index;
                }

            }
            else {
                //if not uniform, then weights are reducted from threads.
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp for reduction(+:my_total_weight)
#endif
                for (mj_lno_t ii = coordinate_begin_index; ii < coordinate_end_index; ++ii){
                    int i = mj_current_coordinate_permutations[ii];
                    my_total_weight += this->mj_weights[0][i];
                }
            }

            int my_thread_id = 0;
#ifdef HAVE_ZOLTAN2_OMP
            my_thread_id = omp_get_thread_num();
#endif
            mj_scalar_t my_thread_min_coord, my_thread_max_coord;
            my_thread_min_coord=my_thread_max_coord
                =mj_current_dim_coords[mj_current_coordinate_permutations[coordinate_begin_index]];


#ifdef HAVE_ZOLTAN2_OMP
#pragma omp for
#endif
            for(mj_lno_t j = coordinate_begin_index + 1; j < coordinate_end_index; ++j){
                int i = mj_current_coordinate_permutations[j];
                if(mj_current_dim_coords[i] > my_thread_max_coord)
                    my_thread_max_coord = mj_current_dim_coords[i];
                if(mj_current_dim_coords[i] < my_thread_min_coord)
                    my_thread_min_coord = mj_current_dim_coords[i];
            }
            this->max_min_coords[my_thread_id] = my_thread_min_coord;
            this->max_min_coords[my_thread_id + this->num_threads] = my_thread_max_coord;

#ifdef HAVE_ZOLTAN2_OMP
//we need a barrier here, because max_min_array might not be filled by some of the threads.
#pragma omp barrier
#pragma omp single nowait
#endif
            {
                min_coordinate = this->max_min_coords[0];
                for(int i = 1; i < this->num_threads; ++i){
                    if(this->max_min_coords[i] < min_coordinate)
                        min_coordinate = this->max_min_coords[i];
                }
            }

#ifdef HAVE_ZOLTAN2_OMP
#pragma omp single nowait
#endif
            {
                max_coordinate = this->max_min_coords[this->num_threads];
                for(int i = this->num_threads + 1; i < this->num_threads * 2; ++i){
                    if(this->max_min_coords[i] > max_coordinate)
                        max_coordinate = this->max_min_coords[i];
                }
            }
        }
        total_weight = my_total_weight;
    }
}


/*! \brief Function that reduces global minimum and maximum coordinates with global total weight from given local arrays.
 * \param current_concurrent_num_parts is the number of parts whose cut lines will be calculated concurrently.
 * \param local_min_max_total is the array holding local min and max coordinate values with local total weight.
 * First concurrentPartCount entries are minimums of the parts, next concurrentPartCount entries are max, and then the total weights.
 * \param global_min_max_total is the output array holding global min and global coordinate values with global total weight.
 * The structure is same as localMinMaxTotal.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_get_global_min_max_coord_totW(
    mj_part_t current_concurrent_num_parts,
    mj_scalar_t *local_min_max_total,
    mj_scalar_t *global_min_max_total){

        //reduce min for first current_concurrent_num_parts elements, reduce max for next
        //concurrentPartCount elements,
        //reduce sum for the last concurrentPartCount elements.
        if(this->comm->getSize()  > 1){
                Teuchos::MultiJaggedCombinedMinMaxTotalReductionOp<int, mj_scalar_t>
                        reductionOp(
                                        current_concurrent_num_parts,
                                        current_concurrent_num_parts,
                                        current_concurrent_num_parts);
                try{
                        reduceAll<int, mj_scalar_t>(
                                        *(this->comm),
                                        reductionOp,
                                        3 * current_concurrent_num_parts,
                                        local_min_max_total,
                                        global_min_max_total);
                }
                Z2_THROW_OUTSIDE_ERROR(*(this->mj_env))
        }
        else {
                mj_part_t s = 3 * current_concurrent_num_parts;
                for (mj_part_t i = 0; i < s; ++i){
                        global_min_max_total[i] = local_min_max_total[i];
                }
        }
}



/*! \brief Function that calculates the new coordinates for the cut lines. Function is called inside the parallel region.
 * \param min_coord minimum coordinate in the range.
 * \param max_coord maximum coordinate in the range.
 *
 * \param num_cuts holds the number of cuts in the current partitioning dimension.
 * \param global_weight holds the global total weight in the current part.
 *
 * \param initial_cut_coords is the output array for the initial cut lines.
 * \param target_part_weights is the output array holding the cumulative ratios of parts in current partitioning.
 * For partitioning to 4 uniformly, target_part_weights will be (0.25 * globalTotalWeight, 0.5 *globalTotalWeight , 0.75 * globalTotalWeight, globalTotalWeight).
 *
 * \param future_num_part_in_parts is the vector that holds how many more parts each part will be divided into more
 * for the parts at the beginning of this coordinate partitioning
 * \param next_future_num_parts_in_parts is the vector that holds how many more parts each part will be divided into more
 * for the parts that will be obtained at the end of this coordinate partitioning.
 * \param concurrent_current_part is the index of the part in the future_num_part_in_parts vector.
 * \param obtained_part_index holds the amount of shift in the next_future_num_parts_in_parts for the output parts.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_get_initial_cut_coords_target_weights(
    mj_scalar_t min_coord,
    mj_scalar_t max_coord,
    mj_part_t num_cuts/*p-1*/ ,
    mj_scalar_t global_weight,
    mj_scalar_t *initial_cut_coords /*p - 1 sized, coordinate of each cut line*/,
    mj_scalar_t *current_target_part_weights /*cumulative weights, at left side of each cut line. p-1 sized*/,

    std::vector <mj_part_t> *future_num_part_in_parts, //the vecto
    std::vector <mj_part_t> *next_future_num_parts_in_parts,
    mj_part_t concurrent_current_part,
    mj_part_t obtained_part_index
){

    mj_scalar_t coord_range = max_coord - min_coord;
    if(this->mj_uniform_parts[0]){
        {
            mj_part_t cumulative = 0;
            //how many total future parts the part will be partitioned into.
            mj_scalar_t total_future_part_count_in_part = mj_scalar_t((*future_num_part_in_parts)[concurrent_current_part]);


            //how much each part should weigh in ideal case.
            mj_scalar_t unit_part_weight = global_weight / total_future_part_count_in_part;
            /*
            cout << "total_future_part_count_in_part:" << total_future_part_count_in_part << endl;
            cout << "global_weight:" << global_weight << endl;
            cout << "unit_part_weight" << unit_part_weight <<endl;
            */
            for(mj_part_t i = 0; i < num_cuts; ++i){
                cumulative += (*next_future_num_parts_in_parts)[i + obtained_part_index];

                /*
                cout << "obtained_part_index:" << obtained_part_index <<
                                " (*next_future_num_parts_in_parts)[i + obtained_part_index]:" << (*next_future_num_parts_in_parts)[i + obtained_part_index] <<
                                " cumulative:" << cumulative << endl;
                */
                //set target part weight.
                current_target_part_weights[i] = cumulative * unit_part_weight;
                //cout <<"i:" << i << " current_target_part_weights:" << current_target_part_weights[i] << endl;
                //set initial cut coordinate.
                initial_cut_coords[i] = min_coord + (coord_range *
                                         cumulative) / total_future_part_count_in_part;
            }
            current_target_part_weights[num_cuts] = 1;
        }

        //round the target part weights.
        if (this->mj_uniform_weights[0]){
                for(mj_part_t i = 0; i < num_cuts + 1; ++i){
                current_target_part_weights[i] = long(current_target_part_weights[i] + 0.5);
            }
        }
    }
    else {
        std::cerr << "MJ does not support non uniform part weights" << std::endl;
        exit(1);
    }
}


/*! \brief Function that calculates the new coordinates for the cut lines. Function is called inside the parallel region.
 * \param max_coordinate maximum coordinate in the range.
 * \param min_coordinate minimum coordinate in the range.
 *
 * \param concurrent_current_part_index is the index of the part in the inTotalCounts vector.
 * \param coordinate_begin_index holds the beginning of the coordinates in current part.
 * \param coordinate_end_index holds end of the coordinates in current part.
 * \param mj_current_coordinate_permutations is the permutation array, holds the real indices of coordinates on mj_current_dim_coords array.
 * \param mj_current_dim_coords is the 1D array holding the coordinates.
 * \param mj_part_ids is the array holding the partIds of each coordinate.
 * \param partition_count is the number of parts that the current part will be partitioned into.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::set_initial_coordinate_parts(
    mj_scalar_t &max_coordinate,
    mj_scalar_t &min_coordinate,
    mj_part_t &concurrent_current_part_index,
    mj_lno_t coordinate_begin_index,
    mj_lno_t coordinate_end_index,
    mj_lno_t *mj_current_coordinate_permutations,
    mj_scalar_t *mj_current_dim_coords,
    mj_part_t *mj_part_ids,
    mj_part_t &partition_count
){
    mj_scalar_t coordinate_range = max_coordinate - min_coordinate;

    //if there is single point, or if all points are along a line.
    //set initial part to 0 for all.
    if(ZOLTAN2_ABS(coordinate_range) < this->sEpsilon ){
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp parallel for
#endif
        for(mj_lno_t ii = coordinate_begin_index; ii < coordinate_end_index; ++ii){
                mj_part_ids[mj_current_coordinate_permutations[ii]] = 0;
        }
    }
    else{

        //otherwise estimate an initial part for each coordinate.
        //assuming uniform distribution of points.
        mj_scalar_t slice = coordinate_range / partition_count;

#ifdef HAVE_ZOLTAN2_OMP
#pragma omp parallel for
#endif
        for(mj_lno_t ii = coordinate_begin_index; ii < coordinate_end_index; ++ii){

            mj_lno_t iii = mj_current_coordinate_permutations[ii];
            mj_part_t pp = mj_part_t((mj_current_dim_coords[iii] - min_coordinate) / slice);
            mj_part_ids[iii] = 2 * pp;
        }
    }
}


/*! \brief Function that is responsible from 1D partitioning of the given range of coordinates.
 * \param mj_current_dim_coords is 1 dimensional array holding coordinate values.
 * \param imbalanceTolerance is the maximum allowed imbalance ratio.
 * \param current_work_part is the beginning index of concurrentPartCount parts.
 * \param current_concurrent_num_parts is the number of parts whose cut lines will be calculated concurrently.
 * \param current_cut_coordinates is the array holding the coordinates of the cut.
 * \param total_incomplete_cut_count is the number of cut lines whose positions should be calculated.
 * \param num_partitioning_in_current_dim is the vector that holds how many parts each part will be divided into.
 *
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_1D_part(
    mj_scalar_t *mj_current_dim_coords,
    mj_scalar_t used_imbalance_tolerance,
    mj_part_t current_work_part,
    mj_part_t current_concurrent_num_parts,
    mj_scalar_t *current_cut_coordinates,
    mj_part_t total_incomplete_cut_count,
    std::vector <mj_part_t> &num_partitioning_in_current_dim
){


    mj_part_t rectilinear_cut_count = 0;
    mj_scalar_t *temp_cut_coords = current_cut_coordinates;

    Teuchos::MultiJaggedCombinedReductionOp<mj_part_t, mj_scalar_t>
                 *reductionOp = NULL;
    reductionOp = new Teuchos::MultiJaggedCombinedReductionOp
                     <mj_part_t, mj_scalar_t>(
                                 &num_partitioning_in_current_dim ,
                                 current_work_part ,
                                 current_concurrent_num_parts);

    size_t total_reduction_size = 0;
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp parallel shared(total_incomplete_cut_count,  rectilinear_cut_count)
#endif
    {
        int me = 0;
#ifdef HAVE_ZOLTAN2_OMP
        me = omp_get_thread_num();
#endif
        double *my_thread_part_weights = this->thread_part_weights[me];
        mj_scalar_t *my_thread_left_closest = this->thread_cut_left_closest_point[me];
        mj_scalar_t *my_thread_right_closest = this->thread_cut_right_closest_point[me];

#ifdef HAVE_ZOLTAN2_OMP
#pragma omp single
#endif
            {
                //initialize the lower and upper bounds of the cuts.
                mj_part_t next = 0;
                for(mj_part_t i = 0; i < current_concurrent_num_parts; ++i){

                    mj_part_t num_part_in_dim =  num_partitioning_in_current_dim[current_work_part + i];
                    mj_part_t num_cut_in_dim = num_part_in_dim - 1;
                    total_reduction_size += (4 * num_cut_in_dim + 1);

                    for(mj_part_t ii = 0; ii < num_cut_in_dim; ++ii){
                        this->is_cut_line_determined[next] = false;
                        this->cut_lower_bound_coordinates[next] = global_min_max_coord_total_weight[i]; //min coordinate
                        this->cut_upper_bound_coordinates[next] = global_min_max_coord_total_weight[i + current_concurrent_num_parts]; //max coordinate

                        this->cut_upper_bound_weights[next] = global_min_max_coord_total_weight[i + 2 * current_concurrent_num_parts]; //total weight
                        this->cut_lower_bound_weights[next] = 0;

                        if(this->distribute_points_on_cut_lines){
                            this->process_cut_line_weight_to_put_left[next] = 0;
                        }
                        ++next;
                    }
                }
            }

        //no need to have barrier here.
        //pragma omp single have implicit barrier.

        int iteration = 0;
        while (total_incomplete_cut_count != 0){
            iteration += 1;
            //cout << "\niteration:" << iteration  << " ";
            mj_part_t concurrent_cut_shifts = 0;
            size_t total_part_shift = 0;

            for (mj_part_t kk = 0; kk < current_concurrent_num_parts; ++kk){
                mj_part_t num_parts =  -1;
                num_parts =  num_partitioning_in_current_dim[current_work_part + kk];

                mj_part_t num_cuts = num_parts - 1;
                size_t total_part_count = num_parts + size_t (num_cuts) ;
                if (this->my_incomplete_cut_count[kk] > 0){

                    //although isDone shared, currentDone is private and same for all.
                    bool *current_cut_status = this->is_cut_line_determined + concurrent_cut_shifts;
                    double *my_current_part_weights = my_thread_part_weights + total_part_shift;
                    mj_scalar_t *my_current_left_closest = my_thread_left_closest + concurrent_cut_shifts;
                    mj_scalar_t *my_current_right_closest = my_thread_right_closest + concurrent_cut_shifts;

                    mj_part_t conccurent_current_part = current_work_part + kk;
                    mj_lno_t coordinate_begin_index = conccurent_current_part ==0 ? 0: this->part_xadj[conccurent_current_part -1];
                    mj_lno_t coordinate_end_index = this->part_xadj[conccurent_current_part];
                    mj_scalar_t *temp_current_cut_coords = temp_cut_coords + concurrent_cut_shifts;

                    mj_scalar_t min_coord = global_min_max_coord_total_weight[kk];
                    mj_scalar_t max_coord = global_min_max_coord_total_weight[kk + current_concurrent_num_parts];

                    // compute part weights using existing cuts
                    this->mj_1D_part_get_thread_part_weights(
                        total_part_count,
                        num_cuts,
                        max_coord,//globalMinMaxTotal[kk + concurrentPartCount],//maxScalar,
                        min_coord,//globalMinMaxTotal[kk]//minScalar,
                        coordinate_begin_index,
                        coordinate_end_index,
                        mj_current_dim_coords,
                        temp_current_cut_coords,
                        current_cut_status,
                        my_current_part_weights,
                        my_current_left_closest,
                        my_current_right_closest);

                }

                concurrent_cut_shifts += num_cuts;
                total_part_shift += total_part_count;
            }

            //sum up the results of threads
            this->mj_accumulate_thread_results(
                num_partitioning_in_current_dim,
                current_work_part,
                current_concurrent_num_parts);

            //now sum up the results of mpi processors.
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp single
#endif
            {
                if(this->comm->getSize() > 1){
                        reduceAll<int, mj_scalar_t>( *(this->comm), *reductionOp,
                                        total_reduction_size,
                                        this->total_part_weight_left_right_closests,
                                        this->global_total_part_weight_left_right_closests);

                }
                else {
                        memcpy(
                                this->global_total_part_weight_left_right_closests,
                            this->total_part_weight_left_right_closests,
                            total_reduction_size * sizeof(mj_scalar_t));
                }
            }

            //how much cut will be shifted for the next part in the concurrent part calculation.
            mj_part_t cut_shift = 0;

            //how much the concantaneted array will be shifted for the next part in concurrent part calculation.
            size_t tlr_shift = 0;
            for (mj_part_t kk = 0; kk < current_concurrent_num_parts; ++kk){
                mj_part_t num_parts =  num_partitioning_in_current_dim[current_work_part + kk];
                mj_part_t num_cuts = num_parts - 1;
                size_t num_total_part = num_parts + size_t (num_cuts) ;

                //if the cuts of this cut has already been completed.
                //nothing to do for this part.
                //just update the shift amount and proceed.
                if (this->my_incomplete_cut_count[kk] == 0) {
                        cut_shift += num_cuts;
                        tlr_shift += (num_total_part + 2 * num_cuts);
                        continue;
                }

                mj_scalar_t *current_local_part_weights = this->total_part_weight_left_right_closests  + tlr_shift ;
                mj_scalar_t *current_global_tlr = this->global_total_part_weight_left_right_closests + tlr_shift;
                mj_scalar_t *current_global_left_closest_points = current_global_tlr + num_total_part; //left closest points
                mj_scalar_t *current_global_right_closest_points = current_global_tlr + num_total_part + num_cuts; //right closest points
                mj_scalar_t *current_global_part_weights = current_global_tlr;
                bool *current_cut_line_determined = this->is_cut_line_determined + cut_shift;

                mj_scalar_t *current_part_target_weights = this->target_part_weights + cut_shift + kk;
                mj_scalar_t *current_part_cut_line_weight_to_put_left = this->process_cut_line_weight_to_put_left + cut_shift;

                mj_scalar_t min_coordinate = global_min_max_coord_total_weight[kk];
                mj_scalar_t max_coordinate = global_min_max_coord_total_weight[kk + current_concurrent_num_parts];
                mj_scalar_t global_total_weight = global_min_max_coord_total_weight[kk + current_concurrent_num_parts * 2];
                mj_scalar_t *current_cut_lower_bound_weights = this->cut_lower_bound_weights + cut_shift;
                mj_scalar_t *current_cut_upper_weights = this->cut_upper_bound_weights + cut_shift;
                mj_scalar_t *current_cut_upper_bounds = this->cut_upper_bound_coordinates + cut_shift;
                mj_scalar_t *current_cut_lower_bounds = this->cut_lower_bound_coordinates + cut_shift;

                mj_part_t initial_incomplete_cut_count = this->my_incomplete_cut_count[kk];

                // Now compute the new cut coordinates.
                this->mj_get_new_cut_coordinates(
                                num_total_part,
                                num_cuts,
                                max_coordinate,
                                min_coordinate,
                                global_total_weight,
                                used_imbalance_tolerance,
                                current_global_part_weights,
                                current_local_part_weights,
                                current_part_target_weights,
                                current_cut_line_determined,
                                temp_cut_coords + cut_shift,
                                current_cut_upper_bounds,
                                current_cut_lower_bounds,
                                current_global_left_closest_points,
                                current_global_right_closest_points,
                                current_cut_lower_bound_weights,
                                current_cut_upper_weights,
                                this->cut_coordinates_work_array +cut_shift, //new cut coordinates
                                current_part_cut_line_weight_to_put_left,
                                &rectilinear_cut_count,
                                this->my_incomplete_cut_count[kk]);

                cut_shift += num_cuts;
                tlr_shift += (num_total_part + 2 * num_cuts);
                mj_part_t iteration_complete_cut_count = initial_incomplete_cut_count - this->my_incomplete_cut_count[kk];
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp single
#endif
                {
                        total_incomplete_cut_count -= iteration_complete_cut_count;
                }

            }
            { //This unnecessary bracket works around a compiler bug in NVCC when compiling with OpenMP enabled
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp barrier
#pragma omp single
#endif
            {
                //swap the cut coordinates for next iteration.
                mj_scalar_t *t = temp_cut_coords;
                temp_cut_coords = this->cut_coordinates_work_array;
                this->cut_coordinates_work_array = t;
            }
            }
        }

        // Needed only if keep_cuts; otherwise can simply swap array pointers
        // cutCoordinates and cutCoordinatesWork.
        // (at first iteration, cutCoordinates == cutCoorindates_tmp).
        // computed cuts must be in cutCoordinates.
        if (current_cut_coordinates != temp_cut_coords){
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp single
#endif
                {
                        mj_part_t next = 0;
                        for(mj_part_t i = 0; i < current_concurrent_num_parts; ++i){
                                mj_part_t num_parts = -1;
                                num_parts = num_partitioning_in_current_dim[current_work_part + i];
                                mj_part_t num_cuts = num_parts - 1;

                                for(mj_part_t ii = 0; ii < num_cuts; ++ii){
                                        current_cut_coordinates[next + ii] = temp_cut_coords[next + ii];
                                }
                                next += num_cuts;
                        }
                }

#ifdef HAVE_ZOLTAN2_OMP
#pragma omp single
#endif
            {
                this->cut_coordinates_work_array = temp_cut_coords;
            }
        }
    }
    delete reductionOp;
}


/*! \brief Function that calculates the weights of each part according to given part cut coordinates.
 * Function is called inside the parallel region. Thread specific work arrays are provided
 * as function parameter.
 *
 * \param total_part_count is the sum of number of cutlines and number of parts. Simply it is 2*P - 1.
 * \param num_cuts is the number of cut lines. P - 1.
 * \param max_coord is the maximum coordinate in the part.
 * \param min_coord is the min coordinate in the part.
 * \param coordinate_begin_index is the index of the first coordinate in current part.
 * \param coordinate_end_index is the index of the last coordinate in current part.
 * \param mj_current_dim_coords is 1 dimensional array holding coordinate values.
 *
 * \param temp_current_cut_coords is the array holding the coordinates of each cut line. Sized P - 1.
 * \param current_cut_status is the boolean array to determine if the correct position for a cut line is found.
 * \param my_current_part_weights is the array holding the part weights for the calling thread.
 * \param my_current_left_closest is the array holding the coordinate of the closest points to the cut lines from left for the calling thread..
 * \param my_current_right_closest is the array holding the coordinate of the closest points to the cut lines from right for the calling thread.
 * \param partIds is the array that holds the part ids of the coordinates
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_1D_part_get_thread_part_weights(
    size_t total_part_count,
    mj_part_t num_cuts,
    mj_scalar_t max_coord,
    mj_scalar_t min_coord,
    mj_lno_t coordinate_begin_index,
    mj_lno_t coordinate_end_index,
    mj_scalar_t *mj_current_dim_coords,
    mj_scalar_t *temp_current_cut_coords,
    bool *current_cut_status,
    double *my_current_part_weights,
    mj_scalar_t *my_current_left_closest,
    mj_scalar_t *my_current_right_closest){

        // initializations for part weights, left/right closest
        for (size_t i = 0; i < total_part_count; ++i){
                my_current_part_weights[i] = 0;
        }

        //initialize the left and right closest coordinates
        //to their max value.
        for(mj_part_t i = 0; i < num_cuts; ++i){
                my_current_left_closest[i] = min_coord - 1;
                my_current_right_closest[i] = max_coord + 1;
        }
        //mj_lno_t comparison_count = 0;
        mj_scalar_t minus_EPSILON = -this->sEpsilon;
#ifdef HAVE_ZOLTAN2_OMP
        //no need for the barrier as all threads uses their local memories.
        //dont change the static scheduling here, as it is assumed when the new
        //partitions are created later.
#pragma omp for
#endif
        for (mj_lno_t ii = coordinate_begin_index; ii < coordinate_end_index; ++ii){
                int i = this->coordinate_permutations[ii];

                //the accesses to assigned_part_ids are thread safe
                //since each coordinate is assigned to only a single thread.
                mj_part_t j = this->assigned_part_ids[i] / 2;

                if(j >= num_cuts){
                        j = num_cuts - 1;
                }

                mj_part_t lower_cut_index = 0;
                mj_part_t upper_cut_index = num_cuts - 1;

                mj_scalar_t w = this->mj_uniform_weights[0]? 1:this->mj_weights[0][i];
                bool is_inserted = false;
                bool is_on_left_of_cut = false;
                bool is_on_right_of_cut = false;
                mj_part_t last_compared_part = -1;

                mj_scalar_t coord = mj_current_dim_coords[i];

                while(upper_cut_index >= lower_cut_index)
                {
                        //comparison_count++;
                        last_compared_part = -1;
                        is_on_left_of_cut = false;
                        is_on_right_of_cut = false;
                        mj_scalar_t cut = temp_current_cut_coords[j];
                        mj_scalar_t distance_to_cut = coord - cut;
                        mj_scalar_t abs_distance_to_cut = ZOLTAN2_ABS(distance_to_cut);

                        //if it is on the line.
                        if(abs_distance_to_cut < this->sEpsilon){

                                my_current_part_weights[j * 2 + 1] += w;
                                this->assigned_part_ids[i] = j * 2 + 1;

                                //assign left and right closest point to cut as the point is on the cut.
                                my_current_left_closest[j] = coord;
                                my_current_right_closest[j] = coord;
                                //now we need to check if there are other cuts on the same cut coordinate.
                                //if there are, then we add the weight of the cut to all cuts in the same coordinate.
                                mj_part_t kk = j + 1;
                                while(kk < num_cuts){
                                        // Needed when cuts shared the same position
                                        distance_to_cut =ZOLTAN2_ABS(temp_current_cut_coords[kk] - cut);
                                        if(distance_to_cut < this->sEpsilon){
                                                my_current_part_weights[2 * kk + 1] += w;
                                                my_current_left_closest[kk] = coord;
                                                my_current_right_closest[kk] = coord;
                                                kk++;
                                        }
                                        else{
                                                //cut is far away.
                                                //just check the left closest point for the next cut.
                                                if(coord - my_current_left_closest[kk] > this->sEpsilon){
                                                        my_current_left_closest[kk] = coord;
                                                }
                                                break;
                                        }
                                }


                                kk = j - 1;
                                //continue checking for the cuts on the left if they share the same coordinate.
                                while(kk >= 0){
                                        distance_to_cut =ZOLTAN2_ABS(temp_current_cut_coords[kk] - cut);
                                        if(distance_to_cut < this->sEpsilon){
                                                my_current_part_weights[2 * kk + 1] += w;
                                                //try to write the partId as the leftmost cut.
                                                this->assigned_part_ids[i] = kk * 2 + 1;
                                                my_current_left_closest[kk] = coord;
                                                my_current_right_closest[kk] = coord;
                                                kk--;
                                        }
                                        else{
                                                //if cut is far away on the left of the point.
                                                //then just compare for right closest point.
                                                if(my_current_right_closest[kk] - coord > this->sEpsilon){
                                                        my_current_right_closest[kk] = coord;
                                                }
                                                break;
                                        }
                                }

                                is_inserted = true;
                                break;
                        }
                        else {
                                //if point is on the left of the cut.
                                if (distance_to_cut < 0) {
                                        bool _break = false;
                                        if(j > 0){
                                                //check distance to the cut on the left the current cut compared.
                                                //if point is on the right, then we find the part of the point.
                                                mj_scalar_t distance_to_next_cut = coord - temp_current_cut_coords[j - 1];
                                                if(distance_to_next_cut > this->sEpsilon){
                                                        _break = true;
                                                }
                                        }
                                        //if point is not on the right of the next cut, then
                                        //set the upper bound to this cut.
                                        upper_cut_index = j - 1;
                                        //set the last part, and mark it as on the left of the last part.
                                        is_on_left_of_cut = true;
                                        last_compared_part = j;
                                        if(_break) break;
                                }
                                else {
                                        //if point is on the right of the cut.
                                        bool _break = false;
                                        if(j < num_cuts - 1){
                                                //check distance to the cut on the left the current cut compared.
                                                //if point is on the right, then we find the part of the point.
                                                mj_scalar_t distance_to_next_cut = coord - temp_current_cut_coords[j + 1];
                                                if(distance_to_next_cut < minus_EPSILON){
                         _break = true;
                     }
                                        }

                                        //if point is not on the left of the next cut, then
                                        //set the upper bound to this cut.
                                        lower_cut_index = j + 1;
                                        //set the last part, and mark it as on the right of the last part.
                                        is_on_right_of_cut = true;
                                        last_compared_part = j;
                                        if(_break) break;
                                }
                        }

                        j = (upper_cut_index + lower_cut_index) / 2;
                }
                if(!is_inserted){
                        if(is_on_right_of_cut){

                                //add it to the right of the last compared part.
                                my_current_part_weights[2 * last_compared_part + 2] += w;
                                this->assigned_part_ids[i] = 2 * last_compared_part + 2;

                                //update the right closest point of last compared cut.
                                if(my_current_right_closest[last_compared_part] - coord > this->sEpsilon){
                                        my_current_right_closest[last_compared_part] = coord;
                                }
                                //update the left closest point of the cut on the right of the last compared cut.
                                if(last_compared_part+1 < num_cuts){

                                        if(coord - my_current_left_closest[last_compared_part + 1] > this->sEpsilon){
                                                my_current_left_closest[last_compared_part + 1] = coord;
                                        }
                                }

                        }
                        else if(is_on_left_of_cut){

                                //add it to the left of the last compared part.
                                my_current_part_weights[2 * last_compared_part] += w;
                                this->assigned_part_ids[i] = 2 * last_compared_part;


                                //update the left closest point of last compared cut.
                                if(coord - my_current_left_closest[last_compared_part] > this->sEpsilon){
                                        my_current_left_closest[last_compared_part] = coord;
                                }

                                //update the right closest point of the cut on the left of the last compared cut.
                                if(last_compared_part-1 >= 0){
                                        if(my_current_right_closest[last_compared_part -1] - coord > this->sEpsilon){
                                                my_current_right_closest[last_compared_part -1] = coord;
                                        }
                                }
                        }
                }
        }

        // prefix sum computation.
        //we need prefix sum for each part to determine cut positions.
        for (size_t i = 1; i < total_part_count; ++i){
                // check for cuts sharing the same position; all cuts sharing a position
                // have the same weight == total weight for all cuts sharing the position.
                // don't want to accumulate that total weight more than once.
                if(i % 2 == 0 && i > 1 && i < total_part_count - 1 &&
                                ZOLTAN2_ABS(temp_current_cut_coords[i / 2] - temp_current_cut_coords[i /2 - 1])
                < this->sEpsilon){
                        //i % 2 = 0 when part i represents the cut coordinate.
                        //if it is a cut, and if the next cut also have the same coordinate, then
                        //dont addup.
                        my_current_part_weights[i] = my_current_part_weights[i-2];
                        continue;
                }
                //otherwise do the prefix sum.
                my_current_part_weights[i] += my_current_part_weights[i-1];
        }
}


/*! \brief Function that reduces the result of multiple threads
 * for left and right closest points and part weights in a single mpi process.
 *
 * \param num_partitioning_in_current_dim is the vector that holds the number of cut lines in current dimension for each part.
 * \param current_work_part holds the index of the first part (important when concurrent parts are used.)
 * \param current_concurrent_num_parts is the number of parts whose cut lines will be calculated concurrently.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_accumulate_thread_results(
    const std::vector <mj_part_t> &num_partitioning_in_current_dim,
    mj_part_t current_work_part,
    mj_part_t current_concurrent_num_parts){

#ifdef HAVE_ZOLTAN2_OMP
        //needs barrier here, as it requires all threads to finish mj_1D_part_get_thread_part_weights
        //using parallel region here reduces the performance because of the cache invalidates.
#pragma omp barrier
#pragma omp single
#endif
        {
                size_t tlr_array_shift = 0;
                mj_part_t cut_shift = 0;

                //iterate for all concurrent parts to find the left and right closest points in the process.
                for(mj_part_t i = 0; i < current_concurrent_num_parts; ++i){

                        mj_part_t num_parts_in_part =  num_partitioning_in_current_dim[current_work_part + i];
                        mj_part_t num_cuts_in_part = num_parts_in_part - 1;
                        size_t num_total_part_in_part = num_parts_in_part + size_t (num_cuts_in_part) ;

                        //iterate for cuts in a single part.
                        for(mj_part_t ii = 0; ii < num_cuts_in_part ; ++ii){
                                mj_part_t next = tlr_array_shift + ii;
                                mj_part_t cut_index = cut_shift + ii;
                                if(this->is_cut_line_determined[cut_index]) continue;
                                mj_scalar_t left_closest_in_process = this->thread_cut_left_closest_point[0][cut_index],
                                                right_closest_in_process = this->thread_cut_right_closest_point[0][cut_index];

                                //find the closest points from left and right for the cut in the process.
                                for (int j = 1; j < this->num_threads; ++j){
                                        if (this->thread_cut_right_closest_point[j][cut_index] < right_closest_in_process ){
                                                right_closest_in_process = this->thread_cut_right_closest_point[j][cut_index];
                                        }
                                        if (this->thread_cut_left_closest_point[j][cut_index] > left_closest_in_process ){
                                                left_closest_in_process = this->thread_cut_left_closest_point[j][cut_index];
                                        }
                                }
                                //store the left and right closes points.
                                this->total_part_weight_left_right_closests[num_total_part_in_part +
                                                                            next] = left_closest_in_process;
                                this->total_part_weight_left_right_closests[num_total_part_in_part +
                                                                            num_cuts_in_part + next] = right_closest_in_process;
                        }
                        //set the shift position in the arrays
                        tlr_array_shift += (num_total_part_in_part + 2 * num_cuts_in_part);
                        cut_shift += num_cuts_in_part;
                }

                tlr_array_shift = 0;
                cut_shift = 0;
                size_t total_part_array_shift = 0;

                //iterate for all concurrent parts to find the total weight in the process.
                for(mj_part_t i = 0; i < current_concurrent_num_parts; ++i){

                        mj_part_t num_parts_in_part =  num_partitioning_in_current_dim[current_work_part + i];
                        mj_part_t num_cuts_in_part = num_parts_in_part - 1;
                        size_t num_total_part_in_part = num_parts_in_part + size_t (num_cuts_in_part) ;

                        for(size_t j = 0; j < num_total_part_in_part; ++j){

                                mj_part_t cut_ind = j / 2 + cut_shift;

                                //need to check j !=  num_total_part_in_part - 1
                                                // which is same as j/2 != num_cuts_in_part.
                                //we cannot check it using cut_ind, because of the concurrent part concantanetion.
                                if(j !=  num_total_part_in_part - 1 && this->is_cut_line_determined[cut_ind]) continue;
                                double pwj = 0;
                                for (int k = 0; k < this->num_threads; ++k){
                                        pwj += this->thread_part_weights[k][total_part_array_shift + j];
                                }
                                //size_t jshift = j % total_part_count + i * (total_part_count + 2 * noCuts);
                                this->total_part_weight_left_right_closests[tlr_array_shift + j] = pwj;
                        }
                        cut_shift += num_cuts_in_part;
                        tlr_array_shift += num_total_part_in_part + 2 * num_cuts_in_part;
                        total_part_array_shift += num_total_part_in_part;
                }
        }
        //the other threads needs to wait here.
        //but we don't need a pragma omp barrier.
        //as omp single has already have implicit barrier.
}


/*! \brief
 * Function that calculates the next pivot position,
 * according to given coordinates of upper bound and lower bound, the weights at upper and lower bounds, and the expected weight.
 * \param cut_upper_bound is the upper bound coordinate of the cut.
 * \param cut_lower_bound is the lower bound coordinate of the cut.
 * \param cut_upper_weight is the weights at the upper bound of the cut.
 * \param cut_lower_weight is the weights at the lower bound of the cut.
 * \param expected_weight is the expected weight that should be placed on the left of the cut line.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_calculate_new_cut_position (
        mj_scalar_t cut_upper_bound,
    mj_scalar_t cut_lower_bound,
    mj_scalar_t cut_upper_weight,
    mj_scalar_t cut_lower_weight,
    mj_scalar_t expected_weight,
    mj_scalar_t &new_cut_position){

    if(ZOLTAN2_ABS(cut_upper_bound - cut_lower_bound) < this->sEpsilon){
        new_cut_position = cut_upper_bound; //or lower bound does not matter.
    }


    if(ZOLTAN2_ABS(cut_upper_weight - cut_lower_weight) < this->sEpsilon){
        new_cut_position = cut_lower_bound;
    }

    mj_scalar_t coordinate_range = (cut_upper_bound - cut_lower_bound);
    mj_scalar_t weight_range = (cut_upper_weight - cut_lower_weight);
    mj_scalar_t my_weight_diff = (expected_weight - cut_lower_weight);

    mj_scalar_t required_shift = (my_weight_diff / weight_range);
    int scale_constant = 20;
    int shiftint= int (required_shift * scale_constant);
    if (shiftint == 0) shiftint = 1;
    required_shift = mj_scalar_t (shiftint) / scale_constant;
    new_cut_position = coordinate_range * required_shift + cut_lower_bound;
}


/*! \brief Function that determines the permutation indices of the coordinates.
 * \param num_parts is the number of parts.
 * \param mj_current_dim_coords is 1 dimensional array holding the coordinate values.
 * \param current_concurrent_cut_coordinate is 1 dimensional array holding the cut coordinates.
 * \param coordinate_begin is the start index of the given partition on partitionedPointPermutations.
 * \param coordinate_end is the end index of the given partition on partitionedPointPermutations.
 * \param used_local_cut_line_weight_to_left holds how much weight of the coordinates on the cutline should be put on left side.
 * \param used_thread_part_weight_work is the two dimensional array holding the weight of parts for each thread. Assumes there are 2*P - 1 parts (cut lines are seperate parts).
 * \param out_part_xadj is the indices of coordinates calculated for the partition on next dimension.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_create_new_partitions(
    mj_part_t num_parts,
    mj_scalar_t *mj_current_dim_coords,
    mj_scalar_t *current_concurrent_cut_coordinate,
    mj_lno_t coordinate_begin,
    mj_lno_t coordinate_end,
    mj_scalar_t *used_local_cut_line_weight_to_left,
    double **used_thread_part_weight_work,
    mj_lno_t *out_part_xadj){

        mj_part_t num_cuts = num_parts - 1;

#ifdef HAVE_ZOLTAN2_OMP
#pragma omp parallel
#endif
        {
                int me = 0;
#ifdef HAVE_ZOLTAN2_OMP
                me = omp_get_thread_num();
#endif

                mj_lno_t *thread_num_points_in_parts = this->thread_point_counts[me];
                mj_scalar_t *my_local_thread_cut_weights_to_put_left = NULL;

                //now if the rectilinear partitioning is allowed we decide how
                //much weight each thread should put to left and right.
                if (this->distribute_points_on_cut_lines){
                        my_local_thread_cut_weights_to_put_left = this->thread_cut_line_weight_to_put_left[me];
                        // this for assumes the static scheduling in mj_1D_part calculation.
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp for
#endif
                        for (mj_part_t i = 0; i < num_cuts; ++i){
                                //the left to be put on the left of the cut.
                                mj_scalar_t left_weight = used_local_cut_line_weight_to_left[i];
                                for(int ii = 0; ii < this->num_threads; ++ii){
                                        if(left_weight > this->sEpsilon){
                                                //the weight of thread ii on cut.
                                                mj_scalar_t thread_ii_weight_on_cut = used_thread_part_weight_work[ii][i * 2 + 1] - used_thread_part_weight_work[ii][i * 2 ];
                                                if(thread_ii_weight_on_cut < left_weight){
                                                        //if left weight is bigger than threads weight on cut.
                                                        this->thread_cut_line_weight_to_put_left[ii][i] = thread_ii_weight_on_cut;
                                                }
                                                else {
                                                        //if thread's weight is bigger than space, then put only a portion.
                                                        this->thread_cut_line_weight_to_put_left[ii][i] = left_weight ;
                                                }
                                                left_weight -= thread_ii_weight_on_cut;
                                        }
                                        else {
                                                this->thread_cut_line_weight_to_put_left[ii][i] = 0;
                                        }
                                }
                        }

                        if(num_cuts > 0){
                                //this is a special case. If cutlines share the same coordinate, their weights are equal.
                                //we need to adjust the ratio for that.
                                for (mj_part_t i = num_cuts - 1; i > 0 ; --i){
                                        if(ZOLTAN2_ABS(current_concurrent_cut_coordinate[i] - current_concurrent_cut_coordinate[i -1]) < this->sEpsilon){
                                                my_local_thread_cut_weights_to_put_left[i] -= my_local_thread_cut_weights_to_put_left[i - 1] ;
                                        }
                                        my_local_thread_cut_weights_to_put_left[i] = int ((my_local_thread_cut_weights_to_put_left[i] + LEAST_SIGNIFICANCE) * SIGNIFICANCE_MUL)
                                                                / mj_scalar_t(SIGNIFICANCE_MUL);
                                }
                        }
                }

                for(mj_part_t ii = 0; ii < num_parts; ++ii){
                        thread_num_points_in_parts[ii] = 0;
                }


#ifdef HAVE_ZOLTAN2_OMP
                //dont change static scheduler. the static partitioner used later as well.
#pragma omp for
#endif
                for (mj_lno_t ii = coordinate_begin; ii < coordinate_end; ++ii){

                        mj_lno_t coordinate_index = this->coordinate_permutations[ii];
                        mj_scalar_t coordinate_weight = this->mj_uniform_weights[0]? 1:this->mj_weights[0][coordinate_index];
                        mj_part_t coordinate_assigned_place = this->assigned_part_ids[coordinate_index];
                        mj_part_t coordinate_assigned_part = coordinate_assigned_place / 2;
                        if(coordinate_assigned_place % 2 == 1){
                                //if it is on the cut.
                                if(this->distribute_points_on_cut_lines
                                                && my_local_thread_cut_weights_to_put_left[coordinate_assigned_part] > this->sEpsilon){
                                        //if the rectilinear partitioning is allowed,
                                        //and the thread has still space to put on the left of the cut
                                        //then thread puts the vertex to left.
                                        my_local_thread_cut_weights_to_put_left[coordinate_assigned_part] -= coordinate_weight;
                                        //if putting the vertex to left increased the weight more than expected.
                                        //and if the next cut is on the same coordinate,
                                        //then we need to adjust how much weight next cut puts to its left as well,
                                        //in order to take care of the imbalance.
                                        if(my_local_thread_cut_weights_to_put_left[coordinate_assigned_part] < 0
                                                        && coordinate_assigned_part < num_cuts - 1
                                                        && ZOLTAN2_ABS(current_concurrent_cut_coordinate[coordinate_assigned_part+1] -
                                                                        current_concurrent_cut_coordinate[coordinate_assigned_part]) < this->sEpsilon){
                                                my_local_thread_cut_weights_to_put_left[coordinate_assigned_part + 1] += my_local_thread_cut_weights_to_put_left[coordinate_assigned_part];
                                        }
                                        ++thread_num_points_in_parts[coordinate_assigned_part];
                                        this->assigned_part_ids[coordinate_index] = coordinate_assigned_part;
                                }
                                else{
                                        //if there is no more space on the left, put the coordinate to the right of the cut.
                                        ++coordinate_assigned_part;
                                        //this while loop is necessary when a line is partitioned into more than 2 parts.
                                        while(this->distribute_points_on_cut_lines &&
                                                        coordinate_assigned_part < num_cuts){
                                                //traverse all the cut lines having the same partitiong
                                                if(ZOLTAN2_ABS(current_concurrent_cut_coordinate[coordinate_assigned_part] -
                                                                current_concurrent_cut_coordinate[coordinate_assigned_part - 1])
                                                                < this->sEpsilon){
                                                        //if line has enough space on left, put it there.
                                                        if(my_local_thread_cut_weights_to_put_left[coordinate_assigned_part] >
                                                        this->sEpsilon &&
                                                        my_local_thread_cut_weights_to_put_left[coordinate_assigned_part] >=
                                                        ZOLTAN2_ABS(my_local_thread_cut_weights_to_put_left[coordinate_assigned_part] - coordinate_weight)){
                                                                my_local_thread_cut_weights_to_put_left[coordinate_assigned_part] -= coordinate_weight;
                                                                //Again if it put too much on left of the cut,
                                                                //update how much the next cut sharing the same coordinate will put to its left.
                                                                if(my_local_thread_cut_weights_to_put_left[coordinate_assigned_part] < 0 &&
                                                                                coordinate_assigned_part < num_cuts - 1 &&
                                                                                ZOLTAN2_ABS(current_concurrent_cut_coordinate[coordinate_assigned_part+1] -
                                                                                                current_concurrent_cut_coordinate[coordinate_assigned_part]) < this->sEpsilon){
                                                                        my_local_thread_cut_weights_to_put_left[coordinate_assigned_part + 1] += my_local_thread_cut_weights_to_put_left[coordinate_assigned_part];
                                                                }
                                                                break;
                                                        }
                                                }
                                                else {
                                                        break;
                                                }
                                                ++coordinate_assigned_part;
                                        }
                                        ++thread_num_points_in_parts[coordinate_assigned_part];
                                        this->assigned_part_ids[coordinate_index] = coordinate_assigned_part;
                                }
                        }
                        else {
                                //if it is already assigned to a part, then just put it to the corresponding part.
                                ++thread_num_points_in_parts[coordinate_assigned_part];
                                this->assigned_part_ids[coordinate_index] = coordinate_assigned_part;
                        }
                }



                //now we calculate where each thread will write in new_coordinate_permutations array.
                //first we find the out_part_xadj, by marking the begin and end points of each part found.
                //the below loop find the number of points in each part, and writes it to out_part_xadj
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp for
#endif
                for(mj_part_t j = 0; j < num_parts; ++j){
                        mj_lno_t num_points_in_part_j_upto_thread_i = 0;
                        for (int i = 0; i < this->num_threads; ++i){
                                mj_lno_t thread_num_points_in_part_j = this->thread_point_counts[i][j];
                                //prefix sum to thread point counts, so that each will have private space to write.
                                this->thread_point_counts[i][j] = num_points_in_part_j_upto_thread_i;
                                num_points_in_part_j_upto_thread_i += thread_num_points_in_part_j;

                        }
                        out_part_xadj[j] = num_points_in_part_j_upto_thread_i;// + prev2; //+ coordinateBegin;
                }

                //now we need to do a prefix sum to out_part_xadj[j], to point begin and end of each part.
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp single
#endif
                {
                        //perform prefix sum for num_points in parts.
                        for(mj_part_t j = 1; j < num_parts; ++j){
                                out_part_xadj[j] += out_part_xadj[j - 1];
                        }
                }

                //shift the num points in threads thread to obtain the
                //beginning index of each thread's private space.
                for(mj_part_t j = 1; j < num_parts; ++j){
                        thread_num_points_in_parts[j] += out_part_xadj[j - 1] ;
                }


                //now thread gets the coordinate and writes the index of coordinate to the permutation array
                //using the part index we calculated.
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp for
#endif
                for (mj_lno_t ii = coordinate_begin; ii < coordinate_end; ++ii){
                        mj_lno_t i = this->coordinate_permutations[ii];
                        mj_part_t p =  this->assigned_part_ids[i];
                        this->new_coordinate_permutations[coordinate_begin +
                                                          thread_num_points_in_parts[p]++] = i;
                }
        }
}



/*! \brief Function that calculates the new coordinates for the cut lines. Function is called inside the parallel region.
 *
 * \param num_total_part is the sum of number of cutlines and number of parts. Simply it is 2*P - 1.
 * \param num_cuts is the number of cut lines. P - 1.
 * \param max_coordinate is the maximum coordinate in the current range of coordinates and in the current dimension.
 * \param min_coordinate is the maximum coordinate in the current range of coordinates and in the current dimension.
 * \param global_total_weight is the global total weight in the current range of coordinates.
 * \param used_imbalance_tolerance is the maximum allowed imbalance ratio.
 *
 *
 * \param current_global_part_weights is the array holding the weight of parts. Assumes there are 2*P - 1 parts (cut lines are seperate parts).
 * \param current_local_part_weights is the local totalweight of the processor.
 * \param current_part_target_weights are the desired cumulative part ratios, sized P.
 * \param current_cut_line_determined is the boolean array to determine if the correct position for a cut line is found.
 *
 * \param current_cut_coordinates is the array holding the coordinates of each cut line. Sized P - 1.
 * \param current_cut_upper_bounds is the array holding the upper bound coordinate for each cut line. Sized P - 1.
 * \param current_cut_lower_bounds is the array holding the lower bound coordinate for each cut line. Sized P - 1.
 * \param current_global_left_closest_points is the array holding the closest points to the cut lines from left.
 * \param current_global_right_closest_points is the array holding the closest points to the cut lines from right.
 * \param current_cut_lower_bound_weights is the array holding the weight of the parts at the left of lower bound coordinates.
 * \param current_cut_upper_weights is the array holding the weight of the parts at the left of upper bound coordinates.
 * \param new_current_cut_coordinates is the work array, sized P - 1.
 *
 * \param current_part_cut_line_weight_ratio holds how much weight of the coordinates on the cutline should be put on left side.
 * \param rectilinear_cut_count is the count of cut lines whose balance can be achived via distributing the points in same coordinate to different parts.
 * \param my_num_incomplete_cut is the number of cutlines whose position has not been determined yet. For K > 1 it is the count in a single part (whose cut lines are determined).
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_get_new_cut_coordinates(
                const size_t &num_total_part,
                const mj_part_t &num_cuts,
                const mj_scalar_t &max_coordinate,
                const mj_scalar_t &min_coordinate,
                const mj_scalar_t &global_total_weight,
                const mj_scalar_t &used_imbalance_tolerance,
                mj_scalar_t * current_global_part_weights,
                const mj_scalar_t * current_local_part_weights,
                const mj_scalar_t *current_part_target_weights,
                bool *current_cut_line_determined,
                mj_scalar_t *current_cut_coordinates,
                mj_scalar_t *current_cut_upper_bounds,
                mj_scalar_t *current_cut_lower_bounds,
                mj_scalar_t *current_global_left_closest_points,
                mj_scalar_t *current_global_right_closest_points,
                mj_scalar_t * current_cut_lower_bound_weights,
                mj_scalar_t * current_cut_upper_weights,
                mj_scalar_t *new_current_cut_coordinates,
                mj_scalar_t *current_part_cut_line_weight_to_put_left,
                mj_part_t *rectilinear_cut_count,
                mj_part_t &my_num_incomplete_cut){

        //seen weight in the part
        mj_scalar_t seen_weight_in_part = 0;
        //expected weight for part.
        mj_scalar_t expected_weight_in_part = 0;
        //imbalance for the left and right side of the cut.
        mj_scalar_t imbalance_on_left = 0, imbalance_on_right = 0;


#ifdef HAVE_ZOLTAN2_OMP
#pragma omp for
#endif
        for (mj_part_t i = 0; i < num_cuts; i++){
                //if left and right closest points are not set yet,
                //set it to the cut itself.
                if(min_coordinate - current_global_left_closest_points[i] > this->sEpsilon)
                        current_global_left_closest_points[i] = current_cut_coordinates[i];
                if(current_global_right_closest_points[i] - max_coordinate > this->sEpsilon)
                        current_global_right_closest_points[i] = current_cut_coordinates[i];

        }
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp for
#endif
        for (mj_part_t i = 0; i < num_cuts; i++){

                if(this->distribute_points_on_cut_lines){
                        //init the weight on the cut.
                        this->global_rectilinear_cut_weight[i] = 0;
                        this->process_rectilinear_cut_weight[i] = 0;
                }
                //if already determined at previous iterations,
                //then just write the coordinate to new array, and proceed.
                if(current_cut_line_determined[i]) {
                        new_current_cut_coordinates[i] = current_cut_coordinates[i];
                        continue;
                }

                //current weight of the part at the left of the cut line.
                seen_weight_in_part = current_global_part_weights[i * 2];

                /*
                cout << "seen_weight_in_part:" << i << " is "<< seen_weight_in_part << endl;
                cout << "\tcut:" << current_cut_coordinates[i]
                       << " current_cut_lower_bounds:" << current_cut_lower_bounds[i]
               << " current_cut_upper_bounds:" << current_cut_upper_bounds[i] << endl;
               */
                //expected ratio
                expected_weight_in_part = current_part_target_weights[i];
                //leftImbalance = imbalanceOf(seenW, globalTotalWeight, expected);
                imbalance_on_left = imbalanceOf2(seen_weight_in_part, expected_weight_in_part);
                //rightImbalance = imbalanceOf(globalTotalWeight - seenW, globalTotalWeight, 1 - expected);
                imbalance_on_right = imbalanceOf2(global_total_weight - seen_weight_in_part, global_total_weight - expected_weight_in_part);

                bool is_left_imbalance_valid = ZOLTAN2_ABS(imbalance_on_left) - used_imbalance_tolerance < this->sEpsilon ;
                bool is_right_imbalance_valid = ZOLTAN2_ABS(imbalance_on_right) - used_imbalance_tolerance < this->sEpsilon;

                //if the cut line reaches to desired imbalance.
                if(is_left_imbalance_valid && is_right_imbalance_valid){
                        current_cut_line_determined[i] = true;
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp atomic
#endif
                        my_num_incomplete_cut -= 1;
                        new_current_cut_coordinates [i] = current_cut_coordinates[i];
                        continue;
                }
                else if(imbalance_on_left < 0){
                        //if left imbalance < 0 then we need to move the cut to right.

                        if(this->distribute_points_on_cut_lines){
                                //if it is okay to distribute the coordinate on
                                //the same coordinate to left and right.
                                //then check if we can reach to the target weight by including the
                                //coordinates in the part.
                                if (current_global_part_weights[i * 2 + 1] == expected_weight_in_part){
                                        //if it is we are done.
                                        current_cut_line_determined[i] = true;
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp atomic
#endif
                                        my_num_incomplete_cut -= 1;

                                        //then assign everything on the cut to the left of the cut.
                                        new_current_cut_coordinates [i] = current_cut_coordinates[i];

                                        //for this cut all the weight on cut will be put to left.

                                        current_part_cut_line_weight_to_put_left[i] = current_local_part_weights[i * 2 + 1] - current_local_part_weights[i * 2];
                                        continue;
                                }
                                else if (current_global_part_weights[i * 2 + 1] > expected_weight_in_part){

                                        //if the weight is larger than the expected weight,
                                        //then we need to distribute some points to left, some to right.
                                        current_cut_line_determined[i] = true;
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp atomic
#endif
                                        *rectilinear_cut_count += 1;
                                        //increase the num cuts to be determined with rectilinear partitioning.

#ifdef HAVE_ZOLTAN2_OMP
#pragma omp atomic
#endif
                                        my_num_incomplete_cut -= 1;
                                        new_current_cut_coordinates [i] = current_cut_coordinates[i];
                                        this->process_rectilinear_cut_weight[i] = current_local_part_weights[i * 2 + 1] -
                                                        current_local_part_weights[i * 2];
                                        continue;
                                }
                        }
                        //we need to move further right,so set lower bound to current line, and shift it to the closes point from right.
                        current_cut_lower_bounds[i] = current_global_right_closest_points[i];
                        //set the lower bound weight to the weight we have seen.
                        current_cut_lower_bound_weights[i] = seen_weight_in_part;

                        //compare the upper bound with what has been found in the last iteration.
                        //we try to make more strict bounds for the cut here.
                        for (mj_part_t ii = i + 1; ii < num_cuts ; ++ii){
                                mj_scalar_t p_weight = current_global_part_weights[ii * 2];
                                mj_scalar_t line_weight = current_global_part_weights[ii * 2 + 1];

                                if(p_weight >= expected_weight_in_part){
                                        //if a cut on the right has the expected weight, then we found
                                        //our cut position. Set up and low coordiantes to this new cut coordinate.
                                        //but we need one more iteration to finalize the cut position,
                                        //as wee need to update the part ids.
                                        if(p_weight == expected_weight_in_part){
                                                current_cut_upper_bounds[i] = current_cut_coordinates[ii];
                                                current_cut_upper_weights[i] = p_weight;
                                                current_cut_lower_bounds[i] = current_cut_coordinates[ii];
                                                current_cut_lower_bound_weights[i] = p_weight;
                                        } else if (p_weight < current_cut_upper_weights[i]){
                                                //if a part weight is larger then my expected weight,
                                                //but lower than my upper bound weight, update upper bound.
                                                current_cut_upper_bounds[i] = current_global_left_closest_points[ii];
                                                current_cut_upper_weights[i] = p_weight;
                                        }
                                        break;
                                }
                                //if comes here then pw < ew
                                //then compare the weight against line weight.
                                if(line_weight >= expected_weight_in_part){
                                        //if the line is larger than the expected weight,
                                        //then we need to reach to the balance by distributing coordinates on this line.
                                        current_cut_upper_bounds[i] = current_cut_coordinates[ii];
                                        current_cut_upper_weights[i] = line_weight;
                                        current_cut_lower_bounds[i] = current_cut_coordinates[ii];
                                        current_cut_lower_bound_weights[i] = p_weight;
                                        break;
                                }
                                //if a stricter lower bound is found,
                                //update the lower bound.
                                if (p_weight <= expected_weight_in_part && p_weight >= current_cut_lower_bound_weights[i]){
                                        current_cut_lower_bounds[i] = current_global_right_closest_points[ii] ;
                                        current_cut_lower_bound_weights[i] = p_weight;
                                }
                        }


                        mj_scalar_t new_cut_position = 0;
                        this->mj_calculate_new_cut_position(
                                        current_cut_upper_bounds[i],
                                        current_cut_lower_bounds[i],
                                        current_cut_upper_weights[i],
                                        current_cut_lower_bound_weights[i],
                                        expected_weight_in_part, new_cut_position);

                        //if cut line does not move significantly.
                        //then finalize the search.
                        if (ZOLTAN2_ABS(current_cut_coordinates[i] - new_cut_position) < this->sEpsilon
                                /*|| current_cut_lower_bounds[i] - current_cut_upper_bounds[i] > this->sEpsilon*/
                                ){
                                current_cut_line_determined[i] = true;
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp atomic
#endif
                                my_num_incomplete_cut -= 1;

                                //set the cut coordinate and proceed.
                                new_current_cut_coordinates [i] = current_cut_coordinates[i];
                        } else {
                                new_current_cut_coordinates [i] = new_cut_position;
                        }
                } else {

                        //need to move the cut line to left.
                        //set upper bound to current line.
                        current_cut_upper_bounds[i] = current_global_left_closest_points[i];
                        current_cut_upper_weights[i] = seen_weight_in_part;

                        // compare the current cut line weights with previous upper and lower bounds.
                        for (int ii = i - 1; ii >= 0; --ii){
                                mj_scalar_t p_weight = current_global_part_weights[ii * 2];
                                mj_scalar_t line_weight = current_global_part_weights[ii * 2 + 1];
                                if(p_weight <= expected_weight_in_part){
                                        if(p_weight == expected_weight_in_part){
                                                //if the weight of the part is my expected weight
                                                //then we find the solution.
                                                current_cut_upper_bounds[i] = current_cut_coordinates[ii];
                                                current_cut_upper_weights[i] = p_weight;
                                                current_cut_lower_bounds[i] = current_cut_coordinates[ii];
                                                current_cut_lower_bound_weights[i] = p_weight;
                                        }
                                        else if (p_weight > current_cut_lower_bound_weights[i]){
                                                //if found weight is bigger than the lower bound
                                                //then update the lower bound.
                                                current_cut_lower_bounds[i] = current_global_right_closest_points[ii];
                                                current_cut_lower_bound_weights[i] = p_weight;

                                                //at the same time, if weight of line is bigger than the
                                                //expected weight, then update the upper bound as well.
                                                //in this case the balance will be obtained by distributing weightss
                                                //on this cut position.
                                                if(line_weight > expected_weight_in_part){
                                                        current_cut_upper_bounds[i] = current_global_right_closest_points[ii];
                                                        current_cut_upper_weights[i] = line_weight;
                                                }
                                        }
                                        break;
                                }
                                //if the weight of the cut on the left is still bigger than my weight,
                                //and also if the weight is smaller than the current upper weight,
                                //or if the weight is equal to current upper weight, but on the left of
                                // the upper weight, then update upper bound.
                                if (p_weight >= expected_weight_in_part &&
                                                (p_weight < current_cut_upper_weights[i] ||
                                                                (p_weight == current_cut_upper_weights[i] &&
                                                                                current_cut_upper_bounds[i] > current_global_left_closest_points[ii]
                                                                )
                                                )
                                        ){
                                        current_cut_upper_bounds[i] = current_global_left_closest_points[ii] ;
                                        current_cut_upper_weights[i] = p_weight;
                                }
                        }
                        mj_scalar_t new_cut_position = 0;
                        this->mj_calculate_new_cut_position(
                                        current_cut_upper_bounds[i],
                                        current_cut_lower_bounds[i],
                                        current_cut_upper_weights[i],
                                        current_cut_lower_bound_weights[i],
                                        expected_weight_in_part,
                                        new_cut_position);

                        //if cut line does not move significantly.
                        if (ZOLTAN2_ABS(current_cut_coordinates[i] - new_cut_position) < this->sEpsilon
                                        /*|| current_cut_lower_bounds[i] - current_cut_upper_bounds[i] > this->sEpsilon*/ ){
                                current_cut_line_determined[i] = true;
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp atomic
#endif
                                my_num_incomplete_cut -= 1;
                                //set the cut coordinate and proceed.
                                new_current_cut_coordinates [ i] = current_cut_coordinates[i];
                        } else {
                                new_current_cut_coordinates [ i] = new_cut_position;
                        }
                }
        }

        { // This unnecessary bracket works around a compiler bug in NVCC when enabling OpenMP as well

        //communication to determine the ratios of processors for the distribution
        //of coordinates on the cut lines.
#ifdef HAVE_ZOLTAN2_OMP
        //no need barrier here as it is implicit.
#pragma omp single
#endif
        {
                if(*rectilinear_cut_count > 0){

                        try{
                                Teuchos::scan<int,mj_scalar_t>(
                                                *comm, Teuchos::REDUCE_SUM,
                                                num_cuts,
                                                this->process_rectilinear_cut_weight,
                                                this->global_rectilinear_cut_weight
                                );
                        }
                        Z2_THROW_OUTSIDE_ERROR(*(this->mj_env))

                        for (mj_part_t i = 0; i < num_cuts; ++i){
                                //if cut line weight to be distributed.
                                if(this->global_rectilinear_cut_weight[i] > 0) {
                                        //expected weight to go to left of the cut.
                                        mj_scalar_t expected_part_weight = current_part_target_weights[i];
                                        //the weight that should be put to left of the cut.
                                        mj_scalar_t necessary_weight_on_line_for_left = expected_part_weight - current_global_part_weights[i * 2];
                                        //the weight of the cut in the process
                                        mj_scalar_t my_weight_on_line = this->process_rectilinear_cut_weight[i];
                                        //the sum of the cut weights upto this process, including the weight of this process.
                                        mj_scalar_t weight_on_line_upto_process_inclusive = this->global_rectilinear_cut_weight[i];
                                        //the space on the left side of the cut after all processes before this process (including this process)
                                        //puts their weights on cut to left.
                                        mj_scalar_t space_to_put_left = necessary_weight_on_line_for_left - weight_on_line_upto_process_inclusive;
                                        //add my weight to this space to find out how much space is left to me.
                                        mj_scalar_t space_left_to_me = space_to_put_left + my_weight_on_line;

                                        /*
                                        cout << "expected_part_weight:" << expected_part_weight
                                                        << " necessary_weight_on_line_for_left:" << necessary_weight_on_line_for_left
                                                        << " my_weight_on_line" << my_weight_on_line
                                                        << " weight_on_line_upto_process_inclusive:" << weight_on_line_upto_process_inclusive
                                                        << " space_to_put_left:" << space_to_put_left
                                                        << " space_left_to_me" << space_left_to_me << endl;
                                         */
                                        if(space_left_to_me < 0){
                                                //space_left_to_me is negative and i dont need to put anything to left.
                                                current_part_cut_line_weight_to_put_left[i] = 0;
                                        }
                                        else if(space_left_to_me >= my_weight_on_line){
                                                //space left to me is bigger than the weight of the processor on cut.
                                                //so put everything to left.
                                                current_part_cut_line_weight_to_put_left[i] = my_weight_on_line;
                                                //cout << "setting current_part_cut_line_weight_to_put_left to my_weight_on_line:" << my_weight_on_line << endl;
                                        }
                                        else {
                                                //put only the weight as much as the space.
                                                current_part_cut_line_weight_to_put_left[i] = space_left_to_me ;

                                                //cout << "setting current_part_cut_line_weight_to_put_left to space_left_to_me:" << space_left_to_me << endl;
                                        }

                                }
                        }
                        *rectilinear_cut_count = 0;
                }
        }
        }
}

/*! \brief Function fills up the num_points_in_all_processor_parts, so that
 * it has the number of coordinates in each processor of each part.
 * to access how many points processor i has on part j, num_points_in_all_processor_parts[i * num_parts + j].
 *
 * \param num_procs is the number of processor attending to migration operation.
 * \param num_parts is the number of parts that exist in the current partitioning.
 * \param num_points_in_all_processor_parts is the output array that holds
 * the number of coordinates in each part in each processor.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::get_processor_num_points_in_parts(
    mj_part_t num_procs,
    mj_part_t num_parts,
    mj_gno_t *&num_points_in_all_processor_parts){

        //initially allocation_size is num_parts
        size_t allocation_size = num_parts * (num_procs + 1);

        //this will be output
        //holds how many each processor has in each part.
        //last portion is the sum of all processor points in each part.

        //allocate memory for the local num coordinates in each part.
        mj_gno_t *num_local_points_in_each_part_to_reduce_sum = allocMemory<mj_gno_t>(allocation_size);


        //this is the portion of the memory which will be used
        //at the summation to obtain total number of processors' points in each part.
        mj_gno_t *my_local_points_to_reduce_sum = num_local_points_in_each_part_to_reduce_sum + num_procs * num_parts;
        //this is the portion of the memory where each stores its local number.
        //this information is needed by other processors.
        mj_gno_t *my_local_point_counts_in_each_art = num_local_points_in_each_part_to_reduce_sum + this->myRank * num_parts;

        //initialize the array with 0's.
        memset(num_local_points_in_each_part_to_reduce_sum, 0, sizeof(mj_gno_t)*allocation_size);

        //write the number of coordinates in each part.
        for (mj_part_t i = 0; i < num_parts; ++i){
                mj_lno_t part_begin_index = 0;
                if (i > 0){
                        part_begin_index = this->new_part_xadj[i - 1];
                }
                mj_lno_t part_end_index = this->new_part_xadj[i];
                my_local_points_to_reduce_sum[i] = part_end_index - part_begin_index;
        }

        //copy the local num parts to the last portion of array,
        //so that this portion will represent the global num points in each part after the reduction.
        memcpy (my_local_point_counts_in_each_art,
                        my_local_points_to_reduce_sum,
                        sizeof(mj_gno_t) * (num_parts) );


        //reduceAll operation.
        //the portion that belongs to a processor with index p
        //will start from myRank * num_parts.
        //the global number of points will be held at the index
        try{
                reduceAll<int, mj_gno_t>(
                                *(this->comm),
                                Teuchos::REDUCE_SUM,
                                allocation_size,
                                num_local_points_in_each_part_to_reduce_sum,
                                num_points_in_all_processor_parts);
        }
        Z2_THROW_OUTSIDE_ERROR(*(this->mj_env))
        freeArray<mj_gno_t>(num_local_points_in_each_part_to_reduce_sum);
}



/*! \brief Function checks if should do migration or not.
 * It returns true to point that migration should be done when
 * -migration_reduce_all_population are higher than a predetermined value
 * -num_coords_for_last_dim_part that left for the last dimension partitioning is less than a predetermined value
 * -the imbalance of the processors on the parts are higher than given threshold.
 * \param migration_reduce_all_population is the multiplication of the number of reduceall operations estimated and the number of processors.
 * \param num_coords_for_last_dim_part is the estimated number of coordinates in a part per processor in the last dimension partitioning.
 * \param num_procs is the number of processor attending to migration operation.
 * \param num_parts is the number of parts that exist in the current partitioning.
 * \param num_points_in_all_processor_parts is the input array that holds
 * the number of coordinates in each part in each processor.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
bool AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_check_to_migrate(
    size_t migration_reduce_all_population,
    mj_lno_t num_coords_for_last_dim_part,
    mj_part_t num_procs,
    mj_part_t num_parts,
    mj_gno_t *num_points_in_all_processor_parts){

        //if reduce all count and population in the last dim is too high
    if (migration_reduce_all_population > FUTURE_REDUCEALL_CUTOFF) return true;
    //if the work in a part per processor in the last dim is too low.
    if (num_coords_for_last_dim_part < MIN_WORK_LAST_DIM) return true;

        //if migration is to be checked and the imbalance is too high
    if (this->check_migrate_avoid_migration_option == 0){
        double global_imbalance = 0;
        //global shift to reach the sum of coordiante count in each part.
        size_t global_shift = num_procs * num_parts;

        for (mj_part_t ii = 0; ii < num_procs; ++ii){
                for (mj_part_t i = 0; i < num_parts; ++i){
                        double ideal_num = num_points_in_all_processor_parts[global_shift + i]
                                                                / double(num_procs);

                        global_imbalance += ZOLTAN2_ABS(ideal_num -
                                        num_points_in_all_processor_parts[ii * num_parts + i]) /  (ideal_num);
                }
        }
        global_imbalance /= num_parts;
        global_imbalance /= num_procs;

                /*
        if (this->myRank == 0) {
                cout << "imbalance for next iteration:" << global_imbalance << endl;
        }
        */

        if(global_imbalance <= this->minimum_migration_imbalance){
                return false;
        }
        else {
                return true;
        }
    }
    else {
        //if migration is forced
        return true;
    }
}


/*! \brief Function fills up coordinate_destinations is the output array
 * that holds which part each coordinate should be sent.
 *
 * \param num_parts is the number of parts that exist in the current partitioning.
 * \param part_assignment_proc_begin_indices ([i]) points to the first processor index that part i will be sent to.
 * \param processor_chains_in_parts the array that holds the linked list structure, started from part_assignment_proc_begin_indices ([i]).
 * \param send_count_to_each_proc array array storing the number of points to be sent to each part.
 * \param coordinate_destinations is the output array that holds which part each coordinate should be sent.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::assign_send_destinations(
    mj_part_t num_parts,
    mj_part_t *part_assignment_proc_begin_indices,
    mj_part_t *processor_chains_in_parts,
    mj_lno_t *send_count_to_each_proc,
    int *coordinate_destinations){

    for (mj_part_t p = 0; p < num_parts; ++p){
        mj_lno_t part_begin = 0;
        if (p > 0) part_begin = this->new_part_xadj[p - 1];
        mj_lno_t part_end = this->new_part_xadj[p];

        //get the first part that current processor will send its part-p.
        mj_part_t proc_to_sent = part_assignment_proc_begin_indices[p];
        //initialize how many point I sent to this processor.
        mj_lno_t num_total_send = 0;
        for (mj_lno_t j=part_begin; j < part_end; j++){
            mj_lno_t local_ind = this->new_coordinate_permutations[j];
            while (num_total_send >= send_count_to_each_proc[proc_to_sent]){
                //then get the next processor to send the points in part p.
                num_total_send = 0;
                //assign new processor to part_assign_begin[p]
                part_assignment_proc_begin_indices[p] = processor_chains_in_parts[proc_to_sent];
                //remove the previous processor
                processor_chains_in_parts[proc_to_sent] = -1;
                //choose the next processor as the next one to send.
                proc_to_sent = part_assignment_proc_begin_indices[p];
            }
            //write the gno index to corresponding position in sendBuf.
            coordinate_destinations[local_ind] = proc_to_sent;
            ++num_total_send;
        }
    }
}

/*! \brief Function fills up coordinate_destinations is the output array
 * that holds which part each coordinate should be sent.
 *
 * \param num_points_in_all_processor_parts is the array holding the num points in each part in each proc.
 * \param num_parts is the number of parts that exist in the current partitioning.
 * \param num_procs is the number of processor attending to migration operation.

 * \param send_count_to_each_proc array array storing the number of points to be sent to each part.
 * \param processor_ranks_for_subcomm is the ranks of the processors that will be in the subcommunicator with me.
 * \param next_future_num_parts_in_parts is the vector, how many more parts each part will be divided into in the future.
 * \param out_part_index is the index of the part to which the processor is assigned.
 * \param output_part_numbering_begin_index is how much the numbers should be shifted when numbering the result parts.
 * \param coordinate_destinations is the output array that holds which part each coordinate should be sent.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_assign_proc_to_parts(
                mj_gno_t * num_points_in_all_processor_parts,
                mj_part_t num_parts,
                mj_part_t num_procs,
                mj_lno_t *send_count_to_each_proc,
                std::vector<mj_part_t> &processor_ranks_for_subcomm,
                std::vector<mj_part_t> *next_future_num_parts_in_parts,
                mj_part_t &out_part_index,
                mj_part_t &output_part_numbering_begin_index,
                int *coordinate_destinations){


    mj_gno_t *global_num_points_in_parts = num_points_in_all_processor_parts + num_procs * num_parts;
    mj_part_t *num_procs_assigned_to_each_part = allocMemory<mj_part_t>(num_parts);

    //boolean variable if the process finds its part to be assigned.
    bool did_i_find_my_group = false;

    mj_part_t num_free_procs = num_procs;
    mj_part_t minimum_num_procs_required_for_rest_of_parts = num_parts - 1;

    double max_imbalance_difference = 0;
    mj_part_t max_differing_part = 0;

    //find how many processor each part requires.
    for (mj_part_t i=0; i < num_parts; i++){

        //scalar portion of the required processors
        double scalar_required_proc = num_procs *
                (double (global_num_points_in_parts[i]) / double (this->num_global_coords));

        //round it to closest integer.
        mj_part_t required_proc = static_cast<mj_part_t> (0.5 + scalar_required_proc);

        //if assigning the required num procs, creates problems for the rest of the parts.
        //then only assign {num_free_procs - (minimum_num_procs_required_for_rest_of_parts)} procs to this part.
        if (num_free_procs - required_proc < minimum_num_procs_required_for_rest_of_parts){
            required_proc = num_free_procs - (minimum_num_procs_required_for_rest_of_parts);
        }

        //reduce the free processor count
        num_free_procs -= required_proc;
        //reduce the free minimum processor count required for the rest of the part by 1.
        --minimum_num_procs_required_for_rest_of_parts;

        //part (i) is assigned to (required_proc) processors.
        num_procs_assigned_to_each_part[i] = required_proc;

        //because of the roundings some processors might be left as unassigned.
        //we want to assign those processors to the part with most imbalance.
        //find the part with the maximum imbalance here.
        double imbalance_wrt_ideal = (scalar_required_proc - required_proc) /  required_proc;
        if (imbalance_wrt_ideal > max_imbalance_difference){
            max_imbalance_difference = imbalance_wrt_ideal;
            max_differing_part = i;
        }
    }

    //assign extra processors to the part with maximum imbalance than the ideal.
    if (num_free_procs > 0){
        num_procs_assigned_to_each_part[max_differing_part] +=  num_free_procs;
    }

    //now find what are the best processors with least migration for each part.

    //part_assignment_proc_begin_indices ([i]) is the array that holds the beginning
    //index of a processor that processor sends its data for part - i
    mj_part_t *part_assignment_proc_begin_indices = allocMemory<mj_part_t>(num_parts);
    //the next processor send is found in processor_chains_in_parts, in linked list manner.
    mj_part_t *processor_chains_in_parts = allocMemory<mj_part_t>(num_procs);
    mj_part_t *processor_part_assignments = allocMemory<mj_part_t>(num_procs);

    //initialize the assignment of each processor.
    //this has a linked list implementation.
    //the beginning of processors assigned
    //to each part is hold at  part_assignment_proc_begin_indices[part].
    //then the next processor assigned to that part is located at
    //proc_part_assignments[part_assign_begins[part]], this is a chain
    //until the value of -1 is reached.
    for (int i = 0; i < num_procs; ++i ){
        processor_part_assignments[i] = -1;
        processor_chains_in_parts[i] = -1;
    }
    for (int i = 0; i < num_parts; ++i ){
        part_assignment_proc_begin_indices[i] = -1;
    }


    //Allocate memory for sorting data structure.
    uSignedSortItem<mj_part_t, mj_gno_t, char> * sort_item_num_part_points_in_procs = allocMemory <uSignedSortItem<mj_part_t, mj_gno_t, char> > (num_procs);
    for(mj_part_t i = 0; i < num_parts; ++i){
        //the algorithm tries to minimize the cost of migration,
        //by assigning the processors with highest number of coordinates on that part.
        //here we might want to implement a maximum weighted bipartite matching algorithm.
        for(mj_part_t ii = 0; ii < num_procs; ++ii){
                sort_item_num_part_points_in_procs[ii].id = ii;
                //if processor is not assigned yet.
                //add its num points to the sort data structure.
                if (processor_part_assignments[ii] == -1){
                        sort_item_num_part_points_in_procs[ii].val = num_points_in_all_processor_parts[ii * num_parts + i];
                        sort_item_num_part_points_in_procs[ii].signbit = 1; //indicate that the processor has positive weight.
                }
                else {
                        //if processor is already assigned, insert -nLocal - 1 so that it won't be selected again.
                        //would be same if we simply set it to -1,
                        //but more information with no extra cost (which is used later) is provided.
                        //sort_item_num_part_points_in_procs[ii].val = -num_points_in_all_processor_parts[ii * num_parts + i] - 1;

                        //UPDATE: Since above gets warning when unsigned is used to represent, we added extra bit to as sign bit to the sort item.
                        //It is 1 for positives, 0 for negatives.
                        sort_item_num_part_points_in_procs[ii].val = num_points_in_all_processor_parts[ii * num_parts + i];
                        sort_item_num_part_points_in_procs[ii].signbit = 0;
                }
        }
        //sort the processors in the part.
        uqSignsort<mj_part_t, mj_gno_t,char>(num_procs, sort_item_num_part_points_in_procs);

        /*
        for(mj_part_t ii = 0; ii < num_procs; ++ii){
          std::cout << "ii:" << ii << " " << sort_item_num_part_points_in_procs[ii].id <<
              " " << sort_item_num_part_points_in_procs[ii].val <<
              " " << int(sort_item_num_part_points_in_procs[ii].signbit) << std::endl;
        }
        */

        mj_part_t required_proc_count =  num_procs_assigned_to_each_part[i];
        mj_gno_t total_num_points_in_part = global_num_points_in_parts[i];
        mj_gno_t ideal_num_points_in_a_proc =
                Teuchos::as<mj_gno_t>(ceil (total_num_points_in_part / double (required_proc_count)));

        //starts sending to least heaviest part.
        mj_part_t next_proc_to_send_index = num_procs - required_proc_count;
        mj_part_t next_proc_to_send_id = sort_item_num_part_points_in_procs[next_proc_to_send_index].id;
        mj_lno_t space_left_in_sent_proc =  ideal_num_points_in_a_proc - sort_item_num_part_points_in_procs[next_proc_to_send_index].val;

        //find the processors that will be assigned to this part, which are the heaviest
        //non assigned processors.
        for(mj_part_t ii = num_procs - 1; ii >= num_procs - required_proc_count; --ii){
            mj_part_t proc_id = sort_item_num_part_points_in_procs[ii].id;
            //assign processor to part - i.
            processor_part_assignments[proc_id] = i;
        }

        bool did_change_sign = false;
        //if processor has a minus count, reverse it.
        for(mj_part_t ii = 0; ii < num_procs; ++ii){
            // TODO:  THE LINE BELOW PRODUCES A WARNING IF gno_t IS UNSIGNED
            // TODO:  SEE BUG 6194
            if (sort_item_num_part_points_in_procs[ii].signbit == 0){
                did_change_sign = true;
                sort_item_num_part_points_in_procs[ii].signbit = 1;
            }
            else {
                break;
            }
        }
        if(did_change_sign){
            //resort the processors in the part for the rest of the processors that is not assigned.
            uqSignsort<mj_part_t, mj_gno_t>(num_procs - required_proc_count, sort_item_num_part_points_in_procs);
        }
        /*
        for(mj_part_t ii = 0; ii < num_procs; ++ii){
          std::cout << "after resort ii:" << ii << " " << sort_item_num_part_points_in_procs[ii].id <<
              " " << sort_item_num_part_points_in_procs[ii].val <<
              " " << int(sort_item_num_part_points_in_procs[ii].signbit ) << std::endl;
        }
        */

        //check if this processors is one of the procs assigned to this part.
        //if it is, then get the group.
        if (!did_i_find_my_group){
            for(mj_part_t ii = num_procs - 1; ii >= num_procs - required_proc_count; --ii){

                mj_part_t proc_id_to_assign = sort_item_num_part_points_in_procs[ii].id;
                //add the proc to the group.
                processor_ranks_for_subcomm.push_back(proc_id_to_assign);

                if(proc_id_to_assign == this->myRank){
                        //if the assigned process is me, then I find my group.
                    did_i_find_my_group = true;
                    //set the beginning of part i to my rank.
                    part_assignment_proc_begin_indices[i] = this->myRank;
                    processor_chains_in_parts[this->myRank] = -1;

                    //set send count to myself to the number of points that I have in part i.
                    send_count_to_each_proc[this->myRank] = sort_item_num_part_points_in_procs[ii].val;

                    //calculate the shift required for the output_part_numbering_begin_index
                    for (mj_part_t in = 0; in < i; ++in){
                        output_part_numbering_begin_index += (*next_future_num_parts_in_parts)[in];
                    }
                    out_part_index = i;
                }
            }
            //if these was not my group,
            //clear the subcomminicator processor array.
            if (!did_i_find_my_group){
                processor_ranks_for_subcomm.clear();
            }
        }

        //send points of the nonassigned coordinates to the assigned coordinates.
        //starts from the heaviest nonassigned processor.
        //TODO we might want to play with this part, that allows more computational imbalance
        //but having better communication balance.
        for(mj_part_t ii = num_procs - required_proc_count - 1; ii >= 0; --ii){
            mj_part_t nonassigned_proc_id = sort_item_num_part_points_in_procs[ii].id;
            mj_lno_t num_points_to_sent = sort_item_num_part_points_in_procs[ii].val;

            //we set number of points to -to_sent - 1 for the assigned processors.
            //we reverse it here. This should not happen, as we have already reversed them above.
#ifdef MJ_DEBUG
            if (num_points_to_sent < 0) {
                cout << "Migration - processor assignments - for part:" << i << "from proc:" << nonassigned_proc_id << " num_points_to_sent:" << num_points_to_sent << std::endl;
                exit(1);
            }
#endif

            //now sends the points to the assigned processors.
            while (num_points_to_sent > 0){
                //if the processor has enough space.
                if (num_points_to_sent <= space_left_in_sent_proc){
                        //reduce the space left in the processor.
                        space_left_in_sent_proc -= num_points_to_sent;
                        //if my rank is the one that is sending the coordinates.
                    if (this->myRank == nonassigned_proc_id){
                        //set my sent count to the sent processor.
                        send_count_to_each_proc[next_proc_to_send_id] = num_points_to_sent;
                        //save the processor in the list (processor_chains_in_parts and part_assignment_proc_begin_indices)
                        //that the processor will send its point in part-i.
                        mj_part_t prev_begin = part_assignment_proc_begin_indices[i];
                        part_assignment_proc_begin_indices[i] = next_proc_to_send_id;
                        processor_chains_in_parts[next_proc_to_send_id] = prev_begin;
                    }
                    num_points_to_sent = 0;
                }
                else {
                    //there might be no space left in the processor.
                    if(space_left_in_sent_proc > 0){
                        num_points_to_sent -= space_left_in_sent_proc;

                        //send as the space left in the processor.
                        if (this->myRank == nonassigned_proc_id){
                                //send as much as the space in this case.
                            send_count_to_each_proc[next_proc_to_send_id] = space_left_in_sent_proc;
                            mj_part_t prev_begin = part_assignment_proc_begin_indices[i];
                            part_assignment_proc_begin_indices[i] = next_proc_to_send_id;
                            processor_chains_in_parts[next_proc_to_send_id] = prev_begin;

                        }
                    }
                    //change the sent part
                    ++next_proc_to_send_index;

#ifdef MJ_DEBUG
                    if(next_part_to_send_index <  nprocs - required_proc_count ){
                        cout << "Migration - processor assignments - for part:"
                                        << i
                                        <<  " next_part_to_send :" << next_part_to_send_index
                                        << " nprocs:" << nprocs
                                        << " required_proc_count:" << required_proc_count
                                        << " Error: next_part_to_send_index <  nprocs - required_proc_count" << std::endl;
                        exit(1)l

                    }
#endif
                    //send the new id.
                    next_proc_to_send_id =  sort_item_num_part_points_in_procs[next_proc_to_send_index].id;
                    //set the new space in the processor.
                    space_left_in_sent_proc = ideal_num_points_in_a_proc - sort_item_num_part_points_in_procs[next_proc_to_send_index].val;
                }
            }
        }
    }



    this->assign_send_destinations(
                num_parts,
            part_assignment_proc_begin_indices,
            processor_chains_in_parts,
            send_count_to_each_proc,
            coordinate_destinations);

    freeArray<mj_part_t>(part_assignment_proc_begin_indices);
    freeArray<mj_part_t>(processor_chains_in_parts);
    freeArray<mj_part_t>(processor_part_assignments);
    freeArray<uSignedSortItem<mj_part_t, mj_gno_t, char> > (sort_item_num_part_points_in_procs);   
    freeArray<mj_part_t > (num_procs_assigned_to_each_part);

}


/*! \brief Function fills up coordinate_destinations is the output array
 * that holds which part each coordinate should be sent. In addition it calculates
 * the shift amount (output_part_numbering_begin_index) to be done when
 * final numberings of the parts are performed.
 *
 * \param num_parts is the number of parts that exist in the current partitioning.
 * \param sort_item_part_to_proc_assignment is the sorted parts with respect to the assigned processors.
 * \param coordinate_destinations is the output array that holds which part each coordinate should be sent.
 * \param output_part_numbering_begin_index is how much the numbers should be shifted when numbering the result parts.
 * \param next_future_num_parts_in_parts is the vector, how many more parts each part will be divided into in the future.
 *
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::assign_send_destinations2(
    mj_part_t num_parts,
    uSortItem<mj_part_t, mj_part_t> * sort_item_part_to_proc_assignment, //input sorted wrt processors
    int *coordinate_destinations,
    mj_part_t &output_part_numbering_begin_index,
    std::vector<mj_part_t> *next_future_num_parts_in_parts){

    mj_part_t part_shift_amount = output_part_numbering_begin_index;
    mj_part_t previous_processor = -1;
    for(mj_part_t i = 0; i < num_parts; ++i){
        mj_part_t p = sort_item_part_to_proc_assignment[i].id;
        //assigned processors are sorted.
        mj_lno_t part_begin_index = 0;
        if (p > 0) part_begin_index = this->new_part_xadj[p - 1];
        mj_lno_t part_end_index = this->new_part_xadj[p];

        mj_part_t assigned_proc = sort_item_part_to_proc_assignment[i].val;
        if (this->myRank == assigned_proc && previous_processor != assigned_proc){
            output_part_numbering_begin_index =  part_shift_amount;
        }
        previous_processor = assigned_proc;
        part_shift_amount += (*next_future_num_parts_in_parts)[p];

        for (mj_lno_t j=part_begin_index; j < part_end_index; j++){
            mj_lno_t localInd = this->new_coordinate_permutations[j];
            coordinate_destinations[localInd] = assigned_proc;
        }
    }
}


/*! \brief Function fills up coordinate_destinations is the output array
 * that holds which part each coordinate should be sent. In addition it calculates
 * the shift amount (output_part_numbering_begin_index) to be done when
 * final numberings of the parts are performed.
 *
 * \param num_points_in_all_processor_parts is the array holding the num points in each part in each proc.
 * \param num_parts is the number of parts that exist in the current partitioning.
 * \param num_procs is the number of processor attending to migration operation.

 * \param send_count_to_each_proc array array storing the number of points to be sent to each part.
 * \param next_future_num_parts_in_parts is the vector, how many more parts each part will be divided into in the future.
 * \param out_num_part is the number of parts assigned to the process.
 * \param out_part_indices is the indices of the part to which the processor is assigned.
 * \param output_part_numbering_begin_index is how much the numbers should be shifted when numbering the result parts.
 * \param coordinate_destinations is the output array that holds which part each coordinate should be sent.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_assign_parts_to_procs(
    mj_gno_t * num_points_in_all_processor_parts,
    mj_part_t num_parts,
    mj_part_t num_procs,
    mj_lno_t *send_count_to_each_proc, //output: sized nprocs, show the number of send point counts to each proc.
    std::vector<mj_part_t> *next_future_num_parts_in_parts,//input how many more partitions the part will be partitioned into.
    mj_part_t &out_num_part, //output, how many parts the processor will have. this is always 1 for this function.
    std::vector<mj_part_t> &out_part_indices, //output: the part indices which the processor is assigned to.
    mj_part_t &output_part_numbering_begin_index, //output: how much the part number should be shifted when setting the solution
    int *coordinate_destinations){
    out_num_part = 0;

    mj_gno_t *global_num_points_in_parts = num_points_in_all_processor_parts + num_procs * num_parts;
    out_part_indices.clear();

    //to sort the parts that is assigned to the processors.
    //id is the part number, sort value is the assigned processor id.
    uSortItem<mj_part_t, mj_part_t> * sort_item_part_to_proc_assignment  = allocMemory <uSortItem<mj_part_t, mj_part_t> >(num_parts);
    uSortItem<mj_part_t, mj_gno_t> * sort_item_num_points_of_proc_in_part_i = allocMemory <uSortItem<mj_part_t, mj_gno_t> >(num_procs);


    //calculate the optimal number of coordinates that should be assigned to each processor.
    mj_lno_t work_each = mj_lno_t (this->num_global_coords / (double (num_procs)) + 0.5f);
    //to hold the left space as the number of coordinates to the optimal number in each proc.
    mj_lno_t *space_in_each_processor = allocMemory <mj_lno_t>(num_procs);
    //initialize left space in each.
    for (mj_part_t i = 0; i < num_procs; ++i){
        space_in_each_processor[i] = work_each;
    }

    //we keep track of how many parts each processor is assigned to.
    //because in some weird inputs, it might be possible that some
    //processors is not assigned to any part. Using these variables,
    //we force each processor to have at least one part.
    mj_part_t *num_parts_proc_assigned = allocMemory <mj_part_t>(num_procs);
    memset(num_parts_proc_assigned, 0, sizeof(mj_part_t) * num_procs);
    int empty_proc_count = num_procs;

    //to sort the parts with decreasing order of their coordiantes.
    //id are the part numbers, sort value is the number of points in each.
    uSortItem<mj_part_t, mj_gno_t> * sort_item_point_counts_in_parts  = allocMemory <uSortItem<mj_part_t, mj_gno_t> >(num_parts);

    //initially we will sort the parts according to the number of coordinates they have.
    //so that we will start assigning with the part that has the most number of coordinates.
    for (mj_part_t i = 0; i < num_parts; ++i){
        sort_item_point_counts_in_parts[i].id = i;
        sort_item_point_counts_in_parts[i].val = global_num_points_in_parts[i];
    }
    //sort parts with increasing order of loads.
    uqsort<mj_part_t, mj_gno_t>(num_parts, sort_item_point_counts_in_parts);


    //assigning parts to the processors
    //traverse the part win decreasing order of load.
    //first assign the heaviest part.
    for (mj_part_t j = 0; j < num_parts; ++j){
        //sorted with increasing order, traverse inverse.
        mj_part_t i = sort_item_point_counts_in_parts[num_parts - 1 - j].id;
        //load of the part
        mj_gno_t load = global_num_points_in_parts[i];

        //assigned processors
        mj_part_t assigned_proc = -1;
        //if not fit best processor.
        mj_part_t best_proc_to_assign = 0;


        //sort processors with increasing number of points in this part.
        for (mj_part_t ii = 0; ii < num_procs; ++ii){
            sort_item_num_points_of_proc_in_part_i[ii].id = ii;

            //if there are still enough parts to fill empty processors, than proceed normally.
            //but if empty processor count is equal to the number of part, then
            //we force to part assignments only to empty processors.
            if (empty_proc_count < num_parts - j || num_parts_proc_assigned[ii] == 0){
                //how many points processor ii has in part i?
                sort_item_num_points_of_proc_in_part_i[ii].val =  num_points_in_all_processor_parts[ii * num_parts + i];
            }
            else {
                sort_item_num_points_of_proc_in_part_i[ii].val  = -1;
            }
        }
        uqsort<mj_part_t, mj_gno_t>(num_procs, sort_item_num_points_of_proc_in_part_i);

        //traverse all processors with decreasing load.
        for (mj_part_t iii = num_procs - 1; iii >= 0; --iii){
            mj_part_t ii = sort_item_num_points_of_proc_in_part_i[iii].id;
            mj_lno_t left_space = space_in_each_processor[ii] - load;
            //if enought space, assign to this part.
            if(left_space >= 0 ){
                assigned_proc = ii;
                break;
            }
            //if space is not enough, store the best candidate part.
            if (space_in_each_processor[best_proc_to_assign] < space_in_each_processor[ii]){
                best_proc_to_assign = ii;
            }
        }

        //if none had enough space, then assign it to best part.
        if (assigned_proc == -1){
            assigned_proc = best_proc_to_assign;
        }

        if (num_parts_proc_assigned[assigned_proc]++ == 0){
                --empty_proc_count;
        }
        space_in_each_processor[assigned_proc] -= load;
        //to sort later, part-i is assigned to the proccessor - assignment.
        sort_item_part_to_proc_assignment[j].id = i; //part i
        sort_item_part_to_proc_assignment[j].val = assigned_proc; //assigned to processor - assignment.


        //if assigned processor is me, increase the number.
        if (assigned_proc == this->myRank){
            out_num_part++;//assigned_part_count;
            out_part_indices.push_back(i);
        }
        //increase the send to that processor by the number of points in that part.
        //as everyone send their coordiantes in this part to the processor assigned to this part.
        send_count_to_each_proc[assigned_proc] += num_points_in_all_processor_parts[this->myRank * num_parts + i];
    }
    freeArray<mj_part_t>(num_parts_proc_assigned);
    freeArray< uSortItem<mj_part_t, mj_gno_t> > (sort_item_num_points_of_proc_in_part_i);
    freeArray<uSortItem<mj_part_t, mj_gno_t> >(sort_item_point_counts_in_parts);
    freeArray<mj_lno_t >(space_in_each_processor);


    //sort assignments with respect to the assigned processors.
    uqsort<mj_part_t, mj_part_t>(num_parts, sort_item_part_to_proc_assignment);
    //fill sendBuf.


    this->assign_send_destinations2(
            num_parts,
            sort_item_part_to_proc_assignment,
            coordinate_destinations,
            output_part_numbering_begin_index,
            next_future_num_parts_in_parts);

    freeArray<uSortItem<mj_part_t, mj_part_t> >(sort_item_part_to_proc_assignment);
}


/*! \brief Function fills up coordinate_destinations is the output array
 * that holds which part each coordinate should be sent. In addition it calculates
 * the shift amount (output_part_numbering_begin_index) to be done when
 * final numberings of the parts are performed.
 *
 * \param num_points_in_all_processor_parts is the array holding the num points in each part in each proc.
 * \param num_parts is the number of parts that exist in the current partitioning.
 * \param num_procs is the number of processor attending to migration operation.

 * \param send_count_to_each_proc array array storing the number of points to be sent to each part.
 * \param processor_ranks_for_subcomm is the ranks of the processors that will be in the subcommunicator with me.
 * \param next_future_num_parts_in_parts is the vector, how many more parts each part will be divided into in the future.
 * \param out_num_part is the number of parts assigned to the process.
 * \param out_part_indices is the indices of the part to which the processor is assigned.
 * \param output_part_numbering_begin_index is how much the numbers should be shifted when numbering the result parts.
 * \param coordinate_destinations is the output array that holds which part each coordinate should be sent.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_migration_part_proc_assignment(
    mj_gno_t * num_points_in_all_processor_parts,
    mj_part_t num_parts,
    mj_part_t num_procs,
    mj_lno_t *send_count_to_each_proc,
    std::vector<mj_part_t> &processor_ranks_for_subcomm,
    std::vector<mj_part_t> *next_future_num_parts_in_parts,
    mj_part_t &out_num_part,
    std::vector<mj_part_t> &out_part_indices,
    mj_part_t &output_part_numbering_begin_index,
    int *coordinate_destinations){



        processor_ranks_for_subcomm.clear();
        // if (this->num_local_coords > 0)
        if (num_procs > num_parts){
                //if there are more processors than the number of current part
                //then processors share the existing parts.
                //at the end each processor will have a single part,
                //but a part will be shared by a group of processors.
                mj_part_t out_part_index = 0;
                this->mj_assign_proc_to_parts(
                                num_points_in_all_processor_parts,
                                num_parts,
                                num_procs,
                                send_count_to_each_proc,
                                processor_ranks_for_subcomm,
                                next_future_num_parts_in_parts,
                                out_part_index,
                                output_part_numbering_begin_index,
                                coordinate_destinations
                );

                out_num_part = 1;
                out_part_indices.clear();
                out_part_indices.push_back(out_part_index);
        }
        else {

                //there are more parts than the processors.
                //therefore a processor will be assigned multiple parts,
                //the subcommunicators will only have a single processor.
                processor_ranks_for_subcomm.push_back(this->myRank);

                //since there are more parts then procs,
                //assign multiple parts to processors.
                this->mj_assign_parts_to_procs(
                                num_points_in_all_processor_parts,
                                num_parts,
                                num_procs,
                                send_count_to_each_proc,
                                next_future_num_parts_in_parts,
                                out_num_part,
                                out_part_indices,
                                output_part_numbering_begin_index,
                                coordinate_destinations);
        }
}

/*! \brief Function fills up coordinate_destinations is the output array
 * that holds which part each coordinate should be sent. In addition it calculates
 * the shift amount (output_part_numbering_begin_index) to be done when
 * final numberings of the parts are performed.
 *
 *
 * \param num_procs is the number of processor attending to migration operation.
 * \param num_new_local_points is the output to represent the new number of local points.
 * \param iteration is the string for the current iteration.
 * \param coordinate_destinations is the output array that holds which part each coordinate should be sent.
 * \param num_parts is the number of parts that exist in the current partitioning.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_migrate_coords(
    mj_part_t num_procs,
    mj_lno_t &num_new_local_points,
    std::string iteration,
    int *coordinate_destinations,
    mj_part_t num_parts)
{
#ifdef ENABLE_ZOLTAN_MIGRATION
    if (sizeof(mj_lno_t) <= sizeof(int)) {

        // Cannot use Zoltan_Comm with local ordinals larger than ints.
        // In Zoltan_Comm_Create, the cast int(this->num_local_coords)
        // may overflow.

        ZOLTAN_COMM_OBJ *plan = NULL;
        MPI_Comm mpi_comm = Teuchos::getRawMpiComm(*(this->comm));
        int num_incoming_gnos = 0;
        int message_tag = 7859;

        this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Migration Z1PlanCreating-" + iteration);
        int ierr = Zoltan_Comm_Create(
                        &plan,
                        int(this->num_local_coords),
                        coordinate_destinations,
                        mpi_comm,
                        message_tag,
                        &num_incoming_gnos);
        Z2_ASSERT_VALUE(ierr, ZOLTAN_OK);
        this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Migration Z1PlanCreating-" + iteration);

        this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Migration Z1Migration-" + iteration);
        mj_gno_t *incoming_gnos = allocMemory< mj_gno_t>(num_incoming_gnos);

        //migrate gnos.
        message_tag++;
        ierr = Zoltan_Comm_Do(
                        plan,
                        message_tag,
                        (char *) this->current_mj_gnos,
                        sizeof(mj_gno_t),
                        (char *) incoming_gnos);
        Z2_ASSERT_VALUE(ierr, ZOLTAN_OK);

        freeArray<mj_gno_t>(this->current_mj_gnos);
        this->current_mj_gnos = incoming_gnos;


        //migrate coordinates
        for (int i = 0; i < this->coord_dim; ++i){
                message_tag++;
                mj_scalar_t *coord = this->mj_coordinates[i];

                this->mj_coordinates[i] = allocMemory<mj_scalar_t>(num_incoming_gnos);
                ierr = Zoltan_Comm_Do(
                                plan,
                                message_tag,
                                (char *) coord,
                                sizeof(mj_scalar_t),
                                (char *) this->mj_coordinates[i]);
                Z2_ASSERT_VALUE(ierr, ZOLTAN_OK);
                freeArray<mj_scalar_t>(coord);
        }

        //migrate weights.
        for (int i = 0; i < this->num_weights_per_coord; ++i){
                message_tag++;
                mj_scalar_t *weight = this->mj_weights[i];

                this->mj_weights[i] = allocMemory<mj_scalar_t>(num_incoming_gnos);
                ierr = Zoltan_Comm_Do(
                                plan,
                                message_tag,
                                (char *) weight,
                                sizeof(mj_scalar_t),
                                (char *) this->mj_weights[i]);
                Z2_ASSERT_VALUE(ierr, ZOLTAN_OK);
                freeArray<mj_scalar_t>(weight);
        }


        //migrate owners.
        int *coord_own = allocMemory<int>(num_incoming_gnos);
        message_tag++;
        ierr = Zoltan_Comm_Do(
                        plan,
                        message_tag,
                        (char *) this->owner_of_coordinate,
                        sizeof(int), (char *) coord_own);
        Z2_ASSERT_VALUE(ierr, ZOLTAN_OK);
        freeArray<int>(this->owner_of_coordinate);
        this->owner_of_coordinate = coord_own;


        //if num procs is less than num parts,
        //we need the part assigment arrays as well, since
        //there will be multiple parts in processor.
        mj_part_t *new_parts = allocMemory<mj_part_t>(num_incoming_gnos);
        if(num_procs < num_parts){
                message_tag++;
                ierr = Zoltan_Comm_Do(
                                plan,
                                message_tag,
                                (char *) this->assigned_part_ids,
                                sizeof(mj_part_t),
                                (char *) new_parts);
                Z2_ASSERT_VALUE(ierr, ZOLTAN_OK);
        }
        freeArray<mj_part_t>(this->assigned_part_ids);
        this->assigned_part_ids = new_parts;

        ierr = Zoltan_Comm_Destroy(&plan);
        Z2_ASSERT_VALUE(ierr, ZOLTAN_OK);
        num_new_local_points = num_incoming_gnos;
        this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Migration Z1Migration-" + iteration);
    }

    else

#endif  // ENABLE_ZOLTAN_MIGRATION
    {
        this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Migration DistributorPlanCreating-" + iteration);
        Tpetra::Distributor distributor(this->comm);
        ArrayView<const mj_part_t> destinations( coordinate_destinations, this->num_local_coords);
        mj_lno_t num_incoming_gnos = distributor.createFromSends(destinations);
        this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Migration DistributorPlanCreating-" + iteration);

        this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Migration DistributorMigration-" + iteration);
        {
                //migrate gnos.
                ArrayRCP<mj_gno_t> received_gnos(num_incoming_gnos);
                ArrayView<mj_gno_t> sent_gnos(this->current_mj_gnos, this->num_local_coords);
                distributor.doPostsAndWaits<mj_gno_t>(sent_gnos, 1, received_gnos());
                freeArray<mj_gno_t>(this->current_mj_gnos);
                this->current_mj_gnos = allocMemory<mj_gno_t>(num_incoming_gnos);
                memcpy(
                                this->current_mj_gnos,
                                received_gnos.getRawPtr(),
                                num_incoming_gnos * sizeof(mj_gno_t));
        }
        //migrate coordinates
        for (int i = 0; i < this->coord_dim; ++i){

                ArrayView<mj_scalar_t> sent_coord(this->mj_coordinates[i], this->num_local_coords);
                ArrayRCP<mj_scalar_t> received_coord(num_incoming_gnos);
                distributor.doPostsAndWaits<mj_scalar_t>(sent_coord, 1, received_coord());
                freeArray<mj_scalar_t>(this->mj_coordinates[i]);
                this->mj_coordinates[i] = allocMemory<mj_scalar_t>(num_incoming_gnos);
                memcpy(
                                this->mj_coordinates[i],
                                received_coord.getRawPtr(),
                                num_incoming_gnos * sizeof(mj_scalar_t));
        }

        //migrate weights.
        for (int i = 0; i < this->num_weights_per_coord; ++i){

                ArrayView<mj_scalar_t> sent_weight(this->mj_weights[i], this->num_local_coords);
                ArrayRCP<mj_scalar_t> received_weight(num_incoming_gnos);
                distributor.doPostsAndWaits<mj_scalar_t>(sent_weight, 1, received_weight());
                freeArray<mj_scalar_t>(this->mj_weights[i]);
                this->mj_weights[i] = allocMemory<mj_scalar_t>(num_incoming_gnos);
                memcpy(
                                this->mj_weights[i],
                                received_weight.getRawPtr(),
                                num_incoming_gnos * sizeof(mj_scalar_t));
        }

        {
                //migrate the owners of the coordinates
                ArrayView<int> sent_owners(this->owner_of_coordinate, this->num_local_coords);
                ArrayRCP<int> received_owners(num_incoming_gnos);
                distributor.doPostsAndWaits<int>(sent_owners, 1, received_owners());
                freeArray<int>(this->owner_of_coordinate);
                this->owner_of_coordinate = allocMemory<int>(num_incoming_gnos);
                memcpy(
                                                this->owner_of_coordinate,
                                                received_owners.getRawPtr(),
                                                num_incoming_gnos * sizeof(int));
        }

        //if num procs is less than num parts,
        //we need the part assigment arrays as well, since
        //there will be multiple parts in processor.
        if(num_procs < num_parts){
                ArrayView<mj_part_t> sent_partids(this->assigned_part_ids, this->num_local_coords);
                ArrayRCP<mj_part_t> received_partids(num_incoming_gnos);
                distributor.doPostsAndWaits<mj_part_t>(sent_partids, 1, received_partids());
                freeArray<mj_part_t>(this->assigned_part_ids);
                this->assigned_part_ids = allocMemory<mj_part_t>(num_incoming_gnos);
                memcpy(
                                this->assigned_part_ids,
                                received_partids.getRawPtr(),
                                num_incoming_gnos * sizeof(mj_part_t));
        }
        else {
                mj_part_t *new_parts = allocMemory<int>(num_incoming_gnos);
                freeArray<mj_part_t>(this->assigned_part_ids);
                this->assigned_part_ids = new_parts;
        }
        this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Migration DistributorMigration-" + iteration);
        num_new_local_points = num_incoming_gnos;

    }
}

/*! \brief Function creates the new subcomminicator for the processors
 * given in processor_ranks_for_subcomm.
 *
 * \param processor_ranks_for_subcomm is the vector that has the ranks of
 * the processors that will be in the same group.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::create_sub_communicator(std::vector<mj_part_t> &processor_ranks_for_subcomm){
    mj_part_t group_size = processor_ranks_for_subcomm.size();
    mj_part_t *ids = allocMemory<mj_part_t>(group_size);
    for(mj_part_t i = 0; i < group_size; ++i) {
        ids[i] = processor_ranks_for_subcomm[i];
    }
    ArrayView<const mj_part_t> idView(ids, group_size);
    this->comm = this->comm->createSubcommunicator(idView);
    freeArray<mj_part_t>(ids);
}


/*! \brief Function writes the new permutation arrays after the migration.
 *
 * \param output_num_parts is the number of parts that is assigned to the processor.
 * \param num_parts is the number of parts right before migration.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::fill_permutation_array(
    mj_part_t output_num_parts,
    mj_part_t num_parts){
        //if there is single output part, then simply fill the permutation array.
    if (output_num_parts == 1){
        for(mj_lno_t i = 0; i < this->num_local_coords; ++i){
            this->new_coordinate_permutations[i] = i;
        }
        this->new_part_xadj[0] = this->num_local_coords;
    }
    else {

        //otherwise we need to count how many points are there in each part.
        //we allocate here as num_parts, because the sent partids are up to num_parts,
        //although there are outout_num_parts different part.
        mj_lno_t *num_points_in_parts = allocMemory<mj_lno_t>(num_parts);
        //part shift holds the which part number an old part number corresponds to.
        mj_part_t *part_shifts = allocMemory<mj_part_t>(num_parts);

        memset(num_points_in_parts, 0, sizeof(mj_lno_t) * num_parts);

        for(mj_lno_t i = 0; i < this->num_local_coords; ++i){
            mj_part_t ii = this->assigned_part_ids[i];
            ++num_points_in_parts[ii];
        }

        //write the end points of the parts.
        mj_part_t p = 0;
        mj_lno_t prev_index = 0;
        for(mj_part_t i = 0; i < num_parts; ++i){
            if(num_points_in_parts[i] > 0)  {
                this->new_part_xadj[p] =  prev_index + num_points_in_parts[i];
                prev_index += num_points_in_parts[i];
                part_shifts[i] = p++;
            }
        }

        //for the rest of the parts write the end index as end point.
        mj_part_t assigned_num_parts = p - 1;
        for (;p < num_parts; ++p){
            this->new_part_xadj[p] =  this->new_part_xadj[assigned_num_parts];
        }
        for(mj_part_t i = 0; i < output_num_parts; ++i){
            num_points_in_parts[i] = this->new_part_xadj[i];
        }

        //write the permutation array here.
        //get the part of the coordinate i, shift it to obtain the new part number.
        //assign it to the end of the new part numbers pointer.
        for(mj_lno_t i = this->num_local_coords - 1; i >= 0; --i){
            mj_part_t part = part_shifts[mj_part_t(this->assigned_part_ids[i])];
            this->new_coordinate_permutations[--num_points_in_parts[part]] = i;
        }

        freeArray<mj_lno_t>(num_points_in_parts);
        freeArray<mj_part_t>(part_shifts);
    }
}


/*! \brief Function checks if should do migration or not.
 * It returns true to point that migration should be done when
 * -migration_reduce_all_population are higher than a predetermined value
 * -num_coords_for_last_dim_part that left for the last dimension partitioning is less than a predetermined value
 * -the imbalance of the processors on the parts are higher than given threshold.

 * \param input_num_parts is the number of parts when migration is called.
 * \param output_num_parts is the output number of parts after migration.
 * \param next_future_num_parts_in_parts is the number of total future parts each
 * part is partitioned into. This will be updated when migration is performed.
 * \param output_part_begin_index is the number that will be used as beginning part number
 * when final solution part numbers are assigned.
 * \param migration_reduce_all_population is the estimated total number of reduceall operations
 * multiplied with number of processors to be used for determining migration.
 *
 * \param num_coords_for_last_dim_part is the estimated number of points in each part,
 * when last dimension partitioning is performed.
 * \param iteration is the string that gives information about the dimension for printing purposes.
 * \param input_part_boxes is the array that holds the part boxes after the migration. (swapped)
 * \param output_part_boxes is the array that holds the part boxes before the migration. (swapped)
 *
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
bool AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::mj_perform_migration(
    mj_part_t input_num_parts, //current umb parts
    mj_part_t &output_num_parts, //output umb parts.
    std::vector<mj_part_t> *next_future_num_parts_in_parts,
    mj_part_t &output_part_begin_index,
    size_t migration_reduce_all_population,
    mj_lno_t num_coords_for_last_dim_part,
    std::string iteration,
    RCP<mj_partBoxVector_t> &input_part_boxes,
    RCP<mj_partBoxVector_t> &output_part_boxes
)
{
        mj_part_t num_procs = this->comm->getSize();
        this->myRank = this->comm->getRank();


        //this array holds how many points each processor has in each part.
        //to access how many points processor i has on part j,
        //num_points_in_all_processor_parts[i * num_parts + j]
        mj_gno_t *num_points_in_all_processor_parts = allocMemory<mj_gno_t>(input_num_parts * (num_procs + 1));

        //get the number of coordinates in each part in each processor.
        this->get_processor_num_points_in_parts(
                        num_procs,
                        input_num_parts,
                        num_points_in_all_processor_parts);


        //check if migration will be performed or not.
        if (!this->mj_check_to_migrate(
                        migration_reduce_all_population,
                        num_coords_for_last_dim_part,
                        num_procs,
                        input_num_parts,
                        num_points_in_all_processor_parts)){
                freeArray<mj_gno_t>(num_points_in_all_processor_parts);
                return false;
        }


        mj_lno_t *send_count_to_each_proc = NULL;
        int *coordinate_destinations = allocMemory<int>(this->num_local_coords);
        send_count_to_each_proc = allocMemory<mj_lno_t>(num_procs);
        for (int i = 0; i < num_procs; ++i) send_count_to_each_proc[i] = 0;

        std::vector<mj_part_t> processor_ranks_for_subcomm;
        std::vector<mj_part_t> out_part_indices;

        //determine which processors are assigned to which parts
        this->mj_migration_part_proc_assignment(
                        num_points_in_all_processor_parts,
                        input_num_parts,
                        num_procs,
                        send_count_to_each_proc,
                        processor_ranks_for_subcomm,
                        next_future_num_parts_in_parts,
                        output_num_parts,
                        out_part_indices,
                        output_part_begin_index,
                        coordinate_destinations);




        freeArray<mj_lno_t>(send_count_to_each_proc);
        std::vector <mj_part_t> tmpv;

        std::sort (out_part_indices.begin(), out_part_indices.end());
        mj_part_t outP = out_part_indices.size();

        mj_gno_t new_global_num_points = 0;
        mj_gno_t *global_num_points_in_parts = num_points_in_all_processor_parts + num_procs * input_num_parts;

        if (this->mj_keep_part_boxes){
                input_part_boxes->clear();
        }

        //now we calculate the new values for next_future_num_parts_in_parts.
        //same for the part boxes.
        for (mj_part_t i = 0; i < outP; ++i){
                mj_part_t ind = out_part_indices[i];
                new_global_num_points += global_num_points_in_parts[ind];
                tmpv.push_back((*next_future_num_parts_in_parts)[ind]);
                if (this->mj_keep_part_boxes){
                        input_part_boxes->push_back((*output_part_boxes)[ind]);
                }
        }
        //swap the input and output part boxes.
        if (this->mj_keep_part_boxes){
                RCP<mj_partBoxVector_t> tmpPartBoxes = input_part_boxes;
                input_part_boxes = output_part_boxes;
                output_part_boxes = tmpPartBoxes;
        }
        next_future_num_parts_in_parts->clear();
        for (mj_part_t i = 0; i < outP; ++i){
                mj_part_t p = tmpv[i];
                next_future_num_parts_in_parts->push_back(p);
        }

        freeArray<mj_gno_t>(num_points_in_all_processor_parts);

        mj_lno_t num_new_local_points = 0;


        //perform the actual migration operation here.
        this->mj_migrate_coords(
                        num_procs,
                        num_new_local_points,
                        iteration,
                        coordinate_destinations,
                        input_num_parts);


        freeArray<int>(coordinate_destinations);

        if(this->num_local_coords != num_new_local_points){
                freeArray<mj_lno_t>(this->new_coordinate_permutations);
                freeArray<mj_lno_t>(this->coordinate_permutations);

                this->new_coordinate_permutations = allocMemory<mj_lno_t>(num_new_local_points);
                this->coordinate_permutations = allocMemory<mj_lno_t>(num_new_local_points);
        }
        this->num_local_coords = num_new_local_points;
        this->num_global_coords = new_global_num_points;



        //create subcommunicator.
        this->create_sub_communicator(processor_ranks_for_subcomm);
        processor_ranks_for_subcomm.clear();

        //fill the new permutation arrays.
        this->fill_permutation_array(
                        output_num_parts,
                        input_num_parts);
        return true;
}


/*! \brief Function creates consistent chunks for task partitioning. Used only in the case of
 * sequential task partitioning, where consistent handle of the points on the cuts are required.
 *
 * \param num_parts is the number of parts.
 * \param mj_current_dim_coords is 1 dimensional array holding the coordinate values.
 * \param current_concurrent_cut_coordinate is 1 dimensional array holding the cut coordinates.
 * \param coordinate_begin is the start index of the given partition on partitionedPointPermutations.
 * \param coordinate_end is the end index of the given partition on partitionedPointPermutations.
 * \param used_local_cut_line_weight_to_left holds how much weight of the coordinates on the cutline should be put on left side.
 *
 * \param out_part_xadj is the indices of begginning and end of the parts in the output partition.
 * \param coordInd is the index according to which the partitioning is done.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::create_consistent_chunks(
    mj_part_t num_parts,
    mj_scalar_t *mj_current_dim_coords,
    mj_scalar_t *current_concurrent_cut_coordinate,
    mj_lno_t coordinate_begin,
    mj_lno_t coordinate_end,
    mj_scalar_t *used_local_cut_line_weight_to_left,
    mj_lno_t *out_part_xadj,
    int coordInd){

        //mj_lno_t numCoordsInPart =  coordinateEnd - coordinateBegin;
        mj_part_t no_cuts = num_parts - 1;



        int me = 0;
        mj_lno_t *thread_num_points_in_parts = this->thread_point_counts[me];
        mj_scalar_t *my_local_thread_cut_weights_to_put_left = NULL;


        //now if the rectilinear partitioning is allowed we decide how
        //much weight each thread should put to left and right.
        if (this->distribute_points_on_cut_lines){

                my_local_thread_cut_weights_to_put_left = this->thread_cut_line_weight_to_put_left[me];
                for (mj_part_t i = 0; i < no_cuts; ++i){
                        //the left to be put on the left of the cut.
                        mj_scalar_t left_weight = used_local_cut_line_weight_to_left[i];
                        //cout << "i:" << i << " left_weight:" << left_weight << endl;
                        for(int ii = 0; ii < this->num_threads; ++ii){
                                if(left_weight > this->sEpsilon){
                                        //the weight of thread ii on cut.
                                        mj_scalar_t thread_ii_weight_on_cut = this->thread_part_weight_work[ii][i * 2 + 1] - this->thread_part_weight_work[ii][i * 2 ];
                                        if(thread_ii_weight_on_cut < left_weight){
                                                this->thread_cut_line_weight_to_put_left[ii][i] = thread_ii_weight_on_cut;
                                        }
                                        else {
                                                this->thread_cut_line_weight_to_put_left[ii][i] = left_weight ;
                                        }
                                        left_weight -= thread_ii_weight_on_cut;
                                }
                                else {
                                        this->thread_cut_line_weight_to_put_left[ii][i] = 0;
                                }
                        }
                }

                if(no_cuts > 0){
                        //this is a special case. If cutlines share the same coordinate, their weights are equal.
                        //we need to adjust the ratio for that.
                        for (mj_part_t i = no_cuts - 1; i > 0 ; --i){
                                if(ZOLTAN2_ABS(current_concurrent_cut_coordinate[i] - current_concurrent_cut_coordinate[i -1]) < this->sEpsilon){
                                        my_local_thread_cut_weights_to_put_left[i] -= my_local_thread_cut_weights_to_put_left[i - 1] ;
                                }
                                my_local_thread_cut_weights_to_put_left[i] = int ((my_local_thread_cut_weights_to_put_left[i] + LEAST_SIGNIFICANCE) * SIGNIFICANCE_MUL)
                                                                                                / mj_scalar_t(SIGNIFICANCE_MUL);
                        }
                }
        }

        for(mj_part_t ii = 0; ii < num_parts; ++ii){
                thread_num_points_in_parts[ii] = 0;
        }

        //for this specific case we dont want to distribute the points along the cut position
        //randomly, as we need a specific ordering of them. Instead,
        //we put the coordinates into a sort item, where we sort those
        //using the coordinates of points on other dimensions and the index.


        //some of the cuts might share the same position.
        //in this case, if cut i and cut j share the same position
        //cut_map[i] = cut_map[j] = sort item index.
        mj_part_t *cut_map = allocMemory<mj_part_t> (no_cuts);


        typedef uMultiSortItem<mj_lno_t, int, mj_scalar_t> multiSItem;
        typedef std::vector< multiSItem > multiSVector;
        typedef std::vector<multiSVector> multiS2Vector;

        //to keep track of the memory allocated.
        std::vector<mj_scalar_t *>allocated_memory;

        //vector for which the coordinates will be sorted.
        multiS2Vector sort_vector_points_on_cut;

        //the number of cuts that have different coordinates.
        mj_part_t different_cut_count = 1;
        cut_map[0] = 0;

        //now we insert 1 sort vector for all cuts on the different
        //positins.if multiple cuts are on the same position, they share sort vectors.
        multiSVector tmpMultiSVector;
        sort_vector_points_on_cut.push_back(tmpMultiSVector);

        for (mj_part_t i = 1; i < no_cuts ; ++i){
                //if cuts share the same cut coordinates
                //set the cutmap accordingly.
                if(ZOLTAN2_ABS(current_concurrent_cut_coordinate[i] - current_concurrent_cut_coordinate[i -1]) < this->sEpsilon){
                        cut_map[i] = cut_map[i-1];
                }
                else {
                        cut_map[i] = different_cut_count++;
                        multiSVector tmp2MultiSVector;
                        sort_vector_points_on_cut.push_back(tmp2MultiSVector);
                }
        }


        //now the actual part assigment.
        for (mj_lno_t ii = coordinate_begin; ii < coordinate_end; ++ii){

                mj_lno_t i = this->coordinate_permutations[ii];

                mj_part_t pp = this->assigned_part_ids[i];
                mj_part_t p = pp / 2;
                //if the coordinate is on a cut.
                if(pp % 2 == 1 ){
                        mj_scalar_t *vals = allocMemory<mj_scalar_t>(this->coord_dim -1);
                        allocated_memory.push_back(vals);

                        //we insert the coordinates to the sort item here.
                        int val_ind = 0;
                        for(int dim = coordInd + 1; dim < this->coord_dim; ++dim){
                                vals[val_ind++] = this->mj_coordinates[dim][i];
                        }
                        for(int dim = 0; dim < coordInd; ++dim){
                                vals[val_ind++] = this->mj_coordinates[dim][i];
                        }
                        multiSItem tempSortItem(i, this->coord_dim -1, vals);
                        //inser the point to the sort vector pointed by the cut_map[p].
                        mj_part_t cmap = cut_map[p];
                        sort_vector_points_on_cut[cmap].push_back(tempSortItem);
                }
                else {
                        //if it is not on the cut, simple sorting.
                        ++thread_num_points_in_parts[p];
                        this->assigned_part_ids[i] = p;
                }
        }

        //sort all the sort vectors.
        for (mj_part_t i = 0; i < different_cut_count; ++i){
                std::sort (sort_vector_points_on_cut[i].begin(), sort_vector_points_on_cut[i].end());
        }

        //we do the part assignment for the points on cuts here.
        mj_part_t previous_cut_map = cut_map[0];

        //this is how much previous part owns the weight of the current part.
        //when target part weight is 1.6, and the part on the left is given 2,
        //the left has an extra 0.4, while the right has missing 0.4 from the previous cut.
        //this parameter is used to balance this issues.
        //in the above example weight_stolen_from_previous_part will be 0.4.
        //if the left part target is 2.2 but it is given 2,
        //then weight_stolen_from_previous_part will be -0.2.
        mj_scalar_t weight_stolen_from_previous_part = 0;
        for (mj_part_t p = 0; p < no_cuts; ++p){

                mj_part_t mapped_cut = cut_map[p];

                //if previous cut map is done, and it does not have the same index,
                //then assign all points left on that cut to its right.
                if (previous_cut_map != mapped_cut){
                        mj_lno_t sort_vector_end = (mj_lno_t)sort_vector_points_on_cut[previous_cut_map].size() - 1;
                        for (; sort_vector_end >= 0; --sort_vector_end){
                                multiSItem t = sort_vector_points_on_cut[previous_cut_map][sort_vector_end];
                                mj_lno_t i = t.index;
                                ++thread_num_points_in_parts[p];
                                this->assigned_part_ids[i] = p;
                        }
                        sort_vector_points_on_cut[previous_cut_map].clear();
                }
                mj_lno_t sort_vector_end = (mj_lno_t)sort_vector_points_on_cut[mapped_cut].size() - 1;

                for (; sort_vector_end >= 0; --sort_vector_end){
                        multiSItem t = sort_vector_points_on_cut[mapped_cut][sort_vector_end];
                        mj_lno_t i = t.index;
                        mj_scalar_t w = this->mj_uniform_weights[0]? 1:this->mj_weights[0][i];


                        //part p has enough space for point i, then put it to point i.
                        if(     my_local_thread_cut_weights_to_put_left[p] + weight_stolen_from_previous_part> this->sEpsilon &&
                                my_local_thread_cut_weights_to_put_left[p] + weight_stolen_from_previous_part - ZOLTAN2_ABS(my_local_thread_cut_weights_to_put_left[p] + weight_stolen_from_previous_part - w)
                                        > this->sEpsilon){

                                my_local_thread_cut_weights_to_put_left[p] -= w;
                                sort_vector_points_on_cut[mapped_cut].pop_back();
                                ++thread_num_points_in_parts[p];
                                this->assigned_part_ids[i] = p;
                                //if putting this weight to left overweights the left cut, then
                                //increase the space for the next cut using weight_stolen_from_previous_part.
                                if(p < no_cuts - 1 && my_local_thread_cut_weights_to_put_left[p] < this->sEpsilon){
                                        if(mapped_cut == cut_map[p + 1] ){
                                                //if the cut before the cut indexed at p was also at the same position
                                                //special case, as we handle the weight differently here.
                                                if (previous_cut_map != mapped_cut){
                                                        weight_stolen_from_previous_part = my_local_thread_cut_weights_to_put_left[p];
                                                }
                                                else {
                                                        //if the cut before the cut indexed at p was also at the same position
                                                        //we assign extra weights cumulatively in this case.
                                                        weight_stolen_from_previous_part += my_local_thread_cut_weights_to_put_left[p];
                                                }
                                        }
                                        else{
                                                weight_stolen_from_previous_part = -my_local_thread_cut_weights_to_put_left[p];
                                        }
                                        //end assignment for part p
                                        break;
                                }
                        } else {
                                //if part p does not have enough space for this point
                                //and if there is another cut sharing the same positon,
                                //again increase the space for the next
                                if(p < no_cuts - 1 && mapped_cut == cut_map[p + 1]){
                                        if (previous_cut_map != mapped_cut){
                                                weight_stolen_from_previous_part = my_local_thread_cut_weights_to_put_left[p];
                                        }
                                        else {
                                                weight_stolen_from_previous_part += my_local_thread_cut_weights_to_put_left[p];
                                        }
                                }
                                else{
                                        weight_stolen_from_previous_part = -my_local_thread_cut_weights_to_put_left[p];
                                }
                                //end assignment for part p
                                break;
                        }
                }
                previous_cut_map = mapped_cut;
        }
        //put everything left on the last cut to the last part.
        mj_lno_t sort_vector_end = (mj_lno_t)sort_vector_points_on_cut[previous_cut_map].size() - 1;
        for (; sort_vector_end >= 0; --sort_vector_end){
                multiSItem t = sort_vector_points_on_cut[previous_cut_map][sort_vector_end];
                mj_lno_t i = t.index;
                ++thread_num_points_in_parts[no_cuts];
                this->assigned_part_ids[i] = no_cuts;
        }
        sort_vector_points_on_cut[previous_cut_map].clear();
        freeArray<mj_part_t> (cut_map);

        //free the memory allocated for vertex sort items .
        mj_lno_t vSize = (mj_lno_t) allocated_memory.size();
        for(mj_lno_t i = 0; i < vSize; ++i){
                freeArray<mj_scalar_t> (allocated_memory[i]);
        }

        //creation of part_xadj as in usual case.
        for(mj_part_t j = 0; j < num_parts; ++j){
                mj_lno_t num_points_in_part_j_upto_thread_i = 0;
                for (int i = 0; i < this->num_threads; ++i){
                        mj_lno_t thread_num_points_in_part_j = this->thread_point_counts[i][j];
                        this->thread_point_counts[i][j] = num_points_in_part_j_upto_thread_i;
                        num_points_in_part_j_upto_thread_i += thread_num_points_in_part_j;

                }
                out_part_xadj[j] = num_points_in_part_j_upto_thread_i;// + prev2; //+ coordinateBegin;
        }

        //perform prefix sum for num_points in parts.
        for(mj_part_t j = 1; j < num_parts; ++j){
                out_part_xadj[j] += out_part_xadj[j - 1];
        }


        //shift the num points in threads thread to obtain the
        //beginning index of each thread's private space.
        for(mj_part_t j = 1; j < num_parts; ++j){
                thread_num_points_in_parts[j] += out_part_xadj[j - 1] ;
        }

        //now thread gets the coordinate and writes the index of coordinate to the permutation array
        //using the part index we calculated.
        for (mj_lno_t ii = coordinate_begin; ii < coordinate_end; ++ii){
                mj_lno_t i = this->coordinate_permutations[ii];
                mj_part_t p =  this->assigned_part_ids[i];
                this->new_coordinate_permutations[coordinate_begin +
                                                  thread_num_points_in_parts[p]++] = i;
        }
}



/*! \brief Function sends the found partids to the owner of the coordinates,
 * if the data is ever migrated. otherwise, it seets the part numbers and returns.
 * \param current_num_parts is the number of parts in the process.
 * \param output_part_begin_index is the number that will be used as beginning part number
 * \param output_part_boxes is the array that holds the part boxes
 * \param is_data_ever_migrated is the boolean value which is true
 * if the data is ever migrated during the partitioning.
 *
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::set_final_parts(
                mj_part_t current_num_parts,
                mj_part_t output_part_begin_index,
                RCP<mj_partBoxVector_t> &output_part_boxes,
                bool is_data_ever_migrated)
{
    this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Part_Assignment");

#ifdef HAVE_ZOLTAN2_OMP
#pragma omp parallel for
#endif
    for(mj_part_t i = 0; i < current_num_parts;++i){

        mj_lno_t begin = 0;
        mj_lno_t end = this->part_xadj[i];

        if(i > 0) begin = this->part_xadj[i -1];
        mj_part_t part_to_set_index = i + output_part_begin_index;
        if (this->mj_keep_part_boxes){
                (*output_part_boxes)[i].setpId(part_to_set_index);
        }
        for (mj_lno_t ii = begin; ii < end; ++ii){
                mj_lno_t k = this->coordinate_permutations[ii];
                this->assigned_part_ids[k] = part_to_set_index;
        }
    }

    //ArrayRCP<const mj_gno_t> gnoList;
    if(!is_data_ever_migrated){
        //freeArray<mj_gno_t>(this->current_mj_gnos);
        //if(this->num_local_coords > 0){
        //    gnoList = arcpFromArrayView(this->mj_gnos);
        //}
    }
    else {
#ifdef ENABLE_ZOLTAN_MIGRATION
      if (sizeof(mj_lno_t) <=  sizeof(int)) {

        // Cannot use Zoltan_Comm with local ordinals larger than ints.
        // In Zoltan_Comm_Create, the cast int(this->num_local_coords)
        // may overflow.

        //if data is migrated, then send part numbers to the original owners.
        ZOLTAN_COMM_OBJ *plan = NULL;
        MPI_Comm mpi_comm = Teuchos::getRawMpiComm(*(this->mj_problemComm));

        int incoming = 0;
        int message_tag = 7856;

        this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Final Z1PlanCreating");
        int ierr = Zoltan_Comm_Create( &plan, int(this->num_local_coords),
                        this->owner_of_coordinate, mpi_comm, message_tag,
                        &incoming);
        Z2_ASSERT_VALUE(ierr, ZOLTAN_OK);
        this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Final Z1PlanCreating" );

        mj_gno_t *incoming_gnos = allocMemory< mj_gno_t>(incoming);

        message_tag++;
        this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Final Z1PlanComm");
        ierr = Zoltan_Comm_Do( plan, message_tag, (char *) this->current_mj_gnos,
                        sizeof(mj_gno_t), (char *) incoming_gnos);
        Z2_ASSERT_VALUE(ierr, ZOLTAN_OK);

        freeArray<mj_gno_t>(this->current_mj_gnos);
        this->current_mj_gnos = incoming_gnos;

        mj_part_t *incoming_partIds = allocMemory< mj_part_t>(incoming);

        message_tag++;
        ierr = Zoltan_Comm_Do( plan, message_tag, (char *) this->assigned_part_ids,
                        sizeof(mj_part_t), (char *) incoming_partIds);
        Z2_ASSERT_VALUE(ierr, ZOLTAN_OK);
        freeArray<mj_part_t>(this->assigned_part_ids);
        this->assigned_part_ids = incoming_partIds;

        this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Final Z1PlanComm");
        ierr = Zoltan_Comm_Destroy(&plan);
        Z2_ASSERT_VALUE(ierr, ZOLTAN_OK);

        this->num_local_coords = incoming;
        //gnoList = arcp(this->current_mj_gnos, 0, this->num_local_coords, true);
      }
      else

#endif  // !ENABLE_ZOLTAN_MIGRATION
      {
        //if data is migrated, then send part numbers to the original owners.
        this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Final DistributorPlanCreating");
        Tpetra::Distributor distributor(this->mj_problemComm);
        ArrayView<const mj_part_t> owners_of_coords(this->owner_of_coordinate, this->num_local_coords);
        mj_lno_t incoming = distributor.createFromSends(owners_of_coords);
        this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Final DistributorPlanCreating" );

        this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Final DistributorPlanComm");
        //migrate gnos to actual owners.
        ArrayRCP<mj_gno_t> received_gnos(incoming);
        ArrayView<mj_gno_t> sent_gnos(this->current_mj_gnos, this->num_local_coords);
        distributor.doPostsAndWaits<mj_gno_t>(sent_gnos, 1, received_gnos());
        freeArray<mj_gno_t>(this->current_mj_gnos);
        this->current_mj_gnos = allocMemory<mj_gno_t>(incoming);
        memcpy( this->current_mj_gnos,
                received_gnos.getRawPtr(),
                incoming * sizeof(mj_gno_t));

                //migrate part ids to actual owners.
        ArrayView<mj_part_t> sent_partids(this->assigned_part_ids, this->num_local_coords);
        ArrayRCP<mj_part_t> received_partids(incoming);
        distributor.doPostsAndWaits<mj_part_t>(sent_partids, 1, received_partids());
        freeArray<mj_part_t>(this->assigned_part_ids);
        this->assigned_part_ids = allocMemory<mj_part_t>(incoming);
        memcpy( this->assigned_part_ids,
                received_partids.getRawPtr(),
                incoming * sizeof(mj_part_t));

        this->num_local_coords = incoming;
        this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Final DistributorPlanComm");

      }
    }

    this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Part_Assignment");

    this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Solution_Part_Assignment");

    //ArrayRCP<mj_part_t> partId;
    //partId = arcp(this->assigned_part_ids, 0, this->num_local_coords, true);

    if (this->mj_keep_part_boxes){
        this->kept_boxes = compute_global_box_boundaries(output_part_boxes);

    }

    this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Solution_Part_Assignment");
}

/*! \brief Function frees all allocated work memory.
*/
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::free_work_memory(){
        this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Problem_Free");

        for (int i=0; i < this->coord_dim; i++){
                freeArray<mj_scalar_t>(this->mj_coordinates[i]);
        }
        freeArray<mj_scalar_t *>(this->mj_coordinates);

        for (int i=0; i < this->num_weights_per_coord; i++){
                freeArray<mj_scalar_t>(this->mj_weights[i]);
        }
        freeArray<mj_scalar_t *>(this->mj_weights);

        freeArray<int>(this->owner_of_coordinate);

        for(int i = 0; i < this->num_threads; ++i){
                freeArray<mj_lno_t>(this->thread_point_counts[i]);
        }

        freeArray<mj_lno_t *>(this->thread_point_counts);
        freeArray<double *> (this->thread_part_weight_work);

        if(this->distribute_points_on_cut_lines){
                freeArray<mj_scalar_t>(this->process_cut_line_weight_to_put_left);
                for(int i = 0; i < this->num_threads; ++i){
                        freeArray<mj_scalar_t>(this->thread_cut_line_weight_to_put_left[i]);
                }
                freeArray<mj_scalar_t *>(this->thread_cut_line_weight_to_put_left);
                freeArray<mj_scalar_t>(this->process_rectilinear_cut_weight);
                freeArray<mj_scalar_t>(this->global_rectilinear_cut_weight);
        }

        freeArray<mj_part_t>(this->my_incomplete_cut_count);

        freeArray<mj_scalar_t>(this->max_min_coords);

        freeArray<mj_lno_t>(this->part_xadj);

        freeArray<mj_lno_t>(this->coordinate_permutations);

        freeArray<mj_lno_t>(this->new_coordinate_permutations);

        freeArray<mj_scalar_t>(this->all_cut_coordinates);

        freeArray<mj_scalar_t> (this->process_local_min_max_coord_total_weight);

        freeArray<mj_scalar_t> (this->global_min_max_coord_total_weight);

        freeArray<mj_scalar_t>(this->cut_coordinates_work_array);

        freeArray<mj_scalar_t>(this->target_part_weights);

        freeArray<mj_scalar_t>(this->cut_upper_bound_coordinates);

        freeArray<mj_scalar_t>(this->cut_lower_bound_coordinates);

        freeArray<mj_scalar_t>(this->cut_lower_bound_weights);
        freeArray<mj_scalar_t>(this->cut_upper_bound_weights);
        freeArray<bool>(this->is_cut_line_determined);
        freeArray<mj_scalar_t>(this->total_part_weight_left_right_closests);
        freeArray<mj_scalar_t>(this->global_total_part_weight_left_right_closests);

        for(int i = 0; i < this->num_threads; ++i){
                freeArray<double>(this->thread_part_weights[i]);
                freeArray<mj_scalar_t>(this->thread_cut_right_closest_point[i]);
                freeArray<mj_scalar_t>(this->thread_cut_left_closest_point[i]);
        }

        freeArray<double *>(this->thread_part_weights);
        freeArray<mj_scalar_t *>(this->thread_cut_left_closest_point);
        freeArray<mj_scalar_t *>(this->thread_cut_right_closest_point);

        this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Problem_Free");
}

/*! \brief Multi Jagged  coordinate partitioning algorithm.
 *
 *  \param distribute_points_on_cut_lines_ :  if partitioning can distribute points on same coordinate to different parts.
 *  \param max_concurrent_part_calculation_ : how many parts we can calculate concurrently.
 *  \param check_migrate_avoid_migration_option_ : whether to migrate=1, avoid migrate=2, or leave decision to MJ=0
 *  \param minimum_migration_imbalance_  : when MJ decides whether to migrate, the minimum imbalance for migration.
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::set_partitioning_parameters(
                bool distribute_points_on_cut_lines_,
                int max_concurrent_part_calculation_,
                int check_migrate_avoid_migration_option_,
                mj_scalar_t minimum_migration_imbalance_){
        this->distribute_points_on_cut_lines = distribute_points_on_cut_lines_;
        this->max_concurrent_part_calculation = max_concurrent_part_calculation_;
        this->check_migrate_avoid_migration_option = check_migrate_avoid_migration_option_;
        this->minimum_migration_imbalance = minimum_migration_imbalance_;

}


/*! \brief Multi Jagged  coordinate partitioning algorithm.
 *
 *  \param env   library configuration and problem parameters
 *  \param problemComm the communicator for the problem
 *  \param imbalance_tolerance : the input provided imbalance tolerance.
 *  \param num_global_parts: number of target global parts.
 *  \param part_no_array: part no array, if provided this will be used for partitioning.
 *  \param recursion_depth: if part no array is provided, it is the length of part no array,
 *                                              if part no is not provided than it is the number of steps that algorithm will divide into num_global_parts parts.
 *
 *  \param coord_dim: coordinate dimension
 *  \param num_local_coords: number of local coordinates
 *  \param num_global_coords: number of global coordinates
 *  \param initial_mj_gnos: the list of initial global id's
 *  \param mj_coordinates: the two dimensional coordinate array.
 *
 *  \param num_weights_per_coord: number of weights per coordinate
 *  \param mj_uniform_weights: if weight index [i] has uniform weight or not.
 *  \param mj_weights: the two dimensional array for weights
 *  \param mj_uniform_parts: if the target partitioning aims uniform parts
 *  \param mj_part_sizes: if the target partitioning does not aim uniform parts, then weight of each part.
 *
 *  \param result_assigned_part_ids: Output - 1D pointer, should be provided as null. Memory is given in the function.
 *                      the result partids corresponding to the coordinates given in result_mj_gnos.
 *  \param result_mj_gnos: Output - 1D pointer, should be provided as null. Memory is given in the function.
 *                      the result coordinate global id's corresponding to the part_ids array.
 *
 */
template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
void AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t>::multi_jagged_part(

        const RCP<const Environment> &env,
        RCP<const Comm<int> > &problemComm,

        double imbalance_tolerance_,
        size_t num_global_parts_,
        mj_part_t *part_no_array_,
        int recursion_depth_,

        int coord_dim_,
        mj_lno_t num_local_coords_,
        mj_gno_t num_global_coords_,
        const mj_gno_t *initial_mj_gnos_,
        mj_scalar_t **mj_coordinates_,

        int num_weights_per_coord_,
        bool *mj_uniform_weights_,
        mj_scalar_t **mj_weights_,
        bool *mj_uniform_parts_,
        mj_scalar_t **mj_part_sizes_,

        mj_part_t *&result_assigned_part_ids_,
        mj_gno_t *&result_mj_gnos_
)
{

#ifdef print_debug
    if(comm->getRank() == 0){
        std::cout << "size of gno:" << sizeof(mj_gno_t) << std::endl;
        std::cout << "size of lno:" << sizeof(mj_lno_t) << std::endl;
        std::cout << "size of mj_scalar_t:" << sizeof(mj_scalar_t) << std::endl;
    }
#endif

    this->mj_env = env;
    this->mj_problemComm = problemComm;
    this->myActualRank = this->myRank = this->mj_problemComm->getRank();

    this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Total");
    this->mj_env->debug(3, "In MultiJagged Jagged");

    {
        this->imbalance_tolerance = imbalance_tolerance_;
        this->num_global_parts = num_global_parts_;
        this->part_no_array =  part_no_array_;
        this->recursion_depth = recursion_depth_;

        this->coord_dim = coord_dim_;
        this->num_local_coords = num_local_coords_;
        this->num_global_coords = num_global_coords_;
        this->mj_coordinates = mj_coordinates_; //will copy the memory to this->mj_coordinates.
        this->initial_mj_gnos = (mj_gno_t *) initial_mj_gnos_; //will copy the memory to this->current_mj_gnos[j].

        this->num_weights_per_coord = num_weights_per_coord_;
        this->mj_uniform_weights = mj_uniform_weights_;
        this->mj_weights = mj_weights_; //will copy the memory to this->mj_weights
        this->mj_uniform_parts = mj_uniform_parts_;
        this->mj_part_sizes = mj_part_sizes_;

        this->num_threads = 1;
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp parallel

        {
                this->num_threads = omp_get_num_threads();
        }
#endif
    }
    //this->set_input_data();
    this->set_part_specifications();

    this->allocate_set_work_memory();

    //We duplicate the comm as we create subcommunicators during migration.
    //We keep the problemComm as it is, while comm changes after each migration.
    this->comm = this->mj_problemComm->duplicate();

    //initially there is a single partition
    mj_part_t current_num_parts = 1;
    mj_scalar_t *current_cut_coordinates =  this->all_cut_coordinates;

    this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Problem_Partitioning");

    mj_part_t output_part_begin_index = 0;
    mj_part_t future_num_parts = this->total_num_part;
    bool is_data_ever_migrated = false;

    std::vector<mj_part_t> *future_num_part_in_parts = new std::vector<mj_part_t> ();
    std::vector<mj_part_t> *next_future_num_parts_in_parts = new std::vector<mj_part_t> ();
    next_future_num_parts_in_parts->push_back(this->num_global_parts);

    RCP<mj_partBoxVector_t> input_part_boxes(new mj_partBoxVector_t(), true) ;
    RCP<mj_partBoxVector_t> output_part_boxes(new mj_partBoxVector_t(), true);

    compute_global_box();
    if(this->mj_keep_part_boxes){
        this->init_part_boxes(output_part_boxes);
    }

    for (int i = 0; i < this->recursion_depth; ++i){
        //partitioning array. size will be as the number of current partitions and this
        //holds how many parts that each part will be in the current dimension partitioning.
        std::vector <mj_part_t> num_partitioning_in_current_dim;

        //number of parts that will be obtained at the end of this partitioning.
        //future_num_part_in_parts is as the size of current number of parts.
        //holds how many more parts each should be divided in the further
        //iterations. this will be used to calculate num_partitioning_in_current_dim,
        //as the number of parts that the part will be partitioned
        //in the current dimension partitioning.

        //next_future_num_parts_in_parts will be as the size of outnumParts,
        //and this will hold how many more parts that each output part
        //should be divided. this array will also be used to determine the weight ratios
        //of the parts.
        //swap the arrays to use iteratively..
        std::vector<mj_part_t> *tmpPartVect= future_num_part_in_parts;
        future_num_part_in_parts = next_future_num_parts_in_parts;
        next_future_num_parts_in_parts = tmpPartVect;

        //clear next_future_num_parts_in_parts array as
        //getPartitionArrays expects it to be empty.
        //it also expects num_partitioning_in_current_dim to be empty as well.
        next_future_num_parts_in_parts->clear();

        if(this->mj_keep_part_boxes){
            RCP<mj_partBoxVector_t> tmpPartBoxes = input_part_boxes;
            input_part_boxes = output_part_boxes;
            output_part_boxes = tmpPartBoxes;
            output_part_boxes->clear();
        }

        //returns the total no. of output parts for this dimension partitioning.
        mj_part_t output_part_count_in_dimension =
                        this->update_part_num_arrays(
                                        num_partitioning_in_current_dim,
                                        future_num_part_in_parts,
                                        next_future_num_parts_in_parts,
                                        future_num_parts,
                                        current_num_parts,
                                        i,
                                        input_part_boxes,
                                        output_part_boxes);

        //if the number of obtained parts equal to current number of parts,
        //skip this dimension. For example, this happens when 1 is given in the input
        //part array is given. P=4,5,1,2
        if(output_part_count_in_dimension == current_num_parts) {
            //still need to swap the input output arrays.
            tmpPartVect= future_num_part_in_parts;
            future_num_part_in_parts = next_future_num_parts_in_parts;
            next_future_num_parts_in_parts = tmpPartVect;

            if(this->mj_keep_part_boxes){
                RCP<mj_partBoxVector_t> tmpPartBoxes = input_part_boxes;
                input_part_boxes = output_part_boxes;
                output_part_boxes = tmpPartBoxes;
            }
            continue;
        }


        //get the coordinate axis along which the partitioning will be done.
        int coordInd = i % this->coord_dim;
        mj_scalar_t * mj_current_dim_coords = this->mj_coordinates[coordInd];

        //convert i to string to be used for debugging purposes.
        std::string istring = Teuchos::toString<int>(i);
        this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Problem_Partitioning_" + istring);

        //alloc Memory to point the indices
        //of the parts in the permutation array.
        this->new_part_xadj = allocMemory<mj_lno_t>(output_part_count_in_dimension);

        //the index where in the new_part_xadj will be written.
        mj_part_t output_part_index = 0;
        //whatever is written to output_part_index will be added with putput_coordinate_end_index
        //so that the points will be shifted.
        mj_part_t output_coordinate_end_index = 0;

        mj_part_t current_work_part = 0;
        mj_part_t current_concurrent_num_parts =
                        std::min(current_num_parts - current_work_part, this->max_concurrent_part_calculation);

        mj_part_t obtained_part_index = 0;

        //run for all available parts.
        for (; current_work_part < current_num_parts;
                 current_work_part += current_concurrent_num_parts){

            current_concurrent_num_parts = std::min(current_num_parts - current_work_part,
                                 this->max_concurrent_part_calculation);

            mj_part_t actual_work_part_count = 0;
            //initialization for 1D partitioning.
            //get the min and max coordinates of each part
            //together with the part weights of each part.
            for(int kk = 0; kk < current_concurrent_num_parts; ++kk){
                mj_part_t current_work_part_in_concurrent_parts = current_work_part + kk;

                //if this part wont be partitioned any further
                //dont do any work for this part.
                if (num_partitioning_in_current_dim[current_work_part_in_concurrent_parts] == 1){
                    continue;
                }
                ++actual_work_part_count;
                mj_lno_t coordinate_end_index= this->part_xadj[current_work_part_in_concurrent_parts];
                mj_lno_t coordinate_begin_index = current_work_part_in_concurrent_parts==0 ? 0: this->part_xadj[current_work_part_in_concurrent_parts -1];

/*
                cout << "i:" << i << " j:" << current_work_part + kk
                                << " coordinate_begin_index:" << coordinate_begin_index
                                << " coordinate_end_index:" << coordinate_end_index
                                << " total:" << coordinate_end_index - coordinate_begin_index<< endl;
                                */
                this->mj_get_local_min_max_coord_totW(
                                coordinate_begin_index,
                                coordinate_end_index,
                                this->coordinate_permutations,
                                mj_current_dim_coords,
                            this->process_local_min_max_coord_total_weight[kk], //min_coordinate
                            this->process_local_min_max_coord_total_weight[kk + current_concurrent_num_parts], //max_coordinate
                            this->process_local_min_max_coord_total_weight[kk + 2*current_concurrent_num_parts]); //total_weight

            }

            //1D partitioning
            if (actual_work_part_count > 0){
                //obtain global Min max of the part.
                this->mj_get_global_min_max_coord_totW(
                                current_concurrent_num_parts,
                                this->process_local_min_max_coord_total_weight,
                                this->global_min_max_coord_total_weight);

                //represents the total number of cutlines
                //whose coordinate should be determined.
                mj_part_t total_incomplete_cut_count = 0;

                //Compute weight ratios for parts & cuts:
                //e.g., 0.25  0.25  0.5    0.5  0.75 0.75  1
                //part0  cut0  part1 cut1 part2 cut2 part3
                mj_part_t concurrent_part_cut_shift = 0;
                mj_part_t concurrent_part_part_shift = 0;
                for(int kk = 0; kk < current_concurrent_num_parts; ++kk){
                    mj_scalar_t min_coordinate = this->global_min_max_coord_total_weight[kk];
                    mj_scalar_t max_coordinate = this->global_min_max_coord_total_weight[kk +
                                                     current_concurrent_num_parts];

                    mj_scalar_t global_total_weight = this->global_min_max_coord_total_weight[kk +
                                                        2 * current_concurrent_num_parts];

                    mj_part_t concurrent_current_part_index = current_work_part + kk;

                    mj_part_t partition_count = num_partitioning_in_current_dim[concurrent_current_part_index];

                    mj_scalar_t *usedCutCoordinate = current_cut_coordinates + concurrent_part_cut_shift;
                    mj_scalar_t *current_target_part_weights = this->target_part_weights +
                                                        concurrent_part_part_shift;
                    //shift the usedCutCoordinate array as noCuts.
                    concurrent_part_cut_shift += partition_count - 1;
                    //shift the partRatio array as noParts.
                    concurrent_part_part_shift += partition_count;


                    //calculate only if part is not empty,
                    //and part will be further partitioned.
                    if(partition_count > 1 && min_coordinate <= max_coordinate){

                        //increase num_cuts_do_be_determined by the number of cuts of the current
                        //part's cut line number.
                        total_incomplete_cut_count += partition_count - 1;
                        //set the number of cut lines that should be determined
                        //for this part.
                        this->my_incomplete_cut_count[kk] = partition_count - 1;

                        //get the target weights of the parts.
                        this->mj_get_initial_cut_coords_target_weights(
                                        min_coordinate,
                                        max_coordinate,
                                        partition_count - 1,
                                        global_total_weight,
                                        usedCutCoordinate,
                                        current_target_part_weights,
                                        future_num_part_in_parts,
                                        next_future_num_parts_in_parts,
                                        concurrent_current_part_index,
                                        obtained_part_index);

                        mj_lno_t coordinate_end_index= this->part_xadj[concurrent_current_part_index];
                        mj_lno_t coordinate_begin_index = concurrent_current_part_index==0 ? 0: this->part_xadj[concurrent_current_part_index -1];

                        //get the initial estimated part assignments of the
                        //coordinates.
                        this->set_initial_coordinate_parts(
                            max_coordinate,
                            min_coordinate,
                            concurrent_current_part_index,
                            coordinate_begin_index, coordinate_end_index,
                            this->coordinate_permutations,
                            mj_current_dim_coords,
                            this->assigned_part_ids,
                            partition_count);
                    }
                    else {
                        // e.g., if have fewer coordinates than parts, don't need to do next dim.
                        this->my_incomplete_cut_count[kk] = 0;
                    }
                    obtained_part_index += partition_count;
                }



                //used imbalance, it is always 0, as it is difficult to
                //estimate a range.
                mj_scalar_t used_imbalance = 0;


                // Determine cut lines for all concurrent parts parts here.
                this->mj_1D_part(
                    mj_current_dim_coords,
                    used_imbalance,
                    current_work_part,
                    current_concurrent_num_parts,
                    current_cut_coordinates,
                    total_incomplete_cut_count,
                    num_partitioning_in_current_dim);
            }

            //create new part chunks
            {
                mj_part_t output_array_shift = 0;
                mj_part_t cut_shift = 0;
                size_t tlr_shift = 0;
                size_t partweight_array_shift = 0;

                for(int kk = 0; kk < current_concurrent_num_parts; ++kk){
                    mj_part_t current_concurrent_work_part = current_work_part + kk;
                    mj_part_t num_parts = num_partitioning_in_current_dim[current_concurrent_work_part];

                    //if the part is empty, skip the part.
                    if((num_parts != 1  )
                                &&
                                this->global_min_max_coord_total_weight[kk] >
                             this->global_min_max_coord_total_weight[kk + current_concurrent_num_parts]) {

                        //we still need to write the begin and end point of the
                        //empty part. simply set it zero, the array indices will be shifted later.
                        for(mj_part_t jj = 0; jj < num_parts; ++jj){
                                this->new_part_xadj[output_part_index + output_array_shift + jj] = 0;
                        }
                        cut_shift += num_parts - 1;
                        tlr_shift += (4 *(num_parts - 1) + 1);
                        output_array_shift += num_parts;
                        partweight_array_shift += (2 * (num_parts - 1) + 1);
                        continue;
                    }

                    mj_lno_t coordinate_end= this->part_xadj[current_concurrent_work_part];
                    mj_lno_t coordinate_begin = current_concurrent_work_part==0 ? 0: this->part_xadj[
                                                                current_concurrent_work_part -1];
                    mj_scalar_t *current_concurrent_cut_coordinate = current_cut_coordinates + cut_shift;
                    mj_scalar_t *used_local_cut_line_weight_to_left = this->process_cut_line_weight_to_put_left +
                                                            cut_shift;

                    //mj_scalar_t *used_tlr_array =  this->total_part_weight_left_right_closests + tlr_shift;

                    for(int ii = 0; ii < this->num_threads; ++ii){
                        this->thread_part_weight_work[ii] = this->thread_part_weights[ii] +  partweight_array_shift;
                    }

                    if(num_parts > 1){
                        if(this->mj_keep_part_boxes){
                                //if part boxes are to be stored update the boundaries.
                            for (mj_part_t j = 0; j < num_parts - 1; ++j){
                                (*output_part_boxes)[output_array_shift + output_part_index +
                                 j].updateMinMax(current_concurrent_cut_coordinate[j], 1
                                  /*update max*/, coordInd);

                                (*output_part_boxes)[output_array_shift + output_part_index + j +
                                 1].updateMinMax(current_concurrent_cut_coordinate[j], 0
                                  /*update min*/, coordInd);
                            }
                        }

                        // Rewrite the indices based on the computed cuts.
                        this->mj_create_new_partitions(
                            num_parts,
                            mj_current_dim_coords,
                            current_concurrent_cut_coordinate,
                            coordinate_begin,
                            coordinate_end,
                            used_local_cut_line_weight_to_left,
                            this->thread_part_weight_work,
                            this->new_part_xadj + output_part_index + output_array_shift
                            );

                    }
                    else {
                        //if this part is partitioned into 1 then just copy
                        //the old values.
                        mj_lno_t part_size = coordinate_end - coordinate_begin;
                        *(this->new_part_xadj + output_part_index + output_array_shift) = part_size;
                        memcpy(
                                this->new_coordinate_permutations + coordinate_begin,
                            this->coordinate_permutations + coordinate_begin,
                            part_size * sizeof(mj_lno_t));
                    }
                    cut_shift += num_parts - 1;
                    tlr_shift += (4 *(num_parts - 1) + 1);
                    output_array_shift += num_parts;
                    partweight_array_shift += (2 * (num_parts - 1) + 1);
                }

                //shift cut coordinates so that all cut coordinates are stored.
                //no shift now because we dont keep the cuts.
                //current_cut_coordinates += cut_shift;

                //mj_create_new_partitions from coordinates partitioned the parts and
                //write the indices as if there were a single part.
                //now we need to shift the beginning indices.
                for(mj_part_t kk = 0; kk < current_concurrent_num_parts; ++kk){
                    mj_part_t num_parts = num_partitioning_in_current_dim[ current_work_part + kk];
                    for (mj_part_t ii = 0;ii < num_parts ; ++ii){
                        //shift it by previousCount
                        this->new_part_xadj[output_part_index+ii] += output_coordinate_end_index;
                    }
                    //increase the previous count by current end.
                    output_coordinate_end_index = this->new_part_xadj[output_part_index + num_parts - 1];
                    //increase the current out.
                    output_part_index += num_parts ;
                }
            }
        }
        // end of this partitioning dimension


        int current_world_size = this->comm->getSize();
        long migration_reduce_all_population = this->total_dim_num_reduce_all * current_world_size;


        bool is_migrated_in_current_dimension = false;

        //we migrate if there are more partitionings to be done after this step
        //and if the migration is not forced to be avoided.
        //and the operation is not sequential.
        if (future_num_parts > 1 &&
            this->check_migrate_avoid_migration_option >= 0 &&
            current_world_size > 1){

                this->mj_env->timerStart(MACRO_TIMERS, "MultiJagged - Problem_Migration-" + istring);
                mj_part_t num_parts = output_part_count_in_dimension;
                if ( this->mj_perform_migration(
                                                num_parts,
                                                current_num_parts, //output
                                                next_future_num_parts_in_parts, //output
                                                output_part_begin_index,
                                                migration_reduce_all_population,
                                                this->num_local_coords / (future_num_parts * current_num_parts),
                                                istring,
                                                input_part_boxes, output_part_boxes) ) {
                        is_migrated_in_current_dimension = true;
                        is_data_ever_migrated = true;
                        this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Problem_Migration-" +
                                        istring);
                        //since data is migrated, we reduce the number of reduceAll operations for the last part.
                        this->total_dim_num_reduce_all /= num_parts;
                }
                else {
                        is_migrated_in_current_dimension = false;
                        this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Problem_Migration-" + istring);
                }
        }

        //swap the coordinate permutations for the next dimension.
        mj_lno_t * tmp = this->coordinate_permutations;
        this->coordinate_permutations = this->new_coordinate_permutations;
        this->new_coordinate_permutations = tmp;

        if(!is_migrated_in_current_dimension){
            this->total_dim_num_reduce_all -= current_num_parts;
            current_num_parts = output_part_count_in_dimension;
        }
        freeArray<mj_lno_t>(this->part_xadj);
        this->part_xadj = this->new_part_xadj;
        this->new_part_xadj = NULL;
        this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Problem_Partitioning_" + istring);
    }

    // Partitioning is done
    delete future_num_part_in_parts;
    delete next_future_num_parts_in_parts;

    this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Problem_Partitioning");
    /////////////////////////////End of the partitioning////////////////////////


    //get the final parts of each initial coordinate
    //the results will be written to
    //this->assigned_part_ids for gnos given in this->current_mj_gnos
    this->set_final_parts(
                current_num_parts,
                output_part_begin_index,
                output_part_boxes,
                is_data_ever_migrated);

    result_assigned_part_ids_ = this->assigned_part_ids;
    result_mj_gnos_ = this->current_mj_gnos;

    this->free_work_memory();
    this->mj_env->timerStop(MACRO_TIMERS, "MultiJagged - Total");
    this->mj_env->debug(3, "Out of MultiJagged");

}


/*! \brief Multi Jagged coordinate partitioning algorithm.
 *
 */
template <typename Adapter>
class Zoltan2_AlgMJ : public Algorithm<Adapter>
{
private:

#ifndef DOXYGEN_SHOULD_SKIP_THIS

    typedef CoordinateModel<typename Adapter::base_adapter_t> coordinateModel_t;
    typedef typename Adapter::scalar_t mj_scalar_t;
    typedef typename Adapter::gno_t mj_gno_t;
    typedef typename Adapter::lno_t mj_lno_t;
    typedef typename Adapter::node_t mj_node_t;
    typedef typename Adapter::part_t mj_part_t;
    typedef coordinateModelPartBox<mj_scalar_t, mj_part_t> mj_partBox_t;
    typedef std::vector<mj_partBox_t> mj_partBoxVector_t;
#endif
    AlgMJ<mj_scalar_t, mj_lno_t, mj_gno_t, mj_part_t> mj_partitioner;

    RCP<const Environment> mj_env; //the environment object
    RCP<const Comm<int> > mj_problemComm; //initial comm object
    RCP<const coordinateModel_t> mj_coords; //coordinate adapter

    //PARAMETERS
    double imbalance_tolerance; //input imbalance tolerance.
    size_t num_global_parts; //the targeted number of parts
    mj_part_t *part_no_array; //input part array specifying num part to divide along each dim.
    int recursion_depth; //the number of steps that partitioning will be solved in.

    int coord_dim; // coordinate dimension.
    mj_lno_t num_local_coords; //number of local coords.
    mj_gno_t num_global_coords; //number of global coords.
    const mj_gno_t *initial_mj_gnos; //initial global ids of the coordinates.
    mj_scalar_t **mj_coordinates; //two dimension coordinate array

    int num_weights_per_coord; // number of weights per coordinate
    bool *mj_uniform_weights; //if the coordinates have uniform weights.
    mj_scalar_t **mj_weights; //two dimensional weight array
    bool *mj_uniform_parts; //if the target parts are uniform
    mj_scalar_t **mj_part_sizes; //target part weight sizes.

    bool distribute_points_on_cut_lines; //if partitioning can distribute points on same coordiante to different parts.
    mj_part_t max_concurrent_part_calculation; // how many parts we can calculate concurrently.
    int check_migrate_avoid_migration_option; //whether to migrate=1, avoid migrate=2, or leave decision to MJ=0
    mj_scalar_t minimum_migration_imbalance; //when MJ decides whether to migrate, the minimum imbalance for migration.
    bool mj_keep_part_boxes; //if the boxes need to be kept.

    int num_threads;

    bool mj_run_as_rcb; //if this is set, then recursion depth is adjusted to its maximum value.

    ArrayRCP<mj_part_t> comXAdj_; //communication graph xadj
    ArrayRCP<mj_part_t> comAdj_; //communication graph adj.


    //when we have strided data, it returns a unstrided data in RCP form.
    //we need to hold on to that data, during the execution of mj, so that the data is not released.
    //coordinate_rcp_holder will hold that data, and release it when MJ is deleted.
    ArrayRCP<const mj_scalar_t> * coordinate_ArrayRCP_holder;

    void set_up_partitioning_data(
      const RCP<PartitioningSolution<Adapter> >&solution);

    void set_input_parameters(const Teuchos::ParameterList &p);

    void free_work_memory();

    RCP<mj_partBoxVector_t> getGlobalBoxBoundaries() const;

public:

    Zoltan2_AlgMJ(const RCP<const Environment> &env,
                  RCP<const Comm<int> > &problemComm,
                  const RCP<const coordinateModel_t> &coords) :
                        mj_partitioner(), mj_env(env),
                        mj_problemComm(problemComm),
                        mj_coords(coords),
                        imbalance_tolerance(0),
                        num_global_parts(1), part_no_array(NULL),
                        recursion_depth(0),
                        coord_dim(0),num_local_coords(0), num_global_coords(0),
                        initial_mj_gnos(NULL), mj_coordinates(NULL),
                        num_weights_per_coord(0),
                        mj_uniform_weights(NULL), mj_weights(NULL),
                        mj_uniform_parts(NULL),
                        mj_part_sizes(NULL),
                        distribute_points_on_cut_lines(true),
                        max_concurrent_part_calculation(1),
                        check_migrate_avoid_migration_option(0),
                        minimum_migration_imbalance(0.30),
                        mj_keep_part_boxes(false), num_threads(1), mj_run_as_rcb(false),
                        comXAdj_(), comAdj_(), coordinate_ArrayRCP_holder (NULL)
    {}
    ~Zoltan2_AlgMJ(){
      if (coordinate_ArrayRCP_holder != NULL){
        delete [] this->coordinate_ArrayRCP_holder;
        this->coordinate_ArrayRCP_holder = NULL;
      }
    }

    /*! \brief Set up validators specific to this algorithm
     */
    static void getValidParameters(ParameterList & pl)
    {
      const bool bUnsorted = true; // this clarifies the flag is for unsrorted
      RCP<Zoltan2::IntegerRangeListValidator<int>> mj_parts_Validator =
      Teuchos::rcp( new Zoltan2::IntegerRangeListValidator<int>(bUnsorted) );
      pl.set("mj_parts", "0", "list of parts for multiJagged partitioning "
        "algorithm. As many as the dimension count.", mj_parts_Validator);

      pl.set("mj_concurrent_part_count", 1, "The number of parts whose cut "
        "coordinates will be calculated concurently.", Environment::getAnyIntValidator());

      pl.set("mj_minimum_migration_imbalance", 1.1,
        "mj_minimum_migration_imbalance, the minimum imbalance of the "
        "processors to avoid migration",
        Environment::getAnyDoubleValidator());

      RCP<Teuchos::EnhancedNumberValidator<int>> mj_migration_option_validator =
        Teuchos::rcp( new Teuchos::EnhancedNumberValidator<int>(0, 2) );
      pl.set("mj_migration_option", 1, "Migration option, 0 for decision "
        "depending on the imbalance, 1 for forcing migration, 2 for "
        "avoiding migration", mj_migration_option_validator);

      // bool parameter
      pl.set("mj_keep_part_boxes", false, "Keep the part boundaries of the "
        "geometric partitioning.", Environment::getBoolValidator());

      // bool parameter
      pl.set("mj_enable_rcb", false, "Use MJ as RCB.",
        Environment::getBoolValidator());

      pl.set("mj_recursion_depth", -1, "Recursion depth for MJ: Must be "
        "greater than 0.", Environment::getAnyIntValidator());
    }

    /*! \brief Multi Jagged  coordinate partitioning algorithm.
     *
     *  \param solution  a PartitioningSolution, on input it
     *      contains part information, on return it also contains
     *      the solution and quality metrics.
     */
    void partition(const RCP<PartitioningSolution<Adapter> > &solution);

    mj_partBoxVector_t &getPartBoxesView() const
    {
      RCP<mj_partBoxVector_t> pBoxes = this->getGlobalBoxBoundaries();
      return *pBoxes;
    }

    mj_part_t pointAssign(int dim, mj_scalar_t *point) const;

    void boxAssign(int dim, mj_scalar_t *lower, mj_scalar_t *upper,
                   size_t &nPartsFound, mj_part_t **partsFound) const;


    /*! \brief returns communication graph resulting from MJ partitioning.
     */
    void getCommunicationGraph(
                         const PartitioningSolution<Adapter> *solution,
                         ArrayRCP<mj_part_t> &comXAdj,
                         ArrayRCP<mj_part_t> &comAdj);
};


/*! \brief Multi Jagged  coordinate partitioning algorithm.
 *
 *  \param env   library configuration and problem parameters
 *  \param problemComm the communicator for the problem
 *  \param coords    a CoordinateModel with user data
 *  \param solution  a PartitioningSolution, on input it
 *      contains part information, on return it also contains
 *      the solution and quality metrics.
 */
template <typename Adapter>
void Zoltan2_AlgMJ<Adapter>::partition(
  const RCP<PartitioningSolution<Adapter> > &solution
)
{
    this->set_up_partitioning_data(solution);
    this->set_input_parameters(this->mj_env->getParameters());
    if (this->mj_keep_part_boxes){
        this->mj_partitioner.set_to_keep_part_boxes();
    }
    this->mj_partitioner.set_partitioning_parameters(
                this->distribute_points_on_cut_lines,
                this->max_concurrent_part_calculation,
                this->check_migrate_avoid_migration_option,
                this->minimum_migration_imbalance);

    mj_part_t *result_assigned_part_ids = NULL;
    mj_gno_t *result_mj_gnos = NULL;
    this->mj_partitioner.multi_jagged_part(
                this->mj_env,
                this->mj_problemComm,

                this->imbalance_tolerance,
                this->num_global_parts,
                this->part_no_array,
                this->recursion_depth,

                this->coord_dim,
                this->num_local_coords,
                this->num_global_coords,
                this->initial_mj_gnos,
                this->mj_coordinates,

                this->num_weights_per_coord,
                this->mj_uniform_weights,
                this->mj_weights,
                this->mj_uniform_parts,
                this->mj_part_sizes,

                result_assigned_part_ids,
                result_mj_gnos
                );

    // Reorder results so that they match the order of the input
#if defined(__cplusplus) && __cplusplus >= 201103L
    std::unordered_map<mj_gno_t, mj_lno_t> localGidToLid;
    localGidToLid.reserve(this->num_local_coords);
    for (mj_lno_t i = 0; i < this->num_local_coords; i++)
      localGidToLid[this->initial_mj_gnos[i]] = i;

    ArrayRCP<mj_part_t> partId = arcp(new mj_part_t[this->num_local_coords],
                                      0, this->num_local_coords, true);

    for (mj_lno_t i = 0; i < this->num_local_coords; i++) {
      mj_lno_t origLID = localGidToLid[result_mj_gnos[i]];
      partId[origLID] = result_assigned_part_ids[i];
    }

#else
    Teuchos::Hashtable<mj_gno_t, mj_lno_t>
                       localGidToLid(this->num_local_coords);
    for (mj_lno_t i = 0; i < this->num_local_coords; i++)
      localGidToLid.put(this->initial_mj_gnos[i], i);

    ArrayRCP<mj_part_t> partId = arcp(new mj_part_t[this->num_local_coords],
                                      0, this->num_local_coords, true);

    for (mj_lno_t i = 0; i < this->num_local_coords; i++) {
      mj_lno_t origLID = localGidToLid.get(result_mj_gnos[i]);
      partId[origLID] = result_assigned_part_ids[i];
    }

#endif // C++11 is enabled

    delete [] result_mj_gnos;
    delete [] result_assigned_part_ids;

    solution->setParts(partId);
    this->free_work_memory();
}

/* \brief Freeing the memory allocated.
 * */
template <typename Adapter>
void Zoltan2_AlgMJ<Adapter>::free_work_memory(){
        freeArray<mj_scalar_t *>(this->mj_coordinates);
        freeArray<mj_scalar_t *>(this->mj_weights);
        freeArray<bool>(this->mj_uniform_parts);
        freeArray<mj_scalar_t *>(this->mj_part_sizes);
        freeArray<bool>(this->mj_uniform_weights);

}

/* \brief Sets the partitioning data for multijagged algorithm.
 * */
template <typename Adapter>
void Zoltan2_AlgMJ<Adapter>::set_up_partitioning_data(
  const RCP<PartitioningSolution<Adapter> > &solution
)
{
        this->coord_dim = this->mj_coords->getCoordinateDim();
        this->num_weights_per_coord = this->mj_coords->getNumWeightsPerCoordinate();
        this->num_local_coords = this->mj_coords->getLocalNumCoordinates();
        this->num_global_coords = this->mj_coords->getGlobalNumCoordinates();
        int criteria_dim = (this->num_weights_per_coord ? this->num_weights_per_coord : 1);

        // From the Solution we get part information.
        // If the part sizes for a given criteria are not uniform,
        // then they are values that sum to 1.0.
        this->num_global_parts = solution->getTargetGlobalNumberOfParts();
        //allocate only two dimensional pointer.
        //raw pointer addresess will be obtained from multivector.
        this->mj_coordinates = allocMemory<mj_scalar_t *>(this->coord_dim);
        this->mj_weights = allocMemory<mj_scalar_t *>(criteria_dim);

        //if the partitioning results are to be uniform.
        this->mj_uniform_parts = allocMemory< bool >(criteria_dim);
        //if in a criteria dimension, uniform part is false this shows ratios of
        //the target part weights.
        this->mj_part_sizes =  allocMemory<mj_scalar_t *>(criteria_dim);
        //if the weights of coordinates are uniform in a criteria dimension.
        this->mj_uniform_weights = allocMemory< bool >(criteria_dim);

        typedef StridedData<mj_lno_t, mj_scalar_t> input_t;
        ArrayView<const mj_gno_t> gnos;
        ArrayView<input_t> xyz;
        ArrayView<input_t> wgts;


        this->coordinate_ArrayRCP_holder = new ArrayRCP<const mj_scalar_t> [this->coord_dim + this->num_weights_per_coord];

        this->mj_coords->getCoordinates(gnos, xyz, wgts);
        //obtain global ids.
        ArrayView<const mj_gno_t> mj_gnos = gnos;
        this->initial_mj_gnos = mj_gnos.getRawPtr();

        //extract coordinates from multivector.
        for (int dim=0; dim < this->coord_dim; dim++){
                ArrayRCP<const mj_scalar_t> ar;
                xyz[dim].getInputArray(ar);
                this->coordinate_ArrayRCP_holder[dim] = ar;

                //multiJagged coordinate values assignment
                this->mj_coordinates[dim] =  (mj_scalar_t *)ar.getRawPtr();
        }

        //if no weights are provided set uniform weight.
        if (this->num_weights_per_coord == 0){
                this->mj_uniform_weights[0] = true;
                this->mj_weights[0] = NULL;
        }
        else{
                //if weights are provided get weights for all weight indices
                for (int wdim = 0; wdim < this->num_weights_per_coord; wdim++){
                        ArrayRCP<const mj_scalar_t> ar;
                        wgts[wdim].getInputArray(ar);
                        this->coordinate_ArrayRCP_holder[this->coord_dim + wdim] = ar;
                        this->mj_uniform_weights[wdim] = false;
                        this->mj_weights[wdim] = (mj_scalar_t *) ar.getRawPtr();
                }
        }

        for (int wdim = 0; wdim < criteria_dim; wdim++){
                if (solution->criteriaHasUniformPartSizes(wdim)){
                        this->mj_uniform_parts[wdim] = true;
                        this->mj_part_sizes[wdim] = NULL;
                }
                else{
                        std::cerr << "MJ does not support non uniform target part weights" << std::endl;
                        exit(1);
                }
        }
}

/* \brief Sets the partitioning parameters for multijagged algorithm.
 * \param pl: is the parameter list provided to zoltan2 call
 * */
template <typename Adapter>
void Zoltan2_AlgMJ<Adapter>::set_input_parameters(const Teuchos::ParameterList &pl){

        const Teuchos::ParameterEntry *pe = pl.getEntryPtr("imbalance_tolerance");
        if (pe){
                double tol;
                tol = pe->getValue(&tol);
                this->imbalance_tolerance = tol - 1.0;
        }

    // TODO: May be a more relaxed tolerance is needed. RCB uses 10%
        if (this->imbalance_tolerance <= 0)
                this->imbalance_tolerance= 10e-4;

        //if an input partitioning array is provided.
        this->part_no_array = NULL;
        //the length of the input partitioning array.
        this->recursion_depth = 0;

        if (pl.getPtr<Array <mj_part_t> >("mj_parts")){
                this->part_no_array = (mj_part_t *) pl.getPtr<Array <mj_part_t> >("mj_parts")->getRawPtr();
                this->recursion_depth = pl.getPtr<Array <mj_part_t> >("mj_parts")->size() - 1;
                this->mj_env->debug(2, "mj_parts provided by user");
        }

        //get mj specific parameters.
        this->distribute_points_on_cut_lines = true;
        this->max_concurrent_part_calculation = 1;

        this->mj_run_as_rcb = false;
        int mj_user_recursion_depth = -1;
        this->mj_keep_part_boxes = false;
        this->check_migrate_avoid_migration_option = 0;
        this->minimum_migration_imbalance = 0.35;

        pe = pl.getEntryPtr("mj_minimum_migration_imbalance");
        if (pe){
                double imb;
                imb = pe->getValue(&imb);
                this->minimum_migration_imbalance = imb - 1.0;
        }

        pe = pl.getEntryPtr("mj_migration_option");
        if (pe){
                this->check_migrate_avoid_migration_option = pe->getValue(&this->check_migrate_avoid_migration_option);
        }else {
                this->check_migrate_avoid_migration_option = 0;
        }
        if (this->check_migrate_avoid_migration_option > 1) this->check_migrate_avoid_migration_option = -1;


        pe = pl.getEntryPtr("mj_concurrent_part_count");
        if (pe){
                this->max_concurrent_part_calculation = pe->getValue(&this->max_concurrent_part_calculation);
        }else {
                this->max_concurrent_part_calculation = 1; // Set to 1 if not provided.
        }

        pe = pl.getEntryPtr("mj_keep_part_boxes");
        if (pe){
                this->mj_keep_part_boxes = pe->getValue(&this->mj_keep_part_boxes);
        }else {
                this->mj_keep_part_boxes = false; // Set to invalid value
        }


        // For now, need keep_part_boxes to do pointAssign and boxAssign.
        // pe = pl.getEntryPtr("keep_cuts");
        // if (pe){
        //      int tmp = pe->getValue(&tmp);
        //      if (tmp) this->mj_keep_part_boxes = true;
        // }

        //need to keep part boxes if mapping type is geometric.
        if (this->mj_keep_part_boxes == false){
                pe = pl.getEntryPtr("mapping_type");
                if (pe){
                        int mapping_type = -1;
                        mapping_type = pe->getValue(&mapping_type);
                        if (mapping_type == 0){
                                mj_keep_part_boxes  = true;
                        }
                }
        }

        //need to keep part boxes if mapping type is geometric.
        pe = pl.getEntryPtr("mj_enable_rcb");
        if (pe){
                this->mj_run_as_rcb = pe->getValue(&this->mj_run_as_rcb);
        }else {
                this->mj_run_as_rcb = false; // Set to invalid value
        }

        pe = pl.getEntryPtr("mj_recursion_depth");
        if (pe){
                mj_user_recursion_depth = pe->getValue(&mj_user_recursion_depth);
        }else {
                mj_user_recursion_depth = -1; // Set to invalid value
        }

        bool val = false;
        pe = pl.getEntryPtr("rectilinear");
        if (pe) val = pe->getValue(&val);
        if (val){
                this->distribute_points_on_cut_lines = false;
        } else {
                this->distribute_points_on_cut_lines = true;
        }

        if (this->mj_run_as_rcb){
                mj_user_recursion_depth = (int)(ceil(log ((this->num_global_parts)) / log (2.0)));
        }
        if (this->recursion_depth < 1){
                if (mj_user_recursion_depth > 0){
                        this->recursion_depth = mj_user_recursion_depth;
                }
                else {
                        this->recursion_depth = this->coord_dim;
                }
        }

        this->num_threads = 1;
#ifdef HAVE_ZOLTAN2_OMP
#pragma omp parallel
        {
                this->num_threads = omp_get_num_threads();
        }
#endif

}

/////////////////////////////////////////////////////////////////////////////
template <typename Adapter>
void Zoltan2_AlgMJ<Adapter>::boxAssign(
  int dim,
  typename Adapter::scalar_t *lower,
  typename Adapter::scalar_t *upper,
  size_t &nPartsFound,
  typename Adapter::part_t **partsFound) const
{
  // TODO:  Implement with cuts rather than boxes to reduce algorithmic
  // TODO:  complexity.  Or at least do a search through the boxes, using
  // TODO:  p x q x r x ... if possible.

  nPartsFound = 0;
  *partsFound = NULL;

  if (this->mj_keep_part_boxes) {

    // Get vector of part boxes
    RCP<mj_partBoxVector_t> partBoxes = this->getGlobalBoxBoundaries();

    size_t nBoxes = (*partBoxes).size();
    if (nBoxes == 0) {
      throw std::logic_error("no part boxes exist");
    }

    // Determine whether the box overlaps the globalBox at all
    RCP<mj_partBox_t> globalBox = this->mj_partitioner.get_global_box();

    if (globalBox->boxesOverlap(dim, lower, upper)) {

      std::vector<typename Adapter::part_t> partlist;

      // box overlaps the global box; find specific overlapping boxes
      for (size_t i = 0; i < nBoxes; i++) {
        try {
          if ((*partBoxes)[i].boxesOverlap(dim, lower, upper)) {
            nPartsFound++;
            partlist.push_back((*partBoxes)[i].getpId());

//            std::cout << "Given box (";
//            for (int j = 0; j < dim; j++)
//              std::cout << lower[j] << " ";
//            std::cout << ") x (";
//            for (int j = 0; j < dim; j++)
//              std::cout << upper[j] << " ";
//            std::cout << ") overlaps PartBox "
//                      << (*partBoxes)[i].getpId() << " (";
//            for (int j = 0; j < dim; j++)
//              std::cout << (*partBoxes)[i].getlmins()[j] << " ";
//            std::cout << ") x (";
//            for (int j = 0; j < dim; j++)
//              std::cout << (*partBoxes)[i].getlmaxs()[j] << " ";
//            std::cout << ")" << std::endl;
          }
        }
        Z2_FORWARD_EXCEPTIONS;
      }
      if (nPartsFound) {
        *partsFound = new mj_part_t[nPartsFound];
        for (size_t i = 0; i < nPartsFound; i++)
          (*partsFound)[i] = partlist[i];
      }
    }
    else {
      // Box does not overlap the domain at all.  Find the closest part
      // Not sure how to perform this operation for MJ without having the
      // cuts.  With the RCB cuts, the concept of a part extending to
      // infinity was natural.  With the boxes, it is much more difficult.
      // TODO:  For now, return information indicating NO OVERLAP.

    }
  }
  else {
    throw std::logic_error("need to use keep_cuts parameter for boxAssign");
  }
}

/////////////////////////////////////////////////////////////////////////////
template <typename Adapter>
typename Adapter::part_t Zoltan2_AlgMJ<Adapter>::pointAssign(
  int dim,
  typename Adapter::scalar_t *point) const
{

  // TODO:  Implement with cuts rather than boxes to reduce algorithmic
  // TODO:  complexity.  Or at least do a search through the boxes, using
  // TODO:  p x q x r x ... if possible.

  if (this->mj_keep_part_boxes) {
    typename Adapter::part_t foundPart = -1;

    // Get vector of part boxes
    RCP<mj_partBoxVector_t> partBoxes = this->getGlobalBoxBoundaries();

    size_t nBoxes = (*partBoxes).size();
    if (nBoxes == 0) {
      throw std::logic_error("no part boxes exist");
    }

    // Determine whether the point is within the global domain
    RCP<mj_partBox_t> globalBox = this->mj_partitioner.get_global_box();

    if (globalBox->pointInBox(dim, point)) {

      // point is in the global domain; determine in which part it is.
      size_t i;
      for (i = 0; i < nBoxes; i++) {
        try {
          if ((*partBoxes)[i].pointInBox(dim, point)) {
            foundPart = (*partBoxes)[i].getpId();
//            std::cout << "Point (";
//            for (int j = 0; j < dim; j++) std::cout << point[j] << " ";
//            std::cout << ") found in box " << i << " part " << foundPart
//                      << std::endl;
//            (*partBoxes)[i].print();
            break;
          }
        }
        Z2_FORWARD_EXCEPTIONS;
      }

      if (i == nBoxes) {
        // This error should never occur
        std::ostringstream oss;
        oss << "Point (";
        for (int j = 0; j < dim; j++) oss << point[j] << " ";
        oss << ") not found in domain";
        throw std::logic_error(oss.str());
      }
    }

    else {
      // Point is outside the global domain.
      // Determine to which part it is closest.
      // TODO:  with cuts, would not need this special case

      size_t closestBox = 0;
      mj_scalar_t minDistance = std::numeric_limits<mj_scalar_t>::max();
      mj_scalar_t *centroid = new mj_scalar_t[dim];
      for (size_t i = 0; i < nBoxes; i++) {
        (*partBoxes)[i].computeCentroid(centroid);
        mj_scalar_t sum = 0.;
        mj_scalar_t diff;
        for (int j = 0; j < dim; j++) {
          diff = centroid[j] - point[j];
          sum += diff * diff;
        }
        if (sum < minDistance) {
          minDistance = sum;
          closestBox = i;
        }
      }
      foundPart = (*partBoxes)[closestBox].getpId();
      delete [] centroid;
    }

    return foundPart;
  }
  else {
    throw std::logic_error("need to use keep_cuts parameter for pointAssign");
  }
}

template <typename Adapter>
void Zoltan2_AlgMJ<Adapter>::getCommunicationGraph(
  const PartitioningSolution<Adapter> *solution,
  ArrayRCP<typename Zoltan2_AlgMJ<Adapter>::mj_part_t> &comXAdj,
  ArrayRCP<typename Zoltan2_AlgMJ<Adapter>::mj_part_t> &comAdj)
{
  if(comXAdj_.getRawPtr() == NULL && comAdj_.getRawPtr() == NULL){
    RCP<mj_partBoxVector_t> pBoxes = this->getGlobalBoxBoundaries();
    mj_part_t ntasks =  (*pBoxes).size();
    int dim = (*pBoxes)[0].getDim();
    GridHash<mj_scalar_t, mj_part_t> grid(pBoxes, ntasks, dim);
    grid.getAdjArrays(comXAdj_, comAdj_);
  }
  comAdj = comAdj_;
  comXAdj = comXAdj_;
}


template <typename Adapter>
RCP<typename Zoltan2_AlgMJ<Adapter>::mj_partBoxVector_t>
Zoltan2_AlgMJ<Adapter>::getGlobalBoxBoundaries() const
{
  return this->mj_partitioner.get_kept_boxes();
}


template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
RCP<typename AlgMJ<mj_scalar_t,mj_lno_t,mj_gno_t,mj_part_t>::mj_partBoxVector_t>
AlgMJ<mj_scalar_t,mj_lno_t,mj_gno_t,mj_part_t>::get_kept_boxes() const
{
  if (this->mj_keep_part_boxes)
    return this->kept_boxes;
  else
    throw std::logic_error("Error: part boxes are not stored.");
}

template <typename mj_scalar_t, typename mj_lno_t, typename mj_gno_t,
          typename mj_part_t>
RCP<typename AlgMJ<mj_scalar_t,mj_lno_t,mj_gno_t,mj_part_t>::mj_partBoxVector_t>
AlgMJ<mj_scalar_t,mj_lno_t,mj_gno_t,mj_part_t>::compute_global_box_boundaries(
  RCP<mj_partBoxVector_t> &localPartBoxes
) const
{
  mj_part_t ntasks = this->num_global_parts;
  int dim = (*localPartBoxes)[0].getDim();
  mj_scalar_t *localPartBoundaries = new mj_scalar_t[ntasks * 2 *dim];

  memset(localPartBoundaries, 0, sizeof(mj_scalar_t) * ntasks * 2 *dim);

  mj_scalar_t *globalPartBoundaries = new mj_scalar_t[ntasks * 2 *dim];
  memset(globalPartBoundaries, 0, sizeof(mj_scalar_t) * ntasks * 2 *dim);

  mj_scalar_t *localPartMins = localPartBoundaries;
  mj_scalar_t *localPartMaxs = localPartBoundaries + ntasks * dim;

  mj_scalar_t *globalPartMins = globalPartBoundaries;
  mj_scalar_t *globalPartMaxs = globalPartBoundaries + ntasks * dim;

  mj_part_t boxCount = localPartBoxes->size();
  for (mj_part_t i = 0; i < boxCount; ++i){
    mj_part_t pId = (*localPartBoxes)[i].getpId();
      //cout << "me:" << comm->getRank() << " has:" << pId << endl;

    mj_scalar_t *lmins = (*localPartBoxes)[i].getlmins();
    mj_scalar_t *lmaxs = (*localPartBoxes)[i].getlmaxs();

    for (int j = 0; j < dim; ++j){
      localPartMins[dim * pId + j] = lmins[j];
      localPartMaxs[dim * pId + j] = lmaxs[j];
      /*
      cout << "me:" << comm->getRank()  <<
              " dim * pId + j:"<< dim * pId + j <<
              " localMin:" << localPartMins[dim * pId + j] <<
              " localMax:" << localPartMaxs[dim * pId + j] << endl;
      */
    }
  }

  Teuchos::Zoltan2_BoxBoundaries<int, mj_scalar_t> reductionOp(ntasks * 2 *dim);

  reduceAll<int, mj_scalar_t>(*mj_problemComm, reductionOp,
            ntasks * 2 *dim, localPartBoundaries, globalPartBoundaries);
  RCP<mj_partBoxVector_t> pB(new mj_partBoxVector_t(),true);
  for (mj_part_t i = 0; i < ntasks; ++i){
    Zoltan2::coordinateModelPartBox <mj_scalar_t, mj_part_t> tpb(i, dim,
                                               globalPartMins + dim * i,
                                               globalPartMaxs + dim * i);

    /*
    for (int j = 0; j < dim; ++j){
        cout << "me:" << comm->getRank()  <<
                " dim * pId + j:"<< dim * i + j <<
                " globalMin:" << globalPartMins[dim * i + j] <<
                " globalMax:" << globalPartMaxs[dim * i + j] << endl;
    }
    */
    pB->push_back(tpb);
  }
  delete []localPartBoundaries;
  delete []globalPartBoundaries;
  //RCP <mj_partBoxVector_t> tmpRCPBox(pB, true);
  return pB;
}
} // namespace Zoltan2

#endif