File: fluentMeshToFoam.L

package info (click to toggle)
openfoam 4.0%2Bdfsg1-7~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 163,088 kB
  • sloc: cpp: 830,510; sh: 10,210; ansic: 8,215; xml: 745; lex: 437; awk: 194; sed: 91; makefile: 77; python: 18
file content (1749 lines) | stat: -rw-r--r-- 49,714 bytes parent folder | download | duplicates (2)
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
/*--------------------------------*- C++ -*----------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | Copyright (C) 2011-2016 OpenFOAM Foundation
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    for more details.

    You should have received a copy of the GNU General Public License
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

Application
    fluentMeshToFoam

Description
    Converts a Fluent mesh to OpenFOAM format
    including multiple region and region boundary handling.

\*---------------------------------------------------------------------------*/

%{

#undef yyFlexLexer

 /* ------------------------------------------------------------------------- *\
   ------ local definitions
 \* ------------------------------------------------------------------------- */

#include "argList.H"
#include "Time.H"
#include "IStringStream.H"
#include "polyMesh.H"
#include "emptyPolyPatch.H"
#include "wallPolyPatch.H"
#include "symmetryPolyPatch.H"
#include "cellShape.H"
#include "faceSet.H"
#include "cellSet.H"
#include "meshTools.H"
#include "OFstream.H"

#include "readHexLabel.H"
#include "cellShapeRecognition.H"
#include "repatchPolyTopoChanger.H"


// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

using namespace Foam;

const scalar convertToMeters = 1.0;

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //


label dimensionOfGrid = 0;

label nPoints = 0;
label nFaces = 0;
label nCells = 0;

pointField points(0);
SLList<label> pointGroupZoneID;
SLList<label> pointGroupStartIndex;
SLList<label> pointGroupEndIndex;


faceList faces(0);
labelList owner(0);
labelList neighbour(0);
SLList<label> faceGroupZoneID;
SLList<label> faceGroupStartIndex;
SLList<label> faceGroupEndIndex;

labelList fluentCellModelID(0);
SLList<label> cellGroupZoneID;
SLList<label> cellGroupStartIndex;
SLList<label> cellGroupEndIndex;
SLList<label> cellGroupType;

// number of zones adjusted at run-time if necessary
label maxZoneID = 100;
label zoneIDBuffer = 10;

wordList patchTypeIDs(maxZoneID);
wordList patchNameIDs(maxZoneID);

// Dummy yywrap to keep yylex happy at compile time.
// It is called by yylex but is not used as the mechanism to change file.
// See <<EOF>>
int yyFlexLexer::yywrap()
{
    return 1;
}

%}

one_space                  [ \t\f]
space                      {one_space}*
some_space                 {one_space}+
cspace                     ","{space}
spaceNl                    ({space}|\n|\r)*

alpha                      [_[:alpha:]]
digit                      [[:digit:]]
decDigit                   [[:digit:]]
octalDigit                 [0-7]
hexDigit                   [[:xdigit:]]

lbrac                      "("
rbrac                      ")"
quote                      \"
dash                       "-"
dotColonDash               [.:-]

schemeSpecialInitial       [!$%&*/:<=>?~_^#.]
schemeSpecialSubsequent    [.+-]
schemeSymbol               (({some_space}|{alpha}|{quote}|{schemeSpecialInitial})({alpha}|{quote}|{digit}|{schemeSpecialInitial}|{schemeSpecialSubsequent})*)


identifier                 {alpha}({alpha}|{digit})*
integer                    {decDigit}+
label                      [1-9]{decDigit}*
hexLabel                   {hexDigit}+
zeroLabel                  {digit}*

word                       ({alpha}|{digit}|{dotColonDash})*

exponent_part              [eE][-+]?{digit}+
fractional_constant        [-+]?(({digit}*"."{digit}+)|({digit}+".")|({digit}))

double                     ((({fractional_constant}{exponent_part}?)|({digit}+{exponent_part}))|0)

x                          {double}
y                          {double}
z                          {double}
scalar                     {double}
labelListElement           {space}{zeroLabel}
hexLabelListElement        {space}{hexLabel}
scalarListElement          {space}{double}
schemeSymbolListElement    {space}{schemeSymbol}
labelList                  ({labelListElement}+{space})
hexLabelList               ({hexLabelListElement}+{space})
scalarList                 ({scalarListElement}+{space})
schemeSymbolList           ({schemeSymbolListElement}+{space})

starStar                   ("**")
text                       ({space}({word}*{space})*)

dateDDMMYYYY               ({digit}{digit}"/"{digit}{digit}"/"{digit}{digit}{digit}{digit})
dateDDMonYYYY              ((({digit}{digit}{space})|({digit}{space})){alpha}*{space}{digit}{digit}{digit}{digit})
time                       ({digit}{digit}":"{digit}{digit}":"{digit}{digit})

versionNumber              ({digit}|".")*

comment                    {spaceNl}"(0"{space}
header                     {spaceNl}"(1"{space}
dimension                  {spaceNl}"(2"{space}
point                      {spaceNl}"(10"{space}
fluentFace                 {spaceNl}"(13"{space}
cell                       {spaceNl}"(12"{space}
zoneVariant1               {spaceNl}"(39"{space}
zoneVariant2               {spaceNl}"(45"{space}

unknownPeriodicFace        {spaceNl}"(17"{space}
periodicFace               {spaceNl}"(18"{space}
cellTree                   {spaceNl}"(58"{space}
faceTree                   {spaceNl}"(59"{space}
faceParents                {spaceNl}"(61"{space}

endOfSection               {space}")"{space}



 /* ------------------------------------------------------------------------- *\
                      -----  Exclusive start states -----
 \* ------------------------------------------------------------------------- */

%option stack

%x readComment
%x embeddedCommentState
%x readHeader
%x readDimension
%x readPoint
%x readPointHeader
%x readNumberOfPoints
%x readPointGroupData
%x readPointData
%x readPoints2D
%x readPoints3D
%x fluentFace
%x readFaceHeader
%x readNumberOfFaces
%x readFaceGroupData
%x readFaceData
%x readFacesMixed
%x readFacesUniform
%x cell
%x readCellHeader
%x readNumberOfCells
%x readCellGroupData
%x readCellData
%x readCellsMixed
%x readCellsUniform
%x zone
%x readZoneHeader
%x readZoneGroupData
%x readZoneData
%x readZoneBlock

%x periodicFace
%x cellTree
%x faceTree
%x faceParents

%x unknownBlock
%x embeddedUnknownBlock
%%

%{
    // Point data
    label pointGroupNumberOfComponents = 3;
    label pointi = 0; // index used for reading points

    // Face data
    label faceGroupElementType = -1;
    label facei = 0;

    // Cell data
    label cellGroupElementType = -1;
    label celli = 0;
%}


 /* ------------------------------------------------------------------------- *\
                            ------ Start Lexing ------
 \* ------------------------------------------------------------------------- */

 /*                      ------ Reading control header ------                 */

{comment} {
        yy_push_state(readComment);
    }


<readComment>{quote}{text}{quote} {
    }


<readComment>{spaceNl}{endOfSection} {
        yy_pop_state();
    }

{header} {
        BEGIN(readHeader);
    }

<readHeader>{quote}{text}{quote} {
        Info<< "Reading header: " << YYText() << endl;
    }


{dimension} {
        BEGIN(readDimension);
    }

<readDimension>{space}{label}{space} {
        IStringStream dimOfGridStream(YYText());

        dimensionOfGrid = readLabel(dimOfGridStream);

        Info<< "Dimension of grid: " << dimensionOfGrid << endl;
    }


{point} {
        BEGIN(readPointHeader);
    }

<readPointHeader>{spaceNl}{lbrac}{space}"0"{space}"1"{space} {
        BEGIN(readNumberOfPoints);
    }

<readNumberOfPoints>{space}{hexLabel}{space}{labelList} {

        IStringStream numberOfPointsStream(YYText());

        nPoints = readHexLabel(numberOfPointsStream);

        Info<< "Number of points: " << nPoints << endl;

        // set the size of the points list
        points.setSize(nPoints);

        // meaningless type skipped
        readLabel(numberOfPointsStream);

        // this dimension of grid may be checked against global dimension
        if (numberOfPointsStream)
        {
            // check dimension of grid
            readLabel(numberOfPointsStream);
        }
        else
        {
            Info<< endl;
        }
    }

<readPointHeader>{spaceNl}{lbrac} {
        BEGIN(readPointGroupData);
    }

<readPointGroupData>{space}{hexLabel}{space}{hexLabel}{space}{hexLabel}{labelList} {
        IStringStream pointGroupDataStream(YYText());

        // read point zone-ID, start and end-label
        // the indices will be used for checking later.
        pointGroupZoneID.append(readHexLabel(pointGroupDataStream));

        pointGroupStartIndex.append(readHexLabel(pointGroupDataStream));

        pointGroupEndIndex.append(readHexLabel(pointGroupDataStream));

        // point group type skipped
        readHexLabel(pointGroupDataStream);

        // In FOAM, indices start from zero - adjust
        pointi = pointGroupStartIndex.last() - 1;

        // reset number of components to default
        pointGroupNumberOfComponents = 3;

        // read number of components in the vector
        if (pointGroupDataStream)
        {
            pointGroupNumberOfComponents = readLabel(pointGroupDataStream);
        }
    }

<readNumberOfPoints,readPointGroupData>{endOfSection} {
        BEGIN(readPointData);
    }

<readPointData>{spaceNl}{lbrac} {

        Info<< "Reading points" << endl;

        if (pointGroupNumberOfComponents == 2)
        {
            yy_push_state(readPoints2D);
        }
        else
        {
            yy_push_state(readPoints3D);
        }
    }

<readPoints2D>{spaceNl}{scalarList} {

        IStringStream vertexXyzStream(YYText());

        // Note: coordinates must be read one at the time.
        scalar x = readScalar(vertexXyzStream);
        scalar y = readScalar(vertexXyzStream);

        points[pointi] = point(x, y, 0);
        pointi++;
    }

<readPoints3D>{spaceNl}{scalarList} {

        IStringStream vertexXyzStream(YYText());

        // Note: coordinates must be read one at the time.
        scalar x = readScalar(vertexXyzStream);
        scalar y = readScalar(vertexXyzStream);
        scalar z = readScalar(vertexXyzStream);

        points[pointi] = convertToMeters*point(x, y, z);
        pointi++;
    }

<readPoints2D,readPoints3D>{spaceNl}{endOfSection} {

        // check read of points
        if (pointi != pointGroupEndIndex.last())
        {
            Info<< "problem with reading points: "
                << "start index: " << pointGroupStartIndex.last()
                << " end index: " << pointGroupEndIndex.last()
                << " last points read: " << pointi << endl;
        }

        yy_pop_state();
    }


{fluentFace} {
        BEGIN(readFaceHeader);
    }

<readFaceHeader>{spaceNl}{lbrac}{space}"0"{space}"1"{space} {
        BEGIN(readNumberOfFaces);
    }

<readNumberOfFaces>{space}{hexLabel}{space}{labelListElement}+ {

        IStringStream numberOfFacesStream(YYText());

        nFaces = readHexLabel(numberOfFacesStream);

        Info<< "number of faces: " << nFaces << endl;

        faces.setSize(nFaces);
        owner.setSize(nFaces);
        neighbour.setSize(nFaces);

        // Meaningless type and element type not read
    }

<readFaceHeader>{spaceNl}{lbrac} {
        BEGIN(readFaceGroupData);
    }

<readFaceGroupData>{space}{hexLabel}{space}{hexLabel}{space}{hexLabel}{hexLabelListElement}+ {

        IStringStream faceGroupDataStream(YYText());

        // read fluentFace zone-ID, start and end-label
        faceGroupZoneID.append(readHexLabel(faceGroupDataStream));

        // the indices will be used for checking later.
        faceGroupStartIndex.append(readHexLabel(faceGroupDataStream));

        faceGroupEndIndex.append(readHexLabel(faceGroupDataStream));

        // face group type
        readHexLabel(faceGroupDataStream);

        faceGroupElementType = readHexLabel(faceGroupDataStream);

        // In FOAM, indices start from zero - adjust
        facei = faceGroupStartIndex.last() - 1;
    }

<readNumberOfFaces,readFaceGroupData>{spaceNl}{endOfSection} {
        BEGIN(readFaceData);
    }

<readFaceData>{spaceNl}{lbrac} {

        if (faceGroupElementType == 0)
        {
            Info<< "Reading mixed faces" << endl;
            yy_push_state(readFacesMixed);
        }
        else
        {
            Info<< "Reading uniform faces" << endl;
            yy_push_state(readFacesUniform);
        }
    }

<readFacesMixed>{spaceNl}{hexLabelList} {

        IStringStream mixedFaceStream(YYText());

        face& curFaceLabels = faces[facei];

        // set size of label list
        curFaceLabels.setSize(readLabel(mixedFaceStream));

        forAll(curFaceLabels, i)
        {
            curFaceLabels[i] = readHexLabel(mixedFaceStream) - 1;
        }

        // read neighbour and owner. Neighbour comes first
        neighbour[facei] = readHexLabel(mixedFaceStream) - 1;
        owner[facei] = readHexLabel(mixedFaceStream) - 1;
        facei++;
    }

<readFacesUniform>{spaceNl}{hexLabelList} {

        IStringStream mixedFaceStream(YYText());

        face& curFaceLabels = faces[facei];

        // set size of label list. This is OK because in Fluent the type
        // for edge is 2, for triangle is 3 and for quad is 4
        curFaceLabels.setSize(faceGroupElementType);

        forAll(curFaceLabels, i)
        {
            curFaceLabels[i] = readHexLabel(mixedFaceStream) - 1;
        }

        // read neighbour and owner. Neighbour comes first
        neighbour[facei] = readHexLabel(mixedFaceStream) - 1;
        owner[facei] = readHexLabel(mixedFaceStream) - 1;
        facei++;
    }

<readFacesMixed,readFacesUniform>{spaceNl}{endOfSection} {

        // check read of fluentFaces
        if (facei != faceGroupEndIndex.last())
        {
            Info<< "problem with reading fluentFaces: "
                << "start index: " << faceGroupStartIndex.last()
                << " end index: " << faceGroupEndIndex.last()
                << " last fluentFaces read: " << facei << endl;
        }

        yy_pop_state();
    }


{cell} {
        BEGIN(readCellHeader);
    }

<readCellHeader>{spaceNl}{lbrac}{space}"0"{space}"1"{space} {
        BEGIN(readNumberOfCells);
    }

<readNumberOfCells>{space}{hexLabel}{space}{labelListElement}+ {

        IStringStream numberOfCellsStream(YYText());

        nCells = readHexLabel(numberOfCellsStream);

        Info<< "Number of cells: " << nCells << endl;

        fluentCellModelID.setSize(nCells);

        // Meaningless type and element type not read
    }

<readCellHeader>{spaceNl}{lbrac} {
        BEGIN(readCellGroupData);
    }

<readCellGroupData>{space}{hexLabel}{space}{hexLabel}{space}{hexLabel}{space}{hexLabel} {
        // Warning. This entry must be above the next one because of the lexing
        // rules. It is introduced to deal with the problem of reading
        // non-standard cell definition from Tgrid, which misses the type label.

        Info<< "Tgrid syntax problem: " << YYText() << endl;
        IStringStream cellGroupDataStream(YYText());

        // read cell zone-ID, start and end-label
        cellGroupZoneID.append(readHexLabel(cellGroupDataStream));

        // the indices will be used for checking later.
        cellGroupStartIndex.append(readHexLabel(cellGroupDataStream));

        cellGroupEndIndex.append(readHexLabel(cellGroupDataStream));

        cellGroupType.append(readHexLabel(cellGroupDataStream));

        Info<< "cellGroupZoneID:" << cellGroupZoneID.last()
            << endl;
        Info<< "cellGroupStartIndex:" << cellGroupStartIndex.last()
            << endl;
        Info<< "cellGroupEndIndex:" << cellGroupEndIndex.last()
            << endl;
        Info<< "cellGroupType:" << cellGroupType.last()
            << endl;


        // Note. Potentially skip cell set if type is zero.
        // This entry does not exist in Tgrid files.
        if (dimensionOfGrid == 2)
        {
            // Tgrid creating triangles
            cellGroupElementType = 1;
        }
        else
        {
            cellGroupElementType = 2;
        }

        // In FOAM, indices start from zero - adjust
        celli = cellGroupStartIndex.last() - 1;

        if (cellGroupElementType != 0)
        {
            label lastIndex = cellGroupEndIndex.last();

            for (; celli < lastIndex; celli++)
            {
                fluentCellModelID[celli] = cellGroupElementType;
            }
        }
    }

<readCellGroupData>{space}{hexLabel}{space}{hexLabel}{space}{hexLabel}{space}{hexLabel}{space}{hexLabel} {
        // Warning. See above

        Info<< "Other readCellGroupData: " << YYText() << endl;


        IStringStream cellGroupDataStream(YYText());

        // read cell zone-ID, start and end-label
        cellGroupZoneID.append(readHexLabel(cellGroupDataStream));

        // the indices will be used for checking later.
        cellGroupStartIndex.append(readHexLabel(cellGroupDataStream));

        cellGroupEndIndex.append(readHexLabel(cellGroupDataStream));

        cellGroupType.append(readHexLabel(cellGroupDataStream));

        // Note. Potentially skip cell set if type is zero.

        cellGroupElementType = readHexLabel(cellGroupDataStream);

        // In FOAM, indices start from zero - adjust
        celli = cellGroupStartIndex.last() - 1;

        if (cellGroupElementType != 0)
        {
            Info<< "Reading uniform cells" << endl;
            label lastIndex = cellGroupEndIndex.last();

            for (; celli < lastIndex; celli++)
            {
                fluentCellModelID[celli] = cellGroupElementType;
            }
        }
    }

<readNumberOfCells,readCellGroupData>{endOfSection} {
        BEGIN(readCellData);
    }

<readCellData>{spaceNl}{lbrac} {
        Info<< "Reading mixed cells" << endl;
        yy_push_state(readCellsMixed);
    }

<readCellsMixed>{spaceNl}{labelList} {

        IStringStream fluentCellModelIDStream(YYText());

        label celliD;
        while (fluentCellModelIDStream.read(celliD))
        {
            fluentCellModelID[celli] = celliD;
            celli++;
        }
    }

<readCellsMixed>{spaceNl}{endOfSection} {

        // check read of cells
        if (celli != cellGroupEndIndex.last())
        {
            Info<< "problem with reading cells: "
                << "start index: " << cellGroupStartIndex.last()
                << " end index: " << cellGroupEndIndex.last()
                << " last cells read: " << celli << endl;
        }

        yy_pop_state();
    }



{zoneVariant1} {
        BEGIN(readZoneHeader);
    }

{zoneVariant2} {
        BEGIN(readZoneHeader);
    }

<readZoneHeader>{spaceNl}{lbrac} {
        BEGIN(readZoneGroupData);
    }

<readZoneGroupData>{space}{label}{space}{word}{space}{word} {

        IStringStream zoneDataStream(YYText());

        // cell zone-ID not in hexadecimal!!! Inconsistency
        label zoneID(readLabel(zoneDataStream));

        if (zoneID > maxZoneID - 1)
        {
            // resize the container
            maxZoneID = zoneID + zoneIDBuffer;

            patchTypeIDs.setSize(maxZoneID);
            patchNameIDs.setSize(maxZoneID);
        }

        zoneDataStream >> patchTypeIDs[zoneID];
        zoneDataStream >> patchNameIDs[zoneID];

        Info<< "Read zone1:" << zoneID
            << " name:" << patchNameIDs[zoneID]
            << " patchTypeID:" << patchTypeIDs[zoneID]
            << endl;
    }

<readZoneGroupData>{space}{label}{space}{word}{space}{word}{space}{label} {
        // Fluent manual inconsistency, version 6.1.22
        IStringStream zoneDataStream(YYText());

        // cell zone-ID not in hexadecimal!!! Inconsistency
        label zoneID(readLabel(zoneDataStream));

        if (zoneID > maxZoneID - 1)
        {
            // resize the container
            maxZoneID = zoneID + zoneIDBuffer;

            patchTypeIDs.setSize(maxZoneID);
            patchNameIDs.setSize(maxZoneID);
        }

        zoneDataStream >> patchTypeIDs[zoneID];
        zoneDataStream >> patchNameIDs[zoneID];

        Info<< "Read zone2:" << zoneID
            << " name:" << patchNameIDs[zoneID]
            << " patchTypeID:" << patchTypeIDs[zoneID]
            << endl;
    }

<readZoneGroupData>{endOfSection} {
        BEGIN(readZoneData);
    }

<readZoneData>{spaceNl}{lbrac} {
        Info<< "Reading zone data" << endl;
        yy_push_state(readZoneBlock);
    }

<readZoneBlock>{spaceNl}{schemeSymbolList} {
    }

<readZoneBlock>{lbrac} {
        Info<< "Found unknown block in zone:" << YYText() << endl;
        yy_push_state(unknownBlock);
    }

<readZoneBlock>{endOfSection} {
        yy_pop_state();
    }



 /*             ------ Reading end of section and others ------               */

<readHeader,readDimension,readPointData,readFaceData,readCellData,readZoneData>{spaceNl}{endOfSection} {
        BEGIN(INITIAL);
    }

 /*    ------ Reading unknown type or non-standard comment ------             */


{lbrac}{label} {
        Info<< "Found unknown block:" << YYText() << endl;
        yy_push_state(unknownBlock);
    }

<readComment,unknownBlock,embeddedUnknownBlock>{spaceNl}{schemeSymbol} {
    }

<readComment,unknownBlock,embeddedUnknownBlock>{spaceNl}{lbrac} {
        Info<< "Embedded blocks in comment or unknown:" << YYText() << endl;
        yy_push_state(embeddedUnknownBlock);

    }

<readComment,unknownBlock,embeddedUnknownBlock>{spaceNl}{endOfSection} {
        Info<< "Found end of section in unknown:" << YYText() << endl;
        yy_pop_state();
    }

<unknownBlock,embeddedUnknownBlock>{spaceNl}{labelList} {
    }

<unknownBlock,embeddedUnknownBlock>{spaceNl}{hexLabelList} {
    }

<unknownBlock,embeddedUnknownBlock>{spaceNl}{scalarList} {
    }

<unknownBlock,embeddedUnknownBlock>{spaceNl}{schemeSymbolList} {
    }

<unknownBlock,embeddedUnknownBlock>{spaceNl}{text} {
    }


 /* ------ Ignore remaining space and \n s.  Any other characters are errors. */

<readPoints2D,readPoints3D>.|\n {
    Info<< "ERROR! Do not understand characters: " << YYText() << endl;
    }
.|\n {}


 /*  ------ On EOF return to previous file, if none exists terminate. ------  */

<<EOF>> {
            yyterminate();
    }
%%


#include "fileName.H"
#include <fstream>

// Find label of face.
label findFace(const primitiveMesh& mesh, const face& f)
{
    // Get faces using zeroth vertex of face.
    const labelList& pFaces = mesh.pointFaces()[f[0] ];

    forAll(pFaces, i)
    {
        label facei = pFaces[i];

        if (f == mesh.faces()[facei])
        {
            return facei;
        }
    }

    // Didn't find face. Do what?
    FatalErrorInFunction
        << "Problem : cannot find a single face in the mesh which uses"
        << " vertices " << f << exit(FatalError);

    return -1;
}


int main(int argc, char *argv[])
{
    argList::noParallel();
    argList::validArgs.append("Fluent mesh file");
    argList::addOption
    (
        "scale",
        "factor",
        "geometry scaling factor - default is 1"
    );
    argList::addBoolOption
    (
        "writeSets",
        "write cell zones and patches as sets"
    );
    argList::addBoolOption
    (
        "writeZones",
        "write cell zones as zones"
    );

    argList args(argc, argv);

    if (!args.check())
    {
        FatalError.exit();
    }

    const scalar scaleFactor = args.optionLookupOrDefault("scale", 1.0);

    const bool writeSets  = args.optionFound("writeSets");
    const bool writeZones = args.optionFound("writeZones");

    #include "createTime.H"

    const fileName fluentFile = args[1];
    std::ifstream fluentStream(fluentFile.c_str());

    if (!fluentStream)
    {
        FatalErrorInFunction
            << args.executable()
            << ": file " << fluentFile << " not found"
            << exit(FatalError);
    }

    yyFlexLexer lexer(&fluentStream);
    while (lexer.yylex() != 0)
    {}

    Info<< "\n\nFINISHED LEXING\n\n\n";
    // Lookup table giving number of vertices given a fluent cell type ID
    // Currently not used.
    // label fluentModelNVertices[7] = {-1, 3, 4, 4, 8, 5, 6};

    // Lookup table giving number of vertices given a fluent cell type ID
    label fluentModelNFaces[7] = {-1, 3, 4, 4, 6, 5, 5};

    // Make a list of cell faces to be filled in for owner and neighbour

    labelListList cellFaces(nCells);

    labelList nFacesInCell(nCells, 0);

    forAll(cellFaces, celli)
    {
        cellFaces[celli].setSize(fluentModelNFaces[fluentCellModelID[celli] ]);
    }

    // fill in owner and neighbour

    forAll(owner, facei)
    {
        if (owner[facei] > -1)
        {
            label curCell = owner[facei];
            cellFaces[curCell][nFacesInCell[curCell] ] = facei;

            nFacesInCell[curCell]++;
        }
    }

    forAll(neighbour, facei)
    {
        if (neighbour[facei] > -1)
        {
            label curCell = neighbour[facei];
            cellFaces[curCell][nFacesInCell[curCell] ] = facei;

            nFacesInCell[curCell]++;
        }
    }

    // Construct shapes from face lists
    cellShapeList cellShapes(nCells);

    // Extrude 2-D mesh into 3-D

    Info<< "dimension of grid: " << dimensionOfGrid << endl;
    faceList frontAndBackFaces;

    if (dimensionOfGrid == 2)
    {
        const scalar extrusionFactor = 0.01;

        boundBox box(max(points), min(points));

        const scalar zOffset = extrusionFactor*box.mag();

        // two-dimensional grid. Extrude in z-direction
        Info<< "Grid is 2-D. Extruding in z-direction by: "
            << 2*zOffset << endl;

        pointField oldPoints = points;

        const label pointOffset = oldPoints.size();

        points.setSize(2*pointOffset);

        label nNewPoints = 0;

        // Note: In order for the owner-neighbour rules to be right, the
        // points given by Fluent need to represent the FRONT plane of the
        // geometry. Therefore, the extrusion will be in -z direction
        //
        forAll(oldPoints, pointi)
        {
            points[nNewPoints] = oldPoints[pointi];

            points[nNewPoints].z() = zOffset;

            nNewPoints++;
        }

        forAll(oldPoints, pointi)
        {
            points[nNewPoints] = oldPoints[pointi];

            points[nNewPoints].z() = -zOffset;

            nNewPoints++;
        }

        // 2-D shape recognition
        Info<< "Creating shapes for 2-D cells"<< endl;

        // Set the number of empty faces
        frontAndBackFaces.setSize(2*nCells);

        forAll(fluentCellModelID, celli)
        {
            switch (fluentCellModelID[celli])
            {
                case 1:
                {
                    cellShapes[celli] =
                        cellShape
                        (
                            extrudedTriangleCellShape
                            (
                                celli,
                                cellFaces[celli],
                                faces,
                                owner,
                                neighbour,
                                pointOffset,
                                frontAndBackFaces
                            )
                        );
                }
                break;

                case 3:
                {
                    cellShapes[celli] =
                        cellShape
                        (
                            extrudedQuadCellShape
                            (
                                celli,
                                cellFaces[celli],
                                faces,
                                owner,
                                neighbour,
                                pointOffset,
                                frontAndBackFaces
                            )
                        );
                }
                break;

                default:
                {
                    FatalErrorInFunction
                        << fluentCellModelID[celli]
                        << abort(FatalError);
                }
            }
        }

        // Create new faces
        forAll(faces, facei)
        {

            if (faces[facei].size() != 2)
            {
                FatalErrorInFunction
                    << "fluentMeshToFoam: a 2-D face defined with "
                    << faces[facei].size() << " points." << endl;
            }

            labelList& newFace = faces[facei];

            newFace.setSize(4);

            newFace[2] = newFace[1] + pointOffset;

            newFace[3] = newFace[0] + pointOffset;
        }

        // Create new cells from 2-D shapes
    }
    else
    {
        // 3-D shape recognition
        Info<< "Creating shapes for 3-D cells"<< endl;
        forAll(fluentCellModelID, celli)
        {
            if
            (
                fluentCellModelID[celli] == 2    // tet
             || fluentCellModelID[celli] == 4    // hex
             || fluentCellModelID[celli] == 5    // pyramid
             || fluentCellModelID[celli] == 6    // prism
            )
            {
                cellShapes[celli] =
                    cellShape
                    (
                        create3DCellShape
                        (
                            celli,
                            cellFaces[celli],
                            faces,
                            owner,
                            neighbour,
                            fluentCellModelID[celli]
                        )
                    );
            }
            else
            {
                FatalErrorInFunction
                    << "unrecognised 3-D cell shape: "
                    << fluentCellModelID[celli]
                    << abort(FatalError);
            }
        }
    }

    // boundary faces are oriented such that the owner is zero and the face
    // area vector points into the domain. Turn them round before making patches
    // for Foam compatibility

    forAll(faces, facei)
    {
        if (owner[facei] == -1)
        {
            // reverse face
            labelList oldFace = faces[facei];

            forAllReverse(oldFace, i)
            {
                faces[facei][oldFace.size() - i - 1] =
                    oldFace[i];
            }
        }
    }


    //make patchless mesh before analysing boundaries

    faceListList patches(0);
    wordList patchNames(0);
    wordList patchTypes(0);
    word defaultFacesName = "defaultFaces";
    word defaultFacesType = emptyPolyPatch::typeName;
    wordList patchPhysicalTypes(0);

    // Scale the points

    points *= scaleFactor;

    Info<< "Building patch-less mesh..." << flush;

    polyMesh pShapeMesh
    (
        IOobject
        (
            polyMesh::defaultRegion,
            runTime.constant(),
            runTime
        ),
        xferMove(points),
        cellShapes,
        patches,
        patchNames,
        patchTypes,
        defaultFacesName,
        defaultFacesType,
        patchPhysicalTypes
    );

    //dont write mesh yet, otherwise preservePatchTypes will be broken
    //and zones wont be written
    //checkmesh done after patch addition as well
    Info<< "done." << endl;


    Info<< endl << "Building boundary and internal patches." << endl;
    //adding patches after mesh construction allows topological checks
    //on whether a patch is internal or external, something fluent
    //doesnt seem to mind

    // Make boundary patches

    SLList<label>::iterator faceGroupZoneIDIter = faceGroupZoneID.begin();
    SLList<label>::iterator faceGroupStartIndexIter =
        faceGroupStartIndex.begin();
    SLList<label>::iterator faceGroupEndIndexIter = faceGroupEndIndex.begin();

    // Note. Not all groups of faces will be boundary patches.
    // Take care on construction

    //2D needs extra space for frontAndBack faces
    if (dimensionOfGrid == 2)
    {
        patches.setSize(faceGroupZoneID.size()+1);
        patchNames.setSize(faceGroupZoneID.size()+1);
        patchTypes.setSize(faceGroupZoneID.size()+1);
        patchPhysicalTypes.setSize(faceGroupZoneID.size()+1);
    }
    else
    {
        patches.setSize(faceGroupZoneID.size());
        patchNames.setSize(faceGroupZoneID.size());
        patchTypes.setSize(faceGroupZoneID.size());
        patchPhysicalTypes.setSize(faceGroupZoneID.size());
    }

    label nPatches = 0;

    //colate information for all patches (internal and external)
    for
    (
        ;
        faceGroupZoneIDIter != faceGroupZoneID.end()
     && faceGroupStartIndexIter != faceGroupStartIndex.end()
     && faceGroupEndIndexIter != faceGroupEndIndex.end();
        ++faceGroupZoneIDIter,
        ++faceGroupStartIndexIter,
        ++faceGroupEndIndexIter
    )
    {
        // get face type and name
        const word& curPatchType = patchTypeIDs[faceGroupZoneIDIter()];

        const word& curPatchName = patchNameIDs[faceGroupZoneIDIter()];

        Info<< "Creating patch " << nPatches
            << " for zone: " << faceGroupZoneIDIter()
            << " start: " << faceGroupStartIndexIter()
            << " end: " << faceGroupEndIndexIter()
            << " type: " << curPatchType << " name: " << curPatchName << endl;

        // make patch labels
        label faceLabel = faceGroupStartIndexIter() - 1;

        faceList patchFaces(faceGroupEndIndexIter() - faceLabel);

        forAll(patchFaces, facei)
        {
            if
            (
                faces[faceLabel].size() == 3
             || faces[faceLabel].size() == 4
            )
            {
                patchFaces[facei] = face(faces[faceLabel]);
                faceLabel++;
            }
            else
            {
                FatalErrorInFunction
                    << "unrecognised face shape with "
                    << patchFaces[facei].size() << " vertices"
                    << abort(FatalError);
            }
        }

        //inlets and outlets
        if
        (
            curPatchType == "pressure"
         || curPatchType == "pressure-inlet"
         || curPatchType == "inlet-vent"
         || curPatchType == "intake-fan"
         || curPatchType == "pressure-outlet"
         || curPatchType == "exhaust-fan"
         || curPatchType == "outlet-vent"
         || curPatchType == "pressure-far-field"
         || curPatchType == "velocity-inlet"
         || curPatchType == "mass-flow-inlet"
         || curPatchType == "outflow"
        )
        {
            patches[nPatches] = patchFaces;
            patchTypes[nPatches] = polyPatch::typeName;
            patchNames[nPatches] = curPatchName;

            nPatches++;
        }
        else if (curPatchType == "wall" ) //wall boundaries
        {
            patches[nPatches] = patchFaces;
            patchTypes[nPatches] = wallPolyPatch::typeName;
            patchNames[nPatches] = curPatchName;

            nPatches++;
        }
        else if
        (
            curPatchType == "symmetry"
         || curPatchType == "axis"
        ) //symmetry planes
        {
            patches[nPatches] = patchFaces;
            patchTypes[nPatches] = symmetryPolyPatch::typeName;
            patchNames[nPatches] = curPatchName;

            nPatches++;
        }
        else if
        (
            curPatchType == "interior"
         || curPatchType == "interface"
         || curPatchType == "internal"
         || curPatchType == "solid"
         || curPatchType == "fan"
         || curPatchType == "radiator"
         || curPatchType == "porous-jump"
        ) //interior boundaries - will not be added as patches
        {
            patches[nPatches] = patchFaces;
            patchTypes[nPatches] = "internal";
            patchNames[nPatches] = curPatchName;

            nPatches++;
        }
        else if
        (
            curPatchType == ""
        ) //unnamed face regions default to interior patches
        {
            Info<< "Patch " << faceGroupZoneIDIter()
                << ": Faces are defined but "
                << "not created as a zone." << endl
                << "Null specification is only valid for internal faces."
                << endl;

            patches[nPatches] = patchFaces;
            patchTypes[nPatches] = "internal";
            patchNames[nPatches] = curPatchName;

            nPatches++;
        }
        else //unknown face regions are not handled
        {
            FatalErrorInFunction
                << "fluent patch type " << curPatchType << " not recognised."
                << abort(FatalError);
        }
    }

    //add front and back boundaries for 2D meshes
    if (dimensionOfGrid == 2)
    {
        Info<< "Creating patch for front and back planes" << endl << endl;

        patches[nPatches] = frontAndBackFaces;
        patchTypes[nPatches] = emptyPolyPatch::typeName;
        patchNames[nPatches] = "frontAndBackPlanes";

        nPatches++;
    }

    //Now have all patch information,
    //check whether each patch is internal or external
    //and add boundaries to mesh
    //also write face sets of all patches
    patches.setSize(nPatches);
    patchTypes.setSize(nPatches);
    patchNames.setSize(nPatches);


    //old polyBoundary
    const polyBoundaryMesh& oPatches = pShapeMesh.boundaryMesh();
    // new patches.
    DynamicList<polyPatch*> newPatches(nPatches);

    // For every boundary face the old patch.
    labelList facePatchID(pShapeMesh.nFaces()-pShapeMesh.nInternalFaces(), -1);
    label cMeshFace = pShapeMesh.nInternalFaces();
    label nBoundaries = 0;


    forAll(patches, patchi)
    {
        const faceList& bFaces = patches[patchi];

        label sz = bFaces.size();
        labelList meshFaces(sz,-1);

        // Search faces by point matching
        forAll(bFaces, j)
        {
            const face& f = bFaces[j];
            label cMeshFace = findFace(pShapeMesh, f);
            meshFaces[j] = cMeshFace;
        }


        //check if patch is internal
        //also check internal/external-ness of first patch face
        //internal faces cannot become foam boundaries
        //if a face is defined as internal but is actually external
        //it will be put in a default wall boundary
        //internal boundaries are simply ignored

        if
        (
            patchTypes[patchi] != "internal"
         && !pShapeMesh.isInternalFace(meshFaces[0])
        )
        {
            //first face is external and has valid non-internal type

            //check all faces for externalness just to be sure
            //and mark patch number to global list
            forAll(meshFaces, i)
            {
                label facei = meshFaces[i];

                if (pShapeMesh.isInternalFace(facei))
                {
                    FatalErrorInFunction
                        << "Face " << facei << " on new patch "
                        << patchNames[patchi]
                        << " is not an external face of the mesh." << endl
                        << exit(FatalError);
                }

                if (facePatchID[facei - pShapeMesh.nInternalFaces()]!= -1)
                {
                    FatalErrorInFunction
                        << "Face " << facei << " on new patch "
                        << patchNames[patchi]
                        << " has already been marked for repatching to"
                        << " patch "
                        << facePatchID[facei - pShapeMesh.nInternalFaces()]
                        << exit(FatalError);
                }
                facePatchID[facei - pShapeMesh.nInternalFaces()] = nBoundaries;
            }

            //add to boundary patch

            Info<< "Adding new patch " << patchNames[patchi]
                << " of type " << patchTypes[patchi]
                << " as patch " << nBoundaries << endl;

            // Add patch to new patch list
            newPatches.append
            (
                polyPatch::New
                (
                    patchTypes[patchi],
                    patchNames[patchi],
                    sz,
                    cMeshFace,
                    nBoundaries,
                    oPatches
                ).ptr()
            );
            nBoundaries++;
            cMeshFace += sz;
        }
        else
        {
            Info<< "Patch " << patchNames[patchi]
                 << " is internal to the mesh "
                 << " and is not being added to the boundary."
                 << endl;

        }
    }

    // Check for any remaining boundary faces
    // and add them to a default wall patch
    // this routine should generally not be invoked
    {
        DynamicList<label> defaultBoundaryFaces(facePatchID.size());
        forAll(facePatchID, idI)
        {
            if (facePatchID[idI] == -1)
            {
                defaultBoundaryFaces.append(idI);
                facePatchID[idI] = nBoundaries;
            }
        }
        defaultBoundaryFaces.shrink();

        if (defaultBoundaryFaces.size())
        {
            Warning << " fluent mesh has " << defaultBoundaryFaces.size()
                    << " undefined boundary faces." << endl
                    << " Adding undefined faces to new patch `default_wall`"
                    << endl;

            // Add patch to new patch list

            newPatches.append
            (
                polyPatch::New
                (
                    wallPolyPatch::typeName,
                    "default_wall",
                    defaultBoundaryFaces.size(),
                    cMeshFace,
                    nBoundaries,
                    oPatches
                ).ptr()
            );
            nBoundaries++;
            cMeshFace += defaultBoundaryFaces.size();
        }
    }

    newPatches.shrink();

    // Use facePatchIDs map to reorder boundary faces into compact regions

    repatchPolyTopoChanger repatcher(pShapeMesh);

    // Add new list of patches
    repatcher.changePatches(newPatches);

    // Change patch ids
    forAll(facePatchID, idI)
    {
        label facei = idI + pShapeMesh.nInternalFaces();

        repatcher.changePatchID(facei, facePatchID[idI]);
    }
    repatcher.repatch();


    // Set the precision of the points data to 10
    IOstream::defaultPrecision(max(10u, IOstream::defaultPrecision()));


    // Re-do face matching to write sets
    if (writeSets)
    {
        forAll(patches, patchi)
        {
            const faceList& bFaces = patches[patchi];
            label sz = bFaces.size();

            faceSet pFaceSet(pShapeMesh, patchNames[patchi], sz);

            forAll(bFaces, j)
            {
                const face& f = bFaces[j];
                label cMeshFace = findFace(pShapeMesh, f);
                pFaceSet.insert(cMeshFace);
            }
            Info<< "Writing patch " << patchNames[patchi]
                << " of size " << sz << " to faceSet" << endl;

            pFaceSet.instance() = pShapeMesh.instance();
            pFaceSet.write();
        }
    }


    // Zones
    // will write out cell zones and internal faces for those zones
    // note: zone boundary faces are not added to face zones
    // the names of boundaries bordering on cell zones are written to
    // a list containing the boundary name and cellzone it borders on
    // interior boundaries are handled via faceSets
    // cell zones will only be written if there is more than one

    if (writeZones && cellGroupZoneID.size() > 1)
    {
        Info<< "Adding Zones" << endl;
        List<pointZone*> pz(0);

        label nrCellZones = cellGroupZoneID.size();
        List<cellZone*> cz(nrCellZones);

        // Make face zones for cell zones
        List<faceZone*> fz(nrCellZones);

        // List of patch names and the cellZone(s) they border
        // this is just an info file to make MRF easier to setup
        List<DynamicList<word>> boundaryZones
        (
            pShapeMesh.boundaryMesh().size()
        );

        const polyBoundaryMesh& bPatches = pShapeMesh.boundaryMesh();
        forAll(bPatches, pI)
        {
            boundaryZones[pI].append(bPatches[pI].name());
        }

        label cnt=0;
        SLList<label>::iterator cg = cellGroupZoneID.begin();
        SLList<label>::iterator start = cellGroupStartIndex.begin();
        SLList<label>::iterator end = cellGroupEndIndex.begin();

        for (; cg != cellGroupZoneID.end(); ++cg, ++start, ++end)
        {
            const word& name = patchNameIDs[cg()];
            const word& type = patchTypeIDs[cg()];

            Info<< "Writing cell zone: " << name
                << " of type " << type << " starting at " << start() - 1
                << " ending at " << end() - 1 << " to cellSet." << endl;

            labelList cls(end() - start() + 1);

            // Mark zone cells, used for finding faces
            boolList zoneCell(pShapeMesh.nCells(), false);

            // shift cell indizes by 1
            label nr=0;
            for (label celli = (start() - 1); celli < end(); celli++)
            {
                cls[nr]=celli;
                zoneCell[celli] = true;
                nr++;
            }

            cz[cnt] = new cellZone
            (
                name,
                cls,
                cnt,
                pShapeMesh.cellZones()
            );

            DynamicList<label> zoneFaces(pShapeMesh.nFaces());
            forAll(pShapeMesh.faceNeighbour(), facei)
            {
                label nei = pShapeMesh.faceNeighbour()[facei];
                label own = pShapeMesh.faceOwner()[facei];
                if (nei != -1)
                {
                    if (zoneCell[nei] && zoneCell[own])
                    {
                        zoneFaces.append(facei);
                    }
                }
            }
            zoneFaces.shrink();

            fz[cnt] = new faceZone
            (
                name,
                zoneFaces,
                boolList(zoneFaces.size(), false),
                cnt,
                pShapeMesh.faceZones()
            );

            // Add cell zones to patch zone list
            forAll(bPatches, pI)
            {
                const labelList& faceCells = bPatches[pI].faceCells();
                forAll(faceCells, fcI)
                {
                    if (zoneCell[faceCells[fcI] ])
                    {
                        boundaryZones[pI].append(name);
                        break;
                    }
                }
            }

            cnt++;
        }

        pShapeMesh.addZones(pz, fz, cz);

        forAll(bPatches, pI)
        {
            boundaryZones[pI].shrink();
        }

        fileName bczf
        (
            runTime.path()/runTime.constant()
           /"polyMesh"/"boundaryAdjacentCellZones"
        );

        OFstream boundaryCellZonesFile(bczf);
        forAll(boundaryZones, bzI)
        {
            forAll(boundaryZones[bzI], bzII)
            {
                boundaryCellZonesFile << boundaryZones[bzI][bzII] << " ";
            }

            boundaryCellZonesFile << endl;
        }
    }

    Info<< endl << "Writing mesh..." << flush;

    Info<< " to " << pShapeMesh.instance()/pShapeMesh.meshDir()
        << "  " << flush;

    pShapeMesh.setInstance(pShapeMesh.instance());
    pShapeMesh.write();
    Info<< "done." << endl << endl;

    // Write cellSets for Fluent regions
    // allows easy post-processing
    // set and zone functionality will be integrated some time
    // soon negating the need for double output
    if (writeSets)
    {
        if (cellGroupZoneID.size() > 1)
        {
            Info<< "Writing cell sets" << endl;

            SLList<label>::iterator cg = cellGroupZoneID.begin();
            SLList<label>::iterator start = cellGroupStartIndex.begin();
            SLList<label>::iterator end = cellGroupEndIndex.begin();

            // Note: cellGroupXXX are all Fluent indices (starting at 1)
            // so offset before using.

            for (; cg != cellGroupZoneID.end(); ++cg, ++start, ++end)
            {
                const word& name=patchNameIDs[cg()];
                const word& type=patchTypeIDs[cg()];

                Info<< "Writing cell set: " << name
                    << " of type " << type << " starting at " << start() - 1
                    << " ending at " << end() - 1 << " to cellSet." << endl;

                cellSet internal(pShapeMesh, name, end() - start());

                // shift cell indizes by 1
                for (label celli = start() - 1; celli <= end() - 1; celli++)
                {
                    internal.insert(celli);
                }

                internal.write();
            }
        }
        else
        {
            Info<< "Only one cell group: no set written\n";
        }
    }

    Info<< "\nEnd\n" << endl;
    return 0;
}


 /* ------------------------------------------------------------------------- *\
    ------ End of fluentMeshToFoam.L
 \* ------------------------------------------------------------------------- */