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
#include "meshkit/QuadCleanUp.hpp"

using namespace Jaal;

size_t OneDefectPatch :: MAX_FACES_ALLOWED = 500;

size_t OneDefectPatch :: num_boundaries  = 0;
size_t OneDefectPatch :: num_3_patches   = 0;
size_t OneDefectPatch :: num_4_patches   = 0;
size_t OneDefectPatch :: num_5_patches   = 0;
size_t OneDefectPatch :: disk_remeshable = 0;
double OneDefectPatch :: exec_time       = 0.0;

///////////////////////////////////////////////////////////////////////////////
int TriRemeshTemplate::remesh(Mesh *msh,
                              NodeSequence &anodes,
                              NodeSequence &bnodes,
                              NodeSequence &cnodes, int *partition)
{
     mesh = msh;

     // First thing to do is to clear the existing record.
     newnodes.clear();
     newfaces.clear();

     // We need atleast three nodes on each side ...
     if (anodes.size() < 3) return 1;
     if (bnodes.size() < 3) return 1;
     if (cnodes.size() < 3) return 1;

     if (partition == NULL) {
          segments[0] = anodes.size() - 1;
          segments[1] = bnodes.size() - 1;
          segments[2] = cnodes.size() - 1;

          if (!Face::is_3_sided_convex_loop_quad_meshable(segments, partSegments))
               return 1;
     } else {
          for (int i = 0; i < 6; i++)
               partSegments[i] = partition[i];
     }


     int err;
     if (anodes.back() == bnodes.back()) {
          reverse(bnodes.begin(), bnodes.end());
          swap(partSegments[2], partSegments[3]);
     }

     if (anodes.front() == cnodes.front()) {
          reverse(cnodes.begin(), cnodes.end());
          swap(partSegments[4], partSegments[5]);
     }

     // Ensure that input is closed loop of three sides ...
     assert(anodes.front() == cnodes.back());
     assert(bnodes.front() == anodes.back());
     assert(cnodes.front() == bnodes.back());

     // Ensure that segments are valid ...
     assert((int)anodes.size() == partSegments[0] + partSegments[1] + 1);
     assert((int)bnodes.size() == partSegments[2] + partSegments[3] + 1);
     assert((int)cnodes.size() == partSegments[4] + partSegments[5] + 1);

     // Split Side "A" nodes into a1nodes and b1nodes.
     int a1 = partSegments[0];
     err = split_stl_vector(anodes, a1 + 1, a1nodes, b1nodes);
     if (err) return 1;

     // Split Side "B" nodes into a2nodes and b2nodes.
     int a2 = partSegments[2];
     err = split_stl_vector(bnodes, a2 + 1, a2nodes, b2nodes);
     if (err) return 1;

     // Split Side "C" nodes into a3nodes and b3nodes.
     int a3 = partSegments[4];
     err = split_stl_vector(cnodes, a3 + 1, a3nodes, b3nodes);
     if (err) return 1;

     // Splitting nodes on each side
     Vertex *ca = a1nodes.back();
     Vertex *cb = a2nodes.back();
     Vertex *cc = a3nodes.back();

     // We are not if the centroid will be in the patch, take the risk.
     Vertex *co = Face::centroid(ca, cb, cc);

     mesh->addNode(co);
     newnodes.push_back(co);

     linear_interpolation(mesh, co, ca, a2 + 1, oa_nodes);
     size_t nSize = oa_nodes.size();
     for (size_t i = 1; i < nSize - 1; i++)
          newnodes.push_back(oa_nodes[i]);

     linear_interpolation(mesh, co, cb, a3 + 1, ob_nodes);
     nSize = ob_nodes.size();
     for (size_t i = 1; i < nSize - 1; i++)
          newnodes.push_back(ob_nodes[i]);

     linear_interpolation(mesh, co, cc, a1 + 1, oc_nodes);
     nSize = oc_nodes.size();
     for (size_t i = 1; i < nSize - 1; i++)
          newnodes.push_back(oc_nodes[i]);

     err = quadtemplate.remesh(mesh, b2nodes, a3nodes, oc_nodes, ob_nodes);
     if (!err) addNewElements( quadtemplate.newnodes, quadtemplate.newfaces);

     if (!err) {
          err = quadtemplate.remesh(mesh, a1nodes, oa_nodes, oc_nodes, b3nodes);
          if (!err) addNewElements( quadtemplate.newnodes, quadtemplate.newfaces);
     }

     if (!err) {
          err = quadtemplate.remesh(mesh, a2nodes, ob_nodes, oa_nodes, b1nodes);
          if (!err) addNewElements( quadtemplate.newnodes, quadtemplate.newfaces);
     }

     if (err) {
          discard();
          return 1;
     }

     // Check for any inversion of the element, if there is inversion,
     // undo everthing (i.e. remove new nodes and faces).
     //
     nSize = newfaces.size();
     for (size_t i = 0; i < nSize; i++) {
          if (newfaces[i]->concaveAt() >= 0) {
               discard();
               return 2;
          }
     }

     return 0;
}

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

int
QuadRemeshTemplate :: remesh()
{
     size_t nSize = boundnodes.size();
     assert( nSize == size_t(2 * nx + 2 * ny - 4));

     qnodes.resize(nx * ny);

     //
     // Put the boundary nodes on the structured mesh: The orientation is
     // Counter clockwise ( south->east->north->west );
     //
     int offset, index = 0;

     // South Side ...
     index = 0;
     for (int i = 0; i < nx; i++) {
          offset = i;
          qnodes[i] = boundnodes[index++];
     }

     // East Side
     for (int j = 1; j < ny; j++) {
          offset = j * nx + (nx - 1);
          qnodes[offset] = boundnodes[index++];
     }

     // North Side
     for (int i = nx - 2; i >= 0; i--) {
          offset = (ny - 1) * nx + i;
          qnodes[offset] = boundnodes[index++];
     }

     // West Side
     for (int j = ny - 2; j >= 1; j--) {
          offset = j*nx;
          qnodes[j * nx] = boundnodes[index++];
     }

     // New internal nodes must be generated.(either new or from  the trash bin)
     mesh->objects_from_pool( (nx-2)*(ny-2), newnodes );

     // Assign the coordinates using Transfinite-interpolation method. For 3D
     // Coordinates must be projected on the surface.
     //
     index = 0;
     for (int j = 1; j < ny - 1; j++) {
          for (int i = 1; i < nx - 1; i++) {
               offset = j * nx + i;
               qnodes[offset] = newnodes[index++];
               set_tfi_coords(i, j, nx, ny, qnodes); // Coordinates values
          }
     }

     // All new faces must be generated. ( Objects are either new or from the trash bin)
     mesh->objects_from_pool( (nx-1)*(ny-1), newfaces );

     NodeSequence qc(4);

     // Create new faces ...
     index = 0;
     for (int j = 0; j < ny - 1; j++) {
          for (int i = 0; i < nx - 1; i++) {
               int offset = j * nx + i;
               qc[0] = qnodes[offset];
               qc[1] = qnodes[offset + 1];
               qc[2] = qnodes[offset + 1 + nx];
               qc[3] = qnodes[offset + nx];
               Face *face = newfaces[index++];
               face->setNodes(qc);
               face->setVisitMark(1);
          }
     }

     // Update the mesh ...
     nSize = newnodes.size();
     for (size_t i = 0; i < nSize; i++)
          mesh->reactivate( newnodes[i] );

     nSize = newfaces.size();
     for (size_t i = 0; i < nSize; i++)
          mesh->reactivate( newfaces[i] );

     // Check for any inversion of the element, if there is inversion,
     // undo everthing (i.e. remove new nodes and faces).
     //
     nSize = newfaces.size();
     for (size_t i = 0; i < nSize; i++) {
          if (newfaces[i]->concaveAt() >= 0) {
               discard();
               return 1;
          }
     }

     return 0;
}

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

int
QuadRemeshTemplate ::remesh(Mesh *msh,
                            NodeSequence &anodes,
                            NodeSequence &bnodes,
                            NodeSequence &cnodes,
                            NodeSequence &dnodes )
{
     mesh = msh;

     newnodes.clear();
     newfaces.clear();

     assert(anodes.size() == cnodes.size());
     assert(bnodes.size() == dnodes.size());

     nx = anodes.size();
     ny = bnodes.size();

     boundnodes.resize(2 * nx + 2 * ny - 4);

     int index = 0;

     // First edge is always the reference edge which decides the orientation.
     // Append anodes..
     size_t nSize = anodes.size();
     for (size_t i = 0; i < nSize; i++)
          boundnodes[index++] = anodes[i];

     // Append bnodes ...
     if (bnodes.front() != anodes.back())
          reverse(bnodes.begin(), bnodes.end());

     assert(anodes.back() == bnodes.front());

     nSize = bnodes.size();
     for (size_t i = 1; i < nSize; i++)
          boundnodes[index++] = bnodes[i];

     // Append cnodes ...
     if (cnodes.front() != bnodes.back())
          reverse(cnodes.begin(), cnodes.end());

     assert(bnodes.back() == cnodes.front());

     nSize = cnodes.size();
     for (size_t i = 1; i < nSize; i++)
          boundnodes[index++] = cnodes[i];

     // Append dnodes ...
     if (dnodes.front() != cnodes.back())
          reverse(dnodes.begin(), dnodes.end());

     assert(cnodes.back() == dnodes.front());
     nSize = dnodes.size();
     for (size_t i = 1; i < nSize; i++)
          boundnodes[index++] = dnodes[i];

     // Ensure that loop is closed ...
     assert(anodes.front() == dnodes.back());

     return remesh();
}

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

int
PentaRemeshTemplate :: remesh(Mesh *msh,
                              NodeSequence &anodes,
                              NodeSequence &bnodes,
                              NodeSequence &cnodes,
                              NodeSequence &dnodes,
                              NodeSequence &enodes,
                              int *partition)
{
     //
     // Implicit in this implementation is the orientation of the newly formed
     // faces which is decided by the orientation of the boundary. User need
     // not check for the consistency of the mesh. It will be, if the initial
     // mesh is consistent.
     //
     mesh = msh;

     newnodes.clear();
     newfaces.clear();

     if (partition == NULL) {
          segments[0] = anodes.size() - 1;
          segments[1] = bnodes.size() - 1;
          segments[2] = cnodes.size() - 1;
          segments[3] = dnodes.size() - 1;
          segments[4] = enodes.size() - 1;
          if (!Face::is_5_sided_convex_loop_quad_meshable(segments, partSegments)) {
               cout << "Warning: Penta patch not quad meshable " << endl;
               return 1;
          }
     } else {
          for (int i = 0; i < 10; i++)
               partSegments[i] = partition[i];
     }

     int err;
     // Ensure that input is closed loop of three sides ...
     assert(anodes.front() == enodes.back());
     assert(bnodes.front() == anodes.back());
     assert(cnodes.front() == bnodes.back());
     assert(dnodes.front() == cnodes.back());
     assert(enodes.front() == dnodes.back());

     // Ensure that segments are valid ...
     assert((int)anodes.size() == partSegments[0] + partSegments[1] + 1);
     assert((int)bnodes.size() == partSegments[2] + partSegments[3] + 1);
     assert((int)cnodes.size() == partSegments[4] + partSegments[5] + 1);
     assert((int)dnodes.size() == partSegments[6] + partSegments[7] + 1);
     assert((int)enodes.size() == partSegments[8] + partSegments[9] + 1);

     // Split Side "A" nodes into a1nodes and b1nodes.
     int a1 = partSegments[0];
     err = split_stl_vector(anodes, a1 + 1, a1nodes, b1nodes);
     if (err) return 1;

     // Split Side "B" nodes into a2nodes and b2nodes.
     int a2 = partSegments[2];
     err = split_stl_vector(bnodes, a2 + 1, a2nodes, b2nodes);
     if (err) return 1;

     // Split Side "C" nodes into a3nodes and b3nodes.
     int a3 = partSegments[4];
     err = split_stl_vector(cnodes, a3 + 1, a3nodes, b3nodes);
     if (err) return 1;

     // Split Side "C" nodes into a3nodes and b3nodes.
     int a4 = partSegments[6];
     split_stl_vector(dnodes, a4 + 1, a4nodes, b4nodes);
     if (err) return 1;

     // Split Side "C" nodes into a3nodes and b3nodes.
     int a5 = partSegments[8];
     err = split_stl_vector(enodes, a5 + 1, a5nodes, b5nodes);
     if (err) return 1;

     // Splitting nodes on each side
     Vertex *ca = a1nodes.back();
     Vertex *cb = a2nodes.back();
     Vertex *cc = a3nodes.back();
     Vertex *cd = a4nodes.back();
     Vertex *ce = a5nodes.back();

     // Centoid may not be within the patch. But take the risk.
     Vertex *co = Face::centroid(ca, cb, cc, cd, ce);

     mesh->addNode(co);
     newnodes.push_back(co);

     size_t nSize;
     linear_interpolation(mesh, co, ca, a2 + 1, oa_nodes);
     nSize = oa_nodes.size();
     for (size_t i = 1; i < nSize - 1; i++) {
          newnodes.push_back(oa_nodes[i]);
     }

     linear_interpolation(mesh, co, cb, a3 + 1, ob_nodes);
     nSize = ob_nodes.size();
     for (size_t i = 1; i < nSize - 1; i++) {
          newnodes.push_back(ob_nodes[i]);
     }

     linear_interpolation(mesh, co, cc, a4 + 1, oc_nodes);
     nSize = oc_nodes.size();
     for (size_t i = 1; i < nSize - 1; i++) {
          newnodes.push_back(oc_nodes[i]);
     }

     linear_interpolation(mesh, co, cd, a5 + 1, od_nodes);
     nSize = od_nodes.size();
     for (size_t i = 1; i < nSize - 1; i++) {
          newnodes.push_back(od_nodes[i]);
     }

     linear_interpolation(mesh, co, ce, a1 + 1, oe_nodes);
     nSize = oe_nodes.size();
     for (size_t i = 1; i < nSize - 1; i++) {
          newnodes.push_back(oe_nodes[i]);
     }

     err = quadtemplate.remesh(mesh, a1nodes, oa_nodes, oe_nodes, b5nodes);
     if (!err) addNewElements( quadtemplate.newnodes, quadtemplate.newfaces);

     if (!err) {
          err = quadtemplate.remesh(mesh, a2nodes, ob_nodes, oa_nodes, b1nodes);
          if (!err) addNewElements( quadtemplate.newnodes, quadtemplate.newfaces);
     }

     if (!err) {
          err = quadtemplate.remesh(mesh, a3nodes, oc_nodes, ob_nodes, b2nodes);
          if (!err) addNewElements( quadtemplate.newnodes, quadtemplate.newfaces);
     }

     if (!err) {
          err = quadtemplate.remesh(mesh, a4nodes, od_nodes, oc_nodes, b3nodes );
          if (!err) addNewElements( quadtemplate.newnodes, quadtemplate.newfaces);
     }

     if (!err) {
          err = quadtemplate.remesh(mesh, a5nodes, oe_nodes, od_nodes, b4nodes);
          if (!err) addNewElements( quadtemplate.newnodes, quadtemplate.newfaces);
     }

     if (err) {
          discard();
          return 1;
     }

     // Check for any inversion of the element, if there is inversion,
     // undo everthing (i.e. remove new nodes and faces).
     //
     nSize = newfaces.size();
     for (size_t i = 0; i < nSize; i++) {
          if (newfaces[i]->concaveAt() >= 0) {
               discard();
               return 2;
          }
     }

     return 0;
}

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

void OneDefectPatch::setAttributes()<--- The function 'setAttributes' is never used.
{
     size_t nSize;

     nSize = mesh->getSize(0);
     for (size_t i = 0; i < nSize; i++) {
          Vertex *v = mesh->getNodeAt(i);
          v->setAttribute("DefectPatch", 0);
     }

     nSize = mesh->getSize(2);
     for (size_t i = 0; i < nSize; i++) {
          Face *f = mesh->getFaceAt(i);
          f->setAttribute("DefectPatch", 0);
     }

     nSize = nodepath.size();
     for (size_t i = 0; i < nSize; i++)
          nodepath[i]->setAttribute("DefectPatch", 1);

     nSize = bound_nodes.size();
     for (size_t i = 0; i <  nSize; i++)
          bound_nodes[i]->setAttribute("DefectPatch", 3);

     NodeSet::const_iterator vit;
     for (vit = corners.begin(); vit != corners.end(); ++vit)
          (*vit)->setAttribute("DefectPatch", 2);

     FaceSet::const_iterator it;
     for (it = faces.begin(); it != faces.end(); ++it)
          (*it)->setAttribute("DefectPatch", 1);

}

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

bool OneDefectPatch::isSafe()
{
     FaceSet::const_iterator it;
     for (it = faces.begin(); it != faces.end(); ++it)
          if((*it)->isRemoved()) return 0;

     // Check if the previous updates modified the splitting node degree.
     if (quad_splitting_node) {
          int nSize = quad_splitting_node->getNumRelations(2);
          if ( nSize != quad_splitting_node_degree) return 0;
     }

     return 1;
}
///////////////////////////////////////////////////////////////////////////////

void OneDefectPatch::start_boundary_loop_from(Vertex *vmid)
{
     assert(corners.find(vmid) != corners.end());

     NodeSequence::iterator middle;
     middle = find(bound_nodes.begin(), bound_nodes.end(), vmid);
     assert(middle != bound_nodes.end());

     std::rotate(bound_nodes.begin(), middle, bound_nodes.end());
     assert(bound_nodes[0] == vmid);

     set_boundary_segments();
}
///////////////////////////////////////////////////////////////////////////////

void OneDefectPatch::get_bound_nodes(const Vertex *src, const Vertex *dst, NodeSequence &seq)
{
     int start_pos = getPosOf(src);
     int end_pos = getPosOf(dst);
     int nsize = bound_nodes.size();

     assert(nsize > 1);

     if (end_pos == 0) end_pos = nsize;
     assert(end_pos > start_pos);

     seq.resize(end_pos - start_pos + 1);
     int index = 0;
     for (int i = start_pos; i <= end_pos; i++)
          seq[index++] = bound_nodes[i % nsize];
}

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

bool OneDefectPatch::has_irregular_node_on_first_segment() const
{
     int start_pos = cornerPos[0];
     int end_pos = start_pos + segSize[0] - 1;

     for (int i = 1; i < end_pos - 1; i++)
          if( bound_nodes[i]->getNumRelations(2) < 4 ) return 1;

     return 0;
}

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

bool OneDefectPatch::is_simply_connected()
{
     size_t V = inner_nodes.size() + bound_nodes.size();
     size_t F = faces.size();

     vector<Edge> edges;
     edges.reserve(4 * F);

     FaceSet::const_iterator it;
     for (it = faces.begin(); it != faces.end(); ++it) {
          Face *face = *it;
          for (int i = 0; i < 4; i++) {
               Vertex *v0 = face->getNodeAt(i);
               Vertex *v1 = face->getNodeAt(i + 1);
               Edge edge(v0, v1);
               int found = 0;
               size_t nSize =  edges.size();
               for (size_t j = 0; j < nSize; j++) {
                    if (edges[j].isSameAs(edge)) {
                         found = 1;
                         break;
                    }
               }
               if (!found) edges.push_back(edge);
          }
     }

     size_t E = edges.size();

     if (V - E + F == 1) return 1;
     return 0;
}
///////////////////////////////////////////////////////////////////////////////

int OneDefectPatch::reorient_4_sided_loop()
{
     //Always remeshable, nothing has to be done...
     if ((segSize[0] == segSize[2]) && (segSize[1] == segSize[3])) return 0;

     //////////////////////////////////////////////////////////////////////////
     // Defination:  A four sided convex loop has four segments.
     // Objectives:  A four sided convex loop must be orietned such that
     //   1.  First segment must be smaller than the third one, because
     //       we need to create a triangle patch based at segment#3.
     //
     //   2.  If there are two choices, then the side having irregular
     //       node must be given higher priority. ( Here irregulaty means
     //       that vertex valency < 4 ).
     //
     //   3.  A side having less number of nodes on the first segment than
     //       the third is given preference.
     //
     // Pre-Conditions  :  A loop must be oriented ( CW or CCW ).
     //
     // Date: 17th Nov. 2010.
     //////////////////////////////////////////////////////////////////////////

     Vertex *start_corner = NULL;

     if (segSize[0] == segSize[2]) {
          if (min(segSize[1], segSize[3]) == 2) return 1;
          //  Either Segment 2 or 3 must be starting node
          if (segSize[1] < segSize[3])
               start_corner = bound_nodes[ cornerPos[1] ];
          else
               start_corner = bound_nodes[ cornerPos[3] ];
          start_boundary_loop_from(start_corner);
     }

     if (min(segSize[0], segSize[2]) == 2) return 1;

     if (segSize[2] < segSize[0]) {
          start_corner = bound_nodes[ cornerPos[2] ];
          start_boundary_loop_from(start_corner);
     }

     // By this stage, the loop must be reoriented correctly.
     assert(segSize[0] < segSize[2]);

     // Great, we found one irregular node on the first boundary...
     if (has_irregular_node_on_first_segment()) return 1;

     // If the segment 2 and 3 have same size, Alas, nothing can be done.
     if (segSize[1] == segSize[3]) return 1;

     if (min(segSize[1], segSize[3]) == 2) return 1;

     if (segSize[3] < segSize[1]) {
          start_corner = bound_nodes[ cornerPos[3] ];
          start_boundary_loop_from(start_corner);
     } else {
          start_corner = bound_nodes[ cornerPos[1] ];
          start_boundary_loop_from(start_corner);
     }

     //
     // Note that we didn't check for irregular node here. So if this segment
     // has at least one irregular node, then we are lucky. Otherwise decision
     // to remesh it done based wthere remeshing will result in the reduction
     // of irregular nodes in patch.
     //
     assert(segSize[0] < segSize[2]);
     return 0;
}

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

int OneDefectPatch::remesh_3_sided_patch()
{
     Vertex *c0, *c1, *c2;

     c0 = bound_nodes[ cornerPos[0] ];
     c1 = bound_nodes[ cornerPos[1] ];
     c2 = bound_nodes[ cornerPos[2] ];

     get_bound_nodes(c0, c1, anodes);
     get_bound_nodes(c1, c2, bnodes);
     get_bound_nodes(c2, c0, cnodes);

     int err = template3.remesh(mesh, anodes, bnodes, cnodes, partSegments);
     if( !err ) {
          num_3_patches++;
          for( size_t i = 0; i < template3.newnodes.size(); i++)
               newnodes.push_back( template3.newnodes[i] );
          for( size_t i = 0; i < template3.newfaces.size(); i++)
               newfaces.push_back( template3.newfaces[i] );
     }
     return err;
}
//////////////////////////////////////////////////////////////////////////////

int OneDefectPatch::remesh_4_sided_patch()
{
     int err;
     size_t nSize;
     Vertex *c0, *c1, *c2, *c3, *ta, *tb, *tc;

     newnodes.clear();
     newfaces.clear();

     // Collect landmark nodes on the patch..
     c0 = bound_nodes[ cornerPos[0] ];
     c1 = bound_nodes[ cornerPos[1] ];
     c2 = bound_nodes[ cornerPos[2] ];
     c3 = bound_nodes[ cornerPos[3] ];
     ta = quad_splitting_node;

     if (ta == NULL) {
          if ((segSize[0] == segSize[2]) && (segSize[1] == segSize[3])) {
               get_bound_nodes(c0, c1, anodes);
               get_bound_nodes(c1, c2, bnodes);
               get_bound_nodes(c2, c3, cnodes);
               get_bound_nodes(c3, c0, dnodes);
               err = template4.remesh(mesh, anodes, bnodes, cnodes, dnodes);
               if (!err) {
                   for( size_t i = 0; i < template4.newnodes.size(); i++)
                    newnodes.push_back( template4.newnodes[i] );
                   for( size_t i = 0; i < template4.newfaces.size(); i++)
                    newfaces.push_back( template4.newfaces[i] );
                }
               return err;
          }
     }

     assert(ta != NULL);

     get_bound_nodes(c0, ta, a1nodes);
     get_bound_nodes(ta, c1, a2nodes);

     tb = bound_nodes[cornerPos[2] + a2nodes.size() - 1 ];
     tc = bound_nodes[cornerPos[3] - a1nodes.size() + 1];
     get_bound_nodes(tb, tc, c0nodes);

     linear_interpolation(mesh, ta, tb, segSize[1], abnodes);

     nSize = abnodes.size();
     for (size_t  i = 1; i < nSize - 1; i++)
          newnodes.push_back(abnodes[i]);

     linear_interpolation(mesh, tc, ta, segSize[3], canodes);

     nSize = canodes.size();
     for (size_t i = 1; i < nSize - 1; i++)
          newnodes.push_back(canodes[i]);

     get_bound_nodes(tb, tc, bcnodes);
     get_bound_nodes(c1, c2, b1nodes);
     get_bound_nodes(c2, tb, c2nodes);
     get_bound_nodes(tc, c3, c1nodes);
     get_bound_nodes(c3, c0, d1nodes);

     err = template3.remesh(mesh, abnodes, bcnodes, canodes, partSegments);
     if (!err) {
          for( size_t i = 0; i < template3.newnodes.size(); i++)
               newnodes.push_back( template3.newnodes[i] );
          for( size_t i = 0; i < template3.newfaces.size(); i++)
               newfaces.push_back( template3.newfaces[i] );
     }

     if (!err) {
          err = template4.remesh(mesh, a1nodes, canodes, c1nodes, d1nodes);
          if (!err) {
               for( size_t i = 0; i < template4.newnodes.size(); i++)
                    newnodes.push_back( template4.newnodes[i] );
               for( size_t i = 0; i < template4.newfaces.size(); i++)
                    newfaces.push_back( template4.newfaces[i] );
          }
     }

     if (!err) {
          err = template4.remesh(mesh, a2nodes, b1nodes, c2nodes, abnodes);
          if (!err) {
               for( size_t i = 0; i < template4.newnodes.size(); i++)
                    newnodes.push_back( template4.newnodes[i] );
               for( size_t i = 0; i < template4.newfaces.size(); i++)
                    newfaces.push_back( template4.newfaces[i] );
          }
     }

     if (err) {
          nSize = newfaces.size();
          for (size_t i = 0; i < nSize; i++)
               mesh->remove(newfaces[i]);

          nSize = newnodes.size();
          for (size_t i = 0; i < nSize; i++)
               mesh->remove(newnodes[i]);

          newnodes.clear();
          newfaces.clear();
          return 2;
     }

     if( !err ) num_4_patches++;

     return err;
}

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

int OneDefectPatch::remesh_5_sided_patch()
{
     Vertex *c0, *c1, *c2, *c3, *c4;
     c0 = bound_nodes[ cornerPos[0] ];
     c1 = bound_nodes[ cornerPos[1] ];
     c2 = bound_nodes[ cornerPos[2] ];
     c3 = bound_nodes[ cornerPos[3] ];
     c4 = bound_nodes[ cornerPos[4] ];

     get_bound_nodes(c0, c1, anodes);
     get_bound_nodes(c1, c2, bnodes);
     get_bound_nodes(c2, c3, cnodes);
     get_bound_nodes(c3, c4, dnodes);
     get_bound_nodes(c4, c0, enodes);

     int err = template5.remesh(mesh, anodes, bnodes, cnodes, dnodes, enodes, partSegments);

     if( !err)  {
          num_5_patches++;
          for( size_t i = 0; i < template5.newnodes.size(); i++)
               newnodes.push_back( template5.newnodes[i] );
          for( size_t i = 0; i < template5.newfaces.size(); i++)
               newfaces.push_back( template5.newfaces[i] );
     }

     return err;
}

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

bool OneDefectPatch::is_quad_breakable_at(const Vertex *ta)<--- The function 'is_quad_breakable_at' is never used.
{
     // Landmark nodes on the boundary. There are seven such nodes.
     Vertex *c0, *c1, *tb, *tc;
     //     Vertex  *c2, *c3;
     c0 = bound_nodes[ cornerPos[0] ];
     c1 = bound_nodes[ cornerPos[1] ];
     //     c2 = bound_nodes[ cornerPos[2] ];
     //     c3 = bound_nodes[ cornerPos[3] ];

     get_bound_nodes(c0, ta, a1nodes);
     get_bound_nodes(ta, c1, a2nodes);

     tb = bound_nodes[cornerPos[2] + a2nodes.size() - 1 ];
     tc = bound_nodes[cornerPos[3] - a1nodes.size() + 1];
     get_bound_nodes(tb, tc, c0nodes);

     int segments[3];
     segments[0] = c0nodes.size() - 1;
     segments[1] = segSize[3] - 1;
     segments[2] = segSize[2] - 1;

     if (Face::is_3_sided_convex_loop_quad_meshable(segments, partSegments))
          return 0;

     return 1;
}
//////////////////////////////////////////////////////////////////////////////

bool OneDefectPatch::is_4_sided_convex_loop_quad_meshable()
{
     assert(corners.size() == 4);

     // It is always quadrangulable.
     if ((segSize[0] == segSize[2]) && (segSize[1] == segSize[3])) return 1;

     int nr0 = count_irregular_nodes(0);
     int nr1 = count_irregular_nodes(1);

     //
     // If there are only two irregular nodes in the patch ( inner + boundary)
     // then it may be quadrangable, but it will not reduce number of irregular
     // nodes ( one irregular node and one irregular node on the boundary
     // will be created. Since there is no reduction in #of irregular nodes,
     // it is not profitable, and we just return it.
     //
     // If there are more than two irrgular nodes, then we can ensure that
     // that there will at most two irregular nodes in the patch ( one inside
     // and probably one on the boundary.
     //

     if (nr0 + nr1 == 2) return 0;

     // The loop is reoriented so that the first edge is smaller than the
     // opposite edge ....
     if (reorient_4_sided_loop()) return 0;

     // We need at least 3 points on the first seqment ...
     if (segSize[0] < 3) return 0;

     // Landmark nodes on the boundary. There are seven such nodes.
     Vertex *c0, *c1, *ta, *tb, *tc;<--- The scope of the variable 'tb' can be reduced.<--- The scope of the variable 'tc' can be reduced.
     //     Vertex *c2, *c3;
     c0 = bound_nodes[ cornerPos[0] ];
     c1 = bound_nodes[ cornerPos[1] ];
     //     c2 = bound_nodes[ cornerPos[2] ];
     //     c3 = bound_nodes[ cornerPos[3] ];

     // First let us prioritieze vertices on the first segment that will
     // be tried for splitting the region. First of all, if #of irregular
     // nodes inside the region is 2, then we must have one irregular
     // node on the boundary. But even if the #irregular nodes inside
     // the region > 2, we still prefer irregular node in the boundary
     // as it will reduce irregularity by one.

     // Both end nodes on the segment are not included in splitting.

     // Method: Start node(1,...n-1) and check it could lead to acceptable
     // splitting. A proper splitting means that the triangle sandwitched
     // between two quads regions is "quad-meshable" with one defect.
     //
     // Future Work: It is possible that the triangle region is not "one
     // defect" meshable, but with more than one defect. We will extend
     // this case later.
     //

     NodeSequence trynodes;
     for (int i = 1; i < segSize[0] - 1; i++) {
          if (bound_nodes[i]->getNumRelations(2) == 3)
               trynodes.push_back(bound_nodes[i]);
     }

     if (trynodes.empty() && nr0 == 2) {
          // Patch not remeshable because there are no irregular node on the boundary
          return 0;
     }

     if (nr0 > 2) {
          for (int i = 1; i < segSize[0] - 1; i++) {
               if (bound_nodes[i]->getNumRelations(2) == 4)
                    trynodes.push_back(bound_nodes[i]);
          }
     }

     quad_splitting_node = NULL;

     int segments[3];
     int nSize = trynodes.size();
     for (int i = 0; i < nSize; i++) {
          ta = trynodes[i];
          get_bound_nodes(c0, ta, a1nodes);
          get_bound_nodes(ta, c1, a2nodes);

          tb = bound_nodes[cornerPos[2] + a2nodes.size() - 1 ];
          tc = bound_nodes[cornerPos[3] - a1nodes.size() + 1];

          get_bound_nodes(tb, tc, bcnodes);
          segments[0] = segSize[1] - 1;
          segments[1] = bcnodes.size() - 1;
          segments[2] = segSize[3] - 1;

          if (Face::is_3_sided_convex_loop_quad_meshable(segments, partSegments)) {
               quad_splitting_node = ta;
               quad_splitting_node_degree = ta->getNumRelations(2);
               return 1;
          }
     }

     return 0;
}

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

int OneDefectPatch::init_blob()
{
     nodes.clear();

     inner_nodes.clear();
     bound_nodes.clear();

     faces.clear();
     inner_faces.clear();

     relations02.clear();

     int err;
     size_t nSize;<--- The scope of the variable 'nSize' can be reduced.
     if (apex) {
          err = expand_blob( apex );
          if( err ) return 1;
     } else {
          nSize = nodepath.size();
          assert( nSize > 0);
          for (size_t i = 0; i < nSize; i++) {
               Vertex *v = nodepath[i];
               err = expand_blob(v );
               if( err ) return 1;
          }
     }
     return 0;
}

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

size_t OneDefectPatch::count_irregular_nodes(int where)
{
     NodeSequence::const_iterator it;
     assert(mesh->getAdjTable(0, 2));

     size_t ncount = 0;

     if (where == 0) {
          for (it = inner_nodes.begin(); it != inner_nodes.end(); ++it) {
               Vertex *v = *it;
               if( v->isActive() && (v->getNumRelations(2) != 4)) ncount++;
          }
     } else {
          for (size_t i = 0; i < bound_nodes.size(); i++) {
               Vertex *v = bound_nodes[i];
               if( v->isActive() )
                    if (!v->isBoundary() && v->getNumRelations(2) == 3) ncount++;
          }
     }

     return ncount;
}
////////////////////////////////////////////////////////////////////
int
OneDefectPatch::update_boundary()
{
     StopWatch wc;

     boundary.clear();
     bound_nodes.clear();
     inner_nodes.clear();

     wc.start();

     // We need to rebuild relations locally to identfy corners and boundary.
     FaceSet::const_iterator fiter;

     assert( faces.size() > 0);

     // A boundary edge must have exactly one face neighbor...
     FaceSequence faceneighs;
     for (fiter = faces.begin(); fiter != faces.end(); ++fiter) {
          Face *face = *fiter;
          if( inner_faces.find(face) == inner_faces.end() ) {
               int ncount = 0;
               for (int j = 0; j < 4; j++) {
                    Vertex *v0 = face->getNodeAt(j + 0);
                    Vertex *v1 = face->getNodeAt(j + 1);
                    faceneighs.clear();
                    assert(relations02[v0].size() > 0);
                    assert(relations02[v1].size() > 0);
                    set_intersection(relations02[v0].begin(), relations02[v0].end(),
                                     relations02[v1].begin(), relations02[v1].end(),
                                     back_inserter(faceneighs));
                    if (faceneighs.size() == 1) {
                         ncount = 1;
                         Edge newedge(v0, v1);
                         bound_nodes.push_back(v0);
                         bound_nodes.push_back(v1);
                         boundary.push_back(newedge);
                    }
               }
               if( ncount == 0) inner_faces.insert(face);
          }
     }
     int nSize = bound_nodes.size()/2;
     assert( nSize > 0);

     sort( bound_nodes.begin(), bound_nodes.end() );

     int simple= 1;
     for( int i = 0; i < nSize; i++)  {
          if( bound_nodes[2*i] != bound_nodes[2*i+1] )  {
               simple= 0;
               break;
          }
     }

     if( simple ) {
          sort( bound_nodes.begin(), bound_nodes.end() );
          NodeSequence::iterator it;
          it  = unique( bound_nodes.begin(), bound_nodes.end() );
          bound_nodes.erase( it, bound_nodes.end() );
          set_difference(nodes.begin(), nodes.end(),
                         bound_nodes.begin(), bound_nodes.end(),
                         back_inserter(inner_nodes));
     }

     wc.stop();
     exec_time += wc.getSeconds();

     if( !simple) return 1;

     return 0;
}

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

int
OneDefectPatch::finalize_boundary()
{
     corners.clear();

     // Sequence the chain and start from one of the corner...
     int err = Mesh::make_chain(boundary);
     if (err) return 2;

     size_t nSize = boundary.size();

     Vertex *vertex;<--- The scope of the variable 'vertex' can be reduced.
     for (size_t k = 0; k < nSize; k++) {
          vertex = boundary[k].getNodeAt(0);
          if (relations02[vertex].size() == 1) corners.insert(vertex);

          vertex = boundary[k].getNodeAt(1);
          if (relations02[vertex].size() == 1) corners.insert(vertex);
     }

     if( corners.size() < 3) return 3;

     // Start the chain from one of the corners.
     err = Mesh::rotate_chain(boundary, *corners.begin());
     if (err) return 4;

     bound_nodes.resize( nSize );
     for (size_t k = 0; k < nSize; k++)
          bound_nodes[k] = boundary[k].getNodeAt(0);

     // Split the boundary loop into segments.
     // (i.e. End of the segments are the corners identified earlier )
     set_boundary_segments();

     return 0;
}


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

void OneDefectPatch::set_boundary_segments()
{
     size_t nSize = corners.size();
     // Although this stage will not come in this algorithm...
     if ( nSize == 0) return;

     cornerPos.resize( nSize + 1);

     NodeSet::const_iterator it;
     int index = 0;
     for (it = corners.begin(); it != corners.end(); ++it) {
          cornerPos[index++] = getPosOf(*it);
     }

     cornerPos[corners.size()] = bound_nodes.size();

     sort(cornerPos.begin(), cornerPos.end());

     segSize.resize( nSize );

     for (size_t i = 0; i < nSize; i++)
          segSize[i] = cornerPos[(i + 1)] - cornerPos[i] + 1;
}

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

int OneDefectPatch::get_topological_outer_angle(Vertex *vertex)
{
     FaceSequence vfaces;
     vertex->getRelations( vfaces );

     // How many faces are outside the regions.
     int ncount = 0;
     int nSize  = vfaces.size();
     for (int i = 0; i < nSize; i++)
          if (faces.find(vfaces[i]) == faces.end()) ncount++;

     return ncount - 2;
}
////////////////////////////////////////////////////////////////////////////////

int OneDefectPatch::expand_blob(Vertex *vertex)
{
     FaceSequence vfaces;
     vertex->getRelations( vfaces );

     int nSize = vfaces.size();
     assert( nSize > 0);
     for (int i = 0; i < nSize; i++) {
          Face *face = vfaces[i];
          assert(face->isActive() );
          if( face->isVisited() ) return 1;
          faces.insert(face);
          for (int j = 0; j < 4; j++) {
               Vertex *vf = face->getNodeAt(j);
               relations02[vf].insert(face);
               nodes.insert( vf );
          }
     }
     return 0;
}

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

int OneDefectPatch::expand_blob()
{
     int err;<--- The scope of the variable 'err' can be reduced.
     size_t before_expansion = faces.size();

     size_t nSize = bound_nodes.size();
     assert( nSize > 0);

     for (size_t i = 0; i < nSize; i++) {
          err = expand_blob(bound_nodes[i]);
          if( err ) return 1;
     }

     size_t after_expansion = faces.size();

     // bad luck; no expansion took place....
     if( after_expansion == before_expansion ) return 1;

     return 0;

}

int
OneDefectPatch::build_remeshable_boundary()
{
     assert(mesh->getAdjTable(0, 2));

     /////////////////////////////////////////////////////////////////////////////
     // A valid boundary patch has the following propeties:
     //
     // 1) The loop is closed.
     // 2) The region is simply connected. The Euler characteristic must be
     //    one, which mean there are no holes in the region.
     // 3) The loop has 3, 4 or 5 corner nodes.
     // 4) The loop form almost convex boundary.
     //
     // If these conditions are met, we may try to remesh the region with
     // quadrilateral elements. Sometimes it may not be possible to remesh
     // a reason, or the resulting elements have unacceptable quality that
     // we would like to avoid.
     //
     // A resulting mesh MUST decrease the irregular nodes count.
     //////////////////////////////////////////////////////////////////////////
     int err, topo_convex_region;<--- The scope of the variable 'topo_convex_region' can be reduced.

     err = init_blob();
     if( err ) return 1;

     size_t  nSize;<--- The scope of the variable 'nSize' can be reduced.
     while (1) {
          err = update_boundary();
          if (err) return 2;

          if (faces.size() > MAX_FACES_ALLOWED ) return 3;

          // Expand the blob till topological set is found ..
          topo_convex_region = 1;
          nSize = bound_nodes.size();
          assert( nSize > 0);
          for (size_t i = 0; i < nSize; i++) {
               if (!bound_nodes[i]->isBoundary()) {
                    int topo_angle = get_topological_outer_angle(bound_nodes[i]);
                    if (topo_angle < 0) {
                         err = expand_blob(bound_nodes[i]);
                         if( err ) return 1;
                         topo_convex_region = 0;
                    }
               }
          }

          // A valid patch must contain atleast two irregular nodes ...
          if( topo_convex_region ) {
               if (count_irregular_nodes(0) < 2) {
                    topo_convex_region = 0;
                    err = expand_blob();
                    if( err ) return 1;
               }
          }


          // Now finalize the patch for remeshing...
          if (topo_convex_region) {
               err = finalize_boundary();
               if( err ) {
                    topo_convex_region = 0;
                    err = expand_blob();
                    if( err ) return 1;
               }
          }

          // check the patch for remeshing..
          if (topo_convex_region) {
               int nsides = corners.size();

               if (nsides > 5) return 6;

               int segments[5], meshable = 0;
               switch (nsides) {
               case 3:
                    segments[0] = segSize[0] - 1;
                    segments[1] = segSize[1] - 1;
                    segments[2] = segSize[2] - 1;
                    meshable = Face::is_3_sided_convex_loop_quad_meshable(segments, partSegments);
                    break;

               case 4:
                    meshable = is_4_sided_convex_loop_quad_meshable();
                    break;

               case 5:
                    segments[0] = segSize[0] - 1;
                    segments[1] = segSize[1] - 1;
                    segments[2] = segSize[2] - 1;
                    segments[3] = segSize[3] - 1;
                    segments[4] = segSize[4] - 1;
                    meshable = Face::is_5_sided_convex_loop_quad_meshable(segments, partSegments);
                    break;
               }
               // If the region is meshable, it is good, it will be remeshed in the next step...
               if (meshable) {
                    if (!is_simply_connected()) return 4;
                    return 0;
               }

               /*
                              if ( bound_nodes.size()%2 == 0 && count_irregular_nodes(0) > 4) {
                                   cout << "BoundNodes " << bound_nodes.size() << " " << count_irregular_nodes(0) << endl;
                                   disk_remeshable++;
                              }
               */

               err = expand_blob();
               if( err ) return 1;
          }
     }

     // You should never come at this stage...
     return 1;
}

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

void OneDefectPatch::rollback()
{
     NodeSequence::const_iterator it;
     for (it = inner_nodes.begin(); it != inner_nodes.end(); ++it)
          mesh->reactivate(*it);

     FaceSet::const_iterator fiter;
     for (fiter = faces.begin(); fiter != faces.end(); ++fiter)
          mesh->reactivate(*fiter);

     size_t nSize = newfaces.size();
     for (size_t i = 0; i < nSize; i++)
          mesh->remove(newfaces[i]);
     newfaces.clear();

     nSize = newnodes.size();
     for (size_t i = 0; i < nSize; i++)
          mesh->remove(newnodes[i]);
     newnodes.clear();

}

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

void OneDefectPatch::pre_remesh()
{
     //
     // Before remeshing deactivate all the internal faces and nodes so that all
     // the relations are cleared. They are not removed because if something goes
     // wrong, the data structures are restored using rollback operations.
     //
     FaceSet::const_iterator fiter;
     for (fiter = faces.begin(); fiter != faces.end(); ++fiter)
          mesh->deactivate(*fiter);

     irregular_nodes_removed.clear();
     NodeSequence::const_iterator niter;
     for (niter = inner_nodes.begin(); niter != inner_nodes.end(); ++niter) {
          if (!QuadCleanUp::isRegular(*niter)) irregular_nodes_removed.push_back(*niter);
          mesh->deactivate(*niter);
     }

     // At this stage, we will have an empty patch ...
}

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

void OneDefectPatch::post_remesh()
{
     size_t nSize;

     assert( faces.size() );

     // Remove the old faces ( will go to trash bin );
     FaceSet::const_iterator fiter;
     for (fiter = faces.begin(); fiter != faces.end(); ++fiter)
          mesh->remove(*fiter);

     assert( inner_nodes.size() );
     // Remove the old nodes.. (will go to trash bin );
     NodeSequence::const_iterator niter;
     for (niter = inner_nodes.begin(); niter != inner_nodes.end(); ++niter)
          mesh->remove(*niter);

     // Patch contains new nodes new faces now ...
     faces.clear();
     nSize = newfaces.size();
     assert( nSize );
     for (size_t i = 0; i < nSize; i++) {
          faces.insert(newfaces[i]);
     }
     newfaces.clear();

     inner_nodes.clear();

     nSize = newnodes.size();
     //assert( nSize );
     for (size_t i = 0; i < nSize; i++)
          inner_nodes.push_back(newnodes[i]);
     newnodes.clear();

     int ncount = 0;
     new_defective_node = NULL;
     for (niter = inner_nodes.begin(); niter != inner_nodes.end(); ++niter) {
          Vertex *v = *niter;
          if (!QuadCleanUp::isRegular(v)) {
               ncount++;
               new_defective_node = v;
          }
     }

     if( ncount > 2) {
          cout << "Fatal Error:There must be at the most one defective node in the patch" << endl;
          exit(0);
     }

     nSize = bound_nodes.size();
     assert( nSize );
     for( size_t i = 0; i < nSize; i++) {
          if( QuadCleanUp::isDoublet( bound_nodes[i] ) )  {
               cout << "Warning: Doublet created at the patch boundary: " << endl;
          }
     }

}

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

int OneDefectPatch::remesh()
{
     // Check if any node or element is modifed by previous operations.
     if (!isSafe()) return 1;

     newnodes.clear();
     newfaces.clear();

     if (corners.size() > 5) cout << "Warning: Corners more than 5 " << endl;

#ifdef DEBUG
     int nirregular0 = count_irregular_nodes(0) + count_irregular_nodes(1);
#endif

     // Do some pre-processing before remeshing the patch
     pre_remesh();

     int err = 1;
     switch (corners.size()) {
     case 3:
          err = remesh_3_sided_patch();
          break;
     case 4:
          err = remesh_4_sided_patch();
          break;
     case 5:
          err = remesh_5_sided_patch();
          break;
     }

     if (err) {
          rollback();
          return 1;
     }

     // Do some post-processing of the patch
     post_remesh();

#ifdef DEBUG
     int nirregular1 = count_irregular_nodes(0) + count_irregular_nodes(1);

     // Our method must stricly decrease the number of irregular nodes,
     // otherwise it will be go into infinite loop.

     assert(nirregular1 < nirregular0);
#endif

     return err;
}

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

OneDefectPatch *QuadCleanUp::build_one_defect_patch(Vertex *vertex)
{

     if( defective_patch == NULL )
          defective_patch = new OneDefectPatch(mesh);

     defective_patch->clear();

     if( !vertex->isActive() || isRegular(vertex) ) return NULL;

     if( djkpath == NULL ) {
          djkpath = new DijkstraShortestPath(mesh, 1);
     }

     MeshFilter *filter = new FirstIrregularNode();
     const NodeSequence &nodepath = djkpath->getPath(vertex, filter);
     delete filter;

     if (isRegular(nodepath.front())) return NULL;
     if (isRegular(nodepath.back()))  return NULL;

     defective_patch->set_initial_path( nodepath );

     int err = defective_patch->build_remeshable_boundary();

     if (err) return NULL;

     return defective_patch;
}

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

int QuadCleanUp::remesh_defective_patches()
{
     int relexist0 = mesh->build_relations(0, 0);
     int relexist2 = mesh->build_relations(0, 2);

     mesh->search_boundary();

     if( !mesh->is_consistently_oriented() )
          mesh->make_consistently_oriented();

     djkpath = new DijkstraShortestPath(mesh, 1);

     assert( djkpath);

     assert(mesh->getAdjTable(0, 2));
     OneDefectPatch *patch;

     Jaal::MeshOptimization mopt;

     NodeSequence nextSeq;
     mesh->get_irregular_nodes(irregular_nodes, 4);

     // Record execution time ...
     StopWatch wc[4];

     vector<double> patchCircularity;
     vector<int>    patchIrregularity;
     vector<int>    meshIrregularity;

     meshIrregularity.push_back( irregular_nodes.size() );

     int ncount1 = 0;
     int nfailures = 0;
     size_t  num_curr_irregular_nodes = irregular_nodes.size();

     for( int i = 4; i < 12; i++) {
          OneDefectPatch :: MAX_FACES_ALLOWED = ( int)pow(2,i);
          cout << "Remeshing with maximum patch size :  " << (int)pow(2,i) << endl;
          cout << "#of irregular nodes in the mesh " << irregular_nodes.size() << endl;

          wc[3].start();

          while (1) {

               // for creating disjoint faces ..
               size_t numFaces = mesh->getSize(2);
               for( size_t i = 0; i < numFaces; i++) {
                    Face *f = mesh->getFaceAt(i);
                    f->setVisitMark(0);
               }

               nextSeq.clear();
               size_t ncount2 = 0;
               size_t nSize = irregular_nodes.size();

               for( size_t i = 0; i < nSize; i++) {
                    Vertex *vertex = irregular_nodes[i];
                    if( vertex->isActive() ) {
                         wc[0].start();
                         patch = build_one_defect_patch(vertex);
                         wc[0].stop();
                         if (patch) {
                              wc[1].start();
                              int err = patch->remesh();
                              wc[1].stop();
                              if (!err) {
                                   if( ncount1% 100 == 0) cout << "patch count : " << ncount1 << endl;
                                   double pq = patch->get_isoperimetic_quotient();
                                   patchCircularity.push_back(pq);

                                   int ir = patch->get_irregular_nodes_removed().size();
                                   patchIrregularity.push_back(ir);

                                   num_curr_irregular_nodes -= ir;
                                   Vertex *vtx = patch->get_new_defective_node();
                                   if (vtx) {
                                        nextSeq.push_back(vtx);
                                        num_curr_irregular_nodes += 1;<--- Variable 'num_curr_irregular_nodes' is assigned a value that is never used.
                                   }

/*
                                   num_curr_irregular_nodes = mesh->count_irregular_nodes(4);
                                   meshIrregularity.push_back( num_curr_irregular_nodes);
*/

                                   ncount2++;
                                   ncount1++;
                              } else {
                                   nextSeq.push_back( vertex );  // Because patch was not remeshed
                                   nfailures++;
                              }
                         } else
                              nextSeq.push_back( vertex ); // Because invalid patch occured.
                    }
               }
               irregular_nodes.swap(nextSeq);

               if (ncount2) {
//                  wc[2].start();
//                  mopt.shape_optimize(mesh, MeshOptimization::QUASI_NEWTON, 10);
//                  wc[2].stop();
               }
               if( ncount2 == 0) break;
          }

          wc[2].start();
//        mopt.shape_optimize(mesh, MeshOptimization::QUASI_NEWTON, 10);
          wc[2].stop();

          wc[3].stop();
          cout << "Execution Summary: " << endl;
          cout << "    Time for searching patches  : " << wc[0].getSeconds()  << endl;
          cout << "    Time for remeshing patches  : " << wc[1].getSeconds()  << endl;
          cout << "    Time for shape optimization : " << wc[2].getSeconds()  << endl;
          cout << "    Total Execution time        : " << wc[3].getSeconds() << endl;
     }

     // Perform some aggresive good optimization in the last...
     mopt.shape_optimize(mesh, MeshOptimization::QUASI_NEWTON, 100);

     cout << "#of times boundaries created : " << OneDefectPatch::num_boundaries << endl;
     cout << "Exec time boundaries created : " << OneDefectPatch::exec_time      << endl;
     cout << "3 Sided Patches : " << OneDefectPatch::num_3_patches << endl;
     cout << "4 Sided Patches : " << OneDefectPatch::num_4_patches << endl;
     cout << "5 Sided Patches : " << OneDefectPatch::num_5_patches << endl;
     cout << "n Sides Patches : " << OneDefectPatch::disk_remeshable << endl;
     cout << "#Remesh failure : " << nfailures << endl;

     cout << "Execution Summary: " << endl;
     cout << "    Time for searching patches  : " << wc[0].getSeconds()  << endl;
     cout << "    Time for remeshing patches  : " << wc[1].getSeconds()  << endl;
     cout << "    Time for shape optimization : " << wc[2].getSeconds()  << endl;

     ofstream ofile1( "PatchCircularity.dat", ios::out);
     for( size_t i = 0; i < patchCircularity.size(); i++)
          ofile1 << i+1 << " " << patchCircularity[i] << endl;
     ofile1.close();

     ofstream ofile2( "PatchIrregulaity.dat", ios::out);
     for( size_t i = 0; i < patchIrregularity.size(); i++)
          ofile2 << i+1 << " " << patchIrregularity[i] << endl;
     ofile2.close();

     ofstream ofile3( "MeshIrregulaity.dat", ios::out);
     for( size_t i = 0; i < meshIrregularity.size(); i++)
          ofile3 << i+1 << " " << meshIrregularity[i] << endl;
     ofile3.close();

     if (!relexist0)
          mesh->clear_relations(0, 0);

     if (!relexist2)
          mesh->clear_relations(0, 2);

     return 0;
}

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