ningshuxia
2024-06-18 e83dca6e861b622b54d3392ca0d3f1f1eb69f7c9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
using IStation.Epanet;
using IStation.Epanet.Enums;
using IStation.Epanet.Log;
using IStation.Epanet.Network.Structures;
using IStation.Epanet.Util;
using System.Diagnostics;
using System.Globalization;
using System.Text;
 
namespace IStation.Epanet.Network.IO.Input
{
 
    public class NetParser : InputParser
    {
 
        #region Data indexes
        //-------------------------
        // Generic property indexes
        //-------------------------
        private const int COMMENT_INDEX = 0;  //Comment index
        private const int TAG_INDEX = 1;  //Tag index
 
        //--------------------------
        // Junction property indexes
        //--------------------------
        private const int JUNC_ELEV_INDEX = 2;  //Elevation
        private const int JUNC_DEMAND_INDEX = 3;  //Demand
        private const int JUNC_PATTERN_INDEX = 4;  //Demand pattern
        private const int JUNC_DMNDCAT_INDEX = 5;  //Demand categories
        private const int JUNC_EMITTER_INDEX = 6;  //Emitter coeff.
        private const int JUNC_INITQUAL_INDEX = 7;  //Init. quality
        private const int JUNC_SRCQUAL_INDEX = 8;  //Source quality
        private const int JUNC_SRCPAT_INDEX = 9;  //Source pattern
        private const int JUNC_SRCTYPE_INDEX = 10; //Source type
 
        //---------------------------
        // Reservoir property indexes
        //---------------------------
        private const int RES_HEAD_INDEX = 2;  //Head
        private const int RES_PATTERN_INDEX = 3;  //Head pattern
        private const int RES_INITQUAL_INDEX = 4;  //Init. quality
        private const int RES_SRCQUAL_INDEX = 5;  //Source quality
        private const int RES_SRCPAT_INDEX = 6;  //Source pattern
        private const int RES_SRCTYPE_INDEX = 7;  //Source type
 
        //----------------------
        // Tank property indexes
        //----------------------
        private const int TANK_ELEV_INDEX = 2;  //Elevation
        private const int TANK_INITLVL_INDEX = 3;  //Init. level
        private const int TANK_MINLVL_INDEX = 4;  //Min. level
        private const int TANK_MAXLVL_INDEX = 5;  //Max. level
        private const int TANK_DIAM_INDEX = 6;  //Diameter
        private const int TANK_MINVOL_INDEX = 7;  //Min. volume
        private const int TANK_VCURVE_INDEX = 8;  //Volume curve
        private const int TANK_MIXMODEL_INDEX = 9;  //Mixing model
        private const int TANK_MIXFRAC_INDEX = 10; //Mixing fraction
        private const int TANK_KBULK_INDEX = 11; //Bulk coeff.
        private const int TANK_INITQUAL_INDEX = 12; //Init. quality
        private const int TANK_SRCQUAL_INDEX = 13; //Source quality
        private const int TANK_SRCPAT_INDEX = 14; //Source pattern
        private const int TANK_SRCTYPE_INDEX = 15; //Source type
 
        //----------------------
        // Pipe property indexes
        //----------------------
        private const int PIPE_LEN_INDEX = 2;  //Length
        private const int PIPE_DIAM_INDEX = 3;  //Diameter
        private const int PIPE_ROUGH_INDEX = 4;  //Roughness coeff.
        private const int PIPE_MLOSS_INDEX = 5;  //Minor loss coeff.
        private const int PIPE_STATUS_INDEX = 6;  //Status
        private const int PIPE_KBULK_INDEX = 7;  //Bulk coeff.
        private const int PIPE_KWALL_INDEX = 8;  //Wall coeff.
 
        //----------------------
        // Pump property indexes
        //----------------------
        private const int PUMP_HCURVE_INDEX = 2;  //Head curve
        private const int PUMP_HP_INDEX = 3;  //Horsepower
        private const int PUMP_SPEED_INDEX = 4;  //Speed
        private const int PUMP_PATTERN_INDEX = 5;  //Speed pattern
        private const int PUMP_STATUS_INDEX = 6;  //Status
        private const int PUMP_ECURVE_INDEX = 7;  //Efficiency curve
        private const int PUMP_EPRICE_INDEX = 8;  //Energy price
        private const int PUMP_PRICEPAT_INDEX = 9;  //Price pattern
 
        //-----------------------
        // Valve property indexes
        //-----------------------
        private const int VALVE_DIAM_INDEX = 2;  //Diameter
        private const int VALVE_TYPE_INDEX = 3;  //Type
        private const int VALVE_SETTING_INDEX = 4;  //Setting
        private const int VALVE_MLOSS_INDEX = 5;  //Minor loss coeff.
        private const int VALVE_STATUS_INDEX = 6;  //Status
 
        //---------------------------
        // Map Label property indexes
        //---------------------------
        private const int LABEL_TEXT_INDEX = 0;
        private const int ANCHOR_NODE_INDEX = 3;
        private const int METER_TYPE_INDEX = 4;
        private const int METER_ID_INDEX = 5;
 
        //------------------------
        // Analysis option indexes
        //------------------------
        private const int FLOW_UNITS_INDEX = 0;  //Flow units
        private const int HLOSS_FORM_INDEX = 1;  //Headloss formula
        private const int SPEC_GRAV_INDEX = 2;  //Specific gravity
        private const int VISCOS_INDEX = 3;  //Relative viscosity
        private const int TRIALS_INDEX = 4;  //Max. trials
        private const int ACCURACY_INDEX = 5;  //Hydraul. accuracy
        private const int UNBALANCED_INDEX = 6;  //If unbalanced option
        private const int GLOBAL_PAT_INDEX = 7;  //Default demand pattern
        private const int DEMAND_MULT_INDEX = 8;  //Demand multiplier
        private const int EMITTER_EXP_INDEX = 9;  //Emitter exponent
        private const int STATUS_RPT_INDEX = 10; //Status report option
 
        private const int QUAL_PARAM_INDEX = 11; //Quality parameter
        private const int QUAL_UNITS_INDEX = 12; //Concen. units
        private const int DIFFUS_INDEX = 13; //Diffusivity
        private const int TRACE_NODE_INDEX = 14; //Trace node index
        private const int QUAL_TOL_INDEX = 15; //Quality tolerance
        private const int MAX_SEGS_INDEX = 16; //Max. pipe segments
 
        private const int BULK_ORDER_INDEX = 17; //Bulk reaction order
        private const int WALL_ORDER_INDEX = 18; //Wall reaction order
        private const int GLOBAL_KBULK_INDEX = 19; //Default bulk react. coeff.
        private const int GLOBAL_KWALL_INDEX = 20; //Default wall react. coeff.
        private const int LIMIT_QUAL_INDEX = 21; //Limiting potential concen.
        private const int ROUGH_CORREL_INDEX = 22; //Relation between Kwall & roughness
 
        private const int DURATION_INDEX = 23; //Simulation duration
        private const int HYD_TSTEP_INDEX = 24; //Hydraulic time step
        private const int QUAL_TSTEP_INDEX = 25; //Quality time step
        private const int PAT_TSTEP_INDEX = 26; //Pattern time step
        private const int PAT_START_INDEX = 27; //Pattern start time
        private const int RPT_TSTEP_INDEX = 28; //Reporting time step
        private const int RPT_START_INDEX = 29; //Report start time
        private const int START_TIME_INDEX = 30; //Starting time of day
        private const int TIME_STAT_INDEX = 31; //Time statistic option
 
        private const int EFFIC_INDEX = 32; //Default pump effic.
        private const int EPRICE_INDEX = 33; //Default energy price
        private const int PRICE_PAT_INDEX = 34; //Default price pattern
        private const int DMND_CHARGE_INDEX = 35; //Energy demand charge
        private const int CHECK_FREQ_INDEX = 36;
        private const int MAX_CHECK_INDEX = 37;
        private const int DAMP_LIMIT_INDEX = 38;
 
        #endregion
 
        /// <summary>Object categories</summary>
        public enum ObjectCategories
        {
            JUNCS = 0,
            RESERVS = 1,
            TANKS = 2,
            PIPES = 3,
            PUMPS = 4,
            VALVES = 5,
            LABELS = 6,
            PATTERNS = 7,
            CURVES = 8,
            CNTRLS = 9,
            OPTS = 10,
            VERTICES = 11
        }
 
        /// <summary>EPANET2 *.net project file signature.</summary>
        private const string NETFILE_SIGNATURE = "<EPANET2>";
 
        /// <summary>EPANET2 *.net project file version ID.</summary>
        private const int VERSIONID1 = 20005;
        /// <summary>EPANET2 *.net project file version ID.</summary>
        private const int VERSIONID2 = 20008;
 
        /// <summary>Max. index for network options array.</summary>
        private const int MAXOPTIONS = 38;
        /// <summary>Max. index for node property array.</summary>
        private const int MAXNODEPROPS = 25;
        /// <summary>Max. index for link property array</summary>
        private const int MAXLINKPROPS = 25;
 
        private Reader _reader;
 
        public override Network Parse(Network nw, string fileName)
        {
            net = nw ?? new Network();
 
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
 
            using (fs)
            {
                _reader = new Reader(fs, Encoding.ASCII);
 
                string signature = _reader.ReadString();
 
                //Check for <EPANET2> marker at start of input file
                if (signature != NETFILE_SIGNATURE) throw new EnException(ErrorCode.Err200);
 
                //Read version ID
                int ver = _reader.ReadInteger();
 
                if (ver < VERSIONID1 || ver > VERSIONID2) throw new EnException(ErrorCode.Err200);
 
                //Total up number of network components
                int ncomp = 0;
 
                for (ObjectCategories i = ObjectCategories.JUNCS; i <= ObjectCategories.CNTRLS; i++)
                    ncomp += _reader.ReadInteger();
 
                Debug.Print("Ncomp=" + ncomp);
 
                net.Title.Add(_reader.ReadString());
                net.Title.AddRange(_reader.ReadList());
 
                // TODO: move to end
                ReadOptions();
 
                //Read in time patterns.
                ReadPatterns();
 
                //Read in curves.
                ReadCurves();
 
                //Read in junctions.
                ReadJunctions();
 
                //Read in reservoirs
                ReadReservoirs();
 
                //Read in tanks
                ReadTanks();
 
                //Read in pipes, pumps, & valves
                ReadPipes();
                ReadPumps();
                ReadValves();
 
                //Read in control rules.
                ReadControls();
                ReadRules();
 
                //Read in map labels.
                ReadLabels();
 
            }
 
            AdjustData(net);
 
            net.FieldsMap.Prepare(net.UnitsFlag, net.FlowFlag, net.PressFlag, net.QualFlag, net.ChemUnits, net.SpGrav, net.HStep);
 
            Convert();
 
            return net;
        }
 
        private void ReadLabels()
        {
            int n = _reader.ReadInteger();
 
            if (n <= 0) return;
 
            for (int i = 0; i < n; i++)
            {
                Label mlabel = new Label(_reader.ReadString())
                {
                    Position = _reader.ReadPoint(),
                    Anchor = net.GetNode(_reader.ReadString()),
                    FontName = _reader.ReadString(),
                    FontSize = _reader.ReadInteger(),
                    FontBold = _reader.ReadBoolean(),
                    FontItalic = _reader.ReadBoolean(),
                    MeterType = (Label.MeterTypes)_reader.ReadInteger(),
                    MeterId = _reader.ReadString()
                };
 
                net.Labels.Add(mlabel);
            }
        }
 
        private void ReadRules()
        {
            var lines = _reader.ReadList();
            List<string> tok = new List<string>(Constants.MAXTOKS);
            Rule currentRule = null;
 
 
            foreach (string line in lines)
            {
                if (string.IsNullOrEmpty(line))
                    continue;
 
                if (GetTokens(line, tok) == 0)
                    continue;
 
                tok[0].TryParse(out Rulewords key);
                if (key == Rulewords.RULE)
                {
                    currentRule = new Rule(tok[1]);
                    net.Rules.Add(currentRule);
                }
                else
                {
                    currentRule?.Code.Add(line);
                }
            }
 
        }
 
        private void ReadControls()
        {
            var lines = _reader.ReadList();
            List<string> tok = new List<string>(Constants.MAXTOKS);
 
            foreach (string line in lines)
            {
                if (string.IsNullOrEmpty(line))
                    continue;
 
                if (GetTokens(line, tok) == 0)
                    continue;
 
                try
                {
 
                    int n = tok.Count;
                    StatusType status = StatusType.ACTIVE;
 
                    double setting = double.NaN, level = 0.0;
                    TimeSpan time = TimeSpan.Zero;
 
                    if (n < 6)
                        throw new EnException(ErrorCode.Err201, SectType.CONTROLS, line);
 
                    Node node = null;
                    Link link = net.GetLink(tok[1]);
 
                    if (link == null)
                        throw new EnException(ErrorCode.Err204, SectType.CONTROLS, tok[0]);
 
                    LinkType ltype = link.LinkType;
 
                    if (ltype == LinkType.Pipe && ((Pipe)link).HasCheckValve)
                        throw new EnException(ErrorCode.Err207, SectType.CONTROLS, tok[0]);
 
                    if (tok[2].Match(StatusType.OPEN.ToString()))
                    {
                        status = StatusType.OPEN;
                        switch (ltype)
                        {
                            case LinkType.Pump:
                                setting = 1.0;
                                break;
                            case LinkType.VALVE:
                                if (((Valve)link).ValveType == ValveType.GPV)
                                    setting = link.Kc;
                                break;
                        }
                    }
                    else if (tok[2].Match(StatusType.CLOSED.ToString()))
                    {
                        status = StatusType.CLOSED;
                        switch (ltype)
                        {
                            case LinkType.Pump:
                                setting = 0.0;
                                break;
                            case LinkType.VALVE:
                                if (((Valve)link).ValveType == ValveType.GPV)
                                    setting = link.Kc;
                                break;
                        }
                    }
                    else if (ltype == LinkType.VALVE && ((Valve)link).ValveType == ValveType.GPV)
                    {
                        throw new EnException(ErrorCode.Err206, SectType.CONTROLS, tok[0]);
                    }
                    else if (!tok[2].ToDouble(out setting))
                    {
                        throw new EnException(ErrorCode.Err202, SectType.CONTROLS, tok[0]);
                    }
 
                    if (ltype == LinkType.Pump || ltype == LinkType.Pipe)
                    {
                        if (!double.IsNaN(setting))
                        {
                            if (setting < 0.0)
                                throw new EnException(ErrorCode.Err202, SectType.CONTROLS, tok[0]);
 
                            status = setting.IsZero() ? StatusType.CLOSED : StatusType.OPEN;
                        }
                    }
 
                    ControlType ctype;
 
                    if (tok[4].Match(Keywords.w_TIME))
                        ctype = ControlType.Timer;
                    else if (tok[4].Match(Keywords.w_CLOCKTIME))
                        ctype = ControlType.TimeOfDay;
                    else
                    {
                        if (n < 8)
                            throw new EnException(ErrorCode.Err201, SectType.CONTROLS, line);
 
                        if ((node = net.GetNode(tok[5])) == null)
                            throw new EnException(ErrorCode.Err203, SectType.CONTROLS, tok[0]);
 
                        if (tok[6].Match(Keywords.w_BELOW))
                            ctype = ControlType.LowLevel;
                        else if (tok[6].Match(Keywords.w_ABOVE))
                            ctype = ControlType.HiLevel;
                        else
                            throw new EnException(ErrorCode.Err201, SectType.CONTROLS, line);
                    }
 
                    switch (ctype)
                    {
                        case ControlType.Timer:
                        case ControlType.TimeOfDay:
 
                            switch (n)
                            {
                                case 6:
                                    time = Utilities.ToTimeSpan(tok[5]);
                                    break;
                                case 7:
                                    time = Utilities.ToTimeSpan(tok[5], tok[6]);
                                    break;
                            }
 
                            if (time == TimeSpan.MinValue)
                                throw new EnException(ErrorCode.Err201, SectType.CONTROLS, line);
 
                            break;
 
                        case ControlType.LowLevel:
                        case ControlType.HiLevel:
                            if (!tok[7].ToDouble(out level))
                                throw new EnException(ErrorCode.Err202, SectType.CONTROLS, tok[0]);
 
                            break;
                    }
 
                    Control cntr = new Control
                    {
                        Link = link,
                        Node = node,
                        Type = ctype,
                        Status = status,
                        Setting = setting,
                        Time = ctype == ControlType.TimeOfDay ? time.TimeOfDay() : time,
                        Grade = level
                    };
 
                    net.Controls.Add(cntr);
                }
                catch (EnException ex)
                {
                    LogException(ex);
                }
            }
        }
 
        private void ReadPumps()
        {
            int n = _reader.ReadInteger();
 
            if (n <= 0)
                return;
 
            for (int i = 0; i < n; i++)
            {
                string name = _reader.ReadString();
                Node j1 = net.GetNode(_reader.ReadString());
                Node j2 = net.GetNode(_reader.ReadString());
                var points = _reader.ReadVertices();
                var data = _reader.ReadArray(MAXLINKPROPS);
 
                if (net.GetLink(name) != null)
                {
                    LogException(new EnException(ErrorCode.Err215, SectType.PUMPS, name));
                    continue;
                }
 
                if (j1 == null || j2 == null)
                {
                    LogException(new EnException(ErrorCode.Err203, SectType.PUMPS, name));
                    continue;
                }
 
                if (j1.Equals(j2))
                {
                    LogException(new EnException(ErrorCode.Err222, SectType.PUMPS, name));
                    continue;
                }
 
                Pump pump = new Pump(name)
                {
                    FirstNode = j1,
                    SecondNode = j2,
                };
 
                if (points.Length > 0)
                    pump.Vertices.AddRange(points);
 
                if (!string.IsNullOrEmpty(data[COMMENT_INDEX]))
                    pump.Comment = data[COMMENT_INDEX];
 
                if (!string.IsNullOrEmpty(data[TAG_INDEX]))
                    pump.Tag = data[TAG_INDEX];
 
                //----------------------------------
 
                if (!string.IsNullOrEmpty(data[PUMP_HP_INDEX]))
                {
                    if (!data[PUMP_HP_INDEX].ToDouble(out double y) || y <= 0.0)
                    {
                        LogException(new EnException(ErrorCode.Err202, SectType.PUMPS, name));
                    }
                    else
                    {
                        pump.Ptype = PumpType.CONST_HP;
                        pump.Km = y;
                    }
                }
 
                if (!string.IsNullOrEmpty(data[PUMP_HCURVE_INDEX]))
                {
                    Curve curve = net.GetCurve(data[PUMP_HCURVE_INDEX]);
                    if (curve == null)
                    {
                        LogException(new EnException(ErrorCode.Err206, SectType.PUMPS, name));
                    }
                    else
                    {
                        pump.HCurve = curve;
                    }
                }
 
                if (!string.IsNullOrEmpty(data[PUMP_PATTERN_INDEX]))
                {
                    Pattern p = net.GetPattern(data[PUMP_PATTERN_INDEX]);
 
                    if (p == null)
                    {
                        LogException(new EnException(ErrorCode.Err205, SectType.PUMPS, name));
                    }
                    else
                    {
                        pump.UPat = p;
                    }
                }
 
 
                if (!string.IsNullOrEmpty(data[PUMP_SPEED_INDEX]))
                {
                    if (!data[PUMP_SPEED_INDEX].ToDouble(out double y) || y < 0.0)
                    {
                        LogException(new EnException(ErrorCode.Err202, SectType.PUMPS, name));
                    }
                    else
                    {
                        pump.Kc = y;
                    }
                }
 
                //------------------------------
 
                if (!string.IsNullOrEmpty(data[PUMP_ECURVE_INDEX]))
                {
                    Curve curve = net.GetCurve(data[PUMP_ECURVE_INDEX]);
 
                    if (curve == null)
                    {
                        LogException(new EnException(ErrorCode.Err217, SectType.ENERGY, name));
                    }
                    else
                    {
                        pump.ECurve = curve;
                    }
                }
 
                if (!string.IsNullOrEmpty(data[PUMP_EPRICE_INDEX]))
                {
                    if (!data[PUMP_EPRICE_INDEX].ToDouble(out double cost))
                    {
                        LogException(new EnException(ErrorCode.Err217, SectType.ENERGY, name));
                    }
                    else
                    {
                        pump.ECost = cost;
                    }
                }
 
                if (!string.IsNullOrEmpty(data[PUMP_PRICEPAT_INDEX]))
                {
                    Pattern pattern = net.GetPattern(data[PUMP_PRICEPAT_INDEX]);
 
                    if (pattern == null)
                    {
                        LogException(new EnException(ErrorCode.Err217, SectType.ENERGY, name));
                    }
                    else
                    {
                        pump.EPat = pattern;
                    }
                }
 
 
                // FIXME: status changes
                if (!string.IsNullOrEmpty(data[PUMP_STATUS_INDEX]))
                {
                    StatusType status = (StatusType)(-1);
                    if (data[PUMP_STATUS_INDEX].Match(Keywords.w_OPEN))
                    {
                        status = StatusType.OPEN;
                    }
                    else if (data[PUMP_STATUS_INDEX].Match(Keywords.w_CLOSED))
                    {
                        status = StatusType.CLOSED;
                    }
                    else
                    {
                        LogException(new EnException(ErrorCode.Err211, SectType.STATUS, name));
                    }
 
                    if (status >= 0)
                        ChangeStatus(pump, status, 0.0);
                }
 
                net.Links.Add(pump);
            }
        }
 
        private void ReadValves()
        {
            int n = _reader.ReadInteger();
 
            if (n <= 0)
                return;
 
            for (int i = 0; i < n; i++)
            {
                StatusType status = StatusType.OPEN;
 
                string name = _reader.ReadString();
                Node j1 = net.GetNode(_reader.ReadString());
                Node j2 = net.GetNode(_reader.ReadString());
                var points = _reader.ReadVertices();
                var data = _reader.ReadArray(MAXLINKPROPS);
 
 
                if (net.GetLink(name) != null)
                {
                    LogException(new EnException(ErrorCode.Err215, SectType.VALVES, name));
                    continue;
                }
 
                if (j1 == null || j2 == null)
                {
                    LogException(new EnException(ErrorCode.Err203, SectType.VALVES, name));
                    continue;
                }
 
                if (j1.Equals(j2))
                {
                    LogException(new EnException(ErrorCode.Err222, SectType.VALVES, name));
                    continue;
                }
 
                if (!data[VALVE_TYPE_INDEX].TryParse(out ValveType type))
                {
                    LogException(new EnException(ErrorCode.Err201, SectType.VALVES, data[VALVE_TYPE_INDEX]));
                    continue;
                }
 
                if (!data[VALVE_DIAM_INDEX].ToDouble(out double diam) || diam <= 0.0)
                {
                    LogException(new EnException(ErrorCode.Err202, SectType.VALVES, name));
                    continue;
                }
 
                Valve valve = new Valve(name, type)
                {
                    FirstNode = j1,
                    SecondNode = j2
                };
 
                if (type == ValveType.GPV)
                { /* Headloss curve for GPV */
                    Curve t = net.GetCurve(data[VALVE_SETTING_INDEX]);
                    if (t == null)
                    {
                        LogException(new EnException(ErrorCode.Err206, SectType.VALVES, name));
                        continue;
                    }
 
                    // setting = net.Curves.IndexOf(t);
                    log.Warning("GPV Valve, index as roughness !");
                    valve.Curve = t;
                    status = StatusType.OPEN;
                }
                else if (!data[VALVE_SETTING_INDEX].ToDouble(out double _))
                {
                    LogException(new EnException(ErrorCode.Err202));
                    continue;
                }
 
                if (!data[VALVE_MLOSS_INDEX].ToDouble(out double lcoeff) || lcoeff < 0.0)
                {
                    LogException(new EnException(ErrorCode.Err202, SectType.VALVES, name));
                    continue;
                }
 
                /* Check that PRV, PSV, or FCV not connected to a tank & */
                /* check for illegal connections between pairs of valves.*/
                if (j1.NodeType > NodeType.Junction || j2.NodeType > NodeType.Junction)
                {
                    if (type == ValveType.PRV || type == ValveType.PSV || type == ValveType.FCV)
                    {
                        LogException(new EnException(ErrorCode.Err219, SectType.VALVES, name));
                        continue;
                    }
                }
 
                if (!Valvecheck(net, type, j1, j2))
                    throw new EnException(ErrorCode.Err220);
 
                valve.FirstNode = j1;
                valve.SecondNode = j2;
                valve.Lenght = 0.0;
                valve.Diameter = diam;
                valve.Kc = 0.0;
                valve.Km = lcoeff;
                valve.Kb = double.NaN;
                valve.Kw = double.NaN;
                valve.Status = status;
 
                if (points.Length > 0)
                    valve.Vertices.AddRange(points);
 
                if (!string.IsNullOrEmpty(data[COMMENT_INDEX]))
                    valve.Comment = data[COMMENT_INDEX];
 
                if (!string.IsNullOrEmpty(data[TAG_INDEX]))
                    valve.Tag = data[TAG_INDEX];
 
                net.Links.Add(valve);
            }
        }
 
        private void ReadPipes()
        {
            int n = _reader.ReadInteger();
 
            if (n <= 0) return;
 
            for (int i = 0; i < n; i++)
            {
                string name = _reader.ReadString();
                Node j1 = net.GetNode(_reader.ReadString());
                Node j2 = net.GetNode(_reader.ReadString());
                var points = _reader.ReadVertices();
                var data = _reader.ReadArray(MAXLINKPROPS);
 
                if (net.GetLink(name) != null)
                {
                    LogException(new EnException(ErrorCode.Err215, SectType.JUNCTIONS, name));
                    continue;
                }
 
                if (j1 == null || j2 == null)
                {
                    LogException(new EnException(ErrorCode.Err203, SectType.PIPES, name));
                    continue;
                }
 
                if (j1.Equals(j2))
                {
                    LogException(new EnException(ErrorCode.Err222, SectType.PIPES, name));
                    continue;
                }
 
 
 
                if (!data[PIPE_LEN_INDEX].ToDouble(out double length) || length <= 0.0 ||
                    !data[PIPE_DIAM_INDEX].ToDouble(out double diam) || diam <= 0.0 ||
                    !data[PIPE_ROUGH_INDEX].ToDouble(out double rcoeff) || rcoeff <= 0.0 ||
                    !data[PIPE_MLOSS_INDEX].ToDouble(out double lcoeff) || lcoeff < 0.0
                )
                {
                    LogException(new EnException(ErrorCode.Err202, SectType.PIPES, name));
                    continue;
                }
 
                StatusType status = StatusType.OPEN;
                bool isCv = false;
 
                if (data[PIPE_STATUS_INDEX].Match(Keywords.w_CV))
                {
                    isCv = true;
                }
                else if (data[PIPE_STATUS_INDEX].Match(Keywords.w_CLOSED))
                {
                    status = StatusType.CLOSED;
                }
                else if (data[PIPE_STATUS_INDEX].Match(Keywords.w_OPEN))
                {
                    status = StatusType.OPEN;
                }
                else
                {
                    LogException(new EnException(ErrorCode.Err202, SectType.PIPES, name));
                    continue;
                }
 
                Pipe link = new Pipe(name)
                {
                    FirstNode = j1,
                    SecondNode = j2,
                    Lenght = length,
                    Diameter = diam,
                    Kc = rcoeff,
                    Km = lcoeff,
                    Kb = double.NaN,
                    Kw = double.NaN,
                    HasCheckValve = isCv,
                    Status = status
                };
 
                if (points.Length > 0)
                    link.Vertices.AddRange(points);
 
                if (!string.IsNullOrEmpty(data[COMMENT_INDEX]))
                    link.Comment = data[COMMENT_INDEX];
 
                if (!string.IsNullOrEmpty(data[TAG_INDEX]))
                    link.Tag = data[TAG_INDEX];
 
                if (!string.IsNullOrEmpty(data[PIPE_KBULK_INDEX]))
                {
                    if (!data[PIPE_KBULK_INDEX].ToDouble(out double kb))
                    {
                        LogException(new EnException(ErrorCode.Err202, SectType.PIPES, name));
                    }
                    else
                    {
                        link.Kb = kb;
                    }
                }
 
                if (!string.IsNullOrEmpty(data[PIPE_KWALL_INDEX]))
                {
                    if (!data[PIPE_KWALL_INDEX].ToDouble(out double kw))
                    {
                        LogException(new EnException(ErrorCode.Err202, SectType.PIPES, name));
                    }
                    else
                    {
                        link.Kw = kw;
                    }
                }
 
                net.Links.Add(link);
            }
        }
 
        private void ReadTanks()
        {
            int n = _reader.ReadInteger();
            if (n <= 0) return;
 
            for (int i = 0; i < n; i++)
            {
                Curve vcurve = null;
 
                string name = _reader.ReadString();
                var point = _reader.ReadPoint();
                var data = _reader.ReadArray(MAXNODEPROPS);
 
                if (net.GetNode(name) != null)
                {
                    LogException(new EnException(ErrorCode.Err215, SectType.TANKS, name));
                    continue;
                }
 
                if (!data[TANK_ELEV_INDEX].ToDouble(out double el))
                {
                    LogException(new EnException(ErrorCode.Err202, SectType.TANKS, data[TANK_ELEV_INDEX]));
                    continue;
                }
 
                if (!data[TANK_INITLVL_INDEX].ToDouble(out double initlevel))
                {
                    LogException(new EnException(ErrorCode.Err202, SectType.TANKS, data[TANK_INITLVL_INDEX]));
                    continue;
                }
 
                if (!data[TANK_MINLVL_INDEX].ToDouble(out double minlevel))
                {
                    LogException(new EnException(ErrorCode.Err202, SectType.TANKS, data[TANK_MINLVL_INDEX]));
                    continue;
                }
 
                if (!data[TANK_MAXLVL_INDEX].ToDouble(out double maxlevel))
                {
                    LogException(new EnException(ErrorCode.Err202, SectType.TANKS, data[TANK_MAXLVL_INDEX]));
                    continue;
                }
 
                if (!data[TANK_DIAM_INDEX].ToDouble(out double diam) || diam < 0)
                {
                    LogException(new EnException(ErrorCode.Err202, SectType.TANKS, data[TANK_DIAM_INDEX]));
                    continue;
                }
 
                if (!data[TANK_MINVOL_INDEX].ToDouble(out double minvol) || minvol < 0)
                {
                    LogException(new EnException(ErrorCode.Err202, SectType.TANKS, data[TANK_MINVOL_INDEX]));
                    continue;
                }
 
                if (!string.IsNullOrEmpty(data[TANK_VCURVE_INDEX]))
                {
                    if ((vcurve = net.GetCurve(data[TANK_VCURVE_INDEX])) == null)
                    {
                        LogException(new EnException(ErrorCode.Err206, SectType.TANKS, data[TANK_VCURVE_INDEX]));
                    }
                }
 
                var tank = new Tank(name) { Coordinate = point };
 
                if (!string.IsNullOrEmpty(data[COMMENT_INDEX]))
                    tank.Comment = data[COMMENT_INDEX];
 
                if (!string.IsNullOrEmpty(data[TAG_INDEX]))
                    tank.Tag = data[TAG_INDEX];
 
                tank.RptFlag = false;
                tank.Elevation = el;
                tank.C0 = 0.0;
                tank.QualSource = null;
                tank.Ke = 0.0;
 
                tank.H0 = initlevel;
                tank.Hmin = minlevel;
                tank.Hmax = maxlevel;
                tank.Area = diam;
                tank.Pattern = null;
                tank.Kb = double.NaN;
 
                double area = Math.PI * diam * diam / 4.0d;
 
                tank.Vmin = area * minlevel;
                if (minvol > 0.0)
                    tank.Vmin = minvol;
 
                tank.V0 = tank.Vmin + area * (initlevel - minlevel);
                tank.Vmax = tank.Vmin + area * (maxlevel - minlevel);
 
                tank.Vcurve = vcurve;
                tank.MixModel = MixType.Mix1;
                tank.V1Max = 1.0;
 
                if (!string.IsNullOrEmpty(data[TANK_MIXMODEL_INDEX]))
                {
                    if (!data[TANK_MIXMODEL_INDEX].TryParse(out MixType type))
                    {
                        LogException(new EnException(ErrorCode.Err201, SectType.MIXING, data[TANK_MIXMODEL_INDEX]));
                    }
                    else
                    {
                        tank.MixModel = type;
 
                        if (type == MixType.Mix2 && !string.IsNullOrEmpty(data[TANK_MIXFRAC_INDEX]))
                        {
                            if (!data[TANK_MIXFRAC_INDEX].ToDouble(out double v))
                            {
                                LogException(new EnException(ErrorCode.Err209, SectType.MIXING, name));
                            }
                            else
                            {
                                if (v.IsZero())
                                    v = 1.0;
 
                                tank.V1Max = v;
                            }
                        }
 
                    }
                }
 
                if (!string.IsNullOrEmpty(data[TANK_KBULK_INDEX]))
                {
                    if (!data[TANK_KBULK_INDEX].ToDouble(out double kb))
                    {
                        LogException(new EnException(ErrorCode.Err209, SectType.REACTIONS, name));
                    }
                    else
                    {
                        tank.Kb = kb;
                    }
                }
 
                if (!string.IsNullOrEmpty(data[TANK_INITQUAL_INDEX]))
                {
                    if (!data[TANK_INITQUAL_INDEX].ToDouble(out double c0))
                    {
                        LogException(new EnException(ErrorCode.Err202, SectType.QUALITY, data[TANK_INITQUAL_INDEX]));
                    }
                    else
                    {
                        tank.C0 = c0;
                    }
                }
 
                if (!string.IsNullOrEmpty(data[TANK_SRCQUAL_INDEX]))
                {
                    Pattern pat = null;
 
                    if (!data[TANK_SRCQUAL_INDEX].ToDouble(out double c0))
                    {
                        LogException(new EnException(ErrorCode.Err202, SectType.SOURCES, data[TANK_SRCQUAL_INDEX]));
                    }
                    else if (!data[TANK_SRCTYPE_INDEX].TryParse(out SourceType type))
                    {
                        LogException(new EnException(ErrorCode.Err201, SectType.SOURCES, data[TANK_SRCTYPE_INDEX]));
                    }
                    else if (!string.IsNullOrEmpty(data[TANK_SRCPAT_INDEX]) && (pat = net.GetPattern(data[TANK_SRCPAT_INDEX])) == null)
                    {
                        LogException(new EnException(ErrorCode.Err205, SectType.SOURCES, data[TANK_SRCPAT_INDEX]));
                    }
                    else
                    {
                        tank.QualSource = new QualSource(type, c0, pat);
                    }
                }
 
                net.Nodes.Add(tank);
            }
        }
 
        private void ReadReservoirs()
        {
 
            int n = _reader.ReadInteger();
 
            if (n <= 0) return;
 
            for (int i = 0; i < n; i++)
            {
                string name = _reader.ReadString();
                var point = _reader.ReadPoint();
                var data = _reader.ReadArray(MAXNODEPROPS);
 
                if (net.GetNode(name) != null)
                {
                    LogException(new EnException(ErrorCode.Err215, SectType.RESERVOIRS, name));
                    continue;
                }
 
                var tank = new Tank(name) { Coordinate = point };
 
                if (!string.IsNullOrEmpty(data[COMMENT_INDEX]))
                    tank.Comment = data[COMMENT_INDEX];
 
                if (!string.IsNullOrEmpty(data[TAG_INDEX]))
                    tank.Tag = data[TAG_INDEX];
 
                if (!data[RES_HEAD_INDEX].ToDouble(out double head))
                {
                    LogException(new EnException(ErrorCode.Err202, SectType.RESERVOIRS, data[RES_HEAD_INDEX]));
                    continue;
                }
 
                tank.Elevation = head;
 
                if (!string.IsNullOrEmpty(data[RES_PATTERN_INDEX]))
                {
                    Pattern pat = net.GetPattern(data[RES_PATTERN_INDEX]);
 
                    if (pat == null)
                    {
                        LogException(new EnException(ErrorCode.Err205, tank.Name, data[RES_PATTERN_INDEX]));
                    }
 
                    tank.Pattern = pat;
 
                }
 
                if (!string.IsNullOrEmpty(data[RES_INITQUAL_INDEX]))
                {
                    if (!data[RES_INITQUAL_INDEX].ToDouble(out double c0))
                    {
                        LogException(new EnException(ErrorCode.Err202, SectType.RESERVOIRS, data[RES_INITQUAL_INDEX]));
                    }
                    else
                    {
                        tank.C0 = c0;
                    }
                }
 
                if (!string.IsNullOrEmpty(data[RES_SRCQUAL_INDEX]))
                {
                    Pattern pat = null;
 
                    if (!data[RES_SRCQUAL_INDEX].ToDouble(out double c0))
                    {
                        LogException(new EnException(ErrorCode.Err202, SectType.SOURCES, data[RES_SRCQUAL_INDEX]));
                    }
                    else if (!data[RES_SRCTYPE_INDEX].TryParse(out SourceType type))
                    {
                        LogException(new EnException(ErrorCode.Err201, SectType.SOURCES, data[RES_SRCTYPE_INDEX]));
                    }
                    else if (!string.IsNullOrEmpty(data[RES_SRCPAT_INDEX]) && (pat = net.GetPattern(data[RES_SRCPAT_INDEX])) == null)
                    {
                        LogException(new EnException(ErrorCode.Err205, SectType.SOURCES, data[RES_SRCPAT_INDEX]));
                    }
                    else
                    {
                        tank.QualSource = new QualSource(type, c0, pat);
                    }
                }
 
                net.Nodes.Add(tank);
            }
        }
 
        private void ReadJunctions()
        {
 
 
            int n = _reader.ReadInteger();
 
            if (n <= 0) return;
 
            for (int i = 0; i < n; i++)
            {
                string name = _reader.ReadString();
                var position = _reader.ReadPoint();
                var data = _reader.ReadArray(MAXNODEPROPS);
                var demands = _reader.ReadList();
 
                if (net.GetNode(name) != null)
                {
                    LogException(new EnException(ErrorCode.Err215, SectType.JUNCTIONS, name));
                    continue;
                }
 
                var node = new Junction(name) { Coordinate = position };
 
 
                if (!string.IsNullOrEmpty(data[COMMENT_INDEX]))
                    node.Comment = data[COMMENT_INDEX];
 
                if (!string.IsNullOrEmpty(data[TAG_INDEX]))
                    node.Tag = data[TAG_INDEX];
 
                if (!data[JUNC_ELEV_INDEX].ToDouble(out double el))
                {
                    LogException(new EnException(ErrorCode.Err202, SectType.JUNCTIONS, name));
                    continue;
                }
 
                node.Elevation = el;
 
                if (!string.IsNullOrEmpty(data[JUNC_DEMAND_INDEX]))
                {
                    if (!data[JUNC_DEMAND_INDEX].ToDouble(out double demand))
                    {
                        LogException(new EnException(ErrorCode.Err202, SectType.JUNCTIONS, name));
                        continue;
                    }
 
                    node.PrimaryDemand.Base = demand;
                }
                else
                {
                    // node.PrimaryDemand.Base = 0;
                }
 
                if (!string.IsNullOrEmpty(data[JUNC_PATTERN_INDEX]))
                {
                    Pattern pattern = net.GetPattern(data[JUNC_PATTERN_INDEX]);
                    if (pattern == null)
                    {
                        LogException(new EnException(ErrorCode.Err205, SectType.JUNCTIONS, data[JUNC_PATTERN_INDEX]));
                    }
                    else
                    {
                        node.PrimaryDemand.Pattern = pattern;
                    }
                }
 
                if (int.TryParse(data[JUNC_DMNDCAT_INDEX], out int demandCount) && demandCount > 1)
                {
                    foreach (string s in demands)
                    {
                        Pattern pat;
 
                        string[] demandData = s.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
 
                        if (demandData.Length < 2)
                        {
                            // TODO:ERROR?
                        }
                        else if (!demandData[0].ToDouble(out double @base))
                        {
                            LogException(new EnException(ErrorCode.Err202, SectType.JUNCTIONS, name));
                        }
                        else if ((pat = net.GetPattern(demandData[1])) == null)
                        {
                            LogException(new EnException(ErrorCode.Err205, SectType.JUNCTIONS, demandData[1]));
                        }
                        else
                        {
                            node.Demands.Add(new Demand(@base, pat));
                        }
 
                    }
                }
 
                if (!string.IsNullOrEmpty(data[JUNC_EMITTER_INDEX]))
                {
                    if (node.NodeType == NodeType.Tank)
                    {
                        LogException(new EnException(ErrorCode.Err209, data[JUNC_EMITTER_INDEX], name));
                    }
                    else if (!data[JUNC_EMITTER_INDEX].ToDouble(out double k) || k < 0.0)
                    {
                        LogException(new EnException(ErrorCode.Err202));
                    }
                    else
                    {
                        node.Ke = k;
                    }
                }
 
                if (!string.IsNullOrEmpty(data[JUNC_INITQUAL_INDEX]))
                {
                    if (!data[JUNC_INITQUAL_INDEX].ToDouble(out double c0))
                    {
                        LogException(new EnException(ErrorCode.Err202));
                    }
                    else
                    {
                        node.C0 = c0;
                    }
                }
 
                if (!string.IsNullOrEmpty(data[JUNC_SRCQUAL_INDEX]))
                {
                    Pattern pat = null;
 
                    if (!data[JUNC_SRCQUAL_INDEX].ToDouble(out double c0))
                    {
                        LogException(new EnException(ErrorCode.Err202, SectType.SOURCES, data[JUNC_SRCQUAL_INDEX]));
                    }
                    else if (!data[JUNC_SRCTYPE_INDEX].TryParse(out SourceType type))
                    {
                        LogException(new EnException(ErrorCode.Err201, SectType.SOURCES, data[JUNC_SRCTYPE_INDEX]));
                    }
                    else if (!string.IsNullOrEmpty(data[JUNC_SRCPAT_INDEX]) && (pat = net.GetPattern(data[JUNC_SRCPAT_INDEX])) == null)
                    {
                        LogException(new EnException(ErrorCode.Err205, SectType.SOURCES, data[JUNC_SRCPAT_INDEX]));
                    }
                    else
                    {
                        node.QualSource = new QualSource(type, c0, pat);
                    }
                }
 
                net.Nodes.Add(node);
            }
        }
 
        private void ReadCurves()
        {
            int n = _reader.ReadInteger();
 
            if (n < 0) return;
 
            for (int i = 0; i < n; i++)
            {
                var curve = new Curve(_reader.ReadString())
                {
                    Comment = _reader.ReadString()
                };
 
                string sCurveType = _reader.ReadString();
 
                try
                {
                    curve.Type = (CurveType)Enum.Parse(typeof(CurveType), sCurveType, true);
                }
                catch
                {
 
                }
 
                var xa = _reader.ReadList();
                var ya = _reader.ReadList();
 
                for (int j = 0; j < xa.Count; j++)
                    curve.Add(
                        double.Parse(xa[j], NumberFormatInfo.InvariantInfo),
                        double.Parse(ya[j], NumberFormatInfo.InvariantInfo));
 
                net.Curves.Add(curve);
            }
        }
 
        private void ReadPatterns()
        {
            int n = _reader.ReadInteger();
 
            if (n < 0) return;
 
            for (int i = 0; i < n; i++)
            {
                var pat = new Pattern(_reader.ReadString())
                {
                    Comment = _reader.ReadString()
                };
 
                var multipliers = _reader.ReadList();
 
                foreach (string s in multipliers)
                {
                    if (s.ToDouble(out double factor))
                    {
                        pat.Add(factor);
                    }
                    else
                    {
                        LogException(new EnException(ErrorCode.Err202, "PATTERNS", s));
                        // FIXME: what to do here?
                        break;
                    }
                }
 
                net.Patterns.Add(pat);
            }
        }
 
        private static TimeSpan GetSeconds(string value)
        {
            value = (value ?? string.Empty).Trim();
            if (string.IsNullOrEmpty(value)) return TimeSpan.MinValue;
 
            int index = value.LastIndexOfAny(new[] { ' ', '\t' });
 
            return index == -1
                ? Utilities.ToTimeSpan(value)
                : Utilities.ToTimeSpan(value.Substring(0, index), value.Substring(index + 1));
        }
 
        private void ReadOptions()
        {
            var options = _reader.ReadArray(MAXOPTIONS);
 
            net.AutoLength = _reader.ReadBoolean();
 
            //-----------------------------------------------------------------------------------
 
            string line = options[FLOW_UNITS_INDEX];
 
            {
                if (line.TryParse(out FlowUnitsType flag))
                {
                    net.FlowFlag = flag;
                }
                else
                {
                    LogException(new EnException(ErrorCode.Err201, SectType.OPTIONS, "UNITS " + line));
                }
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[HLOSS_FORM_INDEX];
            {
                if (line.TryParse(out HeadLossFormulaType flag))
                {
                    net.FormFlag = flag;
                }
                else
                {
                    LogException(new EnException(ErrorCode.Err201, SectType.OPTIONS, "HEADLOSS " + line));
                }
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[SPEC_GRAV_INDEX];
 
            if (line.ToDouble(out double y) && y > 0)
            {
                net.SpGrav = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.OPTIONS, "SPECIFIC GRAVITY " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[VISCOS_INDEX];
 
            if (line.ToDouble(out y))
            {
                net.Viscos = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.OPTIONS, "VISCOSITY " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[TRIALS_INDEX];
 
            if (line.ToDouble(out y) && y > 0)
            {
                net.MaxIter = (int)y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.OPTIONS, "TRIALS " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[ACCURACY_INDEX];
 
            if (line.ToDouble(out y) && y > 0)
            {
                y = Math.Max(y, 1e-5);
                y = Math.Min(y, 1e-1);
                net.HAcc = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.OPTIONS, "ACCURACY " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[UNBALANCED_INDEX];
 
            if (line.Match(Keywords.w_STOP))
            {
                net.ExtraIter = -1;
            }
            else if (line.Match(Keywords.w_CONTINUE))
            {
                net.ExtraIter = 0;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err201, SectType.OPTIONS, "UNBALANCED " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[GLOBAL_PAT_INDEX];
 
            if (!string.IsNullOrEmpty(line))
            {
                net.DefPatId = line;
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[DEMAND_MULT_INDEX];
 
            if (line.ToDouble(out y) && y > 0)
            {
                net.DMult = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.OPTIONS, "DEMAND MULTIPLIER " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[EMITTER_EXP_INDEX];
 
            if (line.ToDouble(out y) && y > 0)
            {
                net.QExp = 1 / y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.OPTIONS, "EMITTER EXPONENT " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            {
                line = options[STATUS_RPT_INDEX];
 
                if (line.TryParse(out StatusLevel flag) && y > 0)
                {
                    net.StatFlag = flag;
                }
                else
                {
                    LogException(new EnException(ErrorCode.Err201, SectType.REPORT, "STATUS " + line));
                }
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[QUAL_PARAM_INDEX];
 
            {
                net.QualFlag = line.TryParse(out QualType flag) ? flag : QualType.Chem;
 
                string units = options[QUAL_UNITS_INDEX];
 
                switch (net.QualFlag)
                {
                    case QualType.Chem:
                        net.ChemName = line;
                        if (!string.IsNullOrEmpty(units)) net.ChemUnits = units;
                        break;
 
                    case QualType.Trace:
                        // FIXME: parse nodes first!
                        Node node = net.GetNode(options[TRACE_NODE_INDEX]);
 
                        if (node == null)
                        {
                            LogException(new EnException(ErrorCode.Err212, SectType.OPTIONS, "QUALITY TRACE " + line));
                        }
                        else
                        {
                            net.TraceNode = node.Name;
                            net.ChemName = Keywords.u_PERCENT;
                            net.ChemUnits = units;
                        }
 
                        break;
 
                    case QualType.Age:
                        net.ChemName = Keywords.w_AGE;
                        net.ChemUnits = Keywords.u_HOURS;
                        break;
                }
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[DIFFUS_INDEX];
 
            if (line.ToDouble(out y) && y >= 0)
            {
                net.Diffus = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err201, SectType.OPTIONS, "DIFFUSIVITY " + line));
            }
 
 
            //-----------------------------------------------------------------------------------
 
            line = options[QUAL_TOL_INDEX];
 
            if (line.ToDouble(out y) && y > 0)
            {
                net.QTol = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err201, SectType.OPTIONS, "QTOL " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[BULK_ORDER_INDEX];
 
            if (line.ToDouble(out y))
            {
                net.BulkOrder = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.REACTIONS, "ORDER BULK " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[WALL_ORDER_INDEX];
 
            if (string.Equals(line, "Zero", StringComparison.OrdinalIgnoreCase))
            {
                net.WallOrder = 0;
            }
            else if (string.Equals(line, "First", StringComparison.OrdinalIgnoreCase))
            {
                net.WallOrder = 1;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.REACTIONS, "ORDER WALL " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[GLOBAL_KBULK_INDEX];
 
            if (line.ToDouble(out y))
            {
                net.KBulk = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.REACTIONS, "GLOBAL BULK " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[GLOBAL_KWALL_INDEX];
 
            if (line.ToDouble(out y))
            {
                net.KWall = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.REACTIONS, "GLOBAL WALL " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[LIMIT_QUAL_INDEX];
 
            if (line.ToDouble(out y))
            {
                net.CLimit = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.REACTIONS, "LIMITING POTENTIAL " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[ROUGH_CORREL_INDEX];
 
            if (line.ToDouble(out y))
            {
                net.RFactor = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.REACTIONS, "ROUGHNESS CORRELATION " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[DURATION_INDEX];
            TimeSpan t;
 
            if ((t = GetSeconds(line)) != TimeSpan.MinValue)
            {
                net.Duration = t;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.TIMES, "DURATION " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[HYD_TSTEP_INDEX];
 
            if ((t = GetSeconds(line)) != TimeSpan.MinValue)
            {
                net.HStep = t;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.TIMES, "HYDRAULIC TIMESTEP " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[QUAL_TSTEP_INDEX];
 
            if ((t = GetSeconds(line)) != TimeSpan.MinValue)
            {
                //Check if Quality Time Step is in hours instead of minutes
                net.QStep = t > TimeSpan.FromHours(1) ? new TimeSpan(t.Ticks / 60) : t;  //? BUG?
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.TIMES, "QUALITY TIMESTEP " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[PAT_TSTEP_INDEX];
 
            if ((t = GetSeconds(line)) != TimeSpan.MinValue)
            {
                net.PStep = t;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.TIMES, "PATTERN TIMESTEP " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[PAT_START_INDEX];
 
            if ((t = GetSeconds(line)) != TimeSpan.MinValue)
            {
                net.PStart = t;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.TIMES, "PATTERN START " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[RPT_TSTEP_INDEX];
 
            if ((t = GetSeconds(line)) != TimeSpan.MinValue)
            {
                net.RStep = t;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.TIMES, "REPORT TIMESTEP " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[RPT_START_INDEX];
 
            if ((t = GetSeconds(line)) != TimeSpan.MinValue)
            {
                net.RStart = t;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.TIMES, "REPORT START " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[START_TIME_INDEX];
 
            if ((t = GetSeconds(line)) != TimeSpan.MinValue)
            {
                net.Tstart = t.TimeOfDay();
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.TIMES, "START CLOCKTIME " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[TIME_STAT_INDEX];
            {
                if (line.TryParse(out TstatType flag))
                {
                    net.TstatFlag = flag;
                }
                else
                {
                    LogException(new EnException(ErrorCode.Err213, SectType.TIMES, "STATISTIC " + line));
                }
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[EFFIC_INDEX];
 
            if (line.ToDouble(out y) && y > 0)
            {
                net.EPump = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.ENERGY, "GLOBAL EFFIC " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[EPRICE_INDEX];
 
            if (line.ToDouble(out y))
            {
                net.ECost = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.ENERGY, "GLOBAL PRICE " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[EPRICE_INDEX];
 
            if (line.ToDouble(out y))
            {
                net.ECost = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.ENERGY, "GLOBAL PRICE " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[PRICE_PAT_INDEX];
 
            if (!string.IsNullOrEmpty(line))
            {
                Pattern pat = net.GetPattern(line);
 
                if (pat != null)
                {
                    net.EPatId = pat.Name;
                }
                else
                {
                    LogException(new EnException(ErrorCode.Err213, SectType.ENERGY, "GLOBAL PATTERN " + line));
                }
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[DMND_CHARGE_INDEX];
 
            if (line.ToDouble(out y))
            {
                net.DCost = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.ENERGY, "DEMAND CHARGE " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[CHECK_FREQ_INDEX];
 
            if (line.ToDouble(out y) && y > 0)
            {
                net.CheckFreq = (int)y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.OPTIONS, "CHECKFREQ " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[MAX_CHECK_INDEX];
 
            if (line.ToDouble(out y) && y > 0)
            {
                net.MaxCheck = (int)y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.OPTIONS, "MAXCHECK " + line));
            }
 
            //-----------------------------------------------------------------------------------
 
            line = options[DAMP_LIMIT_INDEX];
 
            if (line.ToDouble(out y))
            {
                net.DampLimit = y;
            }
            else
            {
                LogException(new EnException(ErrorCode.Err213, SectType.OPTIONS, "DAMPLIMIT " + line));
            }
 
        }
 
        /// <summary>Delphi TReader partial implementation.</summary>
        /// <remarks>TReader is a specialized filer that reads component data from an associated stream.</remarks>
        private class Reader
        {
            private readonly BinaryReader _br;
 
            public Reader(Stream stream, Encoding enc) { _br = new BinaryReader(stream, enc); }
 
            /// <summary>
            /// Reads the type of the next item on the reader object's stream and returns
            /// with the stream positioned after the value-type indicator.
            /// </summary>
            private TValueType ReadValue() { return (TValueType)_br.ReadByte(); }
 
            /// <summary>
            /// Returns the type of the next item in the reader object's stream without 
            /// moving the position of the stream.
            /// </summary>
            /// <returns></returns>
            private TValueType NextValue() { return (TValueType)unchecked((byte)_br.PeekChar()); }
 
            /// <summary>Reads a tagged string value written by WriteString from the reader object's stream and returns its contents.</summary>
            public string ReadString()
            {
                int len;
 
                switch (ReadValue())
                {
                    case TValueType.vaString:
                        // pascal short string
                        len = _br.ReadByte();
                        return Encoding.ASCII.GetString(_br.ReadBytes(len));
 
                    case TValueType.vaLString:
                        len = _br.ReadInt32();
                        return Encoding.ASCII.GetString(_br.ReadBytes(len));
 
                    case TValueType.vaWString:
                        len = _br.ReadInt32();
                        return Encoding.Unicode.GetString(_br.ReadBytes(len << 1));
 
                    case TValueType.vaUTF8String:
                        len = _br.ReadInt32();
                        return Encoding.UTF8.GetString(_br.ReadBytes(len));
 
                    default:
                        throw new InvalidDataException();
                }
            }
 
            /// <summary>
            /// Reads an integer-type number from the reader object's stream and returns its value.
            /// </summary>
            public int ReadInteger()
            {
                var vt = ReadValue();
                switch (vt)
                {
                    case TValueType.vaInt8:
                        return _br.ReadSByte();
                    case TValueType.vaInt16:
                        return _br.ReadInt16();
                    case TValueType.vaInt32:
                        return _br.ReadInt32();
                    default:
                        throw new InvalidDataException();
                }
            }
 
            public List<string> ReadList()
            {
                var result = new List<string>();
 
                var tv = ReadValue();
                if (tv != TValueType.vaList)
                    throw new InvalidDataException();
 
                while (NextValue() != TValueType.vaNull)
                    result.Add(ReadString());
 
                ReadValue();
 
                return result;
            }
 
            /// <summary>
            /// Reads a boolean from the reader object's stream and returns that boolean value.
            /// </summary>
            public bool ReadBoolean() { return ReadValue() == TValueType.vaTrue; }
 
            /// <summary>
            /// Reads 10-byte extended value from file.
            /// </summary>
            /// <returns></returns>
            private double ReadExtended()
            {
                ulong mantissa = _br.ReadUInt64();
                int expon = _br.ReadInt16();
 
                int sign = (expon & 0x8000) == 0x00 ? 1 : -1;
                expon &= 0x7FFF;
 
                switch (expon)
                {
                    case 0:
                        return mantissa == 0 ? 0 : double.NaN;
 
                    case 0x7FFF:
                        // Infinity or NaN 
 
                        // var integral = mantissa >> 63;
                        mantissa &= 0x7FFFFFFFFFFFFFFF;
 
                        if (mantissa == 0)
                            return sign / 0.0; // return double.PositiveInfinity * sign;
 
                        return double.NaN;
 
                    default:
                        expon -= 16383;
 
                        double f = (mantissa >> 32) * Math.Pow(2, expon - 31);
                        f += (mantissa & 0xFFFFFFFF) * Math.Pow(2, expon - 63);
                        return sign < 0 ? -f : f;
                }
            }
 
            /// <summary>
            /// Reads a floating-point number from the reader object's stream and returns its value.
            /// </summary>
            private double ReadFloat()
            {
                switch (ReadValue())
                {
                    case TValueType.vaExtended:
                        return ReadExtended();
 
                    default:
                        _br.BaseStream.Position--;
                        return ReadInt64();
                }
            }
 
            /// <summary>
            /// Reads an 64-bit integer from the reader object's stream and returns its value.
            /// </summary>
            private long ReadInt64()
            {
                switch (NextValue())
                {
                    case TValueType.vaInt64:
                        ReadValue();
                        return _br.ReadInt64();
 
                    default:
                        return ReadInteger();
                }
 
 
            }
 
            public string[] ReadArray(int ubound)
            {
                ubound++;
 
                int len = ReadInteger();
                // if (len > maxLen) len = maxLen;
 
                string[] result = new string[ubound];
 
                for (int i = 0; i < len; i++)
                    if (i < ubound)
                        result[i] = ReadString();
                    else
                    {
                        // skip remaining strings
                        ReadString();
                    }
 
                return result;
            }
 
            public EnPoint[] ReadVertices()
            {
                int n = ReadInteger();
                EnPoint[] points = new EnPoint[n];
 
                for (int i = 0; i < n; i++)
                    points[i] = ReadPoint();
 
                // if (n > 1) Array.Reverse(points);
                return points;
            }
 
            public EnPoint ReadPoint()
            {
                return new EnPoint(ReadFloat(), ReadFloat());
            }
 
            // ReSharper disable InconsistentNaming
            /// <summary>TValueType defines the kinds of values written to and read from filer objects.</summary>
            private enum TValueType : byte
            {
                ///<summary>identifies the type as the const Variant Null.</summary>
                vaNull,
 
                ///<summary>identifies the type as a list of tagged items ending with a NULL pointer.</summary>
 
                vaList,
 
                ///<summary>identifies the type as an 8-bit integer.</summary>
                vaInt8,
 
                ///<summary>identifies the type as a 16-bit integer.</summary>
                vaInt16,
 
                ///<summary>identifies the type as a 32-bit integer.</summary>
                vaInt32,
 
                ///<summary>identifies the type as a float or long double.</summary>
                vaExtended,
 
                ///<summary>identifies the type as a short string</summary>
                vaString,
 
                ///<summary>identifies the type as an identifier string.</summary>
                vaIdent,
 
                ///<summary>identifies the type as the boolean false.</summary>
                vaFalse,
 
                ///<summary>identifies the type as the boolean true.</summary>
                vaTrue,
 
                ///<summary>identifies the type as a block of binary preceded by a length count.</summary>
                vaBinary,
 
                ///<summary>identifies the type as a set.</summary>
                vaSet,
 
                ///<summary>identifies the type as an AnsiString (long string).</summary>
                vaLString,
 
                ///<summary>identifies the type as nil (Delphi) or NULL (C++).</summary>
                vaNil,
 
                ///<summary>identifies the type as a TCollection.</summary>
                vaCollection,
 
                ///<summary>identifies the type as a Single (float).</summary>
                vaSingle,
 
                ///<summary>identifies the type as a Currency.</summary>
                vaCurrency,
 
                ///<summary>identifies the type as a Date.</summary>
                vaDate,
 
                ///<summary>identifies the type as a WideString.</summary>
                vaWString,
 
                ///<summary>identifies the type as a 64-bit integer.</summary>
                vaInt64,
 
                ///<summary>identifies the type as a UTF8String.</summary>
                vaUTF8String
            }
            // ReSharper restore InconsistentNaming
        }
    }
 
}