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
//- Class:       ChollaEngine
//- Description: Creates the topology for a given geometry described by facets.
//- Owner:       Steven J. Owen
//- Checked by:
//- Version:
//#include <list>
#include <set>
#include <map>
#include <vector>
#include "CubitDefines.h"
#include "ChollaEngine.hpp"
#include "DLIList.hpp"
#include "TDGeomFacet.hpp"
#include "CastTo.hpp"
#include "ChollaSkinTool.hpp"
#include "ChollaVolume.hpp"
#include "ChollaSurface.hpp"
#include "ChollaCurve.hpp"
#include "ChollaPoint.hpp"
#include "CubitFacet.hpp"
#include "CubitFacetData.hpp"
#include "CubitFacetEdge.hpp"
#include "CubitFacetEdgeData.hpp"
#include "CubitPoint.hpp"
#include "CubitPointData.hpp"
#include "FacetEntity.hpp"
#include "FacetEvalTool.hpp"
#include "FacetDataUtil.hpp"
#include "ChollaDebug.hpp"
#include "TDFacetBoundaryEdge.hpp"
#include "TDFacetBoundaryPoint.hpp"
#include "CurveFacetEvalTool.hpp"
#include "Cholla.h"
#include "GfxDebug.hpp"
#include "TDFacetboolData.hpp"
#include "GMem.hpp"

//============================================================================
//Function:  ChollaEngine (PUBLIC) (constructor)
//============================================================================
ChollaEngine::ChollaEngine()
{
  hashCurveArray = NULL;
  hashCurveSize = 0;
  hashPointArray = NULL;
  hashPointSize = 0;
}

//============================================================================
//Function:  ChollaEngine (PUBLIC) (constructor)
//============================================================================
ChollaEngine::ChollaEngine(DLIList<FacetEntity*> &face_list,
                           DLIList<FacetEntity*> &edge_list,
                           DLIList<FacetEntity*> &point_list )
{
  faceList = face_list;
  edgeList = edge_list;
  pointList = point_list;
  set_up_tool_datas();
  hashCurveArray = NULL;
  hashCurveSize = 0;
  hashPointArray = NULL;
  hashPointSize = 0;
  doFlip = CUBIT_FALSE;
}

//============================================================================
//Function:  ChollaEngine (PUBLIC) (constructor)
//============================================================================
ChollaEngine::ChollaEngine(DLIList<CubitFacet*>     &facet_list,
                           DLIList<CubitFacetEdge*> &edge_list,
                           DLIList<CubitPoint*>     &point_list )
{
  CAST_LIST(facet_list, faceList, FacetEntity);
  CAST_LIST(edge_list, edgeList, FacetEntity);
  CAST_LIST(point_list, pointList, FacetEntity);
  set_up_tool_datas();
  hashCurveArray = NULL;
  hashCurveSize = 0;
  hashPointArray = NULL;
  hashPointSize = 0;
  doFlip = CUBIT_FALSE;
}

//============================================================================
//Function:  ChollaEngine (PUBLIC) (constructor)
//Notes: This case is used only when the cholla entities have been generated 
//       directly rather than using create_geometry
//       Does not use the TDGeomFacet Tooldatas
//============================================================================
ChollaEngine::ChollaEngine(DLIList<CubitFacet*>     &facet_list,
                           DLIList<CubitFacetEdge*> &edge_list,
                           DLIList<CubitPoint*>     &point_list,
                           DLIList<ChollaVolume *>  &cholla_volumes,
                           DLIList<ChollaSurface *> &cholla_surfaces,
                           DLIList<ChollaCurve *>   &cholla_curves,
                           DLIList<ChollaPoint *>   &cholla_points )
{
  CAST_LIST(facet_list, faceList, FacetEntity);
  CAST_LIST(edge_list, edgeList, FacetEntity);
  CAST_LIST(point_list, pointList, FacetEntity);
  //set_up_tool_datas();  TDGeomFacet tooldatas should have already been added

  hashCurveArray = NULL;
  hashCurveSize = 0;
  hashPointArray = NULL;
  hashPointSize = 0;
  doFlip = CUBIT_FALSE;
  
  chollaVolumeList = cholla_volumes;
  chollaSurfaceList = cholla_surfaces;
  chollaCurveList = cholla_curves;
  chollaPointList = cholla_points;
}
                          

//============================================================================
//Function:  set_up_tool_datas
//============================================================================
void ChollaEngine::set_up_tool_datas( )
{
  int ii;
  FacetEntity *fe_ptr;
  for (ii=0; ii<faceList.size(); ii++)
  {
    fe_ptr = faceList.get_and_step();
    TDGeomFacet::add_geom_facet( fe_ptr, -1 );
  }
  for (ii=0; ii<pointList.size(); ii++)
  {
    fe_ptr = pointList.get_and_step();
    TDGeomFacet::add_geom_facet( fe_ptr, -1 );
  }
}

CubitStatus ChollaEngine::build_eval_tools()
{
  CubitBoolean use_feature_angle = CUBIT_FALSE; 
  double min_dot = 0.0;                    
  int interp_order = 0;                 
  CubitBoolean smooth_non_manifold = CUBIT_FALSE;
  CubitBoolean split_surfaces = CUBIT_FALSE;

  return build_eval_tools( chollaSurfaceList,
                           chollaCurveList,
                           interp_order, use_feature_angle, 
                           min_dot, smooth_non_manifold,
                           split_surfaces );
}

//============================================================================
//Function:  delete_tool_datas
//============================================================================
void ChollaEngine::delete_tool_datas( )
{
  int ii;
  FacetEntity *fe_ptr;
  for (ii=0; ii<faceList.size(); ii++)
  {
    fe_ptr = faceList.get_and_step();
    fe_ptr->delete_TD( &TDGeomFacet::is_geom_facet );
  }
  for (ii=0; ii<edgeList.size(); ii++)
  {
    fe_ptr = edgeList.get_and_step();
    fe_ptr->delete_TD( &TDGeomFacet::is_geom_facet );
  }
  for (ii=0; ii<pointList.size(); ii++)
  {
    fe_ptr = pointList.get_and_step();
    fe_ptr->delete_TD( &TDGeomFacet::is_geom_facet );
  }
}

//============================================================================
//Function:  delete_eval_tools
//============================================================================
void ChollaEngine::delete_eval_tools()
{

  delete_tool_datas();
  int ii;
  ChollaSurface *cs_ptr = NULL;
  FacetEvalTool *fe_tool_ptr;
  for (ii = chollaSurfaceList.size(); ii > 0; ii-- )
  {
    cs_ptr = chollaSurfaceList.get_and_step();
    fe_tool_ptr = cs_ptr->get_eval_tool();
    if (fe_tool_ptr)
      delete fe_tool_ptr;
  }
  ChollaCurve *cc_ptr = NULL;
  CurveFacetEvalTool *ce_tool_ptr;
  for (ii = chollaCurveList.size(); ii > 0; ii-- )
  {
    cc_ptr = chollaCurveList.get_and_step();
    ce_tool_ptr = cc_ptr->get_eval_tool();
    if (ce_tool_ptr)
      delete ce_tool_ptr;
  }
  faceList.clean_out();
  edgeList.clean_out();
  pointList.clean_out();
}

//============================================================================
//Function:  delete_eval_tools_but_not_facets
//============================================================================
void ChollaEngine::delete_eval_tools_but_not_facets()
{

  delete_tool_datas();
  int ii;
  ChollaSurface *cs_ptr = NULL;
  FacetEvalTool *fe_tool_ptr;
  for (ii = chollaSurfaceList.size(); ii > 0; ii-- )
  {
    cs_ptr = chollaSurfaceList.get_and_step();
    fe_tool_ptr = cs_ptr->get_eval_tool();
    if (fe_tool_ptr)
    {
      DLIList<CubitFacet *>facets;
      fe_tool_ptr->remove_facets(facets);
      delete fe_tool_ptr;
    }
  }
  ChollaCurve *cc_ptr = NULL;
  CurveFacetEvalTool *ce_tool_ptr;
  for (ii = chollaCurveList.size(); ii > 0; ii-- )
  {
    cc_ptr = chollaCurveList.get_and_step();
    ce_tool_ptr = cc_ptr->get_eval_tool();
    if (ce_tool_ptr)
    {
      delete ce_tool_ptr;
    }
  }
  faceList.clean_out();
  edgeList.clean_out();
  pointList.clean_out();
}

//============================================================================
//Function:  ~ChollaEngine (PUBLIC) (destructor)
//============================================================================
ChollaEngine::~ChollaEngine()
{
}

//============================================================================
//Function:  delete (PUBLIC)
//Description: removes all cholla entities stored with the cholla engine
//             usually called before destructor
//============================================================================
void ChollaEngine::delete_me()
{
  delete_tool_datas();
  int ii;
    //clean up any data remaining.
  for (ii = chollaPointList.size(); ii > 0; ii-- )
    delete chollaPointList.remove();
  for (ii = chollaCurveList.size(); ii > 0; ii-- )
    delete chollaCurveList.remove();
  for (ii = chollaSurfaceList.size(); ii > 0; ii-- )
    delete chollaSurfaceList.remove();
  
}

//==================================================================================
//Function:  create_geometry (PUBLIC)
//Description:  Interface function to acutally create the topology
//              for the given mesh.
//==================================================================================
CubitStatus ChollaEngine::create_geometry(
  CubitBoolean use_feature_angle,   // use an angle to define where to break surfaces
  double angle,                     // the feature angle
  int interp_order,                 // 0=linear, 4=b-spline patches
  CubitBoolean smooth_non_manifold, // check for continuity accross >2 valence edges
  CubitBoolean split_surfaces)      // create new FacetEntities to split surfaces at
                                    // at features.  Otherwise - don't mess with the
                                    // FacetEntities. (creates TDs instead)

{
  if (0)
  {
    dump("cyl.cholla", angle);
  }

  //- convert feature angle to a dot product

  double min_dot = 0.0;
  if (use_feature_angle)
  {
    if (angle > 180.0) angle = 180.0;
    if (angle < 0.0) angle = 0.0;
    double rad_angle = (180.0 - angle) * CUBIT_PI / 180.0;
    min_dot = cos( rad_angle );
  }

  //- create one facet surface to start with

  ChollaSkinTool c_skin_tool;
  ChollaSurface *cholla_surface_ptr = NULL;
  CubitStatus stat = c_skin_tool.skin_2d(faceList, cholla_surface_ptr);
  if ( stat != CUBIT_SUCCESS )
    return stat;
  if ( cholla_surface_ptr )
    chollaSurfaceList.append(cholla_surface_ptr);

  // before building the surfaces, orient the facets so they are consistent
  
  DLIList<CubitFacet *>total_facet_list;
  CAST_LIST( faceList, total_facet_list, CubitFacet );
  //stat = check_all_facet_orientations( total_facet_list, doFlip );
  if (stat!=CUBIT_SUCCESS)
    return stat;
  
  // generate the topology from the facets

  stat = create_volume_boundaries( chollaSurfaceList,
                                   use_feature_angle, min_dot, 
                                   split_surfaces );
  if ( stat == CUBIT_FAILURE )
    return stat;

  stat = create_surface_boundaries( chollaSurfaceList, chollaCurveList,
                                    use_feature_angle, min_dot );
  if ( stat == CUBIT_FAILURE )
    return stat;

  stat = create_curve_boundaries( chollaCurveList, chollaPointList );
  if ( stat == CUBIT_FAILURE )
    return stat;

    // Okay.  Now we are ready to actually build the geometry.
  int mydebug = 0;<--- Assignment 'mydebug=0', assigned value is 0
  if (mydebug)<--- Condition 'mydebug' is always false
    print_me();

  stat = build_eval_tools( chollaSurfaceList,
                           chollaCurveList,
                           interp_order, use_feature_angle, 
                           min_dot, smooth_non_manifold,
                           split_surfaces );

  return stat;
}

//=============================================================================
//Function:  create_volume_boundaries (PRIVATE)
//Description: creates the surfaces based on the sideset and element block
//             information
//Author: sjowen
//Date: 10/17/00
//=============================================================================
CubitStatus ChollaEngine::create_volume_boundaries( 
  DLIList<ChollaSurface*> &cholla_surface_sheets,  // output global list of surfaces
  CubitBoolean use_feature_angle,   // define surfaces based on feature angle
  double min_dot,      // minimum dot product between face normals
  CubitBoolean split_surfaces )  // create new FacetEntities to split surfaces at
                                 // at features.  Otherwise - don't mess with the
                                 // FacetEntities. (creates TDs instead)
{
  CubitStatus rv = CUBIT_SUCCESS;

  // Split these surfaces so that there is only one set of continuous
  // faces per surface 

  int ii;
  int num_surfaces = cholla_surface_sheets.size();
  cholla_surface_sheets.reset();
  for ( ii = num_surfaces; ii > 0; ii-- )
  {

    ChollaSurface *chsurf_ptr = cholla_surface_sheets.get_and_step();

    DLIList<FacetEntity*> surf_facet_list;
    FacetEntity *sfacet;    
    chsurf_ptr->get_facets(surf_facet_list);
    DLIList<CubitFacet*> facet_list;
    CubitFacet *facet;
    CubitFacetEdge *fedge;
    int kk, mm;
    int mydebug = 0;<--- Assignment 'mydebug=0', assigned value is 0
    if(mydebug){<--- Condition 'mydebug' is always false
      GfxDebug::clear();
    }
    DLIList<CubitFacetEdge *> feature_edge_list;
    for ( kk = surf_facet_list.size(); kk > 0; kk-- ) {
      sfacet = surf_facet_list.get_and_step();
      facet_list.clean_out();
      sfacet->facets(facet_list);
      facet = facet_list.get();
      TDFacetboolData* tdf = TDFacetboolData::get(facet);
      if ( tdf ) {
        int *cptr;
        cptr = tdf->get_edge_indices( (bool) facet->is_backwards());
        for ( mm = 0; mm < 3; mm++ ) {
          if ( cptr[mm] != 0 ) {
            fedge = facet->edge((2+mm)%3);
            if(mydebug){
              if(facet->is_backwards()){
                facet->edge((1+mm)%3)->debug_draw(CUBIT_GREEN_INDEX);
                facet->edge((mm)%3)->debug_draw(CUBIT_RED_INDEX);
              
                fedge->debug_draw(CUBIT_BLUE_INDEX);
              }
              else
                fedge->debug_draw(CUBIT_WHITE_INDEX);
            }
            
            TDGeomFacet::add_geom_facet(fedge, -1);
            fedge->set_as_feature();
            feature_edge_list.append( fedge );
          }            
        }
      }
    }
    if(mydebug){
      GfxDebug::mouse_xforms();
    }
    // make a list of feature edges

    rv = chsurf_ptr->add_preexisting_feature_edges( feature_edge_list );
		if (rv != CUBIT_SUCCESS)
			return rv;
		
    if (use_feature_angle)
    {
      rv = chsurf_ptr->feature_angle( min_dot, feature_edge_list );
    }
    else
    {
      rv = chsurf_ptr->non_manifold_edges( feature_edge_list );
    }
    if (rv != CUBIT_SUCCESS)
      return rv;

     // crack the surface at the feature edges.  create new edges and
     // points so the facet representation is discontinuous.

    rv = make_features( feature_edge_list, split_surfaces );
    if (rv != CUBIT_SUCCESS)
       return rv;

    // split up the surface

    rv = chsurf_ptr->split_surface( cholla_surface_sheets );
    if (rv != CUBIT_SUCCESS)
       return rv;
  }

  // Clean up any edges that do not form complete loops as a result of 
  // feature angle.  For this implementation we will allow features to exist
  // within the surface without defining a complete loop. -- so the next
  // piece of code is never executed.

  CubitBoolean use_complete_loops_only = CUBIT_FALSE;
  if (use_feature_angle && use_complete_loops_only)
  {
    for ( ii = cholla_surface_sheets.size(); ii > 0; ii-- )
    {
      ChollaSurface *chsurf_ptr = cholla_surface_sheets.get_and_step();
      chsurf_ptr->clean_features();
    }
  }

  // Now that we've broken everything into surfaces, update the surface IDs
  // on the boundary facet tool data

  if (!split_surfaces)
  {
    for ( ii = cholla_surface_sheets.size(); ii > 0; ii-- )
    {
      ChollaSurface *chsurf_ptr = cholla_surface_sheets.get_and_step();
      chsurf_ptr->update_boundary_tool_data();
    }
  }
  return rv;
}


//=============================================================================
//Function:  create_surface_boundaries (PRIVATE)
//Description: creates the curves based on the facet surface information
//Author: sjowen
//Date: 12/3/00
//=============================================================================
CubitStatus ChollaEngine::create_surface_boundaries(
  DLIList<ChollaSurface*> &cholla_surface_list, // global list of surfaces
  DLIList<ChollaCurve*> &cholla_curve_list,     // output global list of curves
  CubitBoolean use_feature_angle,
  double min_dot )
{
  CubitStatus stat = CUBIT_SUCCESS;

    // determine the boundaries for each surface.  One curve per surface

  int ii;
  for ( ii = cholla_surface_list.size(); ii > 0; ii-- )
  {
    ChollaSurface *chsurf_ptr = cholla_surface_list.get_and_step();
    DLIList<ChollaCurve*> chcurve_list;
    chsurf_ptr->get_curves( chcurve_list );
    if (chcurve_list.size() == 0)
    {
      DLIList<FacetEntity*> facet_list;
      chsurf_ptr->get_facets(facet_list);
      ChollaSkinTool c_skin_tool;
      stat = c_skin_tool.skin_2d(facet_list, chsurf_ptr);
      if ( stat != CUBIT_SUCCESS )
        return stat;
    }
  }

  // create a hash list of curves - to speed up classification

  stat = init_hash_curves();
  if (stat != CUBIT_SUCCESS)
  {
    delete_hash_curves();
    return stat;
  }

  // loop through each of the edges on the surfaces
  // Determine which curve it is a part of.
  // Create a new ChollaCurve for each curve
  // Curves are created wherever there is a unique set of associated
  // surfaces 

  int jj, kk;
  for ( ii = cholla_surface_list.size(); ii > 0; ii-- )
  {

    ChollaSurface *chsurf_ptr = cholla_surface_list.get_and_step();
    DLIList<ChollaCurve*> chcurve_list;
    chsurf_ptr->get_curves( chcurve_list );

    // curently there should only be one curve list per surface

    for (jj=chcurve_list.size(); jj>0; jj--)
    {
      ChollaCurve *chcurv_ptr = chcurve_list.get_and_step();
      DLIList<FacetEntity*> facet_list =  chcurv_ptr->get_facet_list();
      FacetEntity *edge_ptr;
      for ( kk = 0; kk < facet_list.size(); kk++)
      {
        edge_ptr = facet_list.get_and_step();
        stat = classify_edge( edge_ptr, cholla_curve_list, chsurf_ptr );
        if (stat != CUBIT_SUCCESS) 
          return stat;
      }

      // delete this ChollaCurve - it should have been replaced by one
      // or more curves bounding this surface

      chsurf_ptr->remove_curve( chcurv_ptr );
      delete chcurv_ptr;
    }
  }
  delete_hash_curves();

  // Split these curves so that there is only one string of continuous
  // edges per curve (it will also order the edges and set the start
  // and end nodes for each curve) 

  int num_curves = cholla_curve_list.size();

  cholla_curve_list.reset();
  for ( ii = num_curves; ii > 0 && stat == CUBIT_SUCCESS; ii-- )
  {
    ChollaCurve *chcurv_ptr = cholla_curve_list.get();

    // if necessary mark nodes that will serve as feature breaks (vertices 
    // will be generatedat them)

    if (use_feature_angle)
    {
      stat = chcurv_ptr->feature_angle( min_dot );
      if (stat != CUBIT_SUCCESS)
         return stat;
    }

    // split the curve based on various criteria

    stat = chcurv_ptr->split_curve( cholla_curve_list );

    // delete this curve (new curves were created in split_curve)

    delete chcurv_ptr;
    cholla_curve_list.change_to(NULL);
    cholla_curve_list.step();
  }
  cholla_curve_list.remove_all_with_value(NULL);

  // update the point->curve associativity

  for (ii=0; ii<cholla_curve_list.size(); ii++)
  {
    ChollaCurve *chcurv_ptr = cholla_curve_list.get_and_step();
    CubitPoint *start_ptr, *end_ptr;
    chcurv_ptr->get_ends( start_ptr, end_ptr );
    TDGeomFacet *td = TDGeomFacet::get_geom_facet( start_ptr );
    td->add_cholla_curve( chcurv_ptr );
    td = TDGeomFacet::get_geom_facet( end_ptr );
    td->add_cholla_curve( chcurv_ptr );
  }

  return stat;
}

//=============================================================================
//Function:  init_hash_curves (PRIVATE)
//Description: create a hash array of all curves.  They are hashed based on the
//             smallest id of any surface attached to the curve 
//Author: sjowen
//Date: 3/7/01
//=============================================================================
CubitStatus ChollaEngine::init_hash_curves( )
{
  /* === find the next highest prime number */

  int num_surfs = chollaSurfaceList.size();
  int i;
  hashCurveSize = num_surfs;
  if (num_surfs < 30) hashCurveSize = 31;
  else 
  {
    i=2;
    while (i<hashCurveSize*0.5 + 1) {
      if (hashCurveSize % i == 0) {
        i=2;
        hashCurveSize++;
      }
      else {
        i++;
      }
    }
  }
  hashCurveArray = new DLIList<ChollaCurve*>[hashCurveSize];

  int key = 0;<--- Variable 'key' is assigned a value that is never used.
  ChollaCurve *chcurv_ptr;
  DLIList<ChollaSurface*> *fsm_list_ptr; 
  for (i=0; i<chollaCurveList.size(); i++)
  {
    chcurv_ptr = chollaCurveList.get_and_step();
    fsm_list_ptr = chcurv_ptr->get_surface_list_ptr();
    key = get_curve_hash_key( fsm_list_ptr );
    hashCurveArray[key].append( chcurv_ptr );   
  }
  return CUBIT_SUCCESS;
}

//=============================================================================
//Function:  delete_hash_curves (PRIVATE)
//Description: delete the hash curve stuff
//Author: sjowen
//Date: 3/7/01
//=============================================================================
void ChollaEngine::delete_hash_curves( )
{
  if (hashCurveArray)
   delete [] hashCurveArray;
  hashCurveArray = NULL;
  hashCurveSize = 0;
}

//=============================================================================
//Function:  get_curve_hash_key (PRIVATE)
//Description: 
//Author: sjowen
//Date: 3/7/01
//=============================================================================
int ChollaEngine::get_curve_hash_key(
  DLIList<ChollaSurface*> *fsm_list_ptr )
{
  int key, j;
  ChollaSurface *chsurf_ptr;
  if (fsm_list_ptr->size() == 0)
  {
    key = 0;
  }
  else
  {
    key = INT_MAX;
    for (j=0; j<fsm_list_ptr->size(); j++)
    {
      chsurf_ptr = fsm_list_ptr->get_and_step();
      if (chsurf_ptr->get_id() < key)
        key = chsurf_ptr->get_id();
    }
  }
  key = key % hashCurveSize;
  return key;
}


//=============================================================================
//Function:  classify_edge (PRIVATE)
//Description: sorts a edge into its correct curve based on its associated
//             surfaces and sidesets/nodesets.  Creates a new block curve if 
//             necessary.
//Author: sjowen
//Date: 12/3/00
//=============================================================================
CubitStatus ChollaEngine::classify_edge(
  FacetEntity *edge_ptr,       // the edge we are classifying
  DLIList<ChollaCurve*> &cholla_curve_list,  // add to one of these
  ChollaSurface *cholla_surf_mesh_ptr )   // the current surface
{
  CubitStatus rv = CUBIT_SUCCESS;

  // see if we have already classified this edge (from another surface)

  TDGeomFacet *td_gm_edge = TDGeomFacet::get_geom_facet(edge_ptr);
  if (td_gm_edge->get_hit_flag() != 0)
    return rv;
  td_gm_edge->set_hit_flag(1);

  // get the surfaces adjacent to this edge

  DLIList<ChollaSurface*> this_chsurf_list;
  td_gm_edge->get_cholla_surfs( this_chsurf_list );
  int this_num_adj = this_chsurf_list.size();
   
  // see if the surfaces defined on this face match any 
  // of the existing block curves

  DLIList<ChollaSurface*> *chsurf_list_ptr;
  ChollaCurve *chcurv_ptr = NULL;
  int found = 0;
  int key = get_curve_hash_key( &this_chsurf_list );
  int ii;
  for (ii=0; ii<hashCurveArray[key].size() && !found; ii++)
  {
    chcurv_ptr = hashCurveArray[key].get();
    // the first one checked should be the same as the last one checked (don't
    // use get_and_step here)  This should speed things up

    // check if surfaces are the same

    chsurf_list_ptr = chcurv_ptr->get_surface_list_ptr( );
    int num_adj = chsurf_list_ptr->size();
    if (num_adj == this_num_adj)
    {
      found = 1;
      int jj, kk;
      for (jj=chsurf_list_ptr->size(); jj>0 && found; jj--)
      {
        int same_surf = 0;
        ChollaSurface *chsurf_ptr = chsurf_list_ptr->get_and_step();
        for(kk=this_chsurf_list.size(); kk>0 && !same_surf; kk--)
        {
          ChollaSurface *this_chsurf_ptr = this_chsurf_list.get_and_step();
          if (this_chsurf_ptr == chsurf_ptr)
          {
            same_surf = 1;
          }
        }
        if (!same_surf)
          found = 0;
      }
    }
    if (!found)
      hashCurveArray[key].step();
  }

  // if the unique set of surfaces that this edge is associated 
  // with was found to already exist for a facet curve -- add the
  // edge to the block curve

  if (found)
  {

    // add the edge to the block curve mesh (make sure it is only added once)

    //int was_added = 
    chcurv_ptr->add_facet_unique( edge_ptr );

    // add the curve to the surface (if needed)

    cholla_surf_mesh_ptr->add_curve_unique( chcurv_ptr );

    // add the curve to the edge
  
    td_gm_edge->add_cholla_curve( chcurv_ptr );
  }

  // if the unique set of surfaces that this edge is associated
  // with is not found, then create a new facet curve and add the edge to it

  else
  {

    // create it and update surface and nodeset info

    int block_id = td_gm_edge->get_block_id();
    ChollaCurve *new_chcurv_ptr = new ChollaCurve( block_id ); 
    for (int mm=0; mm<this_num_adj; mm++)
    {
      new_chcurv_ptr->add_surface( this_chsurf_list.get_and_step() );
    }

    // add the edge

    new_chcurv_ptr->add_facet( edge_ptr );

    // update the surface with this new curve

    cholla_surf_mesh_ptr->add_curve( new_chcurv_ptr );

    // add the new curve to the global list

    cholla_curve_list.append( new_chcurv_ptr ); 

    // add the curve to the edge
  
    td_gm_edge->add_cholla_curve( new_chcurv_ptr );

    // add the new curve to the hash table

    hashCurveArray[key].append( new_chcurv_ptr );
  }
  return rv;
}

//=============================================================================
//Function:  create_curve_boundaries (PRIVATE)
//Description: creates the points based on the nodeset and curve information
//Author: sjowen
//Date: 12/6/00
//=============================================================================
CubitStatus ChollaEngine::create_curve_boundaries(
  DLIList<ChollaCurve*> &cholla_curve_list,   // global list of curves
  DLIList<ChollaPoint*> &cholla_point_list )  // output global list of points
{

  CubitStatus stat = CUBIT_SUCCESS;

  // hash the points for speed

  stat = init_hash_points();
  if (stat != CUBIT_SUCCESS)
  {
    delete_hash_points();
    return stat;
  }

  // loop through each of the end nodes on the curves
  // Determine which point it is a part of.
  // Create a new ChollaPoint for each point

  //int mydebug = 0;
  int ii, kk;
  for ( ii = cholla_curve_list.size(); ii > 0; ii-- )
  {
    ChollaCurve *chcurv_ptr = cholla_curve_list.get_and_step();
    CubitPoint *point_ptr[2];
    chcurv_ptr->get_ends( point_ptr[0], point_ptr[1] );
    for ( kk = 0; kk < 2; kk++)
    {
      stat = classify_point( point_ptr[kk], cholla_point_list, chcurv_ptr );
      if (stat != CUBIT_SUCCESS)
      {
        delete_hash_points();
        return stat;
      }
    }
  }
  delete_hash_points();
  return stat;
}

//=============================================================================
//Function:  classify_point (PRIVATE)
//Description: sorts a point into its correct point based on its associated
//             curve.  Creates a new block point if necessary
//Author: sjowen
//Date: 12/6/00
//=============================================================================
CubitStatus ChollaEngine::classify_point(
  CubitPoint *point_ptr,                     // the node to classify
  DLIList<ChollaPoint*> &cholla_point_list,   // global list of points
  ChollaCurve *chcurv_ptr )                 // curve that the end point is on
{
  int ii;
  int found = 0;
  TDGeomFacet *td_node = TDGeomFacet::get_geom_facet( point_ptr );
  ChollaPoint *chpnt_ptr = NULL;
  DLIList<ChollaCurve*> fcm_list;
  td_node->get_cholla_curves(fcm_list);
  int key = get_point_hash_key( &fcm_list );
  for (ii = 0; ii < hashPointArray[key].size() && !found; ii++)
  {
    chpnt_ptr = hashPointArray[key].get();
    FacetEntity *this_point_ptr = chpnt_ptr->get_facets();
    if (this_point_ptr == point_ptr)
    {
      found = 1;
    }
    else
    {
      hashPointArray[key].step();
    }
  } 

  if (found)
  {
    chpnt_ptr->add_curve( chcurv_ptr );
    chcurv_ptr->add_point( chpnt_ptr );
  }
  else
  {
    ChollaPoint *new_chpnt_ptr = new ChollaPoint(); 
    new_chpnt_ptr->add_facet( point_ptr );
    new_chpnt_ptr->add_curve( chcurv_ptr );
    chcurv_ptr->add_point( new_chpnt_ptr );
    cholla_point_list.append( new_chpnt_ptr );
    hashPointArray[key].append( new_chpnt_ptr );
  }
  return CUBIT_SUCCESS;
}

//=============================================================================
//Function:  init_hash_points (PRIVATE)
//Description: create a hash array of all points.  They are hashed based on the
//             smallest id of any curve attached to the curve 
//Author: sjowen
//Date: 3/7/01
//=============================================================================
CubitStatus ChollaEngine::init_hash_points( )
{
  /* === find the next highest prime number */

  int num_curves = chollaCurveList.size();
  int i;
  hashPointSize = num_curves;
  if (num_curves < 30) hashPointSize = 31;
  else 
  {
    i=2;
    while (i<hashPointSize*0.5 + 1) {
      if (hashPointSize % i == 0) {
        i=2;
        hashPointSize++;
      }
      else {
        i++;
      }
    }
  }
  hashPointArray = new DLIList<ChollaPoint*>[hashPointSize];

  int key = 0;<--- Variable 'key' is assigned a value that is never used.
  ChollaPoint *chpnt_ptr;
  DLIList<ChollaCurve*> *fcm_list_ptr; 
  for (i=0; i<chollaPointList.size(); i++)
  {
    chpnt_ptr = chollaPointList.get_and_step();
    fcm_list_ptr = chpnt_ptr->get_curve_list_ptr();
    key = get_point_hash_key( fcm_list_ptr );
    hashPointArray[key].append( chpnt_ptr );   
  }
  return CUBIT_SUCCESS;
}

//=============================================================================
//Function:  delete_hash_points (PRIVATE)
//Description: delete the hash point stuff
//Author: sjowen
//Date: 3/7/01
//=============================================================================
void ChollaEngine::delete_hash_points( )
{
  if (hashPointArray)
   delete [] hashPointArray;
  hashPointArray = NULL;
  hashPointSize = 0;
}

//=============================================================================
//Function:  get_point_hash_key (PRIVATE)
//Description: 
//Author: sjowen
//Date: 3/7/01
//=============================================================================
int ChollaEngine::get_point_hash_key(
  DLIList<ChollaCurve*> *fcm_list_ptr )
{
  int key, j;
  ChollaCurve *chcurv_ptr;
  if (fcm_list_ptr->size() == 0)
  {
    key = 0;
  }
  else
  {
    key = INT_MAX;
    for (j=0; j<fcm_list_ptr->size(); j++)
    {
      chcurv_ptr = fcm_list_ptr->get_and_step();
      if (chcurv_ptr->get_id() < key)
        key = chcurv_ptr->get_id();
    }
  }
  key = key % hashPointSize;
  return key;
}

//=============================================================================
//Function:  facet_dimension (PRIVATE)
//Description: returns the dimension of a mesh entity.
//=============================================================================
int ChollaEngine::facet_dimension(FacetEntity *facet_ptr)
{
  if (CAST_TO(facet_ptr, CubitFacet) != NULL)
    return 2;
  if (CAST_TO(facet_ptr, CubitFacetEdge) != NULL)
    return 1;
  if (CAST_TO(facet_ptr, CubitPoint) != NULL)
    return 0;
  return -1;
}


//===============================================================================
//Function:  build_eval_tools (PRIVATE)
//Description:  build the CUBIT geometry based on the Facet entity class lists
//===============================================================================
CubitStatus ChollaEngine::build_eval_tools(
  DLIList<ChollaSurface*> &cholla_surface_list,
  DLIList<ChollaCurve*> &cholla_curve_list,
  int interp_order,
  CubitBoolean use_feature_angle,
  double min_dot,
  CubitBoolean smooth_non_manifold,
  CubitBoolean split_surfaces )
{
  CubitStatus stat = CUBIT_SUCCESS;  

  if (stat == CUBIT_SUCCESS)
    stat = build_surface_and_curve_eval_tools( cholla_surface_list,
                                   interp_order, min_dot );  
  if (stat == CUBIT_SUCCESS)
    stat = build_curve_eval_tools( cholla_curve_list, interp_order );

  if (stat == CUBIT_SUCCESS)
    if (interp_order == 4)
      stat = clean_geometry( smooth_non_manifold, split_surfaces,
                           use_feature_angle, min_dot, cholla_curve_list );
  return stat;
}


//===============================================================================
//Function:  build_curve_eval_tools (PRIVATE)
//Description:  From the cholla curve list, create CurveFacetEvalTools
//===============================================================================
CubitStatus ChollaEngine::build_curve_eval_tools(
  DLIList<ChollaCurve*> &cholla_curve_list,
  int /* interp_order */)
{
  CubitStatus stat = CUBIT_SUCCESS;
  int kk;
  for ( kk = cholla_curve_list.size(); kk > 0; kk-- )
  {
    ChollaCurve *chcurv_ptr = cholla_curve_list.get_and_step();
    CurveFacetEvalTool *curv_eval_tool_ptr = chcurv_ptr->get_eval_tool();<--- Shadowed declaration
    if (curv_eval_tool_ptr == NULL)
    {
      CubitPoint *start_point, *end_point;
      chcurv_ptr->get_ends( start_point, end_point );
      
      // if this is a curve without a parent surface then handle it 
      // differently.  (Curves with parents use the surface to evaluate to
      // With only a curve, it must evaluate to the curve)
      // Note the CurveFacetEvalTool for curves that have parent surfaces
      // are computed in build_surface_eval_tools
      
      DLIList<ChollaSurface*> chsurf_list = chcurv_ptr->get_surfaces();
      if (chsurf_list.size() == 0)
      {
        DLIList<FacetEntity*> facet_list;
        DLIList<CubitPoint*> point_list;  // needs to be filled in
        facet_list = chcurv_ptr->get_facet_list();
        DLIList<CubitFacetEdge*> edge_list;
        CAST_LIST( facet_list, edge_list, CubitFacetEdge );
        if (stat != CUBIT_SUCCESS)
          return stat;     

        curv_eval_tool_ptr = new CurveFacetEvalTool;
        stat = curv_eval_tool_ptr->initialize( edge_list, point_list );

        if ( stat != CUBIT_SUCCESS )
        {
            return stat;
        }
        chcurv_ptr->assign_eval_tool(curv_eval_tool_ptr);
      }
      else
      {       
        //fix up the orientation of the Cholla curve
        stat = chcurv_ptr->order_edges();
        if ( stat != CUBIT_SUCCESS )
        {         
          return stat;
        }
        
        DLIList<FacetEntity*> facet_ents;
        facet_ents = chcurv_ptr->get_facet_list();
        DLIList<CubitFacetEdge*> edge_facets;
        CAST_LIST(facet_ents, edge_facets, CubitFacetEdge );
        DLIList<CubitPoint*> ordered_points;
        
        for( int k=0; k<edge_facets.size(); k++ )
        {
          CubitFacetEdge *tmp_edge = edge_facets.get_and_step();          
          if( k==0 )
          {
            ordered_points.append( tmp_edge->point(0) );            
            ordered_points.append( tmp_edge->point(1) );            
          }
          else        
            ordered_points.append( tmp_edge->point(1) );                      
        }     

        FacetEvalTool *surf_eval_tool = chsurf_list.get()->get_eval_tool();
        CurveFacetEvalTool *curv_eval_tool_ptr = new CurveFacetEvalTool;       <--- Shadow variable
        edge_facets.reset();        
        stat = curv_eval_tool_ptr->initialize( edge_facets, ordered_points, surf_eval_tool );          

        if ( stat != CUBIT_SUCCESS )
        {
          return stat;
        }
        chcurv_ptr->assign_eval_tool( curv_eval_tool_ptr );           
      }
    }   
  }
  return stat;
}

//===============================================================================
//Function:  build_surface_eval_tools (PRIVATE)
//Description:  From the facet surface list, create the FacetEvalTools
//===============================================================================
CubitStatus ChollaEngine::build_surface_and_curve_eval_tools(
  DLIList<ChollaSurface*> &cholla_surface_list,
  int interp_order,
  double min_dot)
{
  CubitStatus stat = CUBIT_SUCCESS;
  int ii, kk;

  // make sure the facet flags have been reset

  for ( kk = cholla_surface_list.size(); kk > 0; kk-- )
  {
    ChollaSurface *chsurf_ptr = cholla_surface_list.get_and_step();
    chsurf_ptr->reset_facet_flags();
  }

  // now loop through surfaces and create them

  for ( kk = cholla_surface_list.size(); kk > 0; kk-- )
  {
    ChollaSurface *chsurf_ptr = cholla_surface_list.get_and_step();
    DLIList<FacetEntity*> facet_entity_list;    
    DLIList<CubitPoint*> point_list;
    chsurf_ptr->get_points(point_list);
    chsurf_ptr->get_facets(facet_entity_list);
    DLIList<CubitFacet*> facet_list;
    CAST_LIST( facet_entity_list, facet_list, CubitFacet );

    FacetEvalTool *eval_tool_ptr = new FacetEvalTool();
    eval_tool_ptr->initialize(facet_list, point_list, interp_order, min_dot);

    chsurf_ptr->assign_eval_tool(eval_tool_ptr);

    // go through each of this surface's curves and create CurveFacetEvalTools

    DLIList<ChollaCurve *> chcurv_list;
    chsurf_ptr->get_curves( chcurv_list );
    for (ii=0; ii<chcurv_list.size(); ii++)
    {
      ChollaCurve *chcurv_ptr = chcurv_list.get_and_step();   

      if (chcurv_ptr->get_eval_tool() == NULL)
      {
        //fix up the orientation of the Cholla curve
        stat = chcurv_ptr->order_edges();
        if ( stat != CUBIT_SUCCESS )
        {         
          PRINT_ERROR("Problems ordering edges!!!!!\n");          
          return stat;
        }        
        
        DLIList<FacetEntity*> facet_ents;
        facet_ents = chcurv_ptr->get_facet_list();
        DLIList<CubitFacetEdge*> edge_facets;
        CAST_LIST(facet_ents, edge_facets, CubitFacetEdge );
        DLIList<CubitPoint*> ordered_points;
        
        for( int k=0; k<edge_facets.size(); k++ )
        {
          CubitFacetEdge *tmp_edge = edge_facets.get_and_step();          
          if( k==0 )
          {
            ordered_points.append( tmp_edge->point(0) );            
            ordered_points.append( tmp_edge->point(1) );            
          }
          else        
            ordered_points.append( tmp_edge->point(1) );                      
        }     

        CurveFacetEvalTool *curv_eval_tool_ptr = new CurveFacetEvalTool;       
        edge_facets.reset();        
        stat = curv_eval_tool_ptr->initialize( edge_facets, ordered_points, eval_tool_ptr );          

        if ( stat != CUBIT_SUCCESS )
        {
          return stat;
        }
        chcurv_ptr->assign_eval_tool( curv_eval_tool_ptr );     
      }
    }
  }
  return stat;
}

CubitStatus ChollaEngine::rebuild_surface_and_curve_eval_tools(
  DLIList<ChollaSurface*> &cholla_surface_list,
  int interp_order,
  double min_dot )
{
  CubitStatus stat = CUBIT_SUCCESS;
  int ii, kk;

  // make sure the facet flags have been reset
  for ( kk = cholla_surface_list.size(); kk > 0; kk-- )
  {
    ChollaSurface *chsurf_ptr = cholla_surface_list.get_and_step();
    chsurf_ptr->reset_facet_flags();    
  }

  // get unique list of curves
  DLIList<ChollaCurve *> all_chcurves;
  for ( kk = cholla_surface_list.size(); kk > 0; kk-- )
  {
    ChollaSurface *chsurf_ptr = cholla_surface_list.get_and_step();
    DLIList<ChollaCurve *> chcurv_list;
    chsurf_ptr->get_curves( chcurv_list );
    all_chcurves += chcurv_list;    
  }
  all_chcurves.uniquify_ordered();

  // now loop through surfaces and create them

  for ( kk = cholla_surface_list.size(); kk > 0; kk-- )
  {
    ChollaSurface *chsurf_ptr = cholla_surface_list.get_and_step();
    DLIList<FacetEntity*> facet_entity_list;
    DLIList<CubitPoint*> point_list;
    chsurf_ptr->get_points(point_list);
    chsurf_ptr->get_facets(facet_entity_list);
    DLIList<CubitFacet*> facet_list;
    CAST_LIST( facet_entity_list, facet_list, CubitFacet );

    FacetEvalTool *eval_tool_ptr = chsurf_ptr->get_eval_tool();
    if (NULL != eval_tool_ptr)
    {
      DLIList<CubitFacet*> facets;
      eval_tool_ptr->remove_facets(facets);
      delete eval_tool_ptr;
    }

    eval_tool_ptr = new FacetEvalTool();
    if ( CUBIT_SUCCESS != eval_tool_ptr->initialize(facet_list, point_list, interp_order, min_dot) )
    {
      return CUBIT_FAILURE;
    }

    //eval_tool_ptr = new FacetEvalTool();
    //eval_tool_ptr->replace_facets(facet_list);

    chsurf_ptr->assign_eval_tool(eval_tool_ptr);
  }

  // go through each of the curves and create CurveFacetEvalTools
  for (ii=0; ii<all_chcurves.size(); ii++)
  {
    ChollaCurve *chcurv_ptr = all_chcurves.get_and_step();    

    CubitStatus rv = chcurv_ptr->order_edges();
    if (CUBIT_SUCCESS != rv) {
      PRINT_ERROR("Failed to order edges.\n");
      return rv;
    }

    CurveFacetEvalTool* curve_eval = chcurv_ptr->get_eval_tool();
    if (NULL != curve_eval)
    {
      DLIList<CubitFacetEdge*> eval_facets;
      curve_eval->remove_facets(eval_facets);
      delete curve_eval;
    }

    DLIList<FacetEntity*> facet_ents;
    facet_ents = chcurv_ptr->get_facet_list();
    DLIList<CubitFacetEdge*> edge_facets;
    CAST_LIST(facet_ents, edge_facets, CubitFacetEdge );
    DLIList<CubitPoint*> ordered_points;

    for( int k=0; k<edge_facets.size(); k++ )
    {
      CubitFacetEdge *tmp_edge = edge_facets.get_and_step();          
      if( k==0 )
      {
        ordered_points.append( tmp_edge->point(0) );            
        ordered_points.append( tmp_edge->point(1) );            
      }
      else        
        ordered_points.append( tmp_edge->point(1) );                      
    }     

    CurveFacetEvalTool *curv_eval_tool_ptr = new CurveFacetEvalTool;       
    edge_facets.reset();
    ordered_points.reset();
    stat = curv_eval_tool_ptr->initialize( edge_facets, ordered_points);          

    if ( stat != CUBIT_SUCCESS )
    {
      return stat;
    }
    chcurv_ptr->assign_eval_tool( curv_eval_tool_ptr );       
  }

  return stat; 
}

//===============================================================================
//Function:  determine_curve_orientation (static PUBLIC)
//Description:  Determine orientation of the curve with respect to the surface
//===============================================================================
CubitStatus ChollaEngine::determine_curve_orientation( 
  ChollaSurface *chsurf_ptr,
  ChollaCurve *chcurv_ptr,
  CubitSense & orientation )
{
  // get the first mesh edge on the curve. use it to determine the 
  // orientation of the curve with respect to the surface

  DLIList<FacetEntity*> facet_list = chcurv_ptr->get_facet_list();
  facet_list.reset();
  FacetEntity *facet_ptr = facet_list.get();
  CubitFacetEdge *edge_ptr = CAST_TO( facet_ptr, CubitFacetEdge );
  if (!edge_ptr)
    return CUBIT_FAILURE; // facet edges are not on the list - we shouldn't be here

  // get the adjacent face on this surface

  DLIList<FacetEntity*> adj_face_list;
  edge_ptr->get_parents( adj_face_list );

  DLIList<FacetEntity*> face_ptrs;
  int jj;
  for ( jj = 0; jj < adj_face_list.size(); jj++ )
  {
    FacetEntity* face_ptr = adj_face_list.get_and_step();    
    TDGeomFacet *td_gm_face = TDGeomFacet::get_geom_facet(face_ptr); 
    DLIList<ChollaSurface*> chsurf_list;
    if(td_gm_face)
    {
      td_gm_face->get_cholla_surfs( chsurf_list );
      if (chsurf_list.size())
      {
        ChollaSurface *face_chsurf_ptr = chsurf_list.get();
        if(face_chsurf_ptr == chsurf_ptr)
        {
          face_ptrs.append(face_ptr);
        }
      }
    }
  }
  if(!face_ptrs.size())
    return CUBIT_FAILURE;  // didn't find an adj face on the surface ???
    

  // if there are two, we'll just say the orientation is unknown
  // this happens when there is a non-manifold, callers are responsible for dealing with those
  if(face_ptrs.size() >= 2)
  {
    orientation = CUBIT_UNKNOWN;
    return CUBIT_SUCCESS;
  }

  FacetEntity* face_ptr = face_ptrs[0];

  // determine orientation of nodes on this mesh face

  CubitPoint *start_ptr, *end_ptr;
  chcurv_ptr->get_ends( start_ptr, end_ptr );
  end_ptr = edge_ptr->other_point( start_ptr );
  if (end_ptr == NULL)    
  {  
    return CUBIT_FAILURE;  // the edge list may not be ordered correctly??
  }
  CubitPoint *points[3];
  CubitFacet *tri_ptr = CAST_TO( face_ptr, CubitFacet );
  tri_ptr->points( points[0], points[1], points[2] );
  
  int found = 0;
  for ( jj = 0; jj < 3 && !found; jj++ )
  {
    if (points[jj] == start_ptr)
    {
      int next_jj = (jj + 1)%3;
      int prev_jj = (jj + 2)%3;
      if(points[next_jj] == end_ptr)
      {
        found = 1;
        orientation = CUBIT_FORWARD;
      }
      else if(points[prev_jj] == end_ptr)
      {
        found = 1;
        orientation = CUBIT_REVERSED;
      }
    } 
  } 
  if (!found)
    return CUBIT_FAILURE;  // couldn't determine the orientation

  return CUBIT_SUCCESS;
}

//===============================================================================
//Function:  clean_geometry (PRIVATE)
//Description:  fix the edge control points and the normals so they are conforming
//              (or non-conforming) accross curves
//===============================================================================
CubitStatus ChollaEngine::clean_geometry( 
  CubitBoolean smooth_non_manifold,
  CubitBoolean split_surfaces,
  CubitBoolean use_feature_angle,
  double mindot,
  DLIList <ChollaCurve *> &cholla_curve_list )
{
  int iedge;
  ChollaCurve *chcurv_ptr;
  FacetEntity *fedge_ptr;
  CubitFacetEdge *edge_ptr;
  DLIList <FacetEntity *> facet_list; 
  DLIList<CubitFacetEdge *> feature_edge_list;
  int icurve;
  for (icurve=0; icurve<cholla_curve_list.size(); icurve++)
  {
    chcurv_ptr = cholla_curve_list.get_and_step();
    facet_list.clean_out();
    facet_list = chcurv_ptr->get_facet_list( );
    for (iedge=0; iedge<facet_list.size(); iedge++)
    {
      fedge_ptr = facet_list.get_and_step();
      edge_ptr = CAST_TO( fedge_ptr, CubitFacetEdge );
      feature_edge_list.append( edge_ptr );
    }
  }

  return fix_geometry( smooth_non_manifold,split_surfaces, 
                       use_feature_angle,mindot, feature_edge_list );
}

//=============================================================================
//Function:  check_all_facet_orientations (PUBLIC)
//Description: check for consistent orientation of the facets and set the 
//             isBackwards flag on the facets if necessary  
//Author: sjowen
//Date: 8/14/01
//=============================================================================
CubitStatus ChollaEngine::check_all_facet_orientations(
  DLIList<CubitFacet*> &facet_list,
  CubitBoolean do_flip)
{
  CubitStatus stat = CUBIT_SUCCESS;
  //return CUBIT_SUCCESS;
  // mark facets

  int ii;
  for (ii=0; ii<facet_list.size(); ii++)
    facet_list.get_and_step()->marked(1);

  int mydebug = 0;<--- Assignment 'mydebug=0', assigned value is 0
  if (mydebug)<--- Condition 'mydebug' is always false
  {
    dcolor(CUBIT_YELLOW_INDEX);
    dfldraw(facet_list);
    dview();
  }

  // recursively loop through all facets making sure we are oriented the same
  int nfacets = 0;
  CubitFacet *facet_ptr;
  while ( nfacets < facet_list.size() )
  {
    facet_ptr = facet_list.get_and_step();
    if (facet_ptr->marked() == 1)
    {
      stat = check_facet_orientation( facet_ptr, do_flip, nfacets, mydebug );
      if (stat!= CUBIT_SUCCESS)
        return stat;
    }
  }
  return stat;
}


//=============================================================================
//Function:  check_facet_orientation (PUBLIC)
//Description: check for consistent orientation of the facets and change
//             orientation if necessary  (is NOT recursive function)
//Notes:  If do_flip is CUBIT_TRUE, then the facet topology is actually
//        changed.  Otherwise the is_backwards flag is set
//Author: sjowen
//Date: 6/3/01
//=============================================================================
CubitStatus ChollaEngine::check_facet_orientation(
  CubitFacet *start_facet, 
  CubitBoolean do_flip,
  int &nfacets, int mydebug )
{

  int jj;
  CubitFacet *adjfacet, *facet;
  CubitPoint *cpt0, *cpt1, *adjpt;
  DLIList<CubitFacet *>temp_flist;
  DLIList<CubitFacet *>adj_facet_list;
  temp_flist.append(start_facet);
  if (mydebug)
  {
    dcolor(CUBIT_RED_INDEX);
    dfdraw(start_facet);
  }
  nfacets++;
  start_facet->marked( 0 );
  int adjidx; 
  while(temp_flist.size())
  {
    facet = temp_flist.pop();
    if (facet->marked() == 0)
    {
      for (jj=0; jj<3; jj++)
      {
        cpt0 = facet->point(jj);
        cpt1 = facet->point((jj+1)%3);
        adj_facet_list.clean_out();
        facet->shared_facets(cpt0, cpt1, adj_facet_list);
        if(adj_facet_list.size()==1)
        {
          adjfacet = adj_facet_list.get();
          if (adjfacet->marked() == 1)
          {
            adjidx = adjfacet->point_index( cpt1 ); 
            if (adjidx == -1)
            {
              return CUBIT_FAILURE;
            }
            adjpt = adjfacet->point((adjidx+1)%3);
            if (adjpt != cpt0)
            {        
              // the orientation is not consistent -- flip the orientation of the 
              // adjacent facet

              // an assertion here means that the facets really don't share an
              // edge.  Should not happen!
              
              if (adjfacet->point((adjidx+2)%3) != cpt0)
              {
                return CUBIT_FAILURE;
              }
       
              if (do_flip)
              {
                adjfacet->flip();
              }
              else
              {
                if(adjfacet->is_backwards())
                  adjfacet->is_backwards( 0 );
                else
                  adjfacet->is_backwards( 1 );
              }
              if(mydebug){
                adjfacet->debug_draw(CUBIT_WHITE_INDEX);
              }
            }

            // put its neighbor on the list to be processed later

            if (adjfacet->marked() == 1)
            {
              temp_flist.append( adjfacet );
              adjfacet->marked( 0 );
              if(mydebug)
              {
                dfdraw(adjfacet);
              }
              nfacets++;
            }
          }
        }
      }
    }
  }
  if(mydebug)
    GfxDebug::mouse_xforms();
  return CUBIT_SUCCESS;
}


#ifdef ALPHA_CABLE
//=============================================================================
//Function:  split_surface_at_edges (PUBLIC)
//Description: Given a list of edges that divides a surface into two, this
// function splits the surface and modifies the engine to represent the
// new geometry.
//Author: mbrewer
//Date: 4/22/2004
//=============================================================================
CubitStatus ChollaEngine::split_surface_at_edges(
  ChollaSurface* owning_surface,
  DLIList<CubitFacetEdge *> &feature_edge_list,
  DLIList<ChollaCurve*> &cholla_curves,
  DLIList<ChollaSurface*> &cholla_surfaces)
{
  int i=0;
  DLIList<ChollaSurface*> original_surfaces = chollaSurfaceList;
  DLIList<ChollaCurve*> original_curves = chollaCurveList;
  //mark edges as feature
  CubitFacetEdge* edge_ptr=NULL;
  for(i=0;i<feature_edge_list.size();++i){
    edge_ptr=feature_edge_list.get_and_step();
    TDGeomFacet::add_geom_facet(edge_ptr, -1); 
    TDGeomFacet* td_gm_edge = TDGeomFacet::get_geom_facet(edge_ptr);
    edge_ptr->set_as_feature();
  }
   //Michael temp
  DLIList<FacetEntity*> *surf_facet_list=owning_surface->get_facet_list_ptr();
  int surface_id = owning_surface->get_id();
  for(i=0;i<surf_facet_list->size();++i){
    FacetEntity* face_ptr = surf_facet_list->get_and_step();
    TDGeomFacet *td_gm_face = TDGeomFacet::get_geom_facet(face_ptr);
    td_gm_face->set_hit_flag(surface_id);
  }
  
  CubitStatus rv = make_features( feature_edge_list, CUBIT_FALSE );
  if (rv != CUBIT_SUCCESS)
    return rv;
  
    // split up the surface
  rv = owning_surface->split_surface( cholla_surfaces );
  if (rv != CUBIT_SUCCESS)
    return rv;

  for ( i = cholla_surfaces.size(); i > 0; i-- )
  {
    ChollaSurface *chsurf_ptr = cholla_surfaces.get_and_step();
    chsurf_ptr->update_boundary_tool_data();
    if(chsurf_ptr != owning_surface){
      chollaSurfaceList.append(chsurf_ptr);
     
    }
  }
  rv = create_surface_boundaries( chollaSurfaceList, chollaCurveList,
                                  CUBIT_FALSE, 0.0);
  if ( !rv )
    return rv;

  rv = create_curve_boundaries( chollaCurveList, chollaPointList );
  if ( !rv )
    return rv;

  rv = build_eval_tools( chollaSurfaceList,
                         chollaCurveList,
                         0, CUBIT_FALSE, 
                         0, CUBIT_FALSE, CUBIT_FALSE);
  
  
  cholla_surfaces = chollaSurfaceList;
  cholla_curves = chollaCurveList;

  cholla_surfaces -= original_surfaces;
  cholla_curves -= original_curves;
  
  return rv;
}
#endif//cable

//=============================================================================
//Function:  make_features (PRIVATE)
//Description: add additional edges and points where feature angle requires
//             a break in the surface
//Author: sjowen
//Date:  4/31/01
//=============================================================================
CubitStatus ChollaEngine::make_features(
  DLIList<CubitFacetEdge *> &feature_edge_list,
  CubitBoolean split_surfaces )
{
  CubitStatus rv = CUBIT_SUCCESS;
  int ii, jj;
  CubitFacetEdge *edge_ptr;
  CubitPoint *point_ptr;
  int mydebug = 0;<--- Assignment 'mydebug=0', assigned value is 0
  if(mydebug)<--- Condition 'mydebug' is always false
    GfxDebug::clear();
  for (ii=0; ii<feature_edge_list.size(); ii++)
  {
    edge_ptr = feature_edge_list.get_and_step();
    if(mydebug)
      edge_ptr->debug_draw(CUBIT_YELLOW_INDEX);
    for (jj=0; jj<2; jj++)
    {
      point_ptr = edge_ptr->point( jj );
      point_ptr->marked( 0 );
    }
    edge_ptr->set_flag( 1 );  // mark edges as being feature edges
  }

  if (mydebug)
  {
    GfxDebug::mouse_xforms();
    dcolor(CUBIT_WHITE_INDEX);
    deldraw(feature_edge_list);
    dview();
  }

  for (ii=0; ii<feature_edge_list.size(); ii++)
  {
    edge_ptr = feature_edge_list.get_and_step();
    for (jj=0; jj<2; jj++)
    {
      point_ptr = edge_ptr->point( jj );
      if (0 == point_ptr->marked())
      {
        point_ptr->marked(1);
        if (split_surfaces)
          rv = crack_open_point( point_ptr, mydebug );
        else
          rv = insert_discontinuity_at_point( point_ptr );
        if (rv != CUBIT_SUCCESS)
          return rv;
      }
    }
  }

  for (ii=0; ii<feature_edge_list.size(); ii++)
  {
    feature_edge_list.get_and_step()->set_flag( 0 );
  }
  return rv;
}

//=============================================================================
//Function:  crack_open_point (PRIVATE)
//Description: split the surface facets at a point if required.  Create
//             new points and edges as needed
//Author: sjowen
//Date:  4/31/01
//=============================================================================
CubitStatus ChollaEngine::crack_open_point(
  CubitPoint *point_ptr,  
  int mydebug )
{
  CubitStatus rv = CUBIT_SUCCESS;

  // get facets at this point and mark them all ready for recursion function
  // get_facets_at_point

  int ii, jj;
  DLIList<CubitFacet *> facet_list;
  point_ptr->facets( facet_list );
  CubitFacet *facet_ptr, *adj_facet_ptr;
  for (ii=0; ii<facet_list.size(); ii++)
  {
    facet_ptr = facet_list.get_and_step();
    facet_ptr->marked( 0 );
  }

  // go through and find groups of adjacent facets that will form part of
  // new surfaces

  int totfacets = facet_list.size();
  int numfacets = 0;
  while(numfacets < totfacets)
  {
    facet_list.clean_out();
    point_ptr->facets( facet_list );
    facet_ptr = facet_list.get();
    DLIList<CubitFacet *> adj_facet_list;
    DLIList<CubitFacetEdge *>feature_edge_list;

    // make a list of all facets adjacet this point that are bounded
    // by feature edges.  Start with facet_ptr and recurse until
    // we bump into feature edges at the point.

    rv = get_facets_at_point( point_ptr, facet_ptr, adj_facet_list, 
                              feature_edge_list );
    numfacets += adj_facet_list.size();

    // if the number of facets for this feature are the same as the number of
    // facets at this point, then we are done with this point.  Otherwise
    // create new point and edges 

    if (numfacets < totfacets)
    {
      // create a new point and update the facets

      CubitPoint *new_point_ptr = 
         new CubitPointData( point_ptr->coordinates() );
      TDGeomFacet::add_geom_facet( new_point_ptr , -1);
      for (ii=0; ii<adj_facet_list.size(); ii++)
      {
        adj_facet_ptr = adj_facet_list.get_and_step();

        // facet modifications can only occur with native CUBIT facet data
        // if we are using someone else's data (ie. Sierra) then fail.
        // (Should not be using split_surfaces = TRUE)

        CubitFacetData *cfd_ptr = CAST_TO( adj_facet_ptr, CubitFacetData );
        if (!cfd_ptr)
          return CUBIT_FAILURE;
        new_point_ptr->add_facet( adj_facet_ptr );
        point_ptr->remove_facet( adj_facet_ptr );
        int pidx = adj_facet_ptr->point_index( point_ptr );
        cfd_ptr->set_point( new_point_ptr, pidx );
      }

      // The existing and the new points in some cases have to maintain 
      // the same normal...  so they need to keep track of
      // each other.  They will likely wind up on different surfaces
      // and we don't want to go search for them later

      TDGeomFacet *td_existing_point = TDGeomFacet::get_geom_facet( point_ptr );
      TDGeomFacet *td_new_point = TDGeomFacet::get_geom_facet( new_point_ptr );
      DLIList<CubitPoint *> partner_point_list;

      // add the existing point's partner list to the new point

      CubitPoint *partner_point_ptr;
      TDGeomFacet *td_partner;
      td_existing_point->get_partner_points( partner_point_list );
      for (ii=0; ii<partner_point_list.size(); ii++)
      {
        partner_point_ptr = partner_point_list.get_and_step();
        td_partner = TDGeomFacet::get_geom_facet( partner_point_ptr );
          //added mbrewer:  the check for a pointer here shouldn't
          // be necessary, but I have a case where it fails.  I don't
          // see where the logic is wrong.
        if(!td_partner){
          TDGeomFacet::add_geom_facet( partner_point_ptr , -1);
          td_partner = TDGeomFacet::get_geom_facet( partner_point_ptr );
        }
        td_partner->add_partner_point( new_point_ptr );
        td_new_point->add_partner_point( partner_point_ptr );
      }

      // Add each other as a partner

      td_existing_point->add_partner_point( new_point_ptr );
      td_new_point->add_partner_point( point_ptr );

      // create new edges at the point

      CubitFacetEdgeData *cfed_ptr;
      for (ii=0; ii<feature_edge_list.size(); ii++)
      {
        CubitFacetEdge *edge_ptr = feature_edge_list.get_and_step();
        cfed_ptr = CAST_TO( edge_ptr, CubitFacetEdgeData );
        if (!cfed_ptr)
          return CUBIT_FAILURE;
        rv = CUBIT_FAILURE;
        for (jj=0; jj<adj_facet_list.size() && rv == CUBIT_FAILURE; jj++)
        {
          rv = cfed_ptr->remove_facet( adj_facet_list.get_and_step() );
        }
        if (rv != CUBIT_SUCCESS)
          return rv;
        CubitPoint *p1 = edge_ptr->other_point( point_ptr );

        // create a new edge - the edge constructor will update
        // the facet and its edge use.

        CubitFacetEdge *new_edge_ptr =
          new CubitFacetEdgeData( new_point_ptr, p1 );
        TDGeomFacet::add_geom_facet( new_edge_ptr, -1 );
        new_edge_ptr->set_as_feature();
        if (mydebug)
        {
          dcolor(CUBIT_RED_INDEX);
          dedraw(new_edge_ptr);
        }

        // The existing and the new edges have to maintain the same 
        // control point locations, so they need to keep track of
        // each other.  They will likely wind up on different surfaces
        // and we don't want to go search for them later

        TDGeomFacet *td_existing_edge = TDGeomFacet::get_geom_facet( edge_ptr );
        TDGeomFacet *td_new_edge = TDGeomFacet::get_geom_facet( new_edge_ptr );
        DLIList<CubitFacetEdge *> partner_edge_list;

        // add the existing edge's partner list to the new edge

        CubitFacetEdge *partner_edge_ptr;
        td_existing_edge->get_partner_edges( partner_edge_list );
        for (jj=0; jj<partner_edge_list.size(); jj++)
        {
          partner_edge_ptr = partner_edge_list.get_and_step();
          td_partner = TDGeomFacet::get_geom_facet( partner_edge_ptr );
          td_partner->add_partner_edge( new_edge_ptr );
          td_new_edge->add_partner_edge( partner_edge_ptr );
        }

        // Add each other as a partner

        td_existing_edge->add_partner_edge( new_edge_ptr );
        td_new_edge->add_partner_edge( edge_ptr );
      }

      // update the other edges with the new point

      for (ii=0; ii<adj_facet_list.size(); ii++)
      {
        adj_facet_ptr = adj_facet_list.get_and_step();
        for (jj=0; jj<3; jj++)
        {
          CubitFacetEdge *edge_ptr = adj_facet_ptr->edge( jj );
          cfed_ptr = CAST_TO( edge_ptr, CubitFacetEdgeData );
          if (!cfed_ptr)
            return CUBIT_FAILURE;
          if (cfed_ptr->point( 0 ) == point_ptr)
            cfed_ptr->set_point( new_point_ptr, 0 );
          if (cfed_ptr->point( 1 ) == point_ptr)
            cfed_ptr->set_point( new_point_ptr, 1 );
        }
      }
    }
  }

  return rv;
}

//=============================================================================
//Function:  insert_discontinuity_at_point (PRIVATE)
//Description: does the same as crack_open_point, but does not create new 
//             facet entities at surface boundaries.  Instead, it creates 
//             facet boundary tooldatas to hold the additional control point 
//             and normal data
//Author: sjowen
//Date:  4/31/01
//=============================================================================
CubitStatus ChollaEngine::insert_discontinuity_at_point(
  CubitPoint *point_ptr )
{
  CubitStatus rv = CUBIT_SUCCESS;

  // get facets at this point and mark them all ready for recursion function
  // get_facets_at_point

  int ii;
  DLIList<CubitFacet *> facet_list;
  point_ptr->facets( facet_list );
  CubitFacet *facet_ptr = NULL;
  for (ii=0; ii<facet_list.size(); ii++)
  {
    facet_ptr = facet_list.get_and_step();
    facet_ptr->marked( 0 );
  }

  int mydebug = 0;<--- Assignment 'mydebug=0', assigned value is 0
  if (mydebug) {<--- Condition 'mydebug' is always false
    dfldraw(facet_list);
    dview();
  }

  // go through and find groups of adjacent facets that will form part of
  // new surfaces

  TDFacetBoundaryPoint *td_fbp = 
    TDFacetBoundaryPoint::get_facet_boundary_point( point_ptr );
  int totfacets = facet_list.size();
  int numfacets = 0;
  while(numfacets < totfacets)
  {
    ii = 0;
    int found = 0;
    while(!found && ii < totfacets )
    {
      ii++;
      facet_ptr = facet_list.get_and_step();
      if (facet_ptr != NULL)
        found = 1;
    }
    assert(found);
    DLIList<CubitFacet *> adj_facet_list;
    DLIList<CubitFacetEdge *>feature_edge_list;

    // make a list of all facets adjacet this point that are bounded
    // by feature edges.  Start with facet_ptr and recurse until
    // we bump into feature edges at the point.

    rv = get_facets_at_point( point_ptr, facet_ptr, adj_facet_list, 
                              feature_edge_list );

    if (rv != CUBIT_SUCCESS)
      return rv;
    numfacets += adj_facet_list.size();
    for (ii=0; ii<adj_facet_list.size(); ii++)
    {
      facet_list.move_to( adj_facet_list.get_and_step() );
      facet_list.change_to( NULL );
    }

    // create a new boundary point tooldata if needed and add the facets
    // associated with this surface

    if (td_fbp == NULL)
    {
      TDFacetBoundaryPoint::add_facet_boundary_point( point_ptr );
      td_fbp = TDFacetBoundaryPoint::get_facet_boundary_point( point_ptr );
    }
    td_fbp->add_surf_facets( adj_facet_list );

    // create new boundary edge tooldatas at the point
    for (ii=0; ii<feature_edge_list.size(); ii++)
    {
      CubitFacetEdge *edge_ptr = feature_edge_list.get_and_step();

      TDFacetBoundaryEdge *td_fbe = 
        TDFacetBoundaryEdge::get_facet_boundary_edge( edge_ptr );
      if (td_fbe == NULL)
      {
        TDFacetBoundaryEdge::add_facet_boundary_edge( edge_ptr );
        td_fbe = TDFacetBoundaryEdge::get_facet_boundary_edge( edge_ptr );
      }
      td_fbe->add_surf_facet( adj_facet_list );
    }
  }

  return rv;
}

//=============================================================================
//Function:  get_facets_at_point (PRIVATE)
//Description: make a list of all faces adjacent to a single point that are 
//             bounded by feature edges - recursive function
//Author: sjowen
//Date:  5/2/01
//=============================================================================
CubitStatus ChollaEngine::get_facets_at_point(
  CubitPoint *point_ptr,
  CubitFacet *facet_ptr,
  DLIList<CubitFacet *> &facet_list,
  DLIList<CubitFacetEdge *> &feature_edge_list)
{
  CubitStatus rv = CUBIT_SUCCESS;
  CubitFacetEdge *edge_ptr;
  CubitFacet *adj_facet;
  facet_list.append(facet_ptr);
  facet_ptr->marked( 1 );

  for (int ii=0; ii<3; ii++)
  {
    edge_ptr = facet_ptr->edge( ii );
    if (edge_ptr->contains( point_ptr ))
    {
      if (!edge_ptr->is_feature())
      {
        if (edge_ptr->num_adj_facets() >2)
          return CUBIT_FAILURE;
        adj_facet = edge_ptr->other_facet( facet_ptr );
        if (adj_facet == NULL)
          return CUBIT_FAILURE;
        if (adj_facet->marked() == 0)
        {
          rv = get_facets_at_point( point_ptr, adj_facet, 
                                    facet_list, feature_edge_list );
          if (rv != CUBIT_SUCCESS)
            return rv;
        }
      }
      else
      {
        if (edge_ptr->num_adj_facets() > 1)
        {
          feature_edge_list.append_unique( edge_ptr );
        }
      }
    }
  }
  return rv;
}

//===============================================================================
//Function:  fix_geometry (PUBLIC)
//Description:  fix the edge control points and the normals so they are conforming
//              (or non-conforming) accross curves
//===============================================================================
CubitStatus ChollaEngine::fix_geometry(
  CubitBoolean smooth_non_manifold,
  CubitBoolean split_surfaces,
  CubitBoolean /* use_feature_angle */,
  double mindot,
  DLIList <CubitFacetEdge *> &feature_edge_list )
{
  CubitStatus stat = CUBIT_SUCCESS;

  // unmark all the edges and points

  CubitFacetEdge *edge_ptr; 
  int iedge;
  int flag = (smooth_non_manifold) ? 0 : 1;
  for (iedge = 0; iedge < feature_edge_list.size(); iedge++)
  {
    edge_ptr = feature_edge_list.get_and_step();
    edge_ptr->set_flag( flag );
    edge_ptr->point( 0 )->marked( flag );
    edge_ptr->point( 1 )->marked( flag );
  }

  // for non-manifold edges, find sets of adjacent facets that 
  // we can smooth across.  If adjacent facets do not satisfy the
  // feature angle criteria, then they should have C1 continuity
  // across the edge.  To do this, the normals at the edge's
  // points on partner edges will need to be the same.  This next
  // piece of code potentially alters the point normals.  As a result
  // edge and facet control points will need to be updated.

  DLIList<CubitFacet *>update_facet_list;
  if (smooth_non_manifold)
  {
    DLIList <CubitPoint *> changed_points;
    for (iedge = 0; iedge < feature_edge_list.size(); iedge++)
    {
      edge_ptr = feature_edge_list.get_and_step();
      if (edge_ptr->get_flag() == 1)
        continue;
      edge_ptr->set_flag( 1 );
      if (split_surfaces)
        stat = fix_split_non_manifold_edge( edge_ptr, mindot, 
                                            changed_points );
      else
        stat = fix_non_manifold_edge( edge_ptr, mindot, 
                                      changed_points );
      if (stat != CUBIT_SUCCESS)
        return stat;
    }
    if (changed_points.size() > 0)
      stat = update_edges_at_points( split_surfaces,
                                     changed_points, 
                                     update_facet_list,
                                     mindot );
    if (stat != CUBIT_SUCCESS)
      return stat;
  }

  // For all cases we need to ensure that partner edges share the same
  // control, point locations.  This piece of code goes through and
  // computes an average location for control points on partner edges
  // and sets them back on the edge

  for (iedge = 0; iedge < feature_edge_list.size(); iedge++)
  {
    edge_ptr = feature_edge_list.get_and_step();
    if (edge_ptr->get_flag() == 2)
      continue;
    edge_ptr->set_flag( 2 );
    if (split_surfaces)
      stat = fix_split_edge( edge_ptr, update_facet_list );
    else
      stat = fix_edge( edge_ptr, update_facet_list );
    if (stat != CUBIT_SUCCESS)
      return stat;
  }

  // since we have potentially modified the point normals and edge 
  // control points, we need to fix the facet control points (interior
  // to the facet) The update_facet_list contains a non-unique list of
  // facets that will need to be recomputed.

  int ii;
  CubitFacet *facet_ptr;
  for (ii=0; ii<update_facet_list.size(); ii++)
    update_facet_list.get_and_step()->marked( 0 );

  for (ii=0; ii<update_facet_list.size(); ii++)
  {
    facet_ptr = update_facet_list.get_and_step();
    if (facet_ptr->marked() == 0)
    {
      facet_ptr->marked( 1 );
      stat = FacetEvalTool::init_bezier_facet( facet_ptr );
      if (stat != CUBIT_SUCCESS)
        return stat;
    }
  }

  for (ii=0; ii<update_facet_list.size(); ii++)
    update_facet_list.get_and_step()->marked( 0 );

  return stat;
}

//===============================================================================
//Function:  update_edges_at_points (PRIVATE)
//Description: recompute the edge control points at all facets sharing
//             points in the list
//Date: 05/01
//===============================================================================
CubitStatus ChollaEngine::update_edges_at_points(
  CubitBoolean /* split_surfaces */,        // we are splitting facets to create geometry
  DLIList<CubitPoint *> &point_list,  // points whose edges will be updated
  DLIList<CubitFacet *> &facet_update_list,  // append facets adjacent edges that
                                             // will be updated later
  double mindot )
{
  CubitStatus stat = CUBIT_SUCCESS;
  CubitPoint *point_ptr;
  CubitFacetEdge *edge_ptr;
  DLIList <CubitFacetEdge *> edge_list;
  int ii;
  for (ii=0; ii<point_list.size(); ii++)
  {
    point_ptr = point_list.get_and_step();
    point_ptr->edges( edge_list );
    point_ptr->facets( facet_update_list );
  }
  for (ii=0; ii<edge_list.size(); ii++)
  {
    edge_ptr = edge_list.get_and_step();
    edge_ptr->set_flag( 0 );
  }
  for (ii=0; ii<edge_list.size(); ii++)
  {
    edge_ptr = edge_list.get_and_step();
    if (edge_ptr->get_flag() == 0)
    {
      edge_ptr->set_flag( 1 );
      stat = FacetEvalTool::init_bezier_edge( edge_ptr, mindot );
    }
  }
  return stat;
}

//===============================================================================
//Function:  fix_edge (PRIVATE)
//Description: Enforce the condition where all partner edges to this edge
//             share the same control points.  Compute the average of the
//             partner control points and set on the edge
//Date: 05/01
//===============================================================================
CubitStatus ChollaEngine::fix_edge( CubitFacetEdge *edge_ptr,
                                   DLIList<CubitFacet *> &update_facet_list)
{
  if (edge_ptr->num_adj_facets() == 1)
    return CUBIT_SUCCESS;
  TDFacetBoundaryEdge *td_fbe =
    TDFacetBoundaryEdge::get_facet_boundary_edge( edge_ptr );
  if (!td_fbe)
    return CUBIT_FAILURE;

  edge_ptr->facets( update_facet_list );
  CubitStatus stat = td_fbe->merge_control_points();
  return stat;
}

//===============================================================================
//Function:  fix_split_edge (PRIVATE)
//Description: Enforce the condition where all partner edges to this edge
//             share the same control points.  Compute the average of the
//             partner control points and set on the edge
//Date: 05/01
//===============================================================================
CubitStatus ChollaEngine::fix_split_edge( CubitFacetEdge *edge_ptr,
                                   DLIList<CubitFacet *> &update_facet_list)
{

  // we only need to do this if the edge has any partners.  Otherwise return

  TDGeomFacet *td = TDGeomFacet::get_geom_facet( edge_ptr );
  if (td->num_partner_edges() == 0)
    return CUBIT_SUCCESS;
 
  // get the control points for this edge (oriented with
  // respect to point(0) on the edge)--- This means that
  // the rest of the partners to this edge must also
  // provide control points with respect to the same orientation

  CubitVector control_points[3];
  CubitPoint *start_ptr = edge_ptr->point(0);
  edge_ptr->get_control_points( start_ptr, control_points );

  // get all this edge's partners

  int ii;
  CubitVector partner_control_points[3];
  CubitFacetEdge *partner_edge_ptr;
  CubitPoint *partner_start_ptr;
  DLIList <CubitFacetEdge *> partner_edge_list;
  td->get_partner_edges( partner_edge_list );
  for (ii=0; ii<partner_edge_list.size(); ii++)
  {
    partner_edge_ptr = partner_edge_list.get_and_step();
    partner_edge_ptr->set_flag( 2 );

    // determine the same orientation as the first edge

    partner_start_ptr = partner_edge_ptr->point(0);
    TDGeomFacet *td_point = TDGeomFacet::get_geom_facet( partner_start_ptr );
    if (!td_point->is_partner( start_ptr ))
    {
      partner_start_ptr = partner_edge_ptr->point(1);
      td_point = TDGeomFacet::get_geom_facet( partner_start_ptr );
      if (!td_point->is_partner( start_ptr ))
      {
        PRINT_ERROR("Topology error generating facet geometry\n");
        return CUBIT_FAILURE;
      }
    }

    // get the partner's control points and add to the current
    // totals

    partner_edge_ptr->get_control_points( partner_start_ptr, 
                                      partner_control_points );
    control_points[0] += partner_control_points[0];
    control_points[1] += partner_control_points[1];
    control_points[2] += partner_control_points[2];

    // add this edge's adjacent facets to the update facet list

    partner_edge_ptr->facets( update_facet_list );
  }
  edge_ptr->facets( update_facet_list );

  // average the control point locations

  int nedges = partner_edge_list.size() + 1;
  control_points[0] /= (double)nedges;
  control_points[1] /= (double)nedges;
  control_points[2] /= (double)nedges;

  // set the new control points back on the edges

  edge_ptr->set_control_points( start_ptr, control_points );

  TDGeomFacet *td_point;
  for (ii=0; ii<partner_edge_list.size(); ii++)
  {
    partner_edge_ptr = partner_edge_list.get_and_step();

    // determine the same orientation as the first edge

    partner_start_ptr = partner_edge_ptr->point(0);
    td_point = TDGeomFacet::get_geom_facet( partner_start_ptr );
    if (!td_point->is_partner( start_ptr ))
    {
      partner_start_ptr = partner_edge_ptr->point(1);
      td_point = TDGeomFacet::get_geom_facet( partner_start_ptr );
      if (!td_point->is_partner( start_ptr ))
      {
        PRINT_ERROR("Topology error generating facet geometry\n");
        return CUBIT_FAILURE;
      }
    }
    partner_edge_ptr->set_control_points( partner_start_ptr,
                                           control_points );
  }
  return CUBIT_SUCCESS;
}

//===============================================================================
//Function:  fix_non_split_manifold_edge (PRIVATE)
//Description: Enforce the condition where partner edges on non-manifold edges
//             with >2 adjacent facets that do not satisfy feature criteria
//             will have the same normal accross the edge
//Date: 05/01
//===============================================================================
CubitStatus ChollaEngine::fix_split_non_manifold_edge(
  CubitFacetEdge *edge_ptr,
  double min_dot,
  DLIList <CubitPoint *> &changed_points )
{
  // first check if this edge has 3 or more adjacent facets.  Return now if not

  CubitStatus stat = CUBIT_SUCCESS;
  TDGeomFacet *td = TDGeomFacet::get_geom_facet( edge_ptr );
  int nedges = td->num_partner_edges() + 1;
  if (nedges < 3)
    return stat;

  // make an array of partner edges

  std::vector<int> partner0(nedges);
  std::vector<int> partner1(nedges);
  std::vector<double> partner_dot(nedges);
  int num_partners = 0;
  std::vector<CubitFacetEdge*> edges(nedges);

  edges[0] = edge_ptr;
  DLIList<CubitFacetEdge *> partner_list;
  td->get_partner_edges( partner_list );
  int ii;
  for (ii=0; ii< partner_list.size(); ii++)
  {
    edges[ii+1] = partner_list.get_and_step();
    edges[ii+1]->set_flag( 1 );
  }

  
  // check each facet against every other facet at this edge to
  // see if we need to enforce continuity.  There may be several
  // cases where the feature angle criteria is (not) met.  Find
  // the pair that has the greatest dot product between them.
  // If more than 1 pair has the same dot product and meets criteria
  // then it arbitrarily uses the first one.

  int jj, kk;
  for (ii=0; ii<nedges-1; ii++)
  {
    CubitFacet *facet_ptr = edges[ii]->adj_facet( 0 );
    CubitVector normal = facet_ptr->normal();
    normal.normalize();
    double best_dot = -1.0;
    for (jj=ii+1; jj<nedges; jj++)
    {
      CubitFacet *afacet_ptr = edges[jj]->adj_facet( 0 );
      CubitVector anormal = afacet_ptr->normal();
      anormal.normalize();
      double dot = fabs(normal % anormal);
      if (dot > min_dot && dot > best_dot)
      {

        // check to see if this partner pair has not already
        // been used in another partnership.  If so, then check
        // to see if this match is better.  Otherwise, ignore
        // this match.

        int found = 0;
        for (kk=0; kk<num_partners; kk++)
        {
          if (partner0[kk] == ii || partner0[kk] == jj ||
              partner1[kk] == ii || partner1[kk] == jj)
          {
            found = 1;
            if (dot > partner_dot[kk])
            {
              partner_dot[kk] = dot;
              partner0[kk] = ii;
              partner1[kk] = jj;
            }
          }
        }
        if (!found)
        {
          partner_dot[num_partners] = dot;
          partner0[num_partners] = ii;
          partner1[num_partners] = jj;
          num_partners++;
        }
        best_dot = dot;
      }
    }
  }

  // we found a partner facet(s) that needs to have C1 continuity
  // across this facet.  Merge the normals on the edge so they
  // are the same

  for (ii=0; ii<num_partners; ii++)
  {
    CubitFacetEdge *edge0 = edges[partner0[ii]];
    CubitFacetEdge *edge1 = edges[partner1[ii]];
    for (jj=0; jj<2; jj++)
    {
      CubitPoint *pt0 = edge0->point(jj);

      // find its point partner on the partner edge

      CubitPoint *pt1 = edge1->point( 0 );
      td = TDGeomFacet::get_geom_facet( pt0 );
      if (!td->is_partner( pt1 ))
      {
        pt1 = edge1->point( 1 );
        if (!td->is_partner( pt1 ))
        {
          PRINT_ERROR("Internal error defining continuity across non-manifold edges\n");
          return CUBIT_FAILURE;
        }
      }
      if (pt0->marked() == 0 || pt1->marked() == 0)
      {
        pt0->marked( 1 );
        pt1->marked( 1 );
        changed_points.append( pt0 );
        changed_points.append( pt1 );
        stat = merge_normals( pt0, pt1 );
        if (stat != CUBIT_SUCCESS)
          return stat;
      }
    }
  }
  
  return stat;
}

//===============================================================================
//Function:  fix_non_manifold_edge (PRIVATE)
//Description: Enforce the condition where partner edges on non-manifold edges
//             with >2 adjacent facets that do not satisfy feature criteria
//             will have the same normal accross the edge
//Date: 05/01
//===============================================================================
CubitStatus ChollaEngine::fix_non_manifold_edge(
  CubitFacetEdge *edge_ptr,
  double min_dot,
  DLIList <CubitPoint *> &changed_points )
{
  // first check if this edge has 3 or more adjacent facets.  Return now if not

  CubitStatus stat = CUBIT_SUCCESS;
  int nfacets = edge_ptr->num_adj_facets();
  if (nfacets < 3)
    return stat;

  TDFacetBoundaryEdge *td_fbe =
    TDFacetBoundaryEdge::get_facet_boundary_edge( edge_ptr );
  if (td_fbe == NULL)
  {
    return CUBIT_FAILURE;  // there is supposed to be a tool data here!
  }

  // make an array of partner edges

  int *partner0 = new int [nfacets];
  int *partner1 = new int [nfacets];
  double *partner_dot = new double [nfacets];
  int num_partners = 0;
  CubitFacet **facets = new CubitFacet * [nfacets];
  if (!facets || !partner0 || !partner1 || !partner_dot)
    return CUBIT_FAILURE;
  DLIList <CubitFacet *>adj_facets;
  edge_ptr->facets( adj_facets );
  int ii;
  for (ii=0; ii< adj_facets.size(); ii++)
  {
    facets[ii] = adj_facets.get_and_step();
    facets[ii]->marked( 1 );
  }

  
  // check each facet against every other facet at this edge to
  // see if we need to enforce continuity.  There may be several
  // cases where the feature angle criteria is (not) met.  Find
  // the pair that has the greatest dot product between them.
  // If more than 1 pair has the same dot product and meets criteria
  // then it arbitrarily uses the first one.

  int jj, kk;
  for (ii=0; ii<nfacets-1; ii++)
  {
    CubitFacet *facet_ptr = facets[ii];
    CubitVector normal = facet_ptr->normal();
    normal.normalize();
    double best_dot = -1.0;
    for (jj=ii+1; jj<nfacets; jj++)
    {
      CubitFacet *afacet_ptr = facets[jj];
      CubitVector anormal = afacet_ptr->normal();
      anormal.normalize();
      double dot = fabs(normal % anormal);
      if (dot > min_dot && dot > best_dot)
      {

        // check to see if this partner pair has not already
        // been used in another partnership.  If so, then check
        // to see if this match is better.  Otherwise, ignore
        // this match.

        int found = 0;
        for (kk=0; kk<num_partners; kk++)
        {
          if (partner0[kk] == ii || partner0[kk] == jj ||
              partner1[kk] == ii || partner1[kk] == jj)
          {
            found = 1;
            if (dot > partner_dot[kk])
            {
              partner_dot[kk] = dot;
              partner0[kk] = ii;
              partner1[kk] = jj;
            }
          }
        }
        if (!found)
        {
          partner_dot[num_partners] = dot;
          partner0[num_partners] = ii;
          partner1[num_partners] = jj;
          num_partners++;
        }
        best_dot = dot;
      }
    }
  }

  // we found a partner facet(s) that needs to have C1 continuity
  // across this facet.  Merge the normals on the edge so they
  // are the same

  if (num_partners > 0)
  {
    CubitPoint *pt0 = edge_ptr->point(0);
    CubitPoint *pt1 = edge_ptr->point(1);
    TDFacetBoundaryPoint *td_fbp0 =
      TDFacetBoundaryPoint::get_facet_boundary_point( pt0 );
    TDFacetBoundaryPoint *td_fbp1 =
      TDFacetBoundaryPoint::get_facet_boundary_point( pt1 );
    if (!td_fbp0 || !td_fbp1) {
      delete [] facets;
      delete [] partner0;
      delete [] partner1;
      delete [] partner_dot;
      return CUBIT_FAILURE;
    }

    for (ii=0; ii<num_partners; ii++)
    {
      td_fbp0->merge_normals( facets[partner0[ii]], facets[partner1[ii]] );
      td_fbp1->merge_normals( facets[partner0[ii]], facets[partner1[ii]] );
    }
    pt0->marked( 1 );
    pt1->marked( 1 );
    changed_points.append( pt0 );
    changed_points.append( pt1 );
  }
  
  delete [] facets;
  delete [] partner0;
  delete [] partner1;
  delete [] partner_dot;

  return stat;
}

//===============================================================================
//Function:  merge_normals (PRIVATE)
//Description: Enforce continuity across facets by merging the normals at two
//             points.  Assumes the points are coincident.
//Date: 05/01
//===============================================================================
CubitStatus ChollaEngine::merge_normals(
  CubitPoint *pt0,
  CubitPoint *pt1)
{

  DLIList<CubitFacet*> adj_facet_list0;
  pt0->facets(adj_facet_list0);
  if (adj_facet_list0.size() == 0)
    return CUBIT_FAILURE;

  CubitVector avg_normal(0.0e0, 0.0e0, 0.0e0);
  double totangle = 0.0e0;
  double angle;
  CubitFacet *facet;
  int j;

  // weight the normal by the spanning angle at the point

  for (j = 0; j < adj_facet_list0.size(); j++)
  {
    facet = adj_facet_list0.get_and_step();
    angle = facet->angle( pt0 );
    facet->weight( angle );
    totangle += angle;
  }
  DLIList<CubitFacet*> adj_facet_list1;
  pt1->facets(adj_facet_list1);
  if (adj_facet_list1.size() == 0)
    return CUBIT_FAILURE;
  for (j = 0; j < adj_facet_list1.size(); j++)
  {
    facet = adj_facet_list1.get_and_step();
    angle = facet->angle( pt1 );
    facet->weight( angle );
    totangle += angle;
  }

  // computed weighted normal

  CubitVector normal;
  for (j = 0; j < adj_facet_list0.size(); j++)
  {
    facet = adj_facet_list0.get_and_step();
    normal = facet->normal();
    normal.normalize();
    avg_normal += (facet->weight() / totangle) * normal;
  }
  
  // orientation of facets may be opposite on opposing surfaces.
  // Check for this case and correct of necessary
  
  CubitVector norm0, norm1;
  norm0 = pt0->normal();
  norm0.normalize();
  norm1 = pt1->normal();
  norm1.normalize();
  double dot = norm0 % norm1;
  double sign = 1.0;
  if (dot < 0.0)
    sign = -1.0;

  for (j = 0; j < adj_facet_list1.size(); j++)
  {
    facet = adj_facet_list1.get_and_step();
    normal = sign * facet->normal();
    normal.normalize();
    avg_normal += (facet->weight() / totangle) * normal;
  }

  // set the new normal on both points

  avg_normal.normalize();
  pt0->normal(avg_normal);
  CubitVector temp_vector = sign * avg_normal;
  pt1->normal(temp_vector);
  double coefd = -(pt0->coordinates()%avg_normal);
  pt0->d_coef( coefd );
  pt1->d_coef( sign * coefd );

  return CUBIT_SUCCESS;
}

//===============================================================================
//Function:  print_me (PRIVATE)
//Description: debug
//===============================================================================
void ChollaEngine::print_me()
{
  FILE *fp = fopen( "fbg.out", "w" );
  int ii, jj, kk;
  for (ii=0; ii<chollaSurfaceList.size(); ii++)
  {
    ChollaSurface *chsurf_ptr = chollaSurfaceList.get_and_step();
    fprintf( fp, "*********** Surface %d ***************\n", chsurf_ptr->get_id());
    DLIList<ChollaCurve *> fcm_list;
    chsurf_ptr->get_curves( fcm_list );
    for (jj=0; jj<fcm_list.size(); jj++)
    {
      ChollaCurve *chcurv_ptr = fcm_list.get_and_step();
      fprintf(fp, "   Curve %d\n", chcurv_ptr->get_id() );
      //CubitVector start, end;
      DLIList<ChollaPoint *> fpm_list = chcurv_ptr->get_points();
      for (kk=0; kk<fpm_list.size(); kk++)
      {
        ChollaPoint *chpnt_ptr = fpm_list.get_and_step();
        FacetEntity *facet_point = chpnt_ptr->get_facets();
        if (facet_point)
        {
          CubitPoint *point_ptr = CAST_TO(facet_point, CubitPoint);
          CubitVector pt = point_ptr->coordinates();
          fprintf(fp, "      (%d) x = %8.4f y = %8.4f z = %8.4f\n",
                  chpnt_ptr->get_id(), pt.x(), pt.y(), pt.z());
        }
      }
    }
  }
  fclose(fp);
}

//===============================================================================
//Function:  dump (PUBLIC)
//Description: debug
//===============================================================================
void ChollaEngine::dump( const char *filename, double angle )
{
  int include_results = 0;
  int num_face = faceList.size();
  int num_edge = edgeList.size();
  int num_vert = pointList.size();
  int *face_edge = new int [3*num_face];
  int *edge_vert = new int [2*num_edge];
  double *vert = new double [3*num_vert];

  int ii;
  CubitVector loc;
  CubitPoint *point_ptr;
  pointList.reset();
  for (ii=0; ii<num_vert; ii++)
  {
    point_ptr = dynamic_cast<CubitPoint *>(pointList.get_and_step());
    point_ptr->set_id( ii );
    loc = point_ptr->coordinates();
    vert[ii*3] = loc.x();
    vert[ii*3+1] = loc.y();
    vert[ii*3+2] = loc.z();
  }

  CubitFacetEdge *edge_ptr;
  edgeList.reset();
  for (ii=0; ii<num_edge; ii++)
  {
    edge_ptr = dynamic_cast<CubitFacetEdge *>(edgeList.get_and_step());
    edge_ptr->set_id( ii );
    edge_vert[ii*2] = edge_ptr->point( 0 )->id();
    edge_vert[ii*2+1] = edge_ptr->point( 1 )->id();
  }

  CubitFacet *facet_ptr;
  faceList.reset();
  for(ii=0; ii<num_face; ii++)
  {
    facet_ptr = dynamic_cast<CubitFacet *>(faceList.get_and_step());
    face_edge[ii*3] = facet_ptr->edge( 0 )->id();
    face_edge[ii*3+1] = facet_ptr->edge( 1 )->id();
    face_edge[ii*3+2] = facet_ptr->edge( 2 )->id();
  }

  double *edge_control_points = new double [3*3*num_edge];
  double *tri_control_points = new double [3*6*num_face];
  double *quad_control_points = NULL;

  char mesh_filename[256];
  sprintf(mesh_filename, "%s.mesh", filename);
  dumpMesh(mesh_filename, include_results, angle, num_face, 0, num_edge,
           num_vert, face_edge, NULL, edge_vert, vert, edge_control_points, 
           tri_control_points, quad_control_points);

  constructBezier( angle, num_face, 0, num_edge, num_vert, face_edge, NULL,
                   edge_vert, vert, edge_control_points, tri_control_points,
                   quad_control_points );

  char result_filename[256];
  sprintf(result_filename, "%s.results", filename);
  dumpResults(result_filename, num_edge, num_face, 0, 
              edge_control_points, tri_control_points, quad_control_points );

  include_results = 1;
  char full_filename[256];
  sprintf(full_filename, "%s.full", filename);
  dumpMesh(full_filename, include_results, angle, num_face, 0, num_edge,
           num_vert, face_edge, NULL, edge_vert, vert, edge_control_points, 
           tri_control_points, quad_control_points);

  delete [] face_edge;
  delete [] edge_vert;
  delete [] vert;
  delete [] edge_control_points;
  delete [] tri_control_points;
}

//===============================================================================
//Function:  mark_features (PUBLIC)
//Description: Calling this before ChollaEngine create geometry / topology
// allows you to define features points. This can be used in conjunction
// with the feature angle option or exclusively (original intention).
//===============================================================================
void ChollaEngine::mark_features (DLIList<CubitPoint*> &feature_points)
{
  int ii;
  TDGeomFacet *td_gm = NULL;
  CubitPoint *curr_pt = NULL;

    // loop through supplied CubitPoint*
    // set the hit flag on each one
  
  for (ii=0; ii < feature_points.size(); ++ii)
  {
    curr_pt = feature_points.get_and_step();
    TDGeomFacet::add_geom_facet(curr_pt, -1);
    td_gm = TDGeomFacet::get_geom_facet(curr_pt);
    td_gm->set_hit_flag(1);
    curr_pt->set_as_feature();
  }
}

//===============================================================================
//Function:  mark_features (PUBLIC)
//Description: Calling this before ChollaEngine create geometry / topology
// allows you to define features points. This can be used in conjunction
// with the feature angle option or exclusively (original intention).
//===============================================================================
void ChollaEngine::mark_features (DLIList<CubitFacetEdge*> &feature_edges)
{
  int ii;
  CubitFacetEdge *curr_edge = NULL;
	
	// loop through supplied CubitFaceEdge*
	// set the hit flag on each one

  for (ii=0; ii < feature_edges.size(); ++ii)
  {
    curr_edge = feature_edges.get_and_step();
    curr_edge->set_as_feature();
  }
}

  
static CubitStatus create_tri_facets(int *face_list,int current_position,
                                     CubitPoint **point_list,
                                     DLIList <CubitFacet*> &facet_list)
{
  int step = face_list[current_position];
    //This function is hard coded to work for splitting 4, 5, and 6
    //faceted points into triangles.
  if ( step > 6 || step < 4 )
  {
    PRINT_ERROR("Trying to split facets with wrong function.\n");
    return CUBIT_FAILURE;
  }
    //Basically get the points in a list first.
  int ii = current_position + 1, jj;
  DLIList <CubitPoint*> temp_points;
  
  for( jj = ii; jj < ii+step; jj++ )
  {
    int index_to_point = face_list[jj];
    assert(index_to_point >= 0 );
    temp_points.append(point_list[index_to_point]);
  }
    //Now cycle through the points and creat facets from them.
  CubitPoint *point_1, *point_2, *point_3;
    //This definatly could be improved to get more optimal triangles...
    //Create the first two facets in the normal way.  This is the
    //same for 4, 5 and 6 points.
  for ( jj = 0; jj < 2; jj++ )
  {
    point_1 = temp_points.get_and_step();
    point_2 = temp_points.get_and_step();
    point_3 = temp_points.get();
      //If these are colinear we are screwed...
    CubitFacet *new_facet = (CubitFacet *)
      new CubitFacetData(point_1, point_2, point_3);
    facet_list.append(new_facet);
  }
    //create the third facet for 5 points.
  if ( step == 5 )
  {
      //Now create the last facet with the first point, last point and
      //third point.
    temp_points.reset();
    point_1 = temp_points.prev();
    point_2 = temp_points.get();
    point_3 = temp_points.next(2);
    CubitFacet *new_facet = (CubitFacet *)
      new CubitFacetData(point_1, point_2, point_3);
    facet_list.append(new_facet);
  }
    //create the third and fourth for 6 points.
  else if ( step == 6 )
  {
      //get the current point (should be position 5/6)
    point_1 = temp_points.get();
      //get the next point. (should be position 6/6)
    point_2 = temp_points.next();
      //get the prev(2) point. ( should be position 3/6)
    point_3 = temp_points.prev(2);
    CubitFacet *new_facet = (CubitFacet *)
      new CubitFacetData(point_1, point_2, point_3);
    facet_list.append(new_facet);
      // get the next point. (should be 6/6)
    point_1 = temp_points.next();
      // get the next 2 point ( should be 1/6)
    point_2 = temp_points.next(2);
      //point3 stays the same (position 3/6).
    new_facet = (CubitFacet *)
      new CubitFacetData(point_1, point_2, point_3);
    facet_list.append(new_facet);
  }
  return CUBIT_SUCCESS;
}

//===================================================================================
// Description: given facets in the form of a GMem data structure create new
//              CubitFacet and CubitPoint classes and return in lists
// Notes: 
// Author: 
// Date: 
//===================================================================================
CubitStatus ChollaEngine::get_facets(GMem& gMem, DLIList<CubitFacet*> &facet_list, 
                                     DLIList<CubitPoint*> &dl_point_list,
                                     bool insert_null_facets )
{
  if(gMem.fListCount == 0)
    return CUBIT_FAILURE;

  GPoint* plist = gMem.point_list();
  CubitPoint **point_list = (CubitPoint **)
    new CubitPointData *[gMem.pointListCount];
  double x, y, z;
  int i,j;
  for (i = 0; i<gMem.pointListCount; i++) 
  {
    x = plist[i].x;
    y = plist[i].y;
    z = plist[i].z;
    CubitPoint *new_point = (CubitPoint *) new CubitPointData(x, y, z);
    point_list[i] = new_point;
    dl_point_list.append(new_point);
  } 
  int *face_list = gMem.facet_list();
  int step;
  DLIList<CubitPoint*> temp_points;
  CubitFacet *new_facet;
  int ii, index_to_point;
  CubitStatus stat1;
  for ( i = 0; i < gMem.fListCount; i++ )
  {
    step = face_list[i];
      //Now get the points for this facet.
    switch (step)
    {
      case 3:
        ii = i + 1;
        temp_points.clean_out();
        for( j = ii; j < ii+step; j++ )
        {
          index_to_point = face_list[j];
          assert(index_to_point >= 0 && index_to_point <= gMem.pointListCount );
          temp_points.append(point_list[index_to_point]);
        }

        if( temp_points.get() != temp_points.next() &&
            temp_points.get() != temp_points.next(2) &&
            temp_points.next() != temp_points.next(2) )
        {
          new_facet = (CubitFacet *)
          new CubitFacetData(temp_points.get(), 
                             temp_points.next(),
                             temp_points.next(2) );
          facet_list.append(new_facet);
        }
        i = i+step;
        break;
      case 4:
      case 5:
      case 6:
        stat1 = create_tri_facets(face_list,i, point_list,
                                  facet_list);
        if ( stat1 != CUBIT_SUCCESS )
        {
          PRINT_ERROR("Facets were not triangular and couldn't be split\n");
          return stat1;
        }
        i = i+step;
        break;
      default:
          //We currently can't handle this...
          //Eventually we will have to split this polygon into more facets.
        PRINT_ERROR("Facets were not triangular, and couldn't be made so.\n");
        PRINT_ERROR("Surface has: %d points forming a facet.\n", step);
        if( insert_null_facets )
          facet_list.append( NULL );
        return CUBIT_FAILURE;
    }
  }
  delete [] point_list;
  return CUBIT_SUCCESS;
}

//=============================================================================
//Function: collapses a given curve to a given point_to_keep
//          
//Description:
//Note: the hashing and other data structures are not updated during collapse.
//Author: william roshan quadros
//Date:  12/15/08
//=============================================================================
CubitStatus ChollaEngine::collapse_curve( ChollaCurve *cholla_curve, ChollaPoint *point_to_keep )
{
  // Make sure there are no underlying facet edges connected with this curve
  if( cholla_curve->get_facet_list().size() )
    return CUBIT_FAILURE;
  
  // Disassociate from cholla_surfaces 
  DLIList<ChollaSurface *> &ref_surfaces = cholla_curve->get_surfaces();
  int i;
  ChollaSurface *cholla_surface;
  for( i = 0; i < ref_surfaces.size(); i++ )
  {
    cholla_surface = ref_surfaces.get_and_step();
    cholla_surface->remove_curve( cholla_curve );
  }
  ref_surfaces.clean_out();

  // Disassociate from cholla point_to_delete 
  // Make sure curve has at least one point
  DLIList<ChollaPoint *> &cholla_pnts = cholla_curve->get_points();
  if( 0 == cholla_pnts.size()  )
    return CUBIT_FAILURE;

    // free eval tool
  if( cholla_curve->get_eval_tool() )
  {
    delete cholla_curve->get_eval_tool(); 
  }

  // find the point to delete
  ChollaPoint *first_pnt = cholla_pnts.get_and_step();
  ChollaPoint *last_pnt = cholla_pnts.get();
  ChollaPoint *point_to_del = NULL;
  switch( cholla_pnts.size() )
  {

  case 2:    
    if( point_to_keep == last_pnt )
    {
      point_to_del = first_pnt;
    }
    else
    {
      if( point_to_keep == first_pnt )
      {
        point_to_del = last_pnt;
      }
    }

    // disassociate end points from cholla_curve
    if( point_to_del )
    {
      point_to_del->remove_curve( cholla_curve );
      cholla_pnts.remove( point_to_del );
    }
    if( point_to_keep )
    {
      point_to_keep->remove_curve( cholla_curve );
      cholla_pnts.remove( point_to_keep );
    }

    // Merge two points 
    merge_two_points( point_to_keep, point_to_del );

    break;

  case 1:
    // disassociate end points from cholla_curve
    point_to_del = first_pnt;
    point_to_del->remove_curve( cholla_curve );
    cholla_pnts.remove( point_to_del );
    
    if( 0 == point_to_del->get_curve_list_ptr()->size() )
    {
      // remove point_to_del from ChollaEngine
      remove_point( point_to_del );

      // free point_to_del
      delete point_to_del;
    }    
    break;

  default:
    return CUBIT_FAILURE;
  }


  // Disassociate curve from chollaEngine
  this->remove_curve( cholla_curve );

  // free the cholla_curve
  delete cholla_curve;

  return CUBIT_SUCCESS;
}

  // Merge two points 
CubitStatus ChollaEngine::merge_two_points( ChollaPoint *point_to_keep, ChollaPoint *point_to_del )
{
  // move cholla curves from point_to_del to point_to_keep
  DLIList<ChollaCurve *> &del_pnt_curves = point_to_del->get_curves();
  int i;
  ChollaCurve *cholla_curve;
  for( i = 0; i < del_pnt_curves.size(); i++ )
  {
    cholla_curve = del_pnt_curves.get_and_step();
    
    cholla_curve->remove_point( point_to_del );
    cholla_curve->add_point( point_to_keep );
    point_to_keep->add_curve( cholla_curve );
  }
  del_pnt_curves.clean_out();

  // if point_to_keep facet is null use point_to_del's facet
  if( NULL == point_to_keep->get_facets() && point_to_del->get_facets() )
  {
    point_to_keep->add_facet( point_to_del->get_facets() );
  }
  
  // what we should do with data member id?  should we move if point_to_keep->get_id() !=  0?

  // remove point_to_del from ChollaEngine
  remove_point( point_to_del );

  // free point_to_del
  delete point_to_del;

  return CUBIT_SUCCESS;
}



CubitStatus ChollaEngine::disassociate_surface( ChollaSurface *cholla_surf )
{
   // remove surface from volume
  DLIList<ChollaVolume *> cholla_volumes;
  cholla_surf->get_volumes(cholla_volumes);
  int i;
  ChollaVolume *cholla_volume;
  for (i=0; i<cholla_volumes.size(); i++)
  {
    cholla_volume = cholla_volumes.get_and_step();
    cholla_volume->remove_surface( cholla_surf );
  }
  
   // Disassociate curves from suface
  DLIList< ChollaCurve *> cholla_curves;
  cholla_surf->get_curves( cholla_curves );
  
  ChollaCurve *cholla_curve;
  for( i = 0; i < cholla_curves.size(); i++ )
  {
    cholla_curve = cholla_curves.get_and_step();
    
    cholla_curve->remove_surface( cholla_surf );
    cholla_surf->remove_curve( cholla_curve );
  }
  cholla_curves.clean_out();

  // Remove facet tool if available ?
  if( cholla_surf->get_eval_tool() )
  {
#ifdef _DEBUG
    //PRINT_INFO("WARNING: delete ch_surf->facet_eval_tool safely \n");//   
#endif
    //delete cholla_surf->get_eval_tool();
    // set eval tool to NULL
  }
  
  // remove from ChollaEngine
  remove_surface( cholla_surf );

  return CUBIT_SUCCESS;

}
//=============================================================================
//Function: collapses a given surface 
//Description: currently it disassociates surface with its curves and ChollaEngine 
//Note: make sure there are no underlying facets and model is automatically watertight when input cholla_surf is deleted
//Author: william roshan quadros
//Date:  12/15/08
//=============================================================================

CubitStatus ChollaEngine::collapse_surface( ChollaSurface *cholla_surf )
{
  // Make sure there are no facets 
  if( cholla_surf->get_facet_list().size() )
     return CUBIT_FAILURE; 

  disassociate_surface( cholla_surf );
  
  // free cholla surface
  delete cholla_surf;

  return CUBIT_SUCCESS;
}

CubitStatus ChollaEngine::remove_facet_entity( CubitFacet *facet, ChollaSurface *cholla_surf )
{
  this->faceList.remove( facet );

  if( cholla_surf )
    cholla_surf->remove_facet( facet );

  return CUBIT_SUCCESS;
}
  
CubitStatus ChollaEngine::remove_facet_entity( CubitFacetEdge *facet_edge, ChollaCurve *cholla_curve )
{
  this->edgeList.remove( facet_edge );

  if( cholla_curve )
    cholla_curve->remove_facet( facet_edge );

  return CUBIT_SUCCESS;
}

CubitStatus ChollaEngine::remove_facet_entity( CubitPoint *facet_pnt, ChollaPoint *cholla_point )
{
  this->pointList.remove( facet_pnt );

  if( cholla_point )
    cholla_point->remove_facet(/* facet_pnt */);

  return CUBIT_SUCCESS;
}

CubitStatus ChollaEngine::remove_facet_entity( CubitFacet *facet, std::set<ChollaEntity *> &cholla_surfs )
{
  std::set<ChollaEntity *>::iterator set_it;
  for( set_it = cholla_surfs.begin(); set_it != cholla_surfs.end(); set_it++ )
  {
    if( dynamic_cast< ChollaSurface *>(*set_it) )
    {
      static_cast<ChollaSurface *>(*set_it)->remove_facet( facet );
    }
  }

  this->faceList.remove( facet );

  return CUBIT_SUCCESS;
}
  
CubitStatus ChollaEngine::remove_facet_entity( CubitFacetEdge *facet_edge, std::set<ChollaEntity *> &cholla_curves )
{
  
  std::set<ChollaEntity *>::iterator set_it;
  for( set_it = cholla_curves.begin(); set_it != cholla_curves.end(); set_it++ )
  {
    if( dynamic_cast<ChollaCurve*>(*set_it) )
    { 
      dynamic_cast<ChollaCurve*>(*set_it)->remove_facet( facet_edge );
    }
  }

  this->edgeList.remove( facet_edge );

  return CUBIT_SUCCESS;
}

CubitStatus ChollaEngine::replace_facet_entity( CubitFacetEdge *remove_edge, CubitFacetEdge *replace_edge, std::set<ChollaEntity *> cholla_curves )
{
  std::set<ChollaEntity *>::iterator set_it; 
  for( set_it = cholla_curves.begin(); set_it != cholla_curves.end(); set_it++ )
  {
    if( dynamic_cast<ChollaCurve*>(*set_it) )
    { 
      static_cast<ChollaCurve*>(*set_it)->replace_facet( remove_edge, replace_edge );
    }
  }

  return CUBIT_SUCCESS;
}


CubitStatus ChollaEngine::remove_facet_entity( CubitPoint *facet_pnt, std::set<ChollaEntity *> &cholla_points )
{
  this->pointList.remove( facet_pnt );

  std::set<ChollaEntity *>::iterator set_it;
  for( set_it = cholla_points.begin(); set_it != cholla_points.end(); set_it++ )
  {
    if( dynamic_cast<ChollaPoint*>(*set_it) )
    { 
      static_cast<ChollaPoint*>(*set_it)->remove_facet( facet_pnt );
    }
  }

  return CUBIT_SUCCESS;
}

/*
// disassoicate ch_entity from ch_points, ch_curve, ch_surf, and ch_engine
CubitStatus ChollaEngine::disassociate_curve( ChollaCurve *ch_curve )
{
  
  // disassociate from cholla points
  ch_curve->disassociate_from_points();
  
  // disassociate from cholla surface
  ch_curve->disassociate_from_surfaces();

  // disassociate from cholla engine
  remove_curve( ch_curve );

  return CUBIT_SUCCESS;
}
*/

CubitStatus ChollaEngine::create_surface( int block_id,
                                          ChollaSurface *&new_ch_surf )
{
  new_ch_surf = new ChollaSurface( block_id );
  
  // add it to cholla engine
  chollaSurfaceList.append( new_ch_surf ); 

  return CUBIT_SUCCESS;
}

 // Create new ch_curve and associate with end ch_points.  Add ch_curve to chollaEngine
CubitStatus ChollaEngine::create_curve(int block_id, 
                                       ChollaPoint *new_ch_pnt0, 
                                       ChollaPoint *new_ch_pnt1, 
                                       ChollaCurve *&new_ch_curve
                                    )
{

  
  new_ch_curve = new ChollaCurve( block_id );

  // associate with cholla points
  new_ch_curve->add_point( new_ch_pnt0 );
  new_ch_pnt0->add_curve( new_ch_curve );
  new_ch_curve->add_point( new_ch_pnt1 );
  new_ch_pnt1->add_curve( new_ch_curve );


  // update start and end facet points
  new_ch_curve->set_start( CAST_TO( new_ch_pnt0->get_facets(), CubitPointData) );
  new_ch_curve->set_end( CAST_TO( new_ch_pnt1->get_facets(), CubitPointData) );

  // add it to cholla engine
  chollaCurveList.append( new_ch_curve ); 

  return CUBIT_SUCCESS;
}

CubitStatus ChollaEngine::create_point( CubitPoint *pnt, ChollaPoint * &new_ch_pnt )
{
  new_ch_pnt = new ChollaPoint();
  new_ch_pnt->add_facet( pnt );
  double *coordinate = new double[3];
  CubitVector coord_vect = pnt->coordinates();
  coordinate[0] = coord_vect[0];
  coordinate[1] = coord_vect[1];
  coordinate[2] = coord_vect[2];
  new_ch_pnt->assign_geometric_point( (void*) coordinate );

  return CUBIT_SUCCESS;
}


// disassoicate ch_curve from ch_points, ch_surfs, and ch_engine
CubitStatus ChollaEngine::disassociate_curve( ChollaCurve *ch_curve, bool disassociate_with_vert, bool disassociate_with_surf, bool disassociate_with_model )
{
  // remove ch_curve from ch_point
  int i;
  if( disassociate_with_vert )
  {
    for( i = 0; i < ch_curve->get_points().size(); i++ )
    {
      ch_curve->get_points().get_and_step()->remove_curve( ch_curve );
    }
    // remove ch_points
    ch_curve->get_points().clean_out();
  }

  if( disassociate_with_surf )
  {
    // remove ch_curve in ch_surface
    ChollaSurface *ptr_ch_surf;   
    for( i = 0; i < ch_curve->get_surfaces().size(); i++ )
    {
      ptr_ch_surf = ch_curve->get_surfaces().get_and_step();
      ptr_ch_surf->remove_curve( ch_curve );
    }
    // remove ch_surface
    ch_curve->get_surfaces().clean_out();
  }

  if( disassociate_with_model )
  {
    // remove from ch_engie
    this->remove_curve( ch_curve );
  }

  return CUBIT_SUCCESS;
}

//=============================================================================
//Function: detach_volumes 
//Description: Create independent manifold volumes from the non-manifold set 
//Note: 
//Author:sjowen
//Date:  09/10/09
//=============================================================================
CubitStatus ChollaEngine::detach_volumes()
{
  CubitStatus rv = CUBIT_SUCCESS;
 
  // define maps between the original entities and their copies so we can 
  // use them for detaching the facets
  
  std::map<ChollaSurface *, ChollaSurface *> surf_map;
  std::multimap<ChollaCurve *, ChollaCurve *> curve_map;
  std::multimap<ChollaPoint *, ChollaPoint *> point_map; 
  
  for( int i=chollaVolumeList.size(); i--; )
  {
    ChollaVolume *chvol = chollaVolumeList.get_and_step();
    DLIList<ChollaSurface*> ch_surfaces;
    chvol->get_surfaces( ch_surfaces );    

    std::map<ChollaCurve *, ChollaCurve *> tmp_curve_map;
    std::map<ChollaPoint *, ChollaPoint *> tmp_point_map; 
    
    DLIList<ChollaSurface*> surfaces_to_detach;
    DLIList<ChollaCurve*> curves_to_detach;
    for( int j=ch_surfaces.size(); j--; )
    {
      ChollaSurface *chsurf_ptr = ch_surfaces.get_and_step();     

      // look for any surfaces that are associated with exactly two volumes
      if (chsurf_ptr->num_volumes() == 2)      
        surfaces_to_detach.append( chsurf_ptr );   
      else
      {
        //look for any curves that are attached to two volumes
        DLIList<ChollaCurve*> ch_curves;
        chsurf_ptr->get_curves( ch_curves );
        for( int k=ch_curves.size(); k--; )
        {
          ChollaCurve *tmp_curve = ch_curves.get_and_step();
          if( tmp_curve->num_volumes() > 1 )
            curves_to_detach.append( tmp_curve );
        }
      }
    }   

    //filter out curves that are in surfs in 'surfaces_to_detach'
    //since they will get detached when the parent surface gets detached
    for( int j=curves_to_detach.size(); j--; )
    {
      ChollaCurve *tmp_curve = curves_to_detach.get();
      DLIList<ChollaSurface*> tmp_surfs = tmp_curve->get_surfaces();

      for( int k=tmp_surfs.size(); k--; )
      {
        ChollaSurface *tmp_surf = tmp_surfs.get_and_step();
        if( surfaces_to_detach.is_in_list( tmp_surf ) )
        {
          curves_to_detach.change_to(NULL);
          break;
        }
      }
      curves_to_detach.step();    
    }  
    
    curves_to_detach.remove_all_with_value( NULL );
    curves_to_detach.uniquify_unordered();

    if( surfaces_to_detach.size() || curves_to_detach.size() )
    {
      rv = detach_surfaces( surfaces_to_detach, curves_to_detach, chvol, surf_map, tmp_curve_map, tmp_point_map );
      if (rv != CUBIT_SUCCESS)
        return CUBIT_FAILURE;
      
      //for all detached surfaces, detach all the facets and create new ones for
      //the detached surfaces
      rv = detach_facets(surfaces_to_detach, curves_to_detach, chvol, surf_map, tmp_curve_map, tmp_point_map);
      if (rv != CUBIT_SUCCESS)
        return rv;

      // set the cubitpoints at the correct start/end locations on the cholla curves   
      rv = set_curve_endpoints(tmp_point_map, tmp_curve_map );
      if (rv != CUBIT_SUCCESS)
        return rv;
    }

    //append the map to the multi-map
    std::map<ChollaCurve*, ChollaCurve*>::iterator iter = tmp_curve_map.begin();
    for( ; iter!=tmp_curve_map.end(); iter++)
      curve_map.insert( std::pair<ChollaCurve*,ChollaCurve*>(iter->first, iter->second) );

    //append the map to the multi-map
    std::map<ChollaPoint*, ChollaPoint*>::iterator pt_iter = tmp_point_map.begin();
    for( ; pt_iter!=tmp_point_map.end(); pt_iter++)
      point_map.insert( std::pair<ChollaPoint*,ChollaPoint*>(pt_iter->first, pt_iter->second) );   
  } 
  
  // create the evaluation tools on the new entities
  
  CubitBoolean use_feature_angle = CUBIT_FALSE; 
  double min_dot = 0.0;                    
  int interp_order = 0;                 
  CubitBoolean smooth_non_manifold = CUBIT_FALSE;
  CubitBoolean split_surfaces = CUBIT_FALSE;
  DLIList<ChollaSurface *> cholla_surfaces;
  DLIList<ChollaCurve *> cholla_curves;
  
  // get lists of new surfaces and curves from the maps
  
  std::map<ChollaSurface *, ChollaSurface *>::iterator smap_it;
  for (smap_it=surf_map.begin(); smap_it != surf_map.end(); smap_it++)
  {
    cholla_surfaces.append(smap_it->second);
  }
  
  std::multimap<ChollaCurve *, ChollaCurve *>::iterator cmap_it;
  for (cmap_it=curve_map.begin(); cmap_it != curve_map.end(); cmap_it++)
  {
    cholla_curves.append(cmap_it->second);
  }
  
  // rebuild the new curves so the edges are oriented correctly
  
  for (int ii=0; ii<cholla_curves.size(); ii++)
  {
    ChollaCurve *cholla_curve = cholla_curves.get_and_step();
    DLIList<ChollaPoint *>  cholla_points = cholla_curve->get_points();    
    int periodic = 0;
    if (cholla_points.size() == 1)
      periodic = 1;
    else
      assert(cholla_points.size() == 2);  // assuming we have exactly two end points so far
    CubitPoint *start_point, *end_point;
    cholla_curve->get_ends(start_point, end_point);        
    int max_edges = cholla_curve->num_edges();
    cholla_curve->clean_out_edges();  // edges will be added in build_curve_from_edges 
    rv = cholla_curve->build_curve_from_edges( start_point, periodic, max_edges, NULL, cholla_curve );
    if (rv != CUBIT_SUCCESS)
      return rv;
  } 
  
  // replace the facets on the existing eval tools on the curves and surfaces bounding the interface.
  // for simplicity, just replace them on all the existing eval tools on 
  
  for (int icurv = 0; icurv < chollaCurveList.size(); icurv++)
  {
    ChollaCurve *chcurv_ptr = chollaCurveList.get_and_step();
    CurveFacetEvalTool *ceval = chcurv_ptr->get_eval_tool();
    if (ceval != NULL)
    {
      DLIList<FacetEntity *> fedges = chcurv_ptr->get_facet_list();
      DLIList<CubitFacetEdge *> edges;
      CAST_LIST( fedges, edges, CubitFacetEdge );
      ceval->replace_facets(edges);
    }
  }
  
  for (int isurf=0; isurf<chollaSurfaceList.size(); isurf++)
  {
    ChollaSurface *chsurf_ptr = chollaSurfaceList.get_and_step();
    FacetEvalTool *seval = chsurf_ptr->get_eval_tool();
    if (seval != NULL)
    {
      DLIList<FacetEntity *> ffacets = chsurf_ptr->get_facet_list();
      DLIList<CubitFacet *> facets;
      CAST_LIST( ffacets, facets, CubitFacet );
      seval->replace_facets(facets);
    }
  }
 
  
  // build the eval tools
      
  rv = build_eval_tools(cholla_surfaces,
                        cholla_curves,
                        interp_order, use_feature_angle, 
                        min_dot, smooth_non_manifold,
                        split_surfaces );
    
  return rv;
}

//=============================================================================
//Function: detach_surface 
//Description: given a non-manifold surface in a cholla model, create a copy
//             and update child entities
//Notes:  assumes that chsurf_ptr has exactly 2 adjacent volumes
//Author:sjowen
//Date:  09/18/09
//=============================================================================
CubitStatus ChollaEngine::detach_surfaces(DLIList<ChollaSurface*> &chsurfs,
                                          DLIList<ChollaCurve*> &chcurves,
                                         ChollaVolume *vol_getting_new_surfs,
                                         std::map<ChollaSurface *, ChollaSurface *> &surf_map,
                                         std::map<ChollaCurve *, ChollaCurve *> &curve_map,
                                         std::map<ChollaPoint *, ChollaPoint *> &point_map)
{
  CubitStatus rv = CUBIT_SUCCESS;
  
  // detach the surface from its volumes

  DLIList<ChollaCurve*> all_curves_in_surfs;
  DLIList<ChollaPoint*> all_points_in_surfs;

  std::multimap<ChollaCurve*, ChollaSurface*> orig_curve_to_new_surf_map;
  
  for( int i=chsurfs.size(); i--; )
  {
    ChollaSurface *chsurf_ptr = chsurfs.get_and_step();
    DLIList<ChollaVolume *> chvol_list;
    chsurf_ptr->get_volumes(chvol_list);
    ChollaVolume *chvol1_ptr = chvol_list.get_and_step();
    ChollaVolume *chvol2_ptr = chvol_list.get();

    if( chvol2_ptr != vol_getting_new_surfs )      
    {
      chvol1_ptr = chvol2_ptr;
      chvol2_ptr = vol_getting_new_surfs;      
    }

    if (NULL == chvol1_ptr || NULL == chvol2_ptr) {
      PRINT_ERROR("Unexpected NULL pointer for cholla volume.\n");
      return CUBIT_FAILURE;
    }
    assert(chvol1_ptr != chvol2_ptr);

    // create a copy of the non-manifold surface and attach it to volume 2

    ChollaSurface *newchsurf_ptr = new ChollaSurface( chsurf_ptr->get_block_id() );
    chollaSurfaceList.append(newchsurf_ptr);
    surf_map.insert(std::pair<ChollaSurface *, ChollaSurface *>(chsurf_ptr, newchsurf_ptr));

    chvol2_ptr->remove_surface(chsurf_ptr);
    chsurf_ptr->remove_volume(chvol2_ptr);
    chvol2_ptr->add_surface(newchsurf_ptr);
    newchsurf_ptr->add_volume(chvol2_ptr);
    
    chsurf_ptr->set_merge_partner(newchsurf_ptr);
    newchsurf_ptr->set_merge_partner(chsurf_ptr);

    // detach the curves  
    DLIList<ChollaCurve *> chcurv_list;
    chsurf_ptr->get_curves(chcurv_list);    

    for( int k=chcurv_list.size(); k--; )
    {
      ChollaCurve *chcurve = chcurv_list.get_and_step();
      orig_curve_to_new_surf_map.insert( std::pair<ChollaCurve*, ChollaSurface*>( chcurve, newchsurf_ptr ) );
    }

    all_curves_in_surfs += chcurv_list;

    DLIList<ChollaPoint*> chpt_list;
    chsurf_ptr->get_vertices( chpt_list );
    all_points_in_surfs += chpt_list;
  }

  all_curves_in_surfs.uniquify_unordered();  
  
  for(int icurv = 0; icurv < all_curves_in_surfs.size(); icurv++)
  {    
    ChollaCurve *chcurv_ptr = all_curves_in_surfs.get_and_step();

    std::multimap<ChollaCurve*, ChollaSurface*>::iterator iter, upper_iter;
    DLIList<ChollaSurface*> new_surfs;

    iter = orig_curve_to_new_surf_map.find( chcurv_ptr );

    assert( iter != orig_curve_to_new_surf_map.end() );

    upper_iter = orig_curve_to_new_surf_map.upper_bound( iter->first );

    for(; iter!=upper_iter; ++iter )
      new_surfs.append( iter->second );

    rv = detach_curve( chcurv_ptr, new_surfs, vol_getting_new_surfs, curve_map, point_map );
    if (rv != CUBIT_SUCCESS)
      return rv;  
  }

  for( int i=chcurves.size(); i--; )
  {
    DLIList<ChollaPoint*> tmp_pts = chcurves.get_and_step()->get_points();
    all_points_in_surfs += tmp_pts;
  }

  rv = detach_curves( chcurves, vol_getting_new_surfs, curve_map, point_map );
  if( rv != CUBIT_SUCCESS )
    return rv;

  //add the points in the cholla     
  all_points_in_surfs.uniquify_unordered();
  for (int ipt = 0; ipt < all_points_in_surfs.size(); ipt++)
  {
    ChollaPoint *chpt_ptr = all_points_in_surfs.get_and_step();
    
    rv = detach_point( chpt_ptr, vol_getting_new_surfs, point_map, curve_map );
    if (rv != CUBIT_SUCCESS)
      return rv;
  }   
  
  return rv;
}

CubitStatus ChollaEngine::detach_curves( DLIList<ChollaCurve*> &curves,
                                         ChollaVolume *detaching_volume,                                         
                                         std::map<ChollaCurve *, ChollaCurve *> &curve_map,
                                         std::map<ChollaPoint *, ChollaPoint *> &point_map )
{
  CubitStatus rv = CUBIT_SUCCESS;

  DLIList<ChollaSurface*> tmp_surfs;
  DLIList<ChollaPoint*> points_to_detach;
  for( int i=curves.size(); i--; )
  {    
    ChollaCurve *tmp_curve = curves.get_and_step();    

    //get the surfaces in 'detaching_volume'
    tmp_surfs.clean_out();
    tmp_surfs = tmp_curve->get_surfaces();
    for( int k=0; k<tmp_surfs.size(); k++ )
    {
      if( !tmp_surfs[k]->is_in_volume( detaching_volume) )
        tmp_surfs[k] = NULL;      
    }
    tmp_surfs.remove_all_with_value(NULL);

    rv = detach_curve( tmp_curve, tmp_surfs, detaching_volume, curve_map, point_map );
    if (rv != CUBIT_SUCCESS)
      return rv;

    DLIList<ChollaPoint*> tmp_pts = tmp_curve->get_points();
    points_to_detach += tmp_pts;<--- Variable 'points_to_detach' is assigned a value that is never used.
  }

  //go through the map, setting up merge partners
  std::map<ChollaCurve*, ChollaCurve*>::iterator iter = curve_map.begin();
  for( ; iter != curve_map.end(); iter++ )
  {
    ChollaCurve *ch_curv = iter->first;
    ChollaCurve *new_ch_curv = iter->second;

    ch_curv->set_merge_partner( new_ch_curv );
    new_ch_curv->set_merge_partner( ch_curv );
  }
  return rv;
}                                          

//=============================================================================
//Function: detach_curve 
//Description: given a non-manifold curve in a cholla model, create a copy
//             and update child entities. updates the curve_map
//Author:sjowen
//Date:  09/18/09
//=============================================================================
CubitStatus ChollaEngine::detach_curve(ChollaCurve *chcurv_ptr,
                                       DLIList<ChollaSurface*> &new_surfs,
                                       ChollaVolume *chvol2_ptr,
                                       std::map<ChollaCurve*, ChollaCurve*> &curve_map,
                                       std::map<ChollaPoint*, ChollaPoint*> &point_map )
{   
  // create a copy of the curve on the surface and add it to volume 2  

  ChollaCurve *newchcurv_ptr = new ChollaCurve( chcurv_ptr->get_block_id() );
  chollaCurveList.append( newchcurv_ptr );
  curve_map.insert(std::pair<ChollaCurve *, ChollaCurve *>(chcurv_ptr, newchcurv_ptr));
  
  for( int i=new_surfs.size(); i--; )
  {
    ChollaSurface *newchsurf_ptr = new_surfs.get_and_step();
    newchsurf_ptr->add_curve(newchcurv_ptr);
    newchcurv_ptr->add_surface(newchsurf_ptr);    
  }

  // any surfaces attached to this chcurv that are in vol2 are removed and the newchcurv is added
  DLIList<ChollaSurface *> chcsurf_list = chcurv_ptr->get_surfaces();
  for (int icsurf = 0; icsurf < chcsurf_list.size(); icsurf++)
  {
    ChollaSurface *chcsurf_ptr = chcsurf_list.get_and_step();

    //if the adjacent surfaces are in both volumes, don't do anything
    if(chcsurf_ptr->is_in_volume(chvol2_ptr) )      
    {
      chcurv_ptr->remove_surface(chcsurf_ptr);
      chcsurf_ptr->remove_curve(chcurv_ptr);
      newchcurv_ptr->add_surface(chcsurf_ptr);
      chcsurf_ptr->add_curve_unique(newchcurv_ptr);
    }  
  } 

  return CUBIT_SUCCESS;
}

//=============================================================================
//Function: detach_point 
//Description: given a non-manifold point in a cholla model, create a copy
//             and update connectivity. updates the point_map
//Author:sjowen
//Date:  09/18/09
//=============================================================================
CubitStatus ChollaEngine::detach_point(ChollaPoint *chpt_ptr,
                                       ChollaVolume *chvol2_ptr,
                                       std::map<ChollaPoint *, ChollaPoint *> &point_map,
                                       std::map<ChollaCurve *, ChollaCurve *> &curve_map )                                       
{ 
  
  
  ChollaPoint *newchpt_ptr = new ChollaPoint();
  chollaPointList.append( newchpt_ptr );
  point_map.insert(std::pair<ChollaPoint*, ChollaPoint*>(chpt_ptr, newchpt_ptr));  
     
  //find the curves that it is in
  DLIList<ChollaCurve *> chptcurv_list = chpt_ptr->get_curves();
  for (int iptcurv = 0; iptcurv < chptcurv_list.size(); iptcurv++)
  {
    ChollaCurve *chptcurv_ptr = chptcurv_list.get_and_step();

    // for curves that were copied (on the interface), add the new chollapoint to the new curve

    std::map<ChollaCurve *, ChollaCurve *>::iterator cmap_it;
    cmap_it = curve_map.find(chptcurv_ptr);
    if (cmap_it != curve_map.end())
    {
      ChollaCurve *new_chcurv_ptr = cmap_it->second;      
      new_chcurv_ptr->add_point(newchpt_ptr);
      newchpt_ptr->add_curve(new_chcurv_ptr);
      
      chpt_ptr->set_merge_partner( newchpt_ptr );
      newchpt_ptr->set_merge_partner( chpt_ptr );
    }
    else
    {
      // remove curve in vol 2 (not on interface) from the original point and add it to the new point
      
      if (chptcurv_ptr->is_in_volume(chvol2_ptr))
      {
        chpt_ptr->remove_curve(chptcurv_ptr);
        chptcurv_ptr->remove_point(chpt_ptr);
        newchpt_ptr->add_curve(chptcurv_ptr);
        chptcurv_ptr->add_point(newchpt_ptr);

        chpt_ptr->set_merge_partner( newchpt_ptr );
        newchpt_ptr->set_merge_partner( chpt_ptr );
      }
    }
  }

  return CUBIT_SUCCESS;
}
  

//=============================================================================
//Function: detach_facets 
//Description: detach the individual facets to create a manifold representation
//Note: makes a copy of the facets on the merged surface and its child entities
//      and reconnects them locally
//Author:sjowen
//Date:  09/10/09
//=============================================================================
CubitStatus ChollaEngine::detach_facets(DLIList<ChollaSurface*> &chsurfs,
                                        DLIList<ChollaCurve*> &chcurves,
                                        ChollaVolume *chvol,
                                        std::map<ChollaSurface *, ChollaSurface *> &surf_map,
                                        std::map<ChollaCurve *, ChollaCurve *> &curve_map,
                                        std::map<ChollaPoint *, ChollaPoint *> &point_map)
{  
  
  CubitStatus rv = CUBIT_SUCCESS;
  
  std::vector<CubitPoint *> new_points;
  std::vector<CubitFacetEdge *> new_edges;
  
  rv = copy_facets_at_interface( chsurfs, chcurves, new_points, new_edges,
                                 surf_map, curve_map, point_map );
  if (rv != CUBIT_SUCCESS)
    return rv;
  
  rv = connect_facets_at_interface( chsurfs, chcurves, chvol, new_points, new_edges );
  if (rv != CUBIT_SUCCESS)
    return rv;
  
  return rv;
}
  
//=============================================================================
//Function: copy_facets_at_interface 
//Description: 
//Author:sjowen
//Date:  09/18/09
//=============================================================================
CubitStatus ChollaEngine::copy_facets_at_interface(DLIList<ChollaSurface*> &chsurfs,
                                                   DLIList<ChollaCurve*> &chcurves,
                                                   std::vector<CubitPoint *> &new_points,
                                                   std::vector<CubitFacetEdge *> &new_edges,                                                   
                                                   std::map<ChollaSurface *, ChollaSurface *> &surf_map,
                                                   std::map<ChollaCurve *, ChollaCurve *> &curve_map,
                                                   std::map<ChollaPoint *, ChollaPoint *> &point_map)

{
  CubitStatus rv = CUBIT_SUCCESS;
  
  // first set the marked flags on all facets entities on this surface to -1
  
  int ifacet;
  DLIList<FacetEntity *> facet_list;
  for( int i=chsurfs.size(); i--; )
  {
    ChollaSurface *chsurf_ptr = chsurfs.get_and_step();
    chsurf_ptr->get_facets( facet_list );
  }

  for( int i=chcurves.size(); i--; )
  {
    DLIList<FacetEntity*> tmp_facets = chcurves.get_and_step()->get_facet_list();
    facet_list += tmp_facets;
  }

  FacetDataUtil::mark_facets(facet_list, FACET_ENTITY_UNINITIALIZED);
  
  // create a copy of each of the facet entities on the surface.  The marked flag in the facet will
  // keep track of the new entity created.  It will be a location in the new_points or new_edges
  // array.  Once we are finished with creating points and edges, we can create the new facets
  // given the references in the marked flags.
  
  // create new points
  
  rv = copy_points_at_interface(facet_list, new_points, surf_map, curve_map, point_map);
  if (rv != CUBIT_SUCCESS)
    return rv;
  
  // create new edges
  
  rv = copy_edges_at_interface(facet_list, new_points, new_edges, surf_map, curve_map, point_map);
  if (rv != CUBIT_SUCCESS)
    return rv;
  
  // create new facets
  
  DLIList<CubitFacet *> new_facets;
  for (ifacet = 0; ifacet<facet_list.size(); ifacet++)
  {
    FacetEntity *facet_ptr = facet_list.get_and_step();
    CubitFacet *cfacet_ptr = dynamic_cast<CubitFacet *> (facet_ptr);
    if( cfacet_ptr )
    {
      CubitFacetEdge *fedge, *newfedges[3];
      CubitFacet *newcfacet_ptr;
      for (int ii=0; ii<3; ii++)
      {
        fedge = cfacet_ptr->edge(ii);
        int idx = fedge->marked();
        newfedges[ii] = new_edges[idx];
      }
      newcfacet_ptr = (CubitFacet *) new CubitFacetData(newfedges[0], newfedges[1], newfedges[2]);
      new_facets.append( newcfacet_ptr );
      FacetEntity *newfacet_ptr = dynamic_cast<FacetEntity *> (newcfacet_ptr);
      set_new_facet_owners( 2, facet_ptr, newfacet_ptr, surf_map, curve_map, point_map );
    } 
  }
  
  // make sure facets are oriented consistently on new volume
  if( new_facets.size() )
  {
    CubitFacet *start_facet = new_facets.get(); 
    CubitBoolean do_flip = CUBIT_TRUE;
    int nfacets;
    int mydebug = 0;
    rv = check_facet_orientation(start_facet, do_flip, nfacets, mydebug );
  }
  
  return rv;
}


CubitStatus ChollaEngine::detach_facet_edges(DLIList<ChollaCurve*> &chcurves,
                                             ChollaVolume *detaching_volume,                                             
                                             std::map<ChollaCurve *, ChollaCurve *> &curve_map,
                                             std::map<ChollaPoint *, ChollaPoint *> &point_map )
{  
  
  CubitStatus rv = CUBIT_SUCCESS;
  
  std::vector<CubitPoint *> new_points;
  std::vector<CubitFacetEdge *> new_edges;
  
  rv = copy_facet_edges_at_interface( chcurves, new_points, new_edges, curve_map, point_map );
  if (rv != CUBIT_SUCCESS)
    return rv;

  for (int i=chcurves.size(); i--; )
  {
    ChollaCurve *chcurv_ptr = chcurves.get_and_step();    
    rv = connect_points_at_interface( chcurv_ptr, detaching_volume, new_points );
    if (rv != CUBIT_SUCCESS)
      return rv;
    
    rv = connect_edges_at_interface( chcurv_ptr, detaching_volume, new_edges );
    if (rv != CUBIT_SUCCESS)
      return rv;
  }   
  
  return rv;
}


CubitStatus ChollaEngine::copy_facet_edges_at_interface(DLIList<ChollaCurve*> &chcurves,
                                                   std::vector<CubitPoint *> &new_points,
                                                   std::vector<CubitFacetEdge *> &new_edges,                                                                                                      
                                                   std::map<ChollaCurve *, ChollaCurve *> &curve_map,
                                                   std::map<ChollaPoint *, ChollaPoint *> &point_map)

{
  CubitStatus rv = CUBIT_SUCCESS;
  
  // first set the marked flags on all facets entities to -1  
  DLIList<FacetEntity *> facet_list;
  for( int i=chcurves.size(); i--; )
  {
    ChollaCurve *chcurv_ptr = chcurves.get_and_step();
    DLIList<FacetEntity*> tmp_facet_list = chcurv_ptr->get_facet_list();
    facet_list += tmp_facet_list;
  }

  FacetDataUtil::mark_facets(facet_list, FACET_ENTITY_UNINITIALIZED);
  
  // create a copy of each of the facet entities on the surface.  The marked flag in the facet will
  // keep track of the new entity created.  It will be a location in the new_points or new_edges
  // array.  Once we are finished with creating points and edges, we can create the new facets
  // given the references in the marked flags.
  
  // create new points

  std::map<ChollaSurface *, ChollaSurface *> dummy_surf_map;
  
  rv = copy_points_at_interface(facet_list, new_points, dummy_surf_map, curve_map, point_map);
  if (rv != CUBIT_SUCCESS)
    return rv;
  
  // create new edges
  
  rv = copy_edges_at_interface(facet_list, new_points, new_edges, dummy_surf_map, curve_map, point_map);
  if (rv != CUBIT_SUCCESS)
    return rv;  
  
  return rv;
}

//=============================================================================
//Function: copy_points_at_interface 
//Description: copy the points at the interface        
//Author:sjowen
//Date:  09/18/09
//=============================================================================
CubitStatus ChollaEngine::copy_points_at_interface(DLIList<FacetEntity *> &facet_list,
                                                   std::vector<CubitPoint *> &new_points,                                                   
                                                   std::map<ChollaSurface *, ChollaSurface *> &surf_map,
                                                   std::map<ChollaCurve *, ChollaCurve *> &curve_map,
                                                   std::map<ChollaPoint *, ChollaPoint *> &point_map)
{
  int iploc = 0;
  
  FacetEntity *fe_ptr, *newfe_ptr;
  CubitPoint *point_ptr, *newpoint_ptr;

  for (int ifacet = 0; ifacet<facet_list.size(); ifacet++)
  {
    FacetEntity *facet_ptr = facet_list.get_and_step();
    CubitFacet *cfacet_ptr = dynamic_cast<CubitFacet*>(facet_ptr);
    if( cfacet_ptr )
    {     
      for (int ii=0; ii<3; ii++)
      {
        point_ptr = cfacet_ptr->point(ii);        
        if (point_ptr->marked() == FACET_ENTITY_UNINITIALIZED)
        {
          newpoint_ptr = (CubitPoint *) new CubitPointData( point_ptr->x(), point_ptr->y(), point_ptr->z() );
          new_points.push_back(newpoint_ptr);
          point_ptr->marked(iploc++);
          fe_ptr = dynamic_cast<FacetEntity *> (point_ptr);
          newfe_ptr = dynamic_cast<FacetEntity *> (newpoint_ptr);
          set_new_facet_owners(0, fe_ptr, newfe_ptr, surf_map, curve_map, point_map );
        }   
      } 
    } 
    else
    {
      CubitFacetEdge *cfacet_edge_ptr = dynamic_cast<CubitFacetEdge*>(facet_ptr);      
      for (int ii=0; ii<2; ii++)
      {
        point_ptr = cfacet_edge_ptr->point(ii);
        if (point_ptr->marked() == FACET_ENTITY_UNINITIALIZED)
        {
          newpoint_ptr = (CubitPoint *) new CubitPointData( point_ptr->x(), point_ptr->y(), point_ptr->z() );
          new_points.push_back(newpoint_ptr);
          point_ptr->marked(iploc++);
          fe_ptr = dynamic_cast<FacetEntity *> (point_ptr);
          newfe_ptr = dynamic_cast<FacetEntity *> (newpoint_ptr);
          set_new_facet_owners(0, fe_ptr, newfe_ptr, surf_map, curve_map, point_map );
        }   
      } 
    }
  }
  
  return CUBIT_SUCCESS;
}

//=============================================================================
//Function: copy_edges_at_interface 
//Description: copy the edges at the interface        
//Author:sjowen
//Date:  09/18/09
//=============================================================================
CubitStatus ChollaEngine::copy_edges_at_interface(DLIList<FacetEntity *> &facet_list,
                                                  std::vector<CubitPoint *> &new_points,
                                                  std::vector<CubitFacetEdge *> &new_edges,                                                  
                                                  std::map<ChollaSurface *, ChollaSurface *> &surf_map,
                                                  std::map<ChollaCurve *, ChollaCurve *> &curve_map,
                                                  std::map<ChollaPoint *, ChollaPoint *> &point_map)
{
  int ieloc = 0;
  CubitFacetEdge *edge_ptr, *newedge_ptr;<--- Shadowed declaration
  for (int ifacet = 0; ifacet<facet_list.size(); ifacet++)
  {
    FacetEntity *facet_ptr = facet_list.get_and_step();
    CubitFacet *cfacet_ptr = dynamic_cast<CubitFacet *> (facet_ptr);
    if( cfacet_ptr )
    {      
      for (int ii=0; ii<3; ii++)
      {
        edge_ptr = cfacet_ptr->edge(ii);
        if (edge_ptr->marked() == FACET_ENTITY_UNINITIALIZED)
        {
          CubitPoint *p0 = edge_ptr->point( 0 );
          CubitPoint *p1 = edge_ptr->point( 1 );
          int idx0 = p0->marked();
          int idx1 = p1->marked();
          CubitPoint *newp0 = new_points[idx0];
          CubitPoint *newp1 = new_points[idx1];
          newedge_ptr = (CubitFacetEdge *) new CubitFacetEdgeData( newp0, newp1 );
          new_edges.push_back(newedge_ptr);
          edge_ptr->marked(ieloc++);
          FacetEntity *fe_ptr = dynamic_cast<FacetEntity *> (edge_ptr);
          FacetEntity *newfe_ptr = dynamic_cast<FacetEntity *> (newedge_ptr);
          set_new_facet_owners( 1, fe_ptr, newfe_ptr, surf_map, curve_map, point_map );
        }  
      } 
    }
    else
    {
      CubitFacetEdge *edge_ptr = dynamic_cast<CubitFacetEdge*>(facet_ptr);<--- Shadow variable
      if (edge_ptr->marked() == FACET_ENTITY_UNINITIALIZED)
      {
        CubitPoint *p0 = edge_ptr->point( 0 );
        CubitPoint *p1 = edge_ptr->point( 1 );
        int idx0 = p0->marked();
        int idx1 = p1->marked();
        CubitPoint *newp0 = new_points[idx0];
        CubitPoint *newp1 = new_points[idx1];
        newedge_ptr = (CubitFacetEdge *) new CubitFacetEdgeData( newp0, newp1 );
        new_edges.push_back(newedge_ptr);
        edge_ptr->marked(ieloc++);
        FacetEntity *fe_ptr = dynamic_cast<FacetEntity *> (edge_ptr);
        FacetEntity *newfe_ptr = dynamic_cast<FacetEntity *> (newedge_ptr);
        set_new_facet_owners( 1, fe_ptr, newfe_ptr, surf_map, curve_map, point_map );
      }
    }
  }
  return CUBIT_SUCCESS;
}

//=============================================================================
//Function: connect_facets_at_interface 
//Description: detach the facets from original points and edges and reattach to new copy         
//Author:sjowen
//Date:  09/18/09
//=============================================================================
CubitStatus ChollaEngine::connect_facets_at_interface(DLIList<ChollaSurface*> &chsurfs,
                                                      DLIList<ChollaCurve*> &chcurves,
                                                      ChollaVolume *chvol_ptr,
                                                      std::vector<CubitPoint *> &new_points,
                                                      std::vector<CubitFacetEdge *> &new_edges)
{
  CubitStatus rv = CUBIT_SUCCESS;  
  DLIList<ChollaCurve *> chcurv_list;
  
  for( int i=chsurfs.size(); i--; )
  {
    ChollaSurface *tmp_surf = chsurfs.get_and_step();    
    DLIList<ChollaCurve*> tmp_curves;
    tmp_surf->get_curves( tmp_curves );
    chcurv_list += tmp_curves;
  }

  chcurv_list += chcurves;
  chcurv_list.uniquify_unordered();

  for (int icrv = 0; icrv < chcurv_list.size(); icrv++)
  {
    ChollaCurve *chcurv_ptr = chcurv_list.get_and_step();    
    rv = connect_points_at_interface( chcurv_ptr, chvol_ptr, new_points );
    if (rv != CUBIT_SUCCESS)
      return rv;
    
    rv = connect_edges_at_interface( chcurv_ptr, chvol_ptr, new_edges );
    if (rv != CUBIT_SUCCESS)
      return rv;
  } 

  return rv;
}

//=============================================================================
//Function: connect_points_at_interface 
//Description: find adjacent CubitFacetEdges on volume 2 that needs updating 
//Notes: chcurv_ptr is a curve at the interface on the original volume
//       chvol_ptr is the second volume (new (copied) entities belong to vol 2)
//       This functions gets all edges attached to the original CubitPoints on the 
//       original curve 'chcurv_ptr'.  If any edge is on volume 2 (the volume we are 
//       splitting off) we need to update the edges on that volume to contain the
//       the new CubitPoint.
//Author:sjowen
//Date:  09/18/09
//=============================================================================
CubitStatus ChollaEngine::connect_points_at_interface(ChollaCurve *chcurv_ptr,
                                                      ChollaVolume *chvol_ptr,
                                                      std::vector<CubitPoint *> &new_points)
{
  DLIList<CubitPoint *> cp_list;
  chcurv_ptr->get_facet_points(cp_list, CUBIT_TRUE);
  for (int ip = 0; ip<cp_list.size(); ip++)
  {
    CubitPoint *cp_ptr = cp_list.get_and_step();
    CubitPoint *newcp_ptr = new_points[cp_ptr->marked()];
    
    // set the point into edges that are on volume 2.
    // Note that there is no direct reference from points to edges in our data structure 
    // so no need to add/remove the edge from the point
    
    DLIList<CubitFacetEdge *> pedge_list;
    cp_ptr->edges(pedge_list);
    for (int iedge=0; iedge<pedge_list.size(); iedge++)
    {
      CubitFacetEdge *edge_ptr = pedge_list.get_and_step();
      TDGeomFacet *td_geom = TDGeomFacet::get_geom_facet( edge_ptr );
      if (td_geom->is_in_volume( chvol_ptr ))
      {
        CubitPoint *p0 = edge_ptr->point(0);
        CubitPoint *p1 = edge_ptr->point(1);
        CubitFacetEdgeData *cfed_ptr = dynamic_cast<CubitFacetEdgeData *> (edge_ptr);
        if (p0 == cp_ptr)
          cfed_ptr->set_point( newcp_ptr, 0 );
        else if (p1 == cp_ptr)
          cfed_ptr->set_point( newcp_ptr, 1 );
      }
    }    
    
    // remove facets in volume 2 from the point and add the to the new point
    // update the point reference on the facet
    
    DLIList<CubitFacet *> pfacet_list;
    cp_ptr->facets(pfacet_list);
    for (int ifacet = 0; ifacet < pfacet_list.size(); ifacet++)
    {
      CubitFacet *facet_ptr = pfacet_list.get_and_step();
      TDGeomFacet *td_geom = TDGeomFacet::get_geom_facet( facet_ptr );
      if (td_geom->is_in_volume( chvol_ptr ))
      {
        cp_ptr->remove_facet( facet_ptr );        
        newcp_ptr->add_facet( facet_ptr );
        int ptidx = facet_ptr->point_index(cp_ptr);
        CubitFacetData *cfd_ptr = dynamic_cast<CubitFacetData *> (facet_ptr);
        cfd_ptr->set_point(newcp_ptr, ptidx);
      }
    }
  }
  return CUBIT_SUCCESS;
}

//=============================================================================
//Function: connect_edges_at_interface 
//Description: detach the facet edges from original facets and reattach to new copy         
//Notes:    chcurv_ptr is a curve at the interface on the original volume
//       chvol_ptr is the second volume (new (copied) entities belong to vol 2)
//       This functions gets all CubitFacets attached to any CubitFacetEdges on the  
//       original curve 'chcurv_ptr'.  If any facet is on volume 2 (the volume we are 
//       splitting off) we need to update the edges on that facet on the new volume
//       to contain the new CubitFacetEdge.
//Author:sjowen
//Date:  09/18/09
//=============================================================================
CubitStatus ChollaEngine::connect_edges_at_interface(ChollaCurve *chcurv_ptr,
                                                     ChollaVolume *chvol_ptr,
                                                     std::vector<CubitFacetEdge *> &new_edges)
{
  DLIList<FacetEntity *> fe_list = chcurv_ptr->get_facet_list();
  for (int ie=0; ie<fe_list.size(); ie++)
  {
    FacetEntity *fe_ptr = fe_list.get_and_step();
    CubitFacetEdge *edge_ptr = dynamic_cast<CubitFacetEdge *> (fe_ptr);
    assert(edge_ptr != NULL);
    DLIList<CubitFacet *> efacet_list;
    edge_ptr->facets(efacet_list);
    for (int ifacet=0; ifacet<efacet_list.size(); ifacet++)
    {
      CubitFacet *facet_ptr = efacet_list.get_and_step();
      TDGeomFacet *td_geom = TDGeomFacet::get_geom_facet( facet_ptr );
      if (td_geom->is_in_volume( chvol_ptr ))
      {
        edge_ptr->remove_facet( facet_ptr );
        CubitFacetEdge *newedge_ptr = new_edges[edge_ptr->marked()];
        newedge_ptr->add_facet( facet_ptr );
        int edidx = facet_ptr->edge_index(edge_ptr);
        CubitFacetData *cfd_ptr = dynamic_cast<CubitFacetData *> (facet_ptr);
        cfd_ptr->edge(newedge_ptr, edidx);
      }
    }
  }
  return CUBIT_SUCCESS;
}

//=============================================================================
//Function: set_new_facet_owners 
//Description: update the ownenrship of the new detached facet entity based upon
//             the map set up in detach_volumes
//            
//Author:sjowen
//Date:  09/14/09
//=============================================================================
CubitStatus ChollaEngine::set_new_facet_owners(int type, //0, 1, or 2 based on dimension of facet entity
                                               FacetEntity *fe_ptr, FacetEntity *newfe_ptr,                                                
                                               std::map<ChollaSurface *, ChollaSurface *> &surf_map,
                                               std::map<ChollaCurve *, ChollaCurve *> &curve_map,
                                               std::map<ChollaPoint *, ChollaPoint *> &point_map )
{
  
  // The tooldata on the original facet entity should tell us what cholla entity it belongs
  // to.  Using the map, we can then determine its new cholla entity partner.  With the
  // new merge partner, set the ownership of the new facet.  Note that this manages one-to-many
  // ownership cases where a facet lies on (or is owned by) any number of geometric entities
  
  TDGeomFacet *td_geom = TDGeomFacet::get_geom_facet( fe_ptr );
  TDGeomFacet::add_geom_facet(newfe_ptr, td_geom->get_block_id());
  
  // the original facet entity is owned by one or more surfaces
  
  DLIList<ChollaSurface *> surf_list;
  td_geom->get_cholla_surfs( surf_list );  
  for (int jj=0; jj<surf_list.size(); jj++)
  {
    ChollaSurface *surf_ptr = surf_list.get_and_step();
    std::map<ChollaSurface *, ChollaSurface *>::iterator map_it;
    map_it = surf_map.find( surf_ptr );
    assert(map_it != surf_map.end());
    ChollaSurface *newsurf_ptr = map_it->second;    
    TDGeomFacet *newtdgeom = TDGeomFacet::get_geom_facet( newfe_ptr );
    newtdgeom->add_cholla_surf( newsurf_ptr );
    
    // add this facet entity to the cholla surface only if this is a facet
    
    if (type == 2)
      newsurf_ptr->add_facet(newfe_ptr);
  }

  
  // the original facet entity is owned by one or more curves
  
  DLIList<ChollaCurve *> curv_list;
  td_geom->get_cholla_curves( curv_list );
  for (int jj=0; jj<curv_list.size(); jj++)
  {
    ChollaCurve *curv_ptr = curv_list.get_and_step();
    std::map<ChollaCurve *, ChollaCurve *>::iterator map_it, upper_iter;<--- Unused variable: upper_iter
    map_it = curve_map.find( curv_ptr );
    assert(map_it != curve_map.end());       
    ChollaCurve *newcurv_ptr = NULL;
    newcurv_ptr = map_it->second;
    
    TDGeomFacet *newtdgeom = TDGeomFacet::get_geom_facet( newfe_ptr );
    newtdgeom->add_cholla_curve( newcurv_ptr );
    
    // add this facet entity to the cholla curve only if this is a facetedge
    
    if (type == 1)
      newcurv_ptr->add_facet(newfe_ptr);      
  }
  
  // the original facet entity is owned by one or more points (vertices)
  
  DLIList<ChollaPoint *> point_list;
  td_geom->get_cholla_points( point_list );
  for (int jj=0; jj<point_list.size(); jj++)
  {
    ChollaPoint *point_ptr = point_list.get_and_step();
    std::map<ChollaPoint *, ChollaPoint *>::iterator map_it, upper_iter;<--- Unused variable: upper_iter
    map_it = point_map.find( point_ptr );
    assert(map_it != point_map.end());
    ChollaPoint *newchpoint_ptr = NULL;
    newchpoint_ptr = map_it->second;
  
    TDGeomFacet *newtdgeom = TDGeomFacet::get_geom_facet( newfe_ptr );
    newtdgeom->add_cholla_point( newchpoint_ptr );
    
    // add this facet entity to the cholla point only if this is a cubitpoint
    
    if (type == 0)
      newchpoint_ptr->add_facet(newfe_ptr);
  }
  return CUBIT_SUCCESS;

}

//=============================================================================
//Function: verify_points_to_curves 
//Description: verify the connectivity between points and curves           
//Author:sjowen
//Date:  09/16/09
//=============================================================================
CubitStatus ChollaEngine::verify_points_to_curves()
{
  for (int ii=0; ii<chollaPointList.size(); ii++)
  {
    ChollaPoint *chpt = chollaPointList.get_and_step();
    if (!chpt->verify_curves())
    {
      PRINT_ERROR("ChollaPoint %d not associated with one of its curves.\n", chpt->get_id());
      return CUBIT_FAILURE;
    }
  }
  for (int ii=0; ii<chollaCurveList.size(); ii++)
  {
    ChollaCurve *chcrv = chollaCurveList.get_and_step();
    if (!chcrv->verify_points())
    {
      PRINT_ERROR("ChollaCurve %d not associated with one of its points.\n", chcrv->get_id());
      return CUBIT_FAILURE;
    }
  }
  return CUBIT_SUCCESS;
}

CubitStatus ChollaEngine::set_curve_endpoints(std::map<ChollaPoint *, ChollaPoint *> &point_map,
                                              std::map<ChollaCurve *, ChollaCurve *> &curve_map )
                                              
{   
  DLIList<ChollaPoint*> original_chpts;
  DLIList<ChollaPoint*> new_chpts;
  DLIList<ChollaCurve*> original_chcurves;
  DLIList<ChollaCurve*> new_chcurves;  

  std::map<ChollaCurve*, ChollaCurve*>::iterator curv_iter = curve_map.begin();
  for(; curv_iter!=curve_map.end(); curv_iter++ )
  {
    ChollaCurve *orig_curve = curv_iter->first;
    ChollaCurve *new_curve = curv_iter->second;

    //curves
    original_chcurves.append( orig_curve );
    new_chcurves.append( new_curve );
    
    //points
    DLIList<ChollaPoint*> tmp_pts = orig_curve->get_points();
    original_chpts += tmp_pts;

    tmp_pts.clean_out();
    tmp_pts = new_curve->get_points();
    new_chpts += tmp_pts;
  }

  original_chpts.uniquify_unordered();
  original_chcurves.uniquify_unordered();
  new_chpts.uniquify_unordered();
  new_chcurves.uniquify_unordered();  
  
  std::map<ChollaPoint*,ChollaPoint*>::iterator pt_iter;
  for( int i=original_chpts.size(); i--; )
  {
    ChollaPoint *orig_pt = original_chpts.get_and_step();

    pt_iter = point_map.find( orig_pt );
    assert( pt_iter != point_map.end() );

    ChollaPoint *new_pt = pt_iter->second;    
    
    CubitPoint *new_cp = dynamic_cast<CubitPoint *>(new_pt->get_facets());
    CubitPoint *orig_cp = dynamic_cast<CubitPoint *>(orig_pt->get_facets());

    //get the curves attached to it that are in the original surface
    DLIList<ChollaCurve*> adj_curves = orig_pt->get_curves();

    for( int j=adj_curves.size(); j--; )
    {
      ChollaCurve *orig_curve = adj_curves.get_and_step();

      curv_iter = curve_map.find( orig_curve );

      //use the original curve's start/end pts as a guide to set the new curve's start/end pts
      if( curv_iter != curve_map.end() )
      {
        //if there is a corresponding new curve, get it
        ChollaCurve *new_curve_in_new_surf = curv_iter->second;

        CubitPoint *start, *end;
        orig_curve->get_ends(start, end);        
        assert(orig_cp != NULL);
        assert(start!= NULL);
        assert(end != NULL);

        if ( orig_cp == start )
        {
          new_curve_in_new_surf->set_start(new_cp);
        }        
        if ( orig_cp == end )
        {
          new_curve_in_new_surf->set_end(new_cp);
        }        
      }   
    }
  }

  //for each new point
  for( int i=new_chpts.size(); i--; )
  {
    ChollaPoint *new_point = new_chpts.get_and_step();

    DLIList<ChollaCurve*> curves_in_pt = new_point->get_curves();

    for( int k=curves_in_pt.size(); k--; )
    {
      ChollaCurve *curve_in_pt = curves_in_pt.get_and_step();

      //get adjacent curves that are not new (not in 'new_curves')
      if( !original_chcurves.is_in_list( curve_in_pt ) )
      {
        DLIList<ChollaPoint *> chpts_on_curve = curve_in_pt->get_points();        
        
        // one point on the curve assumes a periodic curve.  set both ends the same

        if (chpts_on_curve.size() == 1)
        {
          ChollaPoint *chpt_on_crv = chpts_on_curve.get();
          CubitPoint *cp = dynamic_cast<CubitPoint *> (chpt_on_crv->get_facets());
          curve_in_pt->set_start(cp);
          curve_in_pt->set_end(cp);
        }

        // standard case. one point of curve is on the interface and one is not.
        // In this case, one of the points has been replaced with a new point.
        // so one of the end point pointers are out of date.  Determine which one
        // and then set it.

        else if (chpts_on_curve.size() == 2)
        {
          ChollaPoint *chpt1_on_crv = chpts_on_curve.get_and_step();
          ChollaPoint *chpt2_on_crv = chpts_on_curve.get();
          CubitPoint *cp1 = dynamic_cast<CubitPoint *> (chpt1_on_crv->get_facets());
          CubitPoint *cp2 = dynamic_cast<CubitPoint *> (chpt2_on_crv->get_facets());
          CubitPoint *curstart, *curend;
          curve_in_pt->get_ends(curstart, curend);
          assert(curstart != NULL);
          assert(curend != NULL);

          if (curstart == cp1)
          {
            curve_in_pt->set_end(cp2);
          }
          else if (curstart == cp2)
          {
            curve_in_pt->set_end(cp1);
          }
          else if (curend == cp2)
          {
            curve_in_pt->set_start(cp1);
          }
          else if (curend == cp1)
          {
            curve_in_pt->set_start(cp2);
          }
          else
          {
            //do this by proximity
            double dist1 = curstart->coordinates().distance_between( cp1->coordinates() );
            double dist2 = curstart->coordinates().distance_between( cp2->coordinates() );

            if( dist1 < dist2 )
              curve_in_pt->set_start( cp1 );
            else if(dist2 < dist1 )
              curve_in_pt->set_start( cp2 );
            else
              assert(0);
          }
        }
        else
          assert(0);
      }
    } 
  }
  return CUBIT_SUCCESS;
}

// EOF