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
#include "FacetProjectTool.hpp"
#include "PST_Data.hpp"
#include "GeometryDefines.h"
#include "CubitMessage.hpp"
#include "CubitPlane.hpp"

#include "GfxDebug.hpp" /* for debugging output */

const int VG_FACET_DEBUG = 145;
const int VG_FACET_BOUNDARY_COLOR = CUBIT_RED_INDEX;
const int VG_FACET_FACET_COLOR = CUBIT_GREEN_INDEX;
const int VG_FACET_IMPRINT_COLOR = CUBIT_WHITE_INDEX;
const int VG_FACET_SEGMENT_COLOR = CUBIT_CYAN_INDEX;
#define VG_FACET_PRINT PRINT_DEBUG(VG_FACET_DEBUG)


//-------------------------------------------------------------------------
// Purpose       : Constructor
//
// Special Notes :  
//
// Creator       : Jason Kraftcheck
//
// Creation Date : 05/11/02
//-------------------------------------------------------------------------
FacetProjectTool::FacetProjectTool( ) 
{ }


static int parent_compare_facets( PST_Face*& f1, PST_Face*& f2 )<--- Parameter 'f1' can be declared with const<--- Parameter 'f2' can be declared with const
{
  return (f1->parent < f2->parent) ? -1 :
         (f1->parent > f2->parent) ?  1 : 0;
}
static int sequence_compare_pts( PST_Point*& p1, PST_Point*& p2 )<--- Parameter 'p1' can be declared with const<--- Parameter 'p2' can be declared with const
{
  return (p1->sequence < p2->sequence) ? -1 :
         (p1->sequence > p2->sequence) ?  1 : 0;
}

//-------------------------------------------------------------------------
// Purpose       : takes a list of edge segments and a surface and returns
//                 the new facets, dudded facets, new points, and new edges
// Special Notes :  
//                 
//
// Creator       : John Fowler
//
// Creation Date : 12/03/02
//-------------------------------------------------------------------------
CubitStatus FacetProjectTool::project(
    DLIList<CubitVector*>& segments,            	// in
    const std::vector<double>& coordinates,		// in
    const std::vector<int>& connections,		// in
    std::vector<int>& duddedFacets, 			// out
    std::vector<int>& newFacets,			// out
    std::vector<int>& newFacetsIndex,		// out
    std::vector<double>& newPoints, 			// out
    std::vector<int>& edges,				// out
    std::vector<int>& segmentPoints,
    const double *tolerance_length
 )
{
  int i;
//   const double TOL_SQR = GEOMETRY_RESABS*GEOMETRY_RESABS; 
                     
  assert(connections.size()%3 == 0);  //  For triangles these must be triples
  assert(coordinates.size()%3 == 0);  //  Coordinates must come in triples   
  DLIList<PST_Edge*> facet_edges;  

    // make the PST edges and faces from the coordinates and connections.
  PST_Edge::make_facets( coordinates, connections, GEOMETRY_RESABS, facet_edges );
  DLIList<PST_Face*> faces;

  CubitStatus success = CUBIT_SUCCESS;
  if(facet_edges.size() > 0)
  {

    PST_Edge::faces( facet_edges, faces );
    populate_data(faces);

      // Order the orignal points by sequence number.  New points
      // will be appended in order.
    pointList.sort(&sequence_compare_pts);
        
      // Do the work
    CubitBoolean point_changed;
    success = do_projection(segments, point_changed, tolerance_length);
    
    bool debug = false;<--- Assignment 'debug=false', assigned value is 0
    if( debug )<--- Condition 'debug' is always false
    {
      GfxDebug::clear();
      for( int j=0; j<facetList.size(); j++ )
        facetList.get_and_step()->debug_draw( CUBIT_CYAN_INDEX );
      GfxDebug::mouse_xforms();
    }

      // fill in segmentPoints
//    assert (segPoints.size() == segments.size());
    segmentPoints.resize( segPoints.size() );
    segPoints.reset();
    for ( i = 0; i < segPoints.size(); i++ )
    {
      PST_Point* pt = segPoints.get_and_step();     
      segmentPoints[i] = pt ? pt->sequence : -1;
      if (point_changed)
        success = CUBIT_FAILURE;
    }
  }
  else
    success = CUBIT_FAILURE;
  
  if (!success)
  {
     cleanup();
     return success;
  }
                                                                                
    //  Now put the points with sequence > coordinates.size()/3 in newPoints.
  int orig_num_points = coordinates.size()/3;
  int num_new_points = pointList.size() - orig_num_points;
  pointList.reset();
  pointList.step(orig_num_points);
  newPoints.resize(num_new_points*3);
  std::vector<double>::iterator ditor = newPoints.begin();
  while( num_new_points-- ) {
    PST_Point* pt = pointList.get_and_step();
    *ditor++ = pt->x();
    *ditor++ = pt->y();
    *ditor++ = pt->z();
  }

  if ( facetList.size() > 1 ) {  //  If only one facet, skip finding dudded facets
    // Sort (group) facets by parent.
    facetList.sort(&parent_compare_facets);

    // Fill in the duddedFacets, newFacets, and newFacetsIndex vectors.  

#ifndef NDEBUG
    int orig_num_facets = connections.size()/3;
#endif
    int new_facet_index = 0;
    DLIList<PST_Point*> facet_pts(3);

    facetList.reset();
    duddedFacets.clear();
    newFacetsIndex.clear();
    newFacets.clear();

    for ( i = facetList.size(); i > 0; ) {
      PST_Face* dudded_facet = 0;
      if( facetList.get()->parent != facetList.next()->parent ) {

          // unmodified original facet - skip it
#ifndef NDEBUG
        PST_Face* facet = facetList.get();
        assert(facet->sequence < orig_num_facets &&
               facet->sequence == facet->parent);
#endif
        facetList.step();
        i--;
      } 
      else {
          // new facets
        
          // put all new facets split from the
          // same original facet (having same parent),
          // including the orignal facet which was 
          // recycled, into newFacets
        PST_Face* facet = 0;
        do {
          facet = facetList.get_and_step();
          i--;
        
          if ( facet->parent == facet->sequence ) {
            assert(!dudded_facet);
            dudded_facet = facet;
          }
      
          facet_pts.clean_out();
          facet->append_points(facet_pts);
          facet_pts.reset();
          newFacets.push_back(facet_pts.get_and_step()->sequence);
          newFacets.push_back(facet_pts.get_and_step()->sequence);
          newFacets.push_back(facet_pts.get_and_step()->sequence);
          new_facet_index += 3;
        } while ( (facet->parent == facetList.get()->parent) && (i > 0) );
      
          // add replaced facet to duddedFacets
        assert(dudded_facet && dudded_facet->sequence < orig_num_facets);
        duddedFacets.push_back(dudded_facet->sequence);
          // add end position in new_facets for the
          // set of replacement facets to newFacetsIndex
        newFacetsIndex.push_back(new_facet_index);
      }
    }  
  }
  
  DLIList<PST_CoEdge*> coedge_list;
  edges.clear();
  finalize_results();
  while( get_result_set(coedge_list) ) {

      // add count and first point
    coedge_list.reset();
    edges.push_back(coedge_list.size() + 1);
    PST_Point* pt = coedge_list.get()->start_point();
    edges.push_back(pt->sequence);
    
      // add all other points
    for( i = coedge_list.size(); i--; ) {
      pt = coedge_list.get_and_step()->end_point();
      edges.push_back(pt->sequence);
    }
  
      // clean up for next iteration
    coedge_list.clean_out();
  }
  edges.push_back(0);  //  terminating zero for next segment length      
  
  cleanup();
  return CUBIT_SUCCESS;
}

 
//-------------------------------------------------------------------------
// Purpose       : fills in the data
//
// Special Notes : populate private data lists and set marks on facet 
//                 entities
//
// Creator       : Jason Kraftcheck, modified by John Fowler --
//		   used to be the class constructor
//
// Creation Date : 05/11/02, 12/03/02
//-------------------------------------------------------------------------
CubitStatus FacetProjectTool::populate_data( const DLIList<PST_Face*>& facets )
{
  facetList = facets;
  int i;
  
    // Mark all connected edges with a 3, and initialize 
    // parent number to sequence number.
  facetList.last();
  for( i = facetList.size(); i--; )
  {
    PST_Face* face = facetList.step_and_get();
    face->parent = face->sequence;
    PST_CoEdge* coe = face->first_coedge();
    do
    {
      coe->edge()->mark = 3;
      coe = coe->next();
    } while( coe != face->first_coedge() );
  }
  
    // Decrement the edge mark by one for each
    // face that contains the edge.
  for( i = facetList.size(); i--; )
  {
    PST_Face* face = facetList.step_and_get();
    PST_CoEdge* coe = face->first_coedge();
    do
    {
      coe->edge()->mark--;
      coe = coe->next();
    } while( coe != face->first_coedge() );
  }
  
    // Populate edgeList and boundaryList with edges
  for( i = facetList.size(); i--; )
  {
    PST_Face* face = facetList.step_and_get();
    PST_CoEdge* coe = face->first_coedge();
    do
    {
      PST_Edge* edge = coe->edge();
      	// If mark is 2, edge was only in one face in the
        // passed list, and is thus on the boundary of the
        // passed patch of faces.
      if( edge->mark == 2 )
      {
        boundaryList.append( edge );
        edgeList.append( edge );
        edge->mark = 0;
      }
      	// If mark is 1, the edge is an interior edge in the
        // patch of faces
      else if( edge->mark == 1 )
      {
        edgeList.append( edge );
        edge->mark = 0;
      }
      	// If the mark on the edge is zero, we have already
        // added it to the list(s).
      else
      {
        assert( edge->mark == 0 );  
      }
      
      coe = coe->next();
    } while( coe != face->first_coedge() );
  }
  
    // Get all the points
  PST_Edge::points( edgeList, pointList );
  
    // Clear marks on all faces connected to our edge
    // list (the passed faces and any faces connected
    // at the boundary edges.)
  for( i = edgeList.size(); i--; )
  {
    PST_Edge* edge = edgeList.step_and_get();
    edge->mark = 0;
    if( edge->forward()->face() )
      edge->forward()->face()->mark = 0;
    if( edge->reverse()->face() )
      edge->reverse()->face()->mark = 0;
  }

    // clear marks on faces
  for( i = facetList.size(); i--; )
    facetList.step_and_get()->mark = 0;
    // Set mark to 1 on boundary edges
  for( i = boundaryList.size(); i--; )
    boundaryList.step_and_get()->mark = 1;
    
  if( DEBUG_FLAG( VG_FACET_DEBUG ) )
  {
//    PST_Face::draw_faces( facetList, VG_FACET_FACET_COLOR, false );
    PST_Edge::debug_draw_edges( boundaryList, VG_FACET_BOUNDARY_COLOR );
  }

  return CUBIT_SUCCESS;
} 
 
//-------------------------------------------------------------------------
// Purpose       : Find the face for which the projection of the passed
//                 position onto the face is closest to the passed
//                 position. 
//
// Special Notes : 
//
// Creator       : Jason Kraftcheck
//
// Creation Date : 05/11/02
//-------------------------------------------------------------------------
PST_Face* FacetProjectTool::closest_face( const CubitVector& position )
{
  PST_Face* result = 0;
  double dist_sqr = 0;
  CubitVector projected;
  
  for( int i = facetList.size(); i--; )
  {
    PST_Face* facet = facetList.step_and_get();
    if( project_to_face( facet, position, projected ) )
    {
      double d = (projected - position).length_squared();
      if( !result || d < dist_sqr )
      {
        result = facet;
        dist_sqr = d;
      }
    }
  }
  
  return result;
}


//-------------------------------------------------------------------------
// Purpose       : Find the edge for which the projection of the passed
//                 position onto the edge is closest to the passed
//                 position.
//
// Special Notes : 
//
// Creator       : Jason Kraftcheck
//
// Creation Date : 05/11/02
//-------------------------------------------------------------------------
PST_Edge* FacetProjectTool::closest_edge( const CubitVector& position )
{
  PST_Edge* result = 0;
  double dist_sqr = 0;
  
  for( int i = edgeList.size(); i--; )
  {
    PST_Edge* edge = edgeList.step_and_get();
    
    double t = edge->closest_on_line( position );
    if( (t > -CUBIT_RESABS) && (t < (1.0 + CUBIT_RESABS)) )
    {
      double d = (edge->position(t) - position).length_squared();
      if( !result || d < dist_sqr )
      {
        result = edge;
        dist_sqr = d;
      }
    }
  }

  return result;
}

//-------------------------------------------------------------------------
// Purpose       : Find the point closest to the passed position.
//
// Special Notes : 
//
// Creator       : Jason Kraftcheck
//
// Creation Date : 05/11/02
//-------------------------------------------------------------------------
PST_Point* FacetProjectTool::closest_point( const CubitVector& position )
{
  PST_Point* result = 0;
  double dist_sqr = 0;
  
  for( int i = pointList.size(); i--; )
  {
    PST_Point* pt = pointList.step_and_get();
    double d = (position - *pt).length_squared();
    if( !result || d < dist_sqr )
    {
      dist_sqr = d;
      result = pt;
    }
  }
  
  return result;
}


//-------------------------------------------------------------------------
// Purpose       : Project the passed position onto the plane of the 
//                 passed facet.  Returns false if projection is outside
//                 the facet.
//
// Special Notes : "result" is unchanged if false is returned.
//
// Creator       : Jason Kraftcheck
//
// Creation Date : 05/11/02
//-------------------------------------------------------------------------
bool FacetProjectTool::project_to_face( PST_Face* triangle,
                                        const CubitVector& position,
                                        CubitVector& result )
{
    // First check if projection of the point will be within
    // the bounds of the triangle.  
  if( ! inside_face( triangle, position ) )
    return false;
  
    // Calculate the actual projection
  result = triangle->plane().project( position );
  return true;
}

//-------------------------------------------------------------------------
// Purpose       : Destructor.  Clear marks on all facet entities.
//
// Special Notes : 
//
// Creator       : Jason Kraftcheck
//
// Creation Date : 05/11/02
//-------------------------------------------------------------------------
FacetProjectTool::~FacetProjectTool()
{
  cleanup();
}


//-------------------------------------------------------------------------
// Purpose       : clean out internal data
//
// Special Notes : 
//
// Creator       : Jason Kraftcheck
//
// Creation Date : 02/13/03
//-------------------------------------------------------------------------
void FacetProjectTool::cleanup()
{
  while( pointList.size() )
    delete pointList.pop();
  facetList.clean_out();
  edgeList.clean_out();
  boundaryList.clean_out();
  imprintResult.clean_out();
  segPoints.clean_out();
}


//-------------------------------------------------------------------------
// Purpose       : Inset a point in the interior of a facet.
//
// Special Notes : Assumes input facet is a triangle, and splits facet
//                 as necessary to ensure that resulting facets are tris.
//
// Creator       : Jason Kraftcheck
//
// Creation Date : 05/11/02
//-------------------------------------------------------------------------
PST_Point* FacetProjectTool::insert_in_face( PST_Face* face, 
                                             const CubitVector& position )
{
  PST_Point* new_point = new PST_Point( position );
  PST_CoEdge* ce1 = face->first_coedge();
  PST_CoEdge* ce2 = ce1->next();
  PST_CoEdge* ce3 = ce2->next();

    // insert non-mainifold edge in face after ce1
  PST_Edge* edge1 = PST_Edge::insert_in_face( new_point, ce1 );
  if( ! edge1 )
  {
    delete new_point;
    return 0;
  }
  new_point->sequence = pointList.size();
  pointList.append(new_point);
  edgeList.append( edge1 );
  if( DEBUG_FLAG( VG_FACET_DEBUG ) )
    edge1->debug_draw( VG_FACET_FACET_COLOR );
  
    // connect non-manifold edge to opposite side of the face
    // to make manifold topology.
  PST_Edge* edge2 = PST_Edge::split_face( ce2, edge1->start_point() == new_point ?
                                               edge1->reverse() : edge1->forward() );   
  if( ! edge2 ) return new_point;
  edgeList.append( edge2 );
  PST_Face* new_face = edge2->other(face);
  new_face->sequence = facetList.size();
  new_face->parent = face->parent;
  facetList.append( new_face );
  if( face->owner() )
    face->owner()->notify_split( face, new_face );
    
  if( DEBUG_FLAG( VG_FACET_DEBUG ) )
    edge2->debug_draw( VG_FACET_FACET_COLOR );
  
    // Split face so that all faces are triangles.
  PST_Face* split_face = ce3->face();
  PST_Edge* edge3 = PST_Edge::split_face( new_point, ce3->end_point(), split_face );
  if( edge3 )
  {
    edgeList.append( edge3 );
    new_face = edge3->other(split_face);
    new_face->sequence = facetList.size();
    new_face->parent = face->parent;
    facetList.append( new_face );
    if( split_face->owner() )
      split_face->owner()->notify_split( split_face, new_face );
  }
  
  return new_point;
}


//-------------------------------------------------------------------------
// Purpose       : Add a point where the passed position is projected
//                 into the facet patch.
//
// Special Notes : May return NULL if projection does not lie within 
//                 facet patch.
//
// Creator       : Jason Kraftcheck
//
// Creation Date : 05/11/02
//-------------------------------------------------------------------------
PST_Point* FacetProjectTool::project( const CubitVector& pos,
                                      const double* tolerance_length )
{
  PST_Point* point = closest_point( pos );
  PST_Edge *  edge = closest_edge ( pos );
  PST_Face *  face = closest_face ( pos );
  
    // find closest facet
  double face_dist = CUBIT_DBL_MAX;
  CubitVector face_pos;
  if( face )
  {
    project_to_face( face, pos, face_pos );
    face_dist = (pos - face_pos).length_squared();
  }
  
    // find closest edge
  double edge_dist = CUBIT_DBL_MAX;
  double edge_pos  = CUBIT_DBL_MAX;
  if( edge )
  {
    edge_pos = edge->closest_on_edge( pos );
    edge_dist = (pos - edge->position(edge_pos)).length_squared();
  }
  
    // find closest point
  double point_dist = CUBIT_DBL_MAX;
  if( point )
  {
    point_dist = (pos - *point).length_squared();
  }
  
    // if the position is closer to a facet than a point or edge...
  if( face && (face_dist < point_dist) && (face_dist < edge_dist) )
  {
      // get a tolerance based on a sample face size. I attempted
      // to do this with a representative facet size but still 
      // ended up with problems.  While this is slower is more
      // robust.  KGM
    double facet_length;

    if(tolerance_length)
    {
      facet_length = *tolerance_length;
    }
    else
    {
      facet_length = face->bounding_length();
    }

    // use the square of the facet length times an arbitrary factor to
    // determine the tolerance
    double tol_sqr = facet_length*facet_length*.00001;

      // check if projected position is within tolerance of
      // any bounding edge of the face.
    PST_CoEdge* coe = face->first_coedge();
    bool insert = true;
    do {
      PST_Edge* e = coe->edge();
      CubitVector p = e->position( e->closest_on_line( face_pos ) );
      double d = (p - face_pos).length_squared();

      // use a relative tolerance here - KGM
      if( d < tol_sqr ) 
      {
        edge = e;
        edge_pos = edge->closest_on_edge( pos );
        face_dist = d;<--- Variable 'face_dist' is assigned a value that is never used.
        edge_dist = d;
        insert = false;
      }
      coe = coe->next();
    } while( coe != face->first_coedge() );
    
      // If projected position was sufficiently far from the edges
      // of the facet, insert an interior point in the facet.  Otherwise
      // fall through and split edge.
    if( insert )
    {
      return insert_in_face( face, face_pos );
    }
  }
  
    // If the point was closer to an edge than a point
  if( edge && (edge_dist <= point_dist) )
  {
      // If within tolerance of an end point of the edge, return
      // the end point.
    CubitVector pt = edge->position( edge_pos );
    if( (pt - *edge->start_point()).length_squared() < GEOMETRY_RESABS*GEOMETRY_RESABS )
      point = edge->start_point();
    else if( (pt - *edge->end_point()).length_squared() < GEOMETRY_RESABS*GEOMETRY_RESABS )
      point = edge->end_point();
      // Otherwise split the edge at the projected position
    else point = split_edge( edge, edge_pos );
  }
  
  if( DEBUG_FLAG( VG_FACET_DEBUG ) && point )
    point->debug_draw( VG_FACET_IMPRINT_COLOR );
  
    // If this was not set in the above if-block, then it is either
    // the closest point in the facet patch or NULL if the position
    // projected outside the facet patch.
  return point;
}    
  
//-------------------------------------------------------------------------
// Purpose       : Split an edge at the specified parameter value on the
//                 edge.  Splits connected facets to maintain triangular
//                 facets.
//
// Special Notes : 
//
// Creator       : Jason Kraftcheck
//
// Creation Date : 05/11/02
//-------------------------------------------------------------------------
PST_Point* FacetProjectTool::split_edge( PST_Edge* edge, double t )
{
  assert( t > 0.0 && t < 1.0 );
  
    // create point
  PST_Point* point = new PST_Point( edge->position(t) );
  
    // get connected faces 
  PST_Face* face1 = edge->forward()->face();
  PST_Face* face2 = edge->reverse()->face();
  
    // point on each triangle opposite the edge to be split
  PST_Point* face1_pt = face1 ? edge->forward()->next()->end_point() : 0;
  PST_Point* face2_pt = face2 ? edge->reverse()->next()->end_point() : 0;

  PST_Edge* face1_edge = 0, *face2_edge = 0;<--- Variable 'face1_edge' is assigned a value that is never used.<--- Variable 'face2_edge' is assigned a value that is never used.
  
    // split edge edge
  PST_Edge* split_edge = edge->split( point );
  if( edge->owner() )
    edge->owner()->notify_split( edge, split_edge );
    // if we split a boundary edge, put the new edge in the
    // list of boundary edges too.
  if( edge->mark )
  {
    split_edge->mark = edge->mark;
    boundaryList.append( split_edge );
  }
    // add edge to our list of edges
  edgeList.append( split_edge );
    // If the first face was not a boundary face (different
    // than the boundary of our patch of facets), then split
    // it so that it remains a triangle.
  if( face1 ) 
  {
    face1_edge = PST_Edge::split_face( point, face1_pt, face1 );
    
    if( face1_edge )
    {
      if( DEBUG_FLAG( VG_FACET_DEBUG ) )
        face1_edge->debug_draw( VG_FACET_FACET_COLOR );

      edgeList.append( face1_edge );
	    PST_Face* new_face = face1_edge->other(face1);
      new_face->sequence = facetList.size();
      new_face->parent = face1->parent;
      facetList.append(new_face );
      
      if( face1->owner() )
        face1->owner()->notify_split( face1, face1_edge->other(face1) );
    }
  }
    // If the second face is not a boundary face, split it
    // so that we still have triangles.
  if( face2 )
  {
    face2_edge = PST_Edge::split_face( point, face2_pt, face2 );
    if( face2_edge )
    {
      if( DEBUG_FLAG( VG_FACET_DEBUG ) )
        face2_edge->debug_draw( VG_FACET_FACET_COLOR );

      edgeList.append( face2_edge );
	    PST_Face* new_face = face2_edge->other(face2);
      new_face->sequence = facetList.size();
      new_face->parent = face2->parent;
      facetList.append( new_face );
      
      if( face2->owner() )
        face2->owner()->notify_split( face2, face2_edge->other(face2) );
    }
  }
  point->sequence = pointList.size();
  pointList.append(point);
  
  return point;
}

//-------------------------------------------------------------------------
// Purpose       : This is the main or outer-loop function for the
//                 polyline projection.  It is called after the input data
//                 is converted to the working representation.  The passed
//                 list of CubitVectors is the polyline.
//
// Special Notes : 
//
// Creator       : Jason Kraftcheck
//
// Creation Date : ??
//-------------------------------------------------------------------------

CubitStatus 
FacetProjectTool::do_projection( const DLIList<CubitVector*>& passed_list, 
                                 CubitBoolean & point_changed,
                                 const double *tolerance_length)
{
  const double TOL_SQR = GEOMETRY_RESABS*GEOMETRY_RESABS;
  point_changed = CUBIT_FALSE;
  DLIList<CubitVector*> segments( passed_list );  
  
  bool first_and_last_points_coincident = false;  
  if( segments[0]->distance_between_squared( *(segments[ segments.size()-1]) ) < TOL_SQR )
    first_and_last_points_coincident = true; 

  segments.reset();
  CubitVector end = *(segments.get_and_step());
  PST_Point* last_point = 0;

  bool did_any_projection = false;
  
  int where_is_last_pt;
  int where_is_end_pt;
  
  bool debug = false;  
  
  for( int i = segments.size(); i > 1; i-- )
  {
    CubitVector start(end);
    end = *(segments.get_and_step());
    
    if( debug )
    {
      GfxDebug::clear();       
      for( int j=facetList.size(); j--; )
        facetList.get_and_step()->debug_draw( CUBIT_CYAN_INDEX+j, false );        
      GfxDebug::draw_point( start, CUBIT_GREEN_INDEX );
      GfxDebug::draw_point( end, CUBIT_RED_INDEX );
      GfxDebug::flush();
      GfxDebug::mouse_xforms();      
    }

    if( DEBUG_FLAG( VG_FACET_DEBUG ) )
    {
      GfxDebug::draw_line( 
      	(float)start.x(), (float)start.y(), (float)start.z(),
        (float)end.x()  , (float)end.y()  , (float)end.z(),
        VG_FACET_SEGMENT_COLOR );     
      GfxDebug::flush();
      GfxDebug::mouse_xforms();
    }

    double facet_dist_tol = start.distance_between_squared( end );
    facet_dist_tol *= 0.0001;

    //determine if start is on/off/on-boundary of facets
    if( !last_point )
    {
      where_is_last_pt = point_on_facets( &start, facet_dist_tol );

      if( 1 == where_is_last_pt || 
          2 == where_is_last_pt  )
      {
        last_point = project( start, tolerance_length );
        
        segPoints.append(last_point); 
        start = *last_point;

        if( first_and_last_points_coincident )
          *(segments[segments.size()-1]) = start;
      }
      else
        segPoints.append(NULL);  //it's not on the facets
    } 

    where_is_end_pt = point_on_facets( &end, facet_dist_tol );

    //both points off the facets
    //or one-on, one-off
    PST_Point *end_pt = NULL;

    //both points off
    //one-point-on && one-point-off
    if( (0 == where_is_last_pt && 0 == where_is_end_pt ) || 
        (0 == where_is_last_pt && 1 == where_is_end_pt ) ||
        (1 == where_is_last_pt && 0 == where_is_end_pt ) )
    {
      //see if segment intersects boundary
      CubitVector int_pt;
      CubitStatus my_status = find_closest_int_point_with_boundary( start, end, int_pt );
      if( CUBIT_FAILURE == my_status )      
      {
        segPoints.append( NULL );
        continue;
      }      

      if( 0 == where_is_last_pt )
      {
        last_point = project( int_pt, tolerance_length );

        if( 0 == where_is_end_pt )
        {
          my_status = find_closest_int_point_with_boundary( end, *last_point, int_pt );
          if( CUBIT_SUCCESS == my_status )
          {
            end_pt = project( int_pt, tolerance_length );
            i++;
            segments.back();
          }          
        } 
        else
        {
          end_pt = project( end, tolerance_length );
          segPoints.append( end_pt );
        }
      }
      else if( 0 == where_is_end_pt )
      {
        end_pt = project( int_pt, tolerance_length );
        i++;
        segments.back();
      }      
    }
    else if( (1 == where_is_last_pt || 2 == where_is_last_pt) && 
             (1 == where_is_end_pt || 2 == where_is_end_pt) )
    {
      end_pt = project( end, tolerance_length );
      segPoints.append( end_pt );
    }         
    else if( (0 == where_is_last_pt && 2 == where_is_end_pt ) || 
             (2 == where_is_last_pt && 0 == where_is_end_pt ) )
    {
      if( 0 == where_is_last_pt && 2 == where_is_end_pt )
      {
        //see if segment intersects boundary
        CubitVector int_pt;
        CubitStatus my_status = find_closest_int_point_with_boundary( start, end, int_pt );
        if( CUBIT_SUCCESS == my_status )
        {
          end_pt = project( end, tolerance_length );
          last_point = project( int_pt, tolerance_length );
          segPoints.append( end_pt );
        }
        else
        {
          segPoints.append(NULL);
          continue;
        }
      }
      else
      {
        //see if segment intersects boundary
        CubitVector int_pt;
        CubitStatus my_status = find_closest_int_point_with_boundary( end, start, int_pt );      

        if( CUBIT_SUCCESS == my_status )
        {
          end_pt = project( int_pt, tolerance_length );                        
          segPoints.append( NULL );
        }
        else
        {
          segPoints.append( NULL );
          continue;
        }
      }
    }

        
    PST_Point* start_point = last_point;
    PST_Point* end_point = end_pt;

    if( debug )
    {
      GfxDebug::draw_line( *last_point, *end_pt, CUBIT_MAGENTA_INDEX );
      GfxDebug::flush();
      GfxDebug::mouse_xforms();
    }

    if(project( last_point, end_pt ) == CUBIT_SUCCESS)
    {
      did_any_projection = true;
      if ((*start_point - *last_point).length_squared() > TOL_SQR)
      {
        segPoints.move_to(start_point);
        segPoints.change_to(last_point);
        point_changed = CUBIT_TRUE;
      }
      if ((*end_pt - *end_point).length_squared() > TOL_SQR)
      {
        segPoints.move_to(end_point);
        segPoints.change_to(end_pt);
        point_changed = CUBIT_TRUE;
      }    
    }

    last_point = end_pt;
    where_is_last_pt = where_is_end_pt;    
  
  } // end for( i = segments )
  
  if( !did_any_projection )
    return CUBIT_FAILURE;

  return CUBIT_SUCCESS;
}

//-------------------------------------------------------------------------
// Purpose       : Determines if a position is off/on/on-boundary of the
//                 facets in this tool.  For off/on/on-boundary returns
//                 0, 1, and 2 respectively.  The passed in tolerance_sq is 
//                 used as a coincidence tolerance.
//
// Special Notes : 
//
// Creator       : Corey Ernst
//
// Creation Date : 24-April-2013
//-------------------------------------------------------------------------

int FacetProjectTool::point_on_facets( 
  CubitVector *pos,  
  double tolerance_sq )
{
  //Return Values:
  //0 is outside of facets
  //1 is inside of facets
  //2 is on boundary of facets

  PST_Point* point = closest_point( *pos );
  PST_Edge *  edge = closest_edge ( *pos );
  PST_Face *  face = closest_face ( *pos );

  // find closest facet
  double face_dist = CUBIT_DBL_MAX;
  CubitVector face_pos;
  if( face )
  {
    project_to_face( face, *pos, face_pos );
    face_dist = (*pos - face_pos).length_squared();
  }

  // find closest edge
  double edge_dist = CUBIT_DBL_MAX;
  double edge_pos  = CUBIT_DBL_MAX;<--- Variable 'edge_pos' is assigned a value that is never used.
  if( edge )
  {
    edge_pos = edge->closest_on_edge( *pos );
    edge_dist = (*pos - edge->position(edge_pos)).length_squared();
  }

  // find closest point
  double point_dist = CUBIT_DBL_MAX;
  if( point )
  {
    point_dist = (*pos - *point).length_squared();
  }  

  // if the position is closer to a facet than a point or edge...
  if( face && (face_dist < point_dist) && (face_dist < edge_dist) )
  {
    // check if projected position is within tolerance of
    // any bounding edge of the face.
    PST_CoEdge* coe = face->first_coedge();
    bool edge_closer = false;
    do {
      PST_Edge* e = coe->edge();
      CubitVector p = e->position( e->closest_on_line( face_pos ) );
      double d = (p - face_pos).length_squared();

      if( d < tolerance_sq ) 
      {
        edge = e;
        edge_pos = edge->closest_on_edge( *pos );
        face_dist = d;<--- Variable 'face_dist' is assigned a value that is never used.
        edge_dist = d;<--- Variable 'edge_dist' is assigned a value that is never used.
        edge_closer = true;
      }
      coe = coe->next();
    } while( coe != face->first_coedge() );
    
    if( edge_closer )
    {      
      if( boundaryList.is_in_list( edge ) )
        return 2;
      else
        return 1;    
    }      
    else
      return 1;    
    
    return 0;
  }

  // If the point was closer to an edge than a point
  if( edge && (edge_dist < point_dist) )
  {
    if( edge_dist < tolerance_sq )
    {
      if( boundaryList.is_in_list( edge ) )
        return 2;
      else
        return 1;
    }
    else
      return 0;
  }

  PST_Edge *first_edge = point->edge();
  PST_Edge *tmp_edge = first_edge;
  if( point_dist < tolerance_sq )
  {
    do
    {
      if( boundaryList.is_in_list( tmp_edge ) )
        return 2;
      tmp_edge = point->next( tmp_edge );
    }
    while( first_edge != tmp_edge );

    return 1;
  }
  return 0;
}


//-------------------------------------------------------------------------
// Purpose       : Finds the closest intersection point to 'start_pt' 
//                 between the boundary facet edges in this tool and a line
//                 segement defined by 'start_pt' and 'end_pt'.  The 
//                 intersection must be at or between the two end points
//                 of the segment.
//
// Special Notes : 
//
// Creator       : Corey Ernst
//
// Creation Date : 24-April-2013
//-------------------------------------------------------------------------
CubitStatus FacetProjectTool::find_closest_int_point_with_boundary( 
  CubitVector &start_pt, CubitVector &end_pt, CubitVector &closest_pt  )
{
  CubitVector seg_direction = end_pt - start_pt;   
  double seg_length_sq = seg_direction.length_squared();
  double shortest_length = CUBIT_DBL_MAX;    
  
  const double TOL_SQR = GEOMETRY_RESABS*GEOMETRY_RESABS;

  bool debug = false;
  
  //find the farthest boundary edge that is on the line segment    
  CubitVector split_position;
  for( int k=boundaryList.size(); k--; )
  {
    PST_Edge *tmp_edge = boundaryList.get_and_step();

    //if lines are parallel
    CubitVector tmp_vec1 = end_pt - start_pt;
    CubitVector tmp_vec2 = tmp_edge->end_coord() - tmp_edge->start_coord();
    tmp_vec1 *= tmp_vec2;
    if( tmp_vec1.length_squared() < TOL_SQR )
      continue;

    double t1 = tmp_edge->closest_on_line( start_pt, end_pt - start_pt );
    
    //ignore points that are coincident with start_pt or end_pt
    CubitVector position_on_edge = tmp_edge->position( t1 );
    double dist_sq_start = position_on_edge.distance_between_squared( start_pt );
    double dist_sq_end = position_on_edge.distance_between_squared( end_pt );
    if( dist_sq_start < TOL_SQR || dist_sq_end < TOL_SQR )      
      continue;

    if( t1 >= 0 && t1 <= 1 )    
    {       
      if( debug )
      {
        GfxDebug::draw_line( start_pt, end_pt, CUBIT_MAGENTA_INDEX );      
        PRINT_INFO("t1 = %f\n", t1 );
        tmp_edge->debug_draw( CUBIT_YELLOW_INDEX ); 
      }
  
      CubitVector tmp_pos = tmp_edge->position( t1 );

      //This checks if the intersection between the edge and segment
      //is not within the segment.
      if( tmp_pos.distance_between_squared( start_pt ) > seg_length_sq || 
          tmp_pos.distance_between_squared( end_pt ) > seg_length_sq )      
        continue;              
      
      if( debug )
      {
        GfxDebug::draw_point( tmp_pos, CUBIT_RED_INDEX );        
        GfxDebug::flush();
        GfxDebug::mouse_xforms(); 
      }

      double tmp_dist = tmp_pos.distance_between( start_pt );
      
      if( tmp_dist < shortest_length )
      {
        shortest_length = tmp_dist;        
        closest_pt = tmp_pos;
      }    
    }
  }

  if( shortest_length == CUBIT_DBL_MAX )
    return CUBIT_FAILURE;

  return CUBIT_SUCCESS;
}


//-------------------------------------------------------------------------
// Purpose       : Given two existing points in a triangulation, add edges
//                 to the triangulation to connect those two points by the
//                 most direct path that does not leave the triangulation.
//
// Special Notes : Thisis the second step of the facet-polyline projection
//                 algorithm.  First each point of the polyline is 
//                 projected onto the facetting.  Second this function is
//                 called to find/create the set of facet edges connecting
//                 those points.
//
// Creator       : Jason Kraftcheck
//
// Creation Date : ??
//-------------------------------------------------------------------------
CubitStatus FacetProjectTool::project( PST_Point* &start, PST_Point* &end )
{
  PST_Edge* edge,* closest_edge, *last_closest_edge=NULL;
  PST_Face* closest_face;
  PST_Point* point;
  PST_Point* start_point = start;  
  CubitStatus stat;
  
  const double TOL_SQR = GEOMETRY_RESABS*GEOMETRY_RESABS;

  while( start_point != end )
  {
      // If the points share an edge, that edge is the result.
      // Return it.
    CubitBoolean is_boundary_edge;
    if( (edge = start_point->common( end )) )
    {
      PST_CoEdge* coedge = edge->end_point() == end ? 
                           edge->forward() : edge->reverse();
      imprintResult.append( coedge );

      if( DEBUG_FLAG( VG_FACET_DEBUG ) )
      {
      	edge->debug_draw( VG_FACET_IMPRINT_COLOR );        
      }
	
      return CUBIT_SUCCESS;
    }    

      // Draw the current segment
    if( DEBUG_FLAG( VG_FACET_DEBUG ) )
    {
      GfxDebug::draw_line( 
      	(float)start_point->x(), (float)start_point->y(), 
        (float)start_point->z(),
        (float)end->x()  , (float)end->y()  , (float)end->z(),
        VG_FACET_SEGMENT_COLOR );
      GfxDebug::flush();
      GfxDebug::mouse_xforms();
    }
    
      // Get face or edge adjacent to start and closest to the polyline segment
    stat = next_around_point( start_point, *end, closest_face, closest_edge, 
                              is_boundary_edge, last_closest_edge );
    
    if(closest_edge)    
      last_closest_edge = closest_edge;    

    if (!stat || (closest_face && closest_edge))
    {
 //     assert(false);
      return stat;
    }

    const CubitVector seg_tan = *end - *start_point;
    double t_seg = 0.0;<--- Shadowed declaration
    point = 0;
    
    if (closest_face)
    {
        // calculate intersection with triangle edge opposite
        // 'start_point'.
      double t_edge;
      edge = closest_face->opposite(start_point);
      PST_Point* edge_start = edge->start_point();
      PST_Point* edge_end   = edge->end_point();
      closest_on_lines( *edge_start, *edge_end - *edge_start,
                        *start_point,  seg_tan, t_edge, t_seg);
      
      const CubitVector  seg_pt = *start_point + t_seg  *  seg_tan;
      const CubitVector edge_pt = (1.0 - t_edge) * *edge_start
                                       + t_edge  * *edge_end;
      
        // if line segment intersects opposite edge of triangle...
      if ( (t_seg < 1.0) || ((seg_pt - edge_pt).length_squared() < TOL_SQR) )
      {
          // Check if intersection is near start of opposite edge
        if ((t_edge <= 0.0) || 
            ((*edge_start - edge_pt).length_squared() < TOL_SQR) ||
            ((*edge_start - seg_pt ).length_squared() < TOL_SQR) )
          point = edge_start;
          // Check if intersection is near end of opposite edge
        else if ((t_edge >= 1.0) || 
                 ((*edge_end - edge_pt).length_squared() < TOL_SQR) ||
                 ((*edge_end -  seg_pt).length_squared() < TOL_SQR))
          point = edge_end;
          // Otherwise intersection is in the interior of the edge
        else
          point = split_edge(edge, t_edge);
      }
        // otherwise segment end is inside triangle
      else
      {
        t_seg = 1.0;
        const CubitVector proj = closest_face->plane().project(*end);
        PST_Edge *edge1, *edge2;
        closest_face->two_edges (start_point, edge1, edge2);
          // Too close to start position - skip segment
        if ( (*start_point - proj).length_squared() < TOL_SQR )
          point = start_point;
          // If close to side of triangle, fall through to edge
          // handling code
        else if (within_tolerance(edge1, *end, GEOMETRY_RESABS) ||
                 within_tolerance(edge1, proj, GEOMETRY_RESABS))
          closest_edge = edge1;
          // If close to side of triangle, fall through to edge
          // handling code
        else if (within_tolerance(edge2, *end, GEOMETRY_RESABS) ||
                 within_tolerance(edge2, proj, GEOMETRY_RESABS))
          closest_edge = edge2;
          // Insert new point in triangle interior...
        else
          point = insert_in_face (closest_face, proj);
      }
    } // if(closest_face)
    
    if (closest_edge)
    {
      PST_Point *const edge_end = closest_edge->other(start_point);
        // If edge and segment ends are equal...
      if ( (*edge_end - *end).length_squared() < TOL_SQR )
      {
        point = edge_end;
        edge = closest_edge;
        if (is_boundary_edge)
          end = edge_end;
      }
        // Otherwise calculate closest point
      else
      {
          // edge and segment share a start point so just need
          // to calculate the projection of each on the other.
        const CubitVector edge_tan = *edge_end - *start_point;
        const double dot_prod = seg_tan % edge_tan;
        const double t_seg  = dot_prod /  seg_tan.length_squared();<--- Shadow variable
        const double t_edge = dot_prod / edge_tan.length_squared();
        
        const CubitVector  seg_pt = *start_point + t_seg  *  seg_tan;
        const CubitVector edge_pt = *start_point + t_edge * edge_tan;
        
          // Too close to start point -- skip segment
        if (t_edge <= 0.0 || t_seg <= 0.0 ||
            (*start_point - edge_pt).length_squared() < TOL_SQR ||
            (*start_point -  seg_pt).length_squared() < TOL_SQR )
          point = start_point;
          // If segment end is near or passed edge end, 
          // then the edge end is the intersection with this triangle
        else if (t_edge > 1.0 || 
                 (*edge_end - edge_pt).length_squared() < TOL_SQR ||
                 (*edge_end -  seg_pt).length_squared() < TOL_SQR)
        {
          //make sure the facet edge is not a boundary edge.
          if (is_boundary_edge && start_point == start)
            start =  edge_end;
          point = edge_end;
        }
          // Otherwise closest point to segment end is in the interior
          // of the edge -- split the edge.
        else
        {
          if(start_point != closest_edge->start_point())
            point = split_edge( closest_edge, 1.0 - t_edge );
          else
            point = split_edge( closest_edge, t_edge );
        }
      }
    } // if(closest_edge)

    if (point == start_point) // skip perpendicular or very short segment
      continue;

    edge = start_point->common( point );
    if (!edge)
    {
      assert(false);
      continue;
    }
    
    if ( !is_boundary_edge || start_point != start )
    { 
       PST_CoEdge* coedge = edge->end_point() == point ?
                            edge->forward() : edge->reverse();
       imprintResult.append(coedge);
    }

    if( DEBUG_FLAG( VG_FACET_DEBUG ) )
    {
      edge->debug_draw( VG_FACET_IMPRINT_COLOR );
      point->debug_draw( VG_FACET_IMPRINT_COLOR );
    }    
    start_point = point;
  }
  
  return CUBIT_SUCCESS;
}

//-------------------------------------------------------------------------
// Purpose       : Check if a point is within the passed tolerance
//                 of a bounded edge.
//
// Special Notes : 
//
// Creator       : Jason Kraftcheck
//
// Creation Date : 09/04/03
//-------------------------------------------------------------------------
bool FacetProjectTool::within_tolerance( PST_Edge* edge,
                                         const CubitVector& point,
                                         double tolerance )
{
  const double t_edge = edge->closest_on_edge( point );
  const CubitVector edge_pos = edge->position(t_edge);
  return (edge_pos - point).length_squared() < tolerance*tolerance;
}

//-------------------------------------------------------------------------
// Purpose       : Given a line segment beginning at a point in the
//                 triangulation, find the face or edge adjacent to the
//                 point and closest to the line segment.
//
// Special Notes : 
//
// Creator       : Jason Kraftcheck
//
// Creation Date : 09/04/03
//-------------------------------------------------------------------------
CubitStatus FacetProjectTool::next_around_point ( PST_Point*& start,
                                        const CubitVector& seg_end,
                                        PST_Face*& closest_face,
                                        PST_Edge*& closest_edge,
                                        CubitBoolean & is_boundary_edge,
                                        PST_Edge *last_closest_edge)
{
  DLIList<PST_Face*> face_list;
  DLIList<PST_Edge*> boundary_edges;
  is_boundary_edge = CUBIT_FALSE; 
  double shortest_dist_sqr = CUBIT_DBL_MAX;
  closest_face = 0;
  closest_edge = 0;
  
  //const double TOL_SQR = GEOMETRY_RESABS*GEOMETRY_RESABS;
  
  const CubitVector tangent = seg_end - *start;
   
    // To traverse the edges in clockwise order about the point,
    // it is necessary to start with the appropriate boundary edge
    // if there is one.  If this point is not on the boundary of 
    // the facet patch, any edge is acceptable.

    // First mark all faces adjacent to the vertex.  This is to make
    // sure disjoint sets of faces (sets of faces with no edges in
    // common) are not missed when traversing edge-face adjacencies.
  start->faces( &face_list );
  for (int i = face_list.size(); i--; )  
    face_list.step_and_get()->mark = true;
  
    // Loop until all faces in face_list have been un-marked
  boundary_edges.clean_out();
  closest_edge = 0;
  closest_face = 0; 
  while (face_list.size())
  {
    PST_Face* face = face_list.pop();
    if (!face->mark)
      continue;

    PST_CoEdge* coedge = face->first_coedge();
    if (coedge->edge()->other(start) == 0)
      coedge = coedge->next();

      // search for the 'first' coedge in the clockwise list.
    PST_CoEdge* first = coedge;
    while (coedge->face())
    {
      if (coedge->end_point() == start)
        coedge = coedge->other();
      else
        coedge = coedge->previous();

      if (coedge == first) // no start, point is not on boundary
        break;
    }

      // keep boundary edges encountered for later
    if (!coedge->face())
      boundary_edges.append(coedge->edge());

      // Of the two edges on the face that are adjacent to the
      // point, begin with the one that is first in clockwise
      // order around the point.
    if (coedge->start_point() == start)
      coedge = coedge->other();
    first = coedge;

      // Traverse adjacent facets in clockwise order
      // around point.
    bool clockwise_of_prev = false;
    while ( (face = coedge->face()) )
    {
      face->mark = false;

        // get vectors for edges of face pointing outwards
        // from vertex.
      assert(coedge->end_point() == start && coedge->next()->start_point() == start);
      CubitVector prev = coedge->other()->direction();
      CubitVector next = coedge->next()->direction();

        // calculate if segment is to the 'inside' of each
        // adjacent edge.
      CubitVector normal = next * prev;  // ccw 
      bool inside_prev = ((tangent * prev) % normal) >= 0.0;
      bool inside_next = ((next * tangent) % normal) >= 0.0;

        // If edge is inside face, check distance from face
      if( (inside_prev && inside_next) )
      {
        // calculate distance from end point to plane of face
        const double plane_coeff = normal % *start;
        const double end_coeff = normal % seg_end;
        const double numerator = end_coeff - plane_coeff;
        const double dist_sqr = (numerator * numerator) / normal.length_squared();         
        
        if (dist_sqr < shortest_dist_sqr)
        {
          closest_face = face;
          closest_edge = 0;
          shortest_dist_sqr = dist_sqr;
        }

        clockwise_of_prev = false;
      }
        // If the edge is above a peak formed by the shared edge of two faces
      else if (inside_next && clockwise_of_prev)
      {
          // calculate distance from end of segment to line of facet edge
        const double dot_prod = tangent % prev;
        const double dist_sqr = 
          tangent.length_squared() - dot_prod * dot_prod / prev.length_squared();

        if (dist_sqr <= shortest_dist_sqr && coedge->edge() != last_closest_edge)
        {
          closest_face = 0;
          closest_edge = coedge->edge();
          shortest_dist_sqr = dist_sqr;
        }
        clockwise_of_prev = false;
      }
        // If clockwise of the face, note for next iteration
      else if (inside_prev)
      {
        clockwise_of_prev = true;
      }
      else
      {
        clockwise_of_prev = false;
      }  

      coedge = coedge->next()->other();
      if (coedge == first)
        break;
    } // while(coedge->face())
    
    if (!coedge->face())
      boundary_edges.append(coedge->edge());
  
  } // while(face_list.size())
  
    // If a closest entity was found, then done.
  if (closest_face || closest_edge)
    return CUBIT_SUCCESS;
    

  //Here we try to intersect the segment with the boundary 
  //facet edge closest to 'start' (farthest from 'end')
  bool debug = false;<--- Assignment 'debug=false', assigned value is 0
  if( !closest_edge )
  {
    CubitVector seg_direction = seg_end - *start;   
    double seg_length = seg_direction.length();
    double longest_length = 0;            
    
    if( debug )<--- Condition 'debug' is always false
    {
      GfxDebug::clear(); 
      start->debug_draw(CUBIT_GREEN_INDEX);
      GfxDebug::draw_point( seg_end, CUBIT_RED_INDEX );
      for( int j=facetList.size(); j--; )
        facetList.get_and_step()->debug_draw( CUBIT_CYAN_INDEX );
      GfxDebug::mouse_xforms(); 
    }
    
    //find the farthest boundary edge that is on the line segment    
    CubitVector split_position;
    for( int k=boundaryList.size(); k--; )
    {
      PST_Edge *tmp_edge = boundaryList.get_and_step();

      if( tmp_edge->start_point() == start ||
          tmp_edge->end_point() == start )
          continue;      

      double t1 = tmp_edge->closest_on_line( *start, seg_end - *start );
      
      if( t1 > 1e-6 && t1 < 1 )
      { 
        CubitVector tmp_pos = tmp_edge->position( t1 );

        if( debug )
        {
          GfxDebug::draw_line( *start, seg_end, CUBIT_MAGENTA_INDEX );
          PRINT_INFO("t1 = %f\n", t1 );
          tmp_edge->debug_draw( CUBIT_YELLOW_INDEX );
          GfxDebug::draw_point( tmp_pos, CUBIT_RED_INDEX );        
          GfxDebug::flush();
          GfxDebug::mouse_xforms(); 
        }

        double tmp_dist = tmp_pos.distance_between( seg_end );

        if( tmp_dist > longest_length && tmp_dist < seg_length )
        {
          longest_length = tmp_dist;
          closest_edge = tmp_edge;
          split_position = tmp_pos;
        }
      }
    }
    
    if( closest_edge )
    {
      start = project( split_position );    

      CubitStatus my_stat = next_around_point( start, seg_end, closest_face, 
        closest_edge, is_boundary_edge, last_closest_edge );

      if( CUBIT_FAILURE == my_stat )
        return CUBIT_FAILURE;
     
      return closest_face ? CUBIT_SUCCESS : CUBIT_FAILURE;      
    }   
  } 
  
  return closest_edge ? CUBIT_SUCCESS : CUBIT_FAILURE;
}

  
  
    
  

//-------------------------------------------------------------------------
// Purpose       : Remove duplciate edges from results if input polyline
//                 was self-intersecting.
//
// Special Notes : 
//
// Creator       : Jason Kraftcheck
//
// Creation Date : ??
//-------------------------------------------------------------------------
void FacetProjectTool::finalize_results()
{
  imprintResult.reset();
  for ( int i = imprintResult.size(); i--; )
  {
    PST_Edge* edge = imprintResult.step_and_get()->edge();
    if (edge->mark)
      imprintResult.change_to(0);
    else
      edge->mark = 1;
  }
  imprintResult.remove_all_with_value(0);
  imprintResult.reset();
}

//-------------------------------------------------------------------------
// Purpose       : Return non-intersecting chains of result edges, in the
//                 same sequence as the input polyline and with the same
//                 orientation.
//
// Special Notes : This is called after the projection is done to get the
//                 resulting facet edge chains.
//
// Creator       : Jason Kraftcheck
//
// Creation Date : 09/04/03
//-------------------------------------------------------------------------
CubitStatus FacetProjectTool::get_result_set( DLIList<PST_CoEdge*>& coedges )
{
  if ( !imprintResult.size() )
    return CUBIT_FAILURE;
  
  imprintResult.reset();
  PST_CoEdge* prev = imprintResult.get();
  imprintResult.change_to(0);
  coedges.append(prev);
  
  for ( int i = imprintResult.size() - 1; i--; )
  {
    PST_CoEdge* coedge = imprintResult.step_and_get();
    PST_Point* pt = prev->end_point();
    if (pt != coedge->start_point())
      break;
    
    int count = 1;
    for (PST_Edge* pt_edge = pt->next(coedge->edge());
         pt_edge != coedge->edge();
         pt_edge = pt->next(pt_edge))
    {
      if (pt_edge->mark)
        count++;
    }
     
    if (count != 2)
      break;
    
    coedges.append(coedge);
    prev = coedge;
    imprintResult.change_to(0);
  }
  
  imprintResult.remove_all_with_value(0);
  return CUBIT_SUCCESS;
}


double FacetProjectTool::closest_on_line( const CubitVector& B,
                                      const CubitVector& M,
                                      const CubitVector& P ) 
{ 
  const double dist_tol_sqr = GEOMETRY_RESABS*GEOMETRY_RESABS;
  double D = M.length_squared();
  return (D < dist_tol_sqr ) ? 0.0 : (M % (P - B)) / D;
}


void FacetProjectTool::closest_on_lines( const CubitVector& B1,
                                     const CubitVector& M1,
                                     const CubitVector& B2,
                                     const CubitVector& M2,
                                     double& t1, double& t2 ) 
{
  CubitVector N = M2 * (M2 * M1);
  double d = N % M1;
  if( fabs(d) < CUBIT_RESABS ) //parallel lines
    t1 = 0.0;
  else
    t1 = ((N % B2) - (N % B1)) / d;

  t2 = closest_on_line( B2, M2, B1 + t1 * M1 );
}
  
      
bool FacetProjectTool::inside_face( PST_Face* face, const CubitVector& pos )
{      
    // This code checks if the position is in the interior of 
    // the prism formed by sweeping the facet infinetly in the
    // direction of, and opposite direction of the facet normal.
  PST_CoEdge* coe = face->first_coedge();
  do {
    CubitVector vect( pos );
    vect -= *coe->start_point();
    vect *= coe->direction();
    if( vect % face->normal() > -CUBIT_RESABS )
      return false;
    coe = coe->next();
  } while( coe != face->first_coedge() );
  return true;
}

/*
static void draw_pt( const std::vector<double>& list, int index, int color )
{
  GfxDebug::draw_point( 
    (float)list[index], (float)list[index+1], (float)list[index+2], color );
}

static void draw_edge( const std::vector<double>& list, int i1, int i2, int color )
{
  i1 *= 3; i2 *= 3;
  GfxDebug::draw_line(
    (float)list[i1], (float)list[i1+1], (float)list[i1+2],
    (float)list[i2], (float)list[i2+1], (float)list[i2+2],
    color );
}

static void draw_tri( const std::vector<double>& pts,
                      const std::vector<int>& tris, int index, 
                      const std::vector<int>& seq, int color )
{
  for ( int i = 0; i < 3; i++ )
  {
    int i1 = tris[index + i];
    int i2 = tris[index + (i + 1) % 3];
    if ( !seq[i1] || !seq[i2] || abs(seq[i1]-seq[i2]) != 1 )
      draw_edge( pts, i1, i2, color );
  }
}
*/

void FacetProjectTool::debug( DLIList<CubitVector*>& segments,
                              std::vector<double>& coordinates,
                              std::vector<int>& connections )
{
#if 1 /* test with old interface */  
  DLIList<PST_Edge*> edges;
  PST_Edge::make_facets(coordinates, connections, GEOMETRY_RESABS, edges);
  
  DLIList<PST_Face*> faces;
  PST_Edge::faces( edges, faces );
  populate_data(faces);
  
  CubitBoolean point_changed;
  do_projection( segments, point_changed );
  
  PST_Edge::debug_draw_edges( edgeList, CUBIT_BLUE_INDEX );
  
  DLIList<PST_CoEdge*> coedges;
  finalize_results();
  while( get_result_set( coedges ) ) {
    edges.clean_out();
    coedges.reverse();
    while (coedges.size()) edges.append(coedges.pop()->edge());
    PST_Edge::debug_draw_edges( edges, CUBIT_WHITE_INDEX );
    PST_Edge::debug_draw_points( edges, CUBIT_WHITE_INDEX );
  }

#else /* test with new interface */

  int i, j;

    // do projection
  std::vector<double> new_pts;
  std::vector<int> dudded, new_facets, facet_index, polyline;
  if( !project( segments, coordinates, connections, dudded, 
                new_facets, facet_index, new_pts, polyline ) )
  {
    PRINT_ERROR("FacetProjectTool::project returned CUBIT_FAILURE\n");
    return;
  } 
  
  assert( connections.size() % 3 == 0 );
  assert( coordinates.size() % 3 == 0 );
  assert( new_facets.size() % 3 == 0 );
  assert( new_pts.size() % 3 == 0 );
  assert( dudded.size() == facet_index.size() );
  int num_old_tri = connections.size() / 3;
  int num_new_tri = new_facets.size() / 3;
  int num_old_pts = coordinates.size() / 3;
  int num_new_pts = new_pts.size() / 3;
  int num_tot_tri = num_new_tri + num_old_tri;
  int num_tot_pts = num_new_pts + num_old_pts;
  
  PRINT_INFO("%d input triangles using %d points.\n", num_old_tri, num_old_pts );
  PRINT_INFO("%d new triangles and %d new poitns.\n", num_new_tri, num_new_pts );
  PRINT_INFO("%d total triangles using %d total points.\n", num_tot_tri, num_tot_pts );
  PRINT_INFO("connections.size() = %d\n", (int)connections.size());
  PRINT_INFO("coordinates.size() = %d\n", (int)coordinates.size());
  PRINT_INFO("dudded.size() = %d\n", (int)dudded.size());
  PRINT_INFO("new_facets.size() = %d\n", (int)new_facets.size());
  PRINT_INFO("facet_index.size() = %d\n", (int)facet_index.size());
  PRINT_INFO("new_pts.size() = %d\n", (int)new_pts.size());
  PRINT_INFO("polyline.size() = %d\n", (int)polyline.size());
  
  for ( i = 0; i < (int)new_facets.size(); i++ )
    if ( new_facets[i] >= num_tot_pts || new_facets[i] < 0 )
      PRINT_ERROR("Invalid value %d at new_facets[%d]\n", new_facets[i], i);
  for ( i = 0; i < (int)dudded.size(); i++ )
    if ( dudded[i] >= num_old_tri || dudded[i] < 0 )
      PRINT_ERROR("Invalid value %d at dudded[%d]\n", dudded[i], i);
  for ( i = 0; i < (int)polyline.size()-1; )
  {
    int count = polyline[i];
    if ( count < 2 )
      PRINT_ERROR("Invalid polyline length %d at polyline[%d]\n", count, i );
    i++;
    for ( j = 0; j < count; j++, i++ )
    {
      if( i >= (int)polyline.size() )
        PRINT_ERROR("Ran out of indices in polyline.\n");
      if ( polyline[i] >= num_tot_pts || polyline[i] < 0 )
        PRINT_ERROR("Invalid value %d at dudded[%d]\n", dudded[i], i);
    }
  }
  
    // draw original points
  for ( i = 0; i < (int)coordinates.size(); i += 3 )
    draw_pt( coordinates, i, CUBIT_BLUE_INDEX );
/*  
    // draw new points
  for ( i = 0; i < (int)new_pts.size(); i += 3 )
    draw_pt( new_pts, i, CUBIT_RED_INDEX ); 
*/  
    // concatenate point lists
  for ( i = 0; i < (int)new_pts.size(); i++ )
    coordinates.push_back(new_pts[i]);
  
    // make reverse mapping for dudded facets
  std::vector<bool> dead(connections.size()/3);
  for ( i = 0; i < (int)dead.size(); i++ )
    dead[i] = false;
  for ( i = 0; i < (int)dudded.size(); i++ )
    dead[dudded[i]] = true;
    
    // make polyline sequence list (this won't work quite
    // right for self-intersecting polylines -- *shrug*)
  std::vector<int> sequence(coordinates.size() / 3);
  for ( i = 0; i < (int)sequence.size(); i++ )
    sequence[i] = 0;
  j = 0;
  for ( i = 0; i < (int)polyline.size(); i++ )
    sequence[polyline[i]] = ++j;
  
  
    // draw orginal facets
  for ( i = 0; i < (int)dead.size(); i++ )
    if( ! dead[i] )
      draw_tri( coordinates, connections, 3*i, sequence, CUBIT_BLUE_INDEX );
  
    // draw new facets
  for ( i = 0; i < (int)new_facets.size(); i += 3 )
    draw_tri( coordinates, new_facets, i, sequence, CUBIT_RED_INDEX );
  
    // draw polyline
  for ( i = 0; i < (int)polyline.size()-1; i++)
  {
    int count = polyline[i];
    if ( count < 2 )
      PRINT_ERROR("Invalid polyline length %d at polyline[%d]\n", count, i );
    int first = ++i;
    for ( j = 0; j < count-1; j++, i++ )
    {
      draw_edge( coordinates, polyline[i], polyline[i+1], CUBIT_WHITE_INDEX );
    }
    if( polyline[first] == polyline[i] )
      PRINT_INFO("Polyline is closed.\n");
  }

  GfxDebug::flush();
#endif
  cleanup();  
}