cloudflight
2024-12-24 801a451429b294a435e1c69db55c70e20c45444d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
/*
 ******************************************************************************
 Project:      OWA HYDRAULIC
 Version:      2.2
 Module:       epanet.c
 Description:  implementation of HYDRAULIC's API functions
 Authors:      see AUTHORS
 Copyright:    see AUTHORS
 License:      see LICENSE
 Last Updated: 11/15/2019
 ******************************************************************************
*/
 
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include <math.h>
 
#include "epanet2_2.h"
#include "types.h"
#define  EXTERN  extern
#include "funcs.h"
#include "text.h"
#include "enumstxt.h"
 
#if W30
#include "vars.h"
#define snprintf _snprintf
#endif
 
/********************************************************************
 
    Project Functions
 
********************************************************************/
 
int DLLEXPORT EN_createproject(EN_Project *p)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  p = pointer to a new HYDRAULIC project
**  Returns: error code
**  Purpose: creates a new HYDRAULIC project
**----------------------------------------------------------------
*/
{
    struct Project *project = (struct Project *)calloc(1, sizeof(struct Project));
    if (project == NULL) return -1;
    getTmpName(project->TmpHydFname);
    getTmpName(project->TmpOutFname);
    getTmpName(project->TmpStatFname);
    *p = project;
    return 0;
}
 
 
 
int DLLEXPORT EN_deleteproject(EN_Project p)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  none
**  Returns: error code
**  Purpose: deletes an HYDRAULIC project
**----------------------------------------------------------------
*/
{
    if (p == NULL) return -1;
    if (p->Openflag) {
      EN_close(p);
    }
    remove(p->TmpHydFname);
    remove(p->TmpOutFname);
    remove(p->TmpStatFname);
    free(p);
    return 0;
}
 
 
 
int DLLEXPORT EN_runproject(EN_Project p, const char *inpFile,
                            const char *rptFile, const char *outFile,
                            void (*pviewprog)(char *))
/*------------------------------------------------------------------------
**   Input:   inpFile = name of HYDRAULIC formatted input file
**            rptFile = name of report file
**            outFile = name of binary output file
**            pviewprog = see note below
**   Output:  none
**   Returns: error code
**   Purpose: runs a complete HYDRAULIC simulation
**
**  The pviewprog() argument is a pointer to a callback function
**  that takes a character string (char *) as its only parameter.
**  The function would reside in and be used by the calling
**  program to display the progress messages that HYDRAULIC generates
**  as it carries out its computations. If this feature is not
**  needed then the argument should be NULL.
**-------------------------------------------------------------------------
*/
{
    int errcode = 0;
 
    // Read in project data from an input file
    ERRCODE(EN_open(p, inpFile, rptFile, outFile));
    p->viewprog = pviewprog;
 
    // Solve for system hydraulics
    if (p->outfile.Hydflag != USE)
    {
      ERRCODE(EN_solveH(p));
    }
 
    // Solve for system water quality
    ERRCODE(EN_solveQ(p));
 
    // Write a formatted output report
    ERRCODE(EN_report(p));
    EN_close(p);
 
    // Return any error or warning code
    if (p->Warnflag) errcode = MAX(errcode, p->Warnflag);
    return errcode;
}
 
 
 
int DLLEXPORT EN_init(EN_Project p, const char *rptFile, const char *outFile,
                      int unitsType, int headLossType)
/*----------------------------------------------------------------
 **  Input:   rptFile = name of report file
 **           outFile = name of binary output file
 **           unitsType = type of flow units (see FlowUnitsType)
 **           headLossType = type of head loss formula (see HeadLossType)
 **  Output:  none
 **  Returns: error code
 **  Purpose: initializes an HYDRAULIC project that isn't opened with
 **           an input file
 **----------------------------------------------------------------
 */
{
    int errcode = 0;
 
    // Set system flags
    p->Openflag = FALSE;
    p->hydraul.OpenHflag = FALSE;
    p->quality.OpenQflag = FALSE;
    p->outfile.SaveHflag = FALSE;
    p->outfile.SaveQflag = FALSE;
    p->Warnflag = FALSE;
    p->report.Messageflag = TRUE;
    p->report.Rptflag = 1;
 
    // Check for valid arguments
    if (unitsType < 0 || unitsType > CMD) return 251;
    if (headLossType < 0 || headLossType > CM) return 251;
 
    // Open files
    errcode = openfiles(p, "", rptFile, outFile);
 
    // Initialize memory used for project's data objects
    initpointers(p);
    ERRCODE(netsize(p));
    ERRCODE(allocdata(p));
    if (errcode) return (errcode);
 
    // Set analysis options
    setdefaults(p);
    p->parser.Flowflag = unitsType;
    p->hydraul.Formflag = headLossType;
 
    // Perform additional initializations
    adjustdata(p);
    initreport(&p->report);
    initunits(p);
    inittanks(p);
    convertunits(p);
    p->parser.MaxPats = 0;
    p->Openflag = TRUE;
    return errcode;
}
 
int DLLEXPORT EN_open(EN_Project p, const char *inpFile, const char *rptFile,
                      const char *outFile)
/*----------------------------------------------------------------
 **  Input:   inpFile = name of input file
 **           rptFile = name of report file
 **           outFile = name of binary output file
 **  Output:  none
 **  Returns: error code
 **  Purpose: opens an HYDRAULIC input file & reads in network data
 **----------------------------------------------------------------
 */
{
  int errcode = 0;
 
  // Set system flags
  p->Openflag = FALSE;
  p->hydraul.OpenHflag = FALSE;
  p->quality.OpenQflag = FALSE;
  p->outfile.SaveHflag = FALSE;
  p->outfile.SaveQflag = FALSE;
  p->Warnflag = FALSE;
  p->report.Messageflag = TRUE;
  p->report.Rptflag = 1;
 
  // Initialize data arrays to NULL
  initpointers(p);
 
  // Open input & report files
  ERRCODE(openfiles(p, inpFile, rptFile, outFile));
  if (errcode > 0)
  {
    errmsg(p, errcode);
    return errcode;
  }
 
  // Allocate memory for project's data arrays
  writewin(p->viewprog, FMT100);
  ERRCODE(netsize(p));
  ERRCODE(allocdata(p));
 
  // Read input data
  ERRCODE(getdata(p));
 
  // Close input file
  if (p->parser.InFile != NULL)
  {
      fclose(p->parser.InFile);
      p->parser.InFile = NULL;
  }
 
  // If using previously saved hydraulics file then open it
  if (p->outfile.Hydflag == USE) ERRCODE(openhydfile(p));
 
  // Write input summary to report file
  if (!errcode)
  {
    if (p->report.Summaryflag) writesummary(p);
    writetime(p, FMT104);
    p->Openflag = TRUE;
  }
  else errmsg(p, errcode);
  return errcode;
}
 
int DLLEXPORT EN_gettitle(EN_Project p, char *line1, char *line2, char *line3)
/*----------------------------------------------------------------
**  Input:   None
**  Output:  line1, line2, line3 = project's title lines
**  Returns: error code
**  Purpose: retrieves the title lines of the project
**----------------------------------------------------------------
*/
{
    if (!p->Openflag) return 102;
    strncpy(line1, p->Title[0], TITLELEN);
    strncpy(line2, p->Title[1], TITLELEN);
    strncpy(line3, p->Title[2], TITLELEN);
    return 0;
}
 
int DLLEXPORT EN_settitle(EN_Project p, char *line1, char *line2, char *line3)
/*----------------------------------------------------------------
**  Input:  line1, line2, line3 = project's title lines
**  Returns: error code
**  Purpose: sets the title lines of the project
**----------------------------------------------------------------
*/
{
    if (!p->Openflag) return 102;
    strncpy(p->Title[0], line1, TITLELEN);
    strncpy(p->Title[1], line2, TITLELEN);
    strncpy(p->Title[2], line3, TITLELEN);
    return 0;
}
 
/********************************************************************
 
    Project Functions
 
********************************************************************/
 
int DLLEXPORT EN_setprojectreport(EN_Project p, int report)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  p = pointer to a new HYDRAULIC project
**  Returns: error code
**  Purpose: creates a new HYDRAULIC project
**----------------------------------------------------------------
*/
{
    if (!p->Openflag) return 102;
    p->isReport = report;
    return 0;
}
 
int DLLEXPORT EN_getcomment(EN_Project p, int object, int index, char *comment)
/*----------------------------------------------------------------
**  Input:   object = a type of object (see EN_ObjectType)
**           index = the object's index
**  Output:  comment = the object's descriptive comment
**  Returns: error code
**  Purpose: Retrieves an object's descriptive comment
**----------------------------------------------------------------
*/
{
    return getcomment(&p->network, object, index, comment);
}
 
int  DLLEXPORT EN_setcomment(EN_Project p, int object, int index, char *comment)
/*----------------------------------------------------------------
**  Input:   object = a type of object (see EN_ObjectType)
**           index = the object's index
**           comment =  a descriptive comment to assign
**  Returns: error code
**  Purpose: Assigns a descriptive comment to an object
**----------------------------------------------------------------
*/
{
    return setcomment(&p->network, object, index, comment);
}
 
int DLLEXPORT EN_getcount(EN_Project p, int object, int *count)
/*----------------------------------------------------------------
**  Input:   object = type of object to count (see EN_CountType)
**  Output:  count = number of objects of the specified type
**  Returns: error code
**  Purpose: Retrieves number of network objects of a given type
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    *count = 0;
    if (!p->Openflag) return 102;
    switch (object)
    {
    case EN_NODECOUNT:
        *count = net->Nnodes;
        break;
    case EN_TANKCOUNT:
        *count = net->Ntanks;
        break;
    case EN_LINKCOUNT:
        *count = net->Nlinks;
        break;
    case EN_PATCOUNT:
        *count = net->Npats;
        break;
    case EN_CURVECOUNT:
        *count = net->Ncurves;
        break;
    case EN_CONTROLCOUNT:
        *count = net->Ncontrols;
        break;
    case EN_RULECOUNT:
        *count = net->Nrules;
        break;
    default:
        return 251;
    }
    return 0;
}
 
int DLLEXPORT EN_saveinpfile(EN_Project p, const char *filename)
/*----------------------------------------------------------------
 **  Input:   filename = name of file to which project is saved
 **  Output:  none
 **  Returns: error code
 **  Purpose: saves project to an HYDRAULIC formatted file
 **----------------------------------------------------------------
 */
{
  if (!p->Openflag) return 102;
  return saveinpfile(p, filename);
}
 
int DLLEXPORT EN_close(EN_Project p)
/*----------------------------------------------------------------
 **  Input:   none
 **  Output:  none
 **  Returns: error code
 **  Purpose: frees all memory & files used by a project
 **----------------------------------------------------------------
 */
{
    // Free all project data
    //[CloudflightÐÞ¸Ä]2023-11-17 
    //if (p->Openflag) writetime(p, FMT105);
    freedata(p);
 
    // Close output file
    closeoutfile(p);
 
    // Close input file
    if (p->parser.InFile != NULL)
    {
        fclose(p->parser.InFile);
        p->parser.InFile = NULL;
    }
 
    // Close report file
    if (p->report.RptFile != NULL && p->report.RptFile != stdout)
    {
        fclose(p->report.RptFile);
        p->report.RptFile = NULL;
    }
 
    // Close hydraulics file
    if (p->outfile.HydFile != NULL)
    {
        fclose(p->outfile.HydFile);
        p->outfile.HydFile = NULL;
    }
 
    // Reset system flags
    p->Openflag = FALSE;
    p->hydraul.OpenHflag = FALSE;
    p->outfile.SaveHflag = FALSE;
    p->quality.OpenQflag = FALSE;
    p->outfile.SaveQflag = FALSE;
    return 0;
}
 
/********************************************************************
 
    Hydraulic Analysis Functions
 
 ********************************************************************/
 
int DLLEXPORT EN_solveH(EN_Project p)
/*----------------------------------------------------------------
 **  Input:   none
 **  Output:  none
 **  Returns: error code
 **  Purpose: solves for network hydraulics in all time periods
 **----------------------------------------------------------------
 */
{
    int errcode;
    long t, tstep;
 
    // Open hydraulics solver
    errcode = EN_openH(p);
    if (!errcode)
    {
        // Initialize hydraulics
        errcode = EN_initH(p, EN_SAVE);
 
        // Analyze each hydraulic time period
        if (!errcode) do
        {
            // Display progress message
            sprintf(p->Msg, "%-10s",
                    clocktime(p->report.Atime, p->times.Htime));
            sprintf(p->Msg, FMT101, p->report.Atime);
            writewin(p->viewprog, p->Msg);
 
            // Solve for hydraulics & advance to next time period
            tstep = 0;
            ERRCODE(EN_runH(p, &t));
            ERRCODE(EN_nextH(p, &tstep));
        } while (tstep > 0);
    }
 
    // Close hydraulics solver
    EN_closeH(p);
    errcode = MAX(errcode, p->Warnflag);
    return errcode;
}
 
int DLLEXPORT EN_saveH(EN_Project p)
/*----------------------------------------------------------------
 **  Input:   none
 **  Output:  none
 **  Returns: error code
 **  Purpose: saves hydraulic results to binary file
 **
 **  Must be called before EN_report() if no WQ simulation made.
 **  Should not be called if EN_solveQ() will be used.
 **----------------------------------------------------------------
 */
{
    int tmpflag;
    int errcode;
 
    // Check if hydraulic results exist
    if (!p->outfile.SaveHflag) return 104;
 
    // Temporarily turn off WQ analysis
    tmpflag = p->quality.Qualflag;
    p->quality.Qualflag = NONE;
 
    // Call WQ solver to simply transfer results from Hydraulics file
    // to Output file at fixed length reporting time intervals
    errcode = EN_solveQ(p);
 
    // Restore WQ analysis option
    p->quality.Qualflag = tmpflag;
    if (errcode) errmsg(p, errcode);
    return errcode;
}
 
int DLLEXPORT EN_openH(EN_Project p)
/*----------------------------------------------------------------
 **  Input:   none
 **  Output:  none
 **  Returns: error code
 **  Purpose: opens a project's hydraulic solver
 **----------------------------------------------------------------
 */
{
    int errcode = 0;
 
    // Check that input data exists
    p->hydraul.OpenHflag = FALSE;
    p->outfile.SaveHflag = FALSE;
    if (!p->Openflag) return 102;
 
    // Check that previously saved hydraulics file not in use
    if (p->outfile.Hydflag == USE) return 107;
 
    // Open hydraulics solver
    ERRCODE(openhyd(p));
    if (!errcode) p->hydraul.OpenHflag = TRUE;
    else errmsg(p, errcode);
    return errcode;
}
 
int DLLEXPORT EN_initH(EN_Project p, int initFlag)
/*----------------------------------------------------------------
 **  Input:   initFlag = 2-digit flag where 1st (left) digit indicates
 **                      if link flows should be re-initialized (1) or
 **                      not (0) and 2nd digit indicates if hydraulic
 **                      results should be saved to file (1) or not (0)
 **  Output:  none
 **  Returns: error code
 **  Purpose: initializes a project's hydraulic solver
 **----------------------------------------------------------------
 */
{
    int errcode = 0;
    int sflag, fflag;
 
    // Reset status flags
    p->outfile.SaveHflag = FALSE;
    p->Warnflag = FALSE;
 
    // Get values of save-to-file flag and reinitialize-flows flag
    fflag = initFlag / EN_INITFLOW;
    sflag = initFlag - fflag * EN_INITFLOW;
 
    // Check that hydraulics solver was opened
    if (!p->hydraul.OpenHflag) return 103;
 
    // Open hydraulics file if requested
    p->outfile.Saveflag = FALSE;
    if (sflag > 0)
    {
        errcode = openhydfile(p);
        if (!errcode) p->outfile.Saveflag = TRUE;
        else
        {
            errmsg(p, errcode);
            return errcode;
        }
    }
 
    // Initialize hydraulics solver
    inithyd(p, fflag);
    //if (p->report.Statflag > 0) writeheader(p, STATHDR, 0);
    return errcode;
}
 
int DLLEXPORT EN_runH(EN_Project p, long *currentTime)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  currentTime = current elapsed time (sec)
**  Returns: error code
**  Purpose: solves network hydraulics at current time point
**----------------------------------------------------------------
*/
{
    int errcode;
 
    *currentTime = 0;
    if (!p->hydraul.OpenHflag) return 103;
    errcode = runhyd(p, currentTime);
    if (errcode) errmsg(p, errcode);
    return errcode;
}
 
int DLLEXPORT EN_nextH(EN_Project p, long *tStep)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  tStep = next hydraulic time step to take (sec)
**  Returns: error code
**  Purpose: determines the time step until the next hydraulic event
**----------------------------------------------------------------
*/
{
    int errcode;
    *tStep = 0;
    if (!p->hydraul.OpenHflag) return 103;
    errcode = nexthyd(p, tStep);
    if (errcode) errmsg(p, errcode);
    else if (p->outfile.Saveflag && *tStep == 0) p->outfile.SaveHflag = TRUE;
    return errcode;
}
 
int DLLEXPORT EN_closeH(EN_Project p)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  none
**  Returns: error code
**  Purpose: closes a project's hydraulic solver
**----------------------------------------------------------------
*/
{
  if (!p->Openflag) return 102;
  if (p->hydraul.OpenHflag) closehyd(p);
  p->hydraul.OpenHflag = FALSE;
  return 0;
}
 
int DLLEXPORT EN_savehydfile(EN_Project p, const char *filename)
/*----------------------------------------------------------------
**  Input:   filename = name of file to which hydraulic results are saved
**  Output:  none
**  Returns: error code
**  Purpose: saves results from a scratch hydraulics file to a
**           permanent one
**----------------------------------------------------------------
*/
{
    FILE *f;
    FILE *HydFile;
    int c;
 
    // Check that hydraulics results exist
    if (p->outfile.HydFile == NULL || !p->outfile.SaveHflag) return 104;
 
    // Open the permanent hydraulics file
    if ((f = fopen(filename, "w+b")) == NULL) return 305;
 
    // Copy from the scratch file to f
    HydFile = p->outfile.HydFile;
    fseek(HydFile, 0, SEEK_SET);
    while ((c = fgetc(HydFile)) != EOF) fputc(c, f);
    fclose(f);
    return 0;
}
 
int DLLEXPORT EN_usehydfile(EN_Project p, const char *filename)
/*----------------------------------------------------------------
**  Input:   filename = name of previously saved hydraulics file
**  Output:  none
**  Returns: error code
**  Purpose: uses contents of a previously saved hydraulics file to
**           run a water quality analysis
**----------------------------------------------------------------
*/
{
    int errcode;
 
    // Check that project was opened & hydraulic solver is closed
    if (!p->Openflag) return 102;
    if (p->hydraul.OpenHflag) return 108;
 
    // Try to open hydraulics file
    strncpy(p->outfile.HydFname, filename, MAXFNAME);
    p->outfile.Hydflag = USE;
    p->outfile.SaveHflag = TRUE;
    errcode = openhydfile(p);
 
    // If error, then reset flags
    if (errcode)
    {
        strcpy(p->outfile.HydFname, "");
        p->outfile.Hydflag = SCRATCH;
        p->outfile.SaveHflag = FALSE;
    }
    return errcode;
}
 
/********************************************************************
 
    Water Quality Analysis Functions
 
 ********************************************************************/
 
int DLLEXPORT EN_solveQ(EN_Project p)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  none
**  Returns: error code
**  Purpose: solves for network water quality in all time periods
**----------------------------------------------------------------
*/
{
    int errcode;
    long t, tstep;
 
    // Open WQ solver
    errcode = EN_openQ(p);
    if (!errcode)
    {
        // Initialize WQ solver
        errcode = EN_initQ(p, EN_SAVE);
        if (!p->quality.Qualflag) writewin(p->viewprog, FMT106);
 
        // Analyze each hydraulic period
        if (!errcode) do
        {
            // Display progress message
            sprintf(p->Msg, "%-10s",
                    clocktime(p->report.Atime, p->times.Htime));
            if (p->quality.Qualflag)
            {
                sprintf(p->Msg, FMT102, p->report.Atime);
                writewin(p->viewprog, p->Msg);
            }
 
            // Retrieve current hydraulic results & update water quality
            // to start of next time period
            tstep = 0;
            ERRCODE(EN_runQ(p, &t));
            ERRCODE(EN_nextQ(p, &tstep));
        } while (tstep > 0);
    }
 
    // Close WQ solver
    EN_closeQ(p);
    return errcode;
}
 
int DLLEXPORT EN_openQ(EN_Project p)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  none
**  Returns: error code
**  Purpose: opens a project's water quality solver
**----------------------------------------------------------------
*/
{
    int errcode = 0;
 
    // Check that hydraulics results exist
    p->quality.OpenQflag = FALSE;
    p->outfile.SaveQflag = FALSE;
    if (!p->Openflag) return 102;
    if (!p->hydraul.OpenHflag && !p->outfile.SaveHflag) return 104;
 
    // Open water quality solver
    ERRCODE(openqual(p));
    if (!errcode) p->quality.OpenQflag = TRUE;
    else errmsg(p, errcode);
    return errcode;
}
 
int DLLEXPORT EN_initQ(EN_Project p, int saveFlag)
/*----------------------------------------------------------------
**  Input:   saveFlag = flag indicating if results should be saved
**                      to the binary output file or not
**  Output:  none
**  Returns: error code
**  Purpose: initializes the water quality solver
**----------------------------------------------------------------
*/
{
    int errcode = 0;
 
    if (!p->quality.OpenQflag) return 105;
    initqual(p);
    p->outfile.SaveQflag = FALSE;
    p->outfile.Saveflag = FALSE;
    if (saveFlag)
    {
        errcode = openoutfile(p);
        if (!errcode) p->outfile.Saveflag = TRUE;
    }
    return errcode;
}
 
int DLLEXPORT EN_runQ(EN_Project p, long *currentTime)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  currentTime = current simulation time (sec)
**  Returns: error code
**  Purpose: retrieves current hydraulic results and saves current
**           results to file.
**----------------------------------------------------------------
*/
{
    int errcode;
 
    *currentTime = 0;
    if (!p->quality.OpenQflag) return 105;
    errcode = runqual(p, currentTime);
    if (errcode) errmsg(p, errcode);
    return errcode;
}
 
int DLLEXPORT EN_nextQ(EN_Project p, long *tStep)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  tStep = time step over which water quality is updated (sec)
**  Returns: error code
**  Purpose: updates water quality throughout the network until
**           next hydraulic event occurs Hydraulic Status:
**----------------------------------------------------------------
*/
{
    int errcode;
 
    *tStep = 0;
    if (!p->quality.OpenQflag) return 105;
    errcode = nextqual(p, tStep);
    if (!errcode && p->outfile.Saveflag && *tStep == 0)
    {
        p->outfile.SaveQflag = TRUE;
    }
    if (errcode) errmsg(p, errcode);
    return errcode;
}
 
int DLLEXPORT EN_stepQ(EN_Project p, long *timeLeft)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  timeLeft = amount of simulation time remaining (sec)
**  Returns: error code
**  Purpose: updates water quality throughout the network over
**           fixed time step
**----------------------------------------------------------------
*/
{
    int errcode;
 
    *timeLeft = 0;
    if (!p->quality.OpenQflag) return 105;
    errcode = stepqual(p, timeLeft);
    if (!errcode && p->outfile.Saveflag && *timeLeft == 0)
    {
        p->outfile.SaveQflag = TRUE;
    }
    if (errcode) errmsg(p, errcode);
    return errcode;
}
 
int DLLEXPORT EN_closeQ(EN_Project p)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  none
**  Returns: error code
**  Purpose: closes a project's water quality solver
**----------------------------------------------------------------
*/
{
    if (!p->Openflag) return 102;
    closequal(p);
    p->quality.OpenQflag = FALSE;
    closeoutfile(p);
    return 0;
}
 
/********************************************************************
    
    Reporting Functions
 
 ********************************************************************/
 
int DLLEXPORT EN_writeline(EN_Project p, char *line)
/*----------------------------------------------------------------
**  Input:   line = line of text
**  Output:  none
**  Returns: error code
**  Purpose: write a line of text to a project's report file
**----------------------------------------------------------------
*/
{
    //°×ÔÆ·ÉÐÞ¸Ä
    return 0;
 
    if (!p->Openflag) return 102;
    writeline(p, line);
    return 0;
}
 
int DLLEXPORT EN_report(EN_Project p)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  none
**  Returns: error code
**  Purpose: writes formatted simulation results to a project's
**           report file
**----------------------------------------------------------------
*/
{
    //°×ÔÆ·ÉÐÞ¸Ä
    return 0;
 
 
 
    int errcode;
 
    // Check if results have been saved to binary output file
    if (!p->outfile.SaveQflag) return 106;
    writewin(p->viewprog, FMT103);
 
    // Write the formatted report
    errcode = writereport(p);
    if (errcode) errmsg(p, errcode);
    return errcode;
}
 
int  DLLEXPORT EN_copyreport(EN_Project p, char *filename)
/*----------------------------------------------------------------
**  Input:   filename = name of file to receive copy of report
**  Output:  none
**  Returns: error code
**  Purpose: copies the contents of a project's report file to
**           another file
**----------------------------------------------------------------
*/
{
    return copyreport(p, filename);
}
 
int DLLEXPORT EN_clearreport(EN_Project p)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  none
**  Returns: error code
**  Purpose: clears the contents of a project's report file
**----------------------------------------------------------------
*/
{
    return clearreport(p);
}
 
int DLLEXPORT EN_resetreport(EN_Project p)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  none
**  Returns: error code
**  Purpose: resets reporting options to their default values
**----------------------------------------------------------------
*/
{
    int i;
 
    if (!p->Openflag) return 102;
    initreport(&p->report);
    for (i = 1; i <= p->network.Nnodes; i++)
    {
        p->network.Node[i].Rpt = 0;
    }
    for (i = 1; i <= p->network.Nlinks; i++)
    {
        p->network.Link[i].Rpt = 0;
    }
    return 0;
}
 
int DLLEXPORT EN_setreport(EN_Project p, char *format)
/*----------------------------------------------------------------
**  Input:   format = a report formatting command
**  Output:  none
**  Returns: error code
**  Purpose: sets a specific set of reporting options
**----------------------------------------------------------------
*/
{
    char s1[MAXLINE + 1];
 
    if (!p->Openflag) return 102;
    if (strlen(format) >= MAXLINE) return 250;
    strcpy(s1, format);
    strcat(s1, "\n");
    if (setreport(p, s1) > 0) return 250;
    else return 0;
}
 
int DLLEXPORT EN_setstatusreport(EN_Project p, int level)
/*----------------------------------------------------------------
**  Input:   level = level of reporting to use (see EN_StatusReport)
**  Output:  none
**  Returns: error code
**  Purpose: sets the level of hydraulic status reporting
**----------------------------------------------------------------
*/
{
    int errcode = 0;
 
    if (level >= EN_NO_REPORT && level <= EN_FULL_REPORT)
    {
        p->report.Statflag = (char)level;
    }
    else errcode = 251;
    return errcode;
}
 
int DLLEXPORT EN_getversion(int *version)
/*----------------------------------------------------------------
**  Input:    none
**  Output:   version = version number of the source code
**  Returns:  error code (should always be 0)
**  Purpose:  retrieves the toolkit API version number
**
**  The version number is set by the constant CODEVERSION found in
**  TYPES.H and is to be interpreted with implied decimals, i.e.,
**  "20100" == "2(.)01(.)00".
**----------------------------------------------------------------
*/
{
    *version = CODEVERSION;
    return 0;
}
 
int DLLEXPORT EN_geterror(int errcode, char *errmsg, int maxLen)
/*----------------------------------------------------------------
**  Input:   errcode = an error or warnng code
**           maxLen = maximum characters that errmsg can hold
**  Output:  errmsg = text of error/warning message
**  Returns: error code
**  Purpose: retrieves the text of the message associated with
**           a particular error/warning code
**----------------------------------------------------------------
*/
{
    char msg1[MAXMSG+1] = "";
    char msg2[MAXMSG+1] = "";
 
    switch (errcode)
    {
    case 1:
        strncpy(errmsg, WARN1, maxLen);
        break;
    case 2:
        strncpy(errmsg, WARN2, maxLen);
        break;
    case 3:
        strncpy(errmsg, WARN3, maxLen);
        break;
    case 4:
        strncpy(errmsg, WARN4, maxLen);
        break;
    case 5:
        strncpy(errmsg, WARN5, maxLen);
        break;
    case 6:
        strncpy(errmsg, WARN6, maxLen);
        break;
    default:
        sprintf(msg1, "Error %d: ", errcode);
        if ((errcode >= 202 && errcode <= 222) ||
            (errcode >= 240 && errcode <= 261)) strcat(msg1, "function call contains ");
        snprintf(errmsg, maxLen, "%s%s", msg1, geterrmsg(errcode, msg2));
    }
    if (strlen(errmsg) == 0)
        return 251;
    else
        return 0;
}
 
 
int DLLEXPORT EN_geterrormsg(EN_Project pr, char* errmsg, int maxLen)
/*----------------------------------------------------------------
**  Input:   errcode = an error or warnng code
**           maxLen = maximum characters that errmsg can hold
**  Output:  errmsg = text of error/warning message
**  Returns: error code
**  Purpose: retrieves the text of the message associated with
**           a particular error/warning code
**----------------------------------------------------------------
*/
{
    // ¼ì²éerrmsgÊÇ·ñΪNULL
    if (errmsg == NULL) {
        return 252; // ·µ»Ø´íÎóÂ룬±íʾerrmsgΪNULL
    }
 
    // »ñÈ¡pr->MsgTextµÄ³¤¶È
    int msgLen = strlen(pr->MsgText);
 
    // È·±£errmsgÓÐ×ã¹»µÄ¿Õ¼äÀ´´æ´¢pr->MsgText
    if (msgLen >= maxLen) {
        return 253; // ·µ»Ø´íÎóÂ룬±íʾerrmsg¿Õ¼ä²»×ã
    }
 
    //Ϊerrmsg·ÖÅä×ã¹»µÄ¿Õ¼ä
    /*errmsg = (char*)malloc(msgLen + 1);*/
 
 
    // ³õʼ»¯errmsgΪ¿Õ×Ö·û´®
    errmsg[0] = '\0';
 
    // ½«pr->MsgTextµÄÄÚÈÝ·ÅÈëerrmsgÖÐ
    strncpy(errmsg, pr->MsgText, msgLen);
    
 
 
    // È·±£errmsgÊÇÒÔNULL½áβµÄ×Ö·û´®
    errmsg[msgLen] = '\0';
 
    if (strlen(errmsg) == 0)
        return 251;
    else
        return 0;
}
 
int DLLEXPORT EN_getstatistic(EN_Project p, int type, double *value)
/*----------------------------------------------------------------
**  Input:   type = type of simulation statistic (see EN_AnalysisStatistic)
**  Output:  value = simulation analysis statistic value
**  Returns: error code
**  Purpose: retrieves the value of a simulation analysis statistic
**----------------------------------------------------------------
*/
{
    switch (type)
    {
    case EN_ITERATIONS:
        *value = p->hydraul.Iterations;
        break;
    case EN_RELATIVEERROR:
        *value = p->hydraul.RelativeError;
        break;
    case EN_MAXHEADERROR:
        *value = p->hydraul.MaxHeadError * p->Ucf[HEAD];
        break;
    case EN_MAXFLOWCHANGE:
        *value = p->hydraul.MaxFlowChange * p->Ucf[FLOW];
        break;
    case EN_DEFICIENTNODES:
        *value = p->hydraul.DeficientNodes;
        break;
    case EN_DEMANDREDUCTION:
        *value = p->hydraul.DemandReduction;
        break;
    case EN_MASSBALANCE:
        *value = p->quality.MassBalance.ratio;
        break;
    default:
        *value = 0.0;
        return 251;
    }
    return 0;
}
 
int DLLEXPORT EN_getresultindex(EN_Project p, int type, int index, int *value)
/*----------------------------------------------------------------
**  Input:   type = type of object (either EN_NODE or EN_LINK)
**           index = the object's index
**  Output:  value = the order in which the object's results were saved
**  Returns: error code
**  Purpose: retrieves the order in which a node's or link's results
**           were saved to an output file.
**----------------------------------------------------------------
*/
{
    *value = 0;
    if (!p->Openflag) return 102;
    if (type == EN_NODE)
    {
        if (index <= 0 || index > p->network.Nnodes) return 203;
        *value = p->network.Node[index].ResultIndex;
    }
    else if (type == EN_LINK)
    {
        if (index <= 0 || index > p->network.Nlinks) return 204;
        *value = p->network.Link[index].ResultIndex;
    }
    else return 251;
    return 0;
}
 
/********************************************************************
 
    Analysis Options Functions
 
********************************************************************/
 
int DLLEXPORT EN_getoption(EN_Project p, int option, double *value)
/*----------------------------------------------------------------
**  Input:   option = an analysis option code (see EN_Option)
**  Output:  value = analysis option value
**  Returns: error code
**  Purpose: retrieves the value of an analysis option
**----------------------------------------------------------------
*/
{
    Hydraul *hyd = &p->hydraul;
    Quality *qual = &p->quality;
 
    double *Ucf = p->Ucf;
    double v = 0.0;
 
    *value = 0.0;
    if (!p->Openflag) return 102;
    switch (option)
    {
    case EN_TRIALS:
        v = (double)hyd->MaxIter;
        break;
    case EN_ACCURACY:
        v = hyd->Hacc;
        break;
    case EN_TOLERANCE:
        v = qual->Ctol * Ucf[QUALITY];
        break;
    case EN_EMITEXPON:
        if (hyd->Qexp > 0.0) v = 1.0 / hyd->Qexp;
        break;
    case EN_DEMANDMULT:
        v = hyd->Dmult;
        break;
    case EN_HEADERROR:
        v = hyd->HeadErrorLimit * Ucf[HEAD];
        break;
    case EN_FLOWCHANGE:
        v = hyd->FlowChangeLimit * Ucf[FLOW];
        break;
    case EN_HEADLOSSFORM:
        v = hyd->Formflag;
        break;
    case EN_GLOBALEFFIC:
        v = hyd->Epump;
        break;
    case EN_GLOBALPRICE:
        v = hyd->Ecost;
        break;
    case EN_GLOBALPATTERN:
        v = hyd->Epat;
        break;
    case EN_DEMANDCHARGE:
        v = hyd->Dcost;
        break;
    case EN_SP_GRAVITY:
        v = hyd->SpGrav;
        break;
    case EN_SP_VISCOS:
        v = hyd->Viscos / VISCOS;
        break;
    case EN_UNBALANCED:
        v = hyd->ExtraIter;
        break;
    case EN_CHECKFREQ:
        v = hyd->CheckFreq;
        break;
    case EN_MAXCHECK:
        v = hyd->MaxCheck;
        break;
    case EN_DAMPLIMIT:
        v = hyd->DampLimit;
        break;
    case EN_SP_DIFFUS:
        v = qual->Diffus / DIFFUS;
        break;
    case EN_BULKORDER:
        v = qual->BulkOrder;
        break;
    case EN_WALLORDER:
        v = qual->WallOrder;
        break;
    case EN_TANKORDER:
        v = qual->TankOrder;
        break;
    case EN_CONCENLIMIT:
        v = qual->Climit * p->Ucf[QUALITY];
        break;
 
    default:
        return 251;
    }
    *value = (double)v;
    return 0;
}
 
int DLLEXPORT EN_setoption(EN_Project p, int option, double value)
/*----------------------------------------------------------------
**  Input:   option  = analysis option code (see EN_Option)
**           value = analysis option value
**  Output:  none
**  Returns: error code
**  Purpose: sets the value for an analysis option
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Hydraul *hyd = &p->hydraul;
    Quality *qual = &p->quality;
 
    int Njuncs = net->Njuncs;
    double *Ucf = p->Ucf;
    int i, j, pat;
    double Ke, n, ucf;
 
    if (!p->Openflag) return 102;
 
    // The EN_UNBALANCED option can be < 0 indicating that the simulation
    // should be halted if no convergence is reached in EN_TRIALS. Other
    // values set the number of additional trials to use with no more
    // link status changes to achieve convergence.
    if (option == EN_UNBALANCED)
    {
        hyd->ExtraIter = (int)value;
        if (hyd->ExtraIter < 0) hyd->ExtraIter = -1;
        return 0;
    }
 
    // All other option values must be non-negative
    if (value < 0.0) return 213;
 
    // Process the speficied option
    switch (option)
    {
    case EN_TRIALS:
        if (value < 1.0) return 213;
        hyd->MaxIter = (int)value;
        break;
 
    case EN_ACCURACY:
        if (value < 1.e-8 || value > 1.e-1) return 213;
        hyd->Hacc = value;
        break;
 
    case EN_TOLERANCE:
        qual->Ctol = value / Ucf[QUALITY];
        break;
 
    case EN_EMITEXPON:
        if (value <= 0.0) return 213;
        n = 1.0 / value;
        ucf = pow(Ucf[FLOW], n) / Ucf[PRESSURE];
        for (i = 1; i <= Njuncs; i++)
        {
            j = EN_getnodevalue(p, i, EN_EMITTER, &Ke);
            if (j == 0 && Ke > 0.0) net->Node[i].Ke = ucf / pow(Ke, n);
        }
        hyd->Qexp = n;
        break;
 
    case EN_DEMANDMULT:
        hyd->Dmult = value;
        break;
 
    case EN_HEADERROR:
        hyd->HeadErrorLimit = value / Ucf[HEAD];
        break;
 
    case EN_FLOWCHANGE:
        hyd->FlowChangeLimit = value / Ucf[FLOW];
        break;
 
    case EN_HEADLOSSFORM:
        // Can't change if hydraulic solver is open
        if (p->hydraul.OpenHflag) return 262;
        i = ROUND(value);
        if (i < HW || i > CM) return 213;
        hyd->Formflag = i;
        if (hyd->Formflag == HW) hyd->Hexp = 1.852;
        else hyd->Hexp = 2.0;
        break;
 
    case EN_GLOBALEFFIC:
        if (value <= 1.0 || value > 100.0) return 213;
        hyd->Epump = value;
        break;
 
    case EN_GLOBALPRICE:
        hyd->Ecost = value;
        break;
 
    case EN_GLOBALPATTERN:
        pat = ROUND(value);
        if (pat < 0 || pat > net->Npats) return 205;
        hyd->Epat = pat;
        break;
 
    case EN_DEMANDCHARGE:
        hyd->Dcost = value;
        break;
 
    case EN_SP_GRAVITY:
        if (value <= 0.0) return 213;
        Ucf[PRESSURE] *= (value / hyd->SpGrav);
        hyd->SpGrav = value;
        break;
 
    case EN_SP_VISCOS:
        if (value <= 0.0) return 213;
        hyd->Viscos = value * VISCOS;
        break;
 
    case EN_CHECKFREQ:
        hyd->CheckFreq = (int)value;
        break;
 
    case EN_MAXCHECK:
        hyd->MaxCheck = (int)value;
        break;
 
    case EN_DAMPLIMIT:
        hyd->DampLimit = value;
        break;
 
    case EN_SP_DIFFUS:
        qual->Diffus = value * DIFFUS;
        break;
 
    case EN_BULKORDER:
        qual->BulkOrder = value;
        break;
 
    case EN_WALLORDER:
        if (value == 0.0 || value == 1.0) qual->WallOrder = value;
        else return 213;
        break;
 
    case EN_TANKORDER:
        qual->TankOrder = value;
        break;
 
    case EN_CONCENLIMIT:
        qual->Climit = value / p->Ucf[QUALITY];
        break;
 
    default:
        return 251;
    }
    return 0;
}
 
int DLLEXPORT EN_getflowunits(EN_Project p, int *units)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  units = flow units code (see EN_FlowUnits)
**  Returns: error code
**  Purpose: retrieves the flow units used by a project
**----------------------------------------------------------------
*/
{
    *units = -1;
    if (!p->Openflag) return 102;
    *units = p->parser.Flowflag;
    return 0;
}
 
int DLLEXPORT EN_setflowunits(EN_Project p, int units)
/*----------------------------------------------------------------
**  Input:   units = flow units code (see EN_FlowUnits)
**  Output:  none
**  Returns: error code
**  Purpose: sets the flow units used by a project
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    int i, j;
    double qfactor, vfactor, hfactor, efactor, xfactor, yfactor;
    double *Ucf = p->Ucf;
 
    if (!p->Openflag) return 102;
 
    // Determine unit system based on flow units
    qfactor = Ucf[FLOW];
    vfactor = Ucf[VOLUME];
    hfactor = Ucf[HEAD];
    efactor = Ucf[ELEV];
 
    p->parser.Flowflag = units;
    switch (units)
    {
    case LPS:
    case LPM:
    case MLD:
    case CMH:
    case CMD:
        p->parser.Unitsflag = SI;
        break;
    default:
        p->parser.Unitsflag = US;
        break;
    }
 
    // Revise pressure units depending on flow units
    if (p->parser.Unitsflag != SI) p->parser.Pressflag = PSI;
    else if (p->parser.Pressflag == PSI) p->parser.Pressflag = METERS;
    initunits(p);
 
    //update curves
    for (i = 1; i <= net->Ncurves; i++)
    {
        switch (net->Curve[i].Type)
        {
        case VOLUME_CURVE:
            xfactor = efactor / Ucf[ELEV];
            yfactor = vfactor / Ucf[VOLUME];
            break;
        case HLOSS_CURVE:
        case PUMP_CURVE:
            xfactor = qfactor / Ucf[FLOW];
            yfactor = hfactor / Ucf[HEAD];
            break;
        case EFFIC_CURVE:
            xfactor = qfactor / Ucf[FLOW];
            yfactor = 1;
            break;
        default:
            xfactor = 1;
            yfactor = 1;
        }
 
        for (j = 0; j < net->Curve[i].Npts; j++)
        {
            net->Curve[i].X[j] = net->Curve[i].X[j] / xfactor;
            net->Curve[i].Y[j] = net->Curve[i].Y[j] / yfactor;
        }
    }
    return 0;
}
 
int DLLEXPORT EN_gettimeparam(EN_Project p, int param, long *value)
/*----------------------------------------------------------------
**  Input:   param = time parameter code (see EN_TimeParameter)
**  Output:  value = time parameter value
**  Returns: error code
**  Purpose: retrieves the value of a time parameter
**----------------------------------------------------------------
*/
{
    Report *rpt = &p->report;
    Times  *time = &p->times;
 
    int i;
 
    *value = 0;
    if (!p->Openflag) return 102;
    if (param < EN_DURATION || param > EN_NEXTEVENTTANK) return 251;
    switch (param)
    {
    case EN_DURATION:
        *value = time->Dur;
        break;
    case EN_HYDSTEP:
        *value = time->Hstep;
        break;
    case EN_QUALSTEP:
        *value = time->Qstep;
        break;
    case EN_PATTERNSTEP:
        *value = time->Pstep;
        break;
    case EN_PATTERNSTART:
        *value = time->Pstart;
        break;
    case EN_REPORTSTEP:
        *value = time->Rstep;
        break;
    case EN_REPORTSTART:
        *value = time->Rstart;
        break;
    case EN_RULESTEP:
        *value = time->Rulestep;
        break;
    case EN_STATISTIC:
        *value = rpt->Tstatflag;
        break;
    case EN_PERIODS:
        *value = rpt->Nperiods;
        break;
    case EN_STARTTIME:
        *value = time->Tstart;
        break;
    case EN_HTIME:
        *value = time->Htime;
        break;
    case EN_QTIME:
        *value = time->Qtime;
    case EN_HALTFLAG:
        break;
    case EN_NEXTEVENT:
        *value = time->Hstep; // find the lesser of the hydraulic time step length,
                              // or the time to next full/empty tank
        tanktimestep(p, value);
        break;
    case EN_NEXTEVENTTANK:
        *value = time->Hstep;
        i = tanktimestep(p, value);
        *value = i;
        break;
    default:
        return 251;
    }
    return 0;
}
 
int DLLEXPORT EN_settimeparam(EN_Project p, int param, long value)
/*----------------------------------------------------------------
**  Input:   param = time parameter code (see EN_TimeParameter)
**           value = time parameter value
**  Output:  none
**  Returns: error code
**  Purpose: sets the value of a time parameter
**----------------------------------------------------------------
*/
{
    Report *rpt = &p->report;
    Times  *time = &p->times;
 
    if (!p->Openflag) return 102;
    if (value < 0) return 213;
    switch (param)
    {
    case EN_DURATION:
        time->Dur = value;
        if (time->Rstart > time->Dur) time->Rstart = 0;
        break;
 
    case EN_HYDSTEP:
        if (value == 0) return 213;
        time->Hstep = value;
        time->Hstep = MIN(time->Pstep, time->Hstep);
        time->Hstep = MIN(time->Rstep, time->Hstep);
        time->Qstep = MIN(time->Qstep, time->Hstep);
        break;
 
    case EN_QUALSTEP:
        if (value == 0) return 213;
        time->Qstep = value;
        time->Qstep = MIN(time->Qstep, time->Hstep);
        break;
 
    case EN_PATTERNSTEP:
        if (value == 0) return 213;
        time->Pstep = value;
        if (time->Hstep > time->Pstep) time->Hstep = time->Pstep;
        break;
 
    case EN_PATTERNSTART:
        time->Pstart = value;
        break;
 
    case EN_REPORTSTEP:
        if (value == 0) return 213;
        time->Rstep = value;
        if (time->Hstep > time->Rstep) time->Hstep = time->Rstep;
        break;
 
    case EN_REPORTSTART:
        if (time->Rstart > time->Dur) return 213;
        time->Rstart = value;
        break;
 
    case EN_RULESTEP:
        if (value == 0) return 213;
        time->Rulestep = value;
        time->Rulestep = MIN(time->Rulestep, time->Hstep);
        break;
 
    case EN_STATISTIC:
        if (value > RANGE) return 213;
        rpt->Tstatflag = (char)value;
        break;
 
    case EN_HTIME:
        time->Htime = value;
        break;
 
    case EN_QTIME:
        time->Qtime = value;
        break;
 
    default:
        return 251;
    }
    return 0;
}
 
int DLLEXPORT EN_getqualinfo(EN_Project p, int *qualType, char *chemName,
                             char *chemUnits, int *traceNode)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  qualType = type of quality analysis to run (see EN_QualityType)
**           chemName = name of chemical constituent
**           chemUnits = concentration units of constituent
**           traceNode = index of node being traced (if applicable)
**  Returns: error code
**  Purpose: retrieves water quality analysis options
**----------------------------------------------------------------
*/
{
    EN_getqualtype(p, qualType, traceNode);
    if (p->quality.Qualflag == CHEM)
    {
        strncpy(chemName, p->quality.ChemName, MAXID);
        strncpy(chemUnits, p->quality.ChemUnits, MAXID);
    }
    else if (p->quality.Qualflag == TRACE)
    {
        strncpy(chemName, w_TRACE, MAXID);
        strncpy(chemUnits, u_PERCENT, MAXID);
    }
    else if (p->quality.Qualflag == AGE)
    {
        strncpy(chemName, w_AGE, MAXID);
        strncpy(chemUnits, u_HOURS, MAXID);
    }
    else
    {
        strncpy(chemName, "", MAXID);
        strncpy(chemUnits, "", MAXID);
    }
    return 0;
}
 
int DLLEXPORT EN_getqualtype(EN_Project p, int *qualType, int *traceNode)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  qualType = type of quality analysis to run (see EN_QualityType)
**           traceNode = index of node being traced (for qualType = EN_TRACE)
**  Output:  none
**  Returns: error code
**  Purpose: retrieves type of quality analysis being made
**----------------------------------------------------------------
*/
{
    *traceNode = 0;
    if (!p->Openflag) return 102;
    *qualType = p->quality.Qualflag;
    if (p->quality.Qualflag == TRACE) *traceNode = p->quality.TraceNode;
    return 0;
}
 
int DLLEXPORT EN_setqualtype(EN_Project p, int qualType, char *chemName,
                             char *chemUnits, char *traceNode)
/*----------------------------------------------------------------
**  Input:   qualType = type of quality analysis to run (see EN_QualityType)
**           chemname = name of chemical constituent
**           chemunits = concentration units of constituent
**           tracenode = ID name of node being traced (if applicable)
**  Output:  none
**  Returns: error code
**  Purpose: sets water quality analysis options
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Report  *rpt = &p->report;
    Quality *qual = &p->quality;
 
    double *Ucf = p->Ucf;
    int i, oldQualFlag, traceNodeIndex;
    double ccf = 1.0;
 
    if (!p->Openflag) return 102;
    if (qual->OpenQflag) return 262;
    if (qualType < NONE || qualType > TRACE) return 251;
    if (qualType == TRACE)
    {
        traceNodeIndex = findnode(net, traceNode);
        if (traceNodeIndex == 0) return 212;
    }
 
    oldQualFlag = qual->Qualflag;
    qual->Qualflag = qualType;
    qual->Ctol *= Ucf[QUALITY];
    if (qual->Qualflag == CHEM) // Chemical analysis
    {
        strncpy(qual->ChemName, chemName, MAXID);
        strncpy(qual->ChemUnits, chemUnits, MAXID);
        strncpy(rpt->Field[QUALITY].Units, qual->ChemUnits, MAXID);
        strncpy(rpt->Field[REACTRATE].Units, qual->ChemUnits, MAXID);
        strcat(rpt->Field[REACTRATE].Units, t_PERDAY);
        ccf = 1.0 / LperFT3;
    }
    if (qual->Qualflag == TRACE) // Source trace analysis
    {
        qual->TraceNode = findnode(net, traceNode);
        if (qual->TraceNode == 0) return 212;
        strncpy(qual->ChemName, w_TRACE, MAXID);
        strncpy(qual->ChemUnits, u_PERCENT, MAXID);
        strcpy(rpt->Field[QUALITY].Units, u_PERCENT);
    }
    if (qual->Qualflag == AGE) // Water age analysis
    {
        strncpy(qual->ChemName, w_AGE, MAXID);
        strncpy(qual->ChemUnits, u_HOURS, MAXID);
        strcpy(rpt->Field[QUALITY].Units, u_HOURS);
    }
 
    // When changing from CHEM to AGE or TRACE, nodes initial quality
    // values must be returned to their original ones
    if ((qual->Qualflag == AGE || qual->Qualflag == TRACE) && oldQualFlag == CHEM)
    {
        for (i = 1; i <= p->network.Nnodes; i++)
        {
            p->network.Node[i].C0 *= Ucf[QUALITY];
        }
    }
 
    Ucf[QUALITY] = ccf;
    Ucf[LINKQUAL] = ccf;
    Ucf[REACTRATE] = ccf;
    qual->Ctol /= Ucf[QUALITY];
    return 0;
}
 
/********************************************************************
 
    Node Functions
 
********************************************************************/
 
int DLLEXPORT EN_addnode(EN_Project p, char *id, int nodeType, int *index)
/*----------------------------------------------------------------
**  Input:   id = node ID name
**           nodeType = type of node (see EN_NodeType)
**  Output:  index = index of newly added node
**  Returns: error code
**  Purpose: adds a new node to a project
**----------------------------------------------------------------
*/
{
    Network  *net = &p->network;
    Hydraul  *hyd = &p->hydraul;
    Quality  *qual = &p->quality;
 
    int i, nIdx, size;
    Stank *tank;
    Snode *node;
    Scontrol *control;
 
    // Cannot modify network structure while solvers are active
    *index = 0;
    if (!p->Openflag) return 102;
    if (hyd->OpenHflag || qual->OpenQflag) return 262;
 
    // Check if id name contains invalid characters
    if (!namevalid(id)) return 252;
 
    // Check if a node with same id already exists
    if (EN_getnodeindex(p, id, &i) == 0) return 215;
    
    // Check for valid node type
    if (nodeType < EN_JUNCTION || nodeType > EN_TANK) return 251; 
 
    // Grow node-related arrays to accomodate the new node
    size = (net->Nnodes + 2) * sizeof(Snode);
    net->Node = (Snode *)realloc(net->Node, size);
    size = (net->Nnodes + 2) * sizeof(double);
    hyd->NodeDemand = (double *)realloc(hyd->NodeDemand, size);
    qual->NodeQual = (double *)realloc(qual->NodeQual, size);
    hyd->NodeHead = (double *)realloc(hyd->NodeHead, size);
 
    // Actions taken when a new Junction is added
    if (nodeType == EN_JUNCTION)
    {
        // shift indices of non-Junction nodes at end of Node array
        for (i = net->Nnodes; i > net->Njuncs; i--)
        {
            hashtable_update(net->NodeHashTable, net->Node[i].ID, i + 1);
            net->Node[i + 1] = net->Node[i];
        }
    
        // set index of new Junction node
        net->Njuncs++;
        nIdx = net->Njuncs;
        node = &net->Node[nIdx];
        node->D = NULL;
        adddemand(node, 0.0, 0, NULL);
 
        // shift indices of Tank array
        for (i = 1; i <= net->Ntanks; i++)
        {
            net->Tank[i].Node += 1;
        }
        // shift indices of Links, if necessary
        for (i = 1; i <= net->Nlinks; i++)
        {
            if (net->Link[i].N1 > net->Njuncs - 1) net->Link[i].N1 += 1;
            if (net->Link[i].N2 > net->Njuncs - 1) net->Link[i].N2 += 1;
        }
        // shift indices of tanks/reservoir nodes in controls
        for (i = 1; i <= net->Ncontrols; ++i)
        {
            control = &net->Control[i];
            if (control->Node > net->Njuncs - 1) control->Node += 1;
        }
        // adjust indices of tanks/reservoirs in Rule premises (see RULES.C)
        adjusttankrules(p);
    }
 
    // Actions taken when a new Tank/Reservoir is added
    else
    {
        nIdx = net->Nnodes + 1;
        node = &net->Node[nIdx];
        node->D = NULL;
        net->Ntanks++;
 
        // resize tanks array
        net->Tank = (Stank *)realloc(net->Tank, (net->Ntanks + 1) * sizeof(Stank));
        tank = &net->Tank[net->Ntanks];
 
        // set default values for new tank or reservoir
        tank->Node = nIdx;
        tank->Pat = 0;
        if (nodeType == EN_TANK) tank->A = 1.0;
        else tank->A = 0;
        tank->Hmin = 0;
        tank->Hmax = 0;
        tank->H0 = 0;
        tank->Vmin = 0;
        tank->Vmax = 0;
        tank->V0 = 0;
        tank->Kb = 0;
        tank->V = 0;
        tank->C = 0;
        tank->Pat = 0;
        tank->Vcurve = 0;
        tank->MixModel = (MixType)0;
        tank->V1max = 10000;
        tank->CanOverflow = FALSE;
    }
    net->Nnodes++;
    p->parser.MaxNodes = net->Nnodes;
    strncpy(node->ID, id, MAXID);
 
    // set default values for new node
    node->Type = (NodeType)nodeType;
    node->El = 0;
    node->S = NULL;
    node->C0 = 0;
    node->Ke = 0;
    node->Rpt = 0;
    node->ResultIndex = 0;
    node->X = MISSING;
    node->Y = MISSING;
    node->Comment = NULL;
 
    // Insert new node into hash table
    hashtable_insert(net->NodeHashTable, node->ID, nIdx);
    *index = nIdx;
    return 0;
}
 
int DLLEXPORT EN_deletenode(EN_Project p, int index, int actionCode)
/*----------------------------------------------------------------
**  Input:   index  = index of the node to delete
**           actionCode = how to treat controls that contain the link
**           or its incident links:
**           EN_UNCONDITIONAL deletes all such controls plus the node,
**           EN_CONDITIONAL does not delete the node if it or any of
**           its links appear in a control and returns an error code
**  Output:  none
**  Returns: error code
**  Purpose: deletes a node from a project
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    int i, nodeType, tankindex;
    Snode *node;
 
    // Cannot modify network structure while solvers are active
    if (!p->Openflag) return 102;
    if (p->hydraul.OpenHflag || p->quality.OpenQflag) return 262;
 
    // Check that node exists
    if (index <= 0 || index > net->Nnodes) return 203;
    if (actionCode < EN_UNCONDITIONAL || actionCode > EN_CONDITIONAL) return 251;
 
    // Can't delete a water quality trace node
    if (index == p->quality.TraceNode) return 260;
 
    // Do not delete a node contained in a control or is connected to a link
    if (actionCode == EN_CONDITIONAL)
    {
        if (incontrols(p, NODE, index)) return 261;
        for (i = 1; i <= net->Nlinks; i++)
        {
            if (net->Link[i].N1 == index ||
                net->Link[i].N2 == index)  return 259;
        }
    }
 
    // Get a reference to the node & its type
    node = &net->Node[index];
    EN_getnodetype(p, index, &nodeType);
 
    // Remove node from its hash table
    hashtable_delete(net->NodeHashTable, node->ID);
 
    // Free memory allocated to node's demands, WQ source & comment
    freedemands(node);
    free(node->S);
    free(node->Comment);
 
    // Shift position of higher entries in Node & Coord arrays down one
    for (i = index; i <= net->Nnodes - 1; i++)
    {
        net->Node[i] = net->Node[i + 1];
        // ... update node's entry in the hash table
        hashtable_update(net->NodeHashTable, net->Node[i].ID, i);
    }
 
    // If deleted node is a tank, remove it from the Tank array
    if (nodeType != EN_JUNCTION)
    {
        tankindex = findtank(net, index);
        for (i = tankindex; i <= net->Ntanks - 1; i++)
        {
            net->Tank[i] = net->Tank[i + 1];
        }
    }
 
    // Shift higher node indices in Tank array down one
    for (i = 1; i <= net->Ntanks; i++)
    {
        if (net->Tank[i].Node > index) net->Tank[i].Node -= 1;
    }
 
    // Delete any links connected to the deleted node
    // (Process links in reverse order to maintain their indexing)
    for (i = net->Nlinks; i >= 1; i--)
    {
        if (net->Link[i].N1 == index ||
            net->Link[i].N2 == index)  EN_deletelink(p, i, EN_UNCONDITIONAL);
    }
 
    // Adjust indices of all link end nodes
    for (i = 1; i <= net->Nlinks; i++)
    {
        if (net->Link[i].N1 > index) net->Link[i].N1 -= 1;
        if (net->Link[i].N2 > index) net->Link[i].N2 -= 1;
    }
 
    // Delete any control containing the node
    for (i = net->Ncontrols; i >= 1; i--)
    {
        if (net->Control[i].Node == index) EN_deletecontrol(p, i);
    }
 
    // Adjust higher numbered link indices in remaining controls
    for (i = 1; i <= net->Ncontrols; i++)
    {
        if (net->Control[i].Node > index) net->Control[i].Node--;
    }
 
    // Make necessary adjustments to rule-based controls
    adjustrules(p, EN_R_NODE, index);
 
    // Reduce counts of node types
    if (nodeType == EN_JUNCTION) net->Njuncs--;
    else net->Ntanks--;
    net->Nnodes--;
    return 0;
}
 
int DLLEXPORT EN_getnodeindex(EN_Project p, char *id, int *index)
/*----------------------------------------------------------------
**  Input:   id = node ID name
**  Output:  index = node index
**  Returns: error code
**  Purpose: retrieves the index of a node
**----------------------------------------------------------------
*/
{
    *index = 0;
    if (!p->Openflag) return 102;
    *index = findnode(&p->network, id);
    if (*index == 0) return 203;
    else return 0;
}
 
int DLLEXPORT EN_getnodeid(EN_Project p, int index, char *id)
/*----------------------------------------------------------------
**  Input:   index = node index
**  Output:  id = node ID name
**  Returns: error code
**  Purpose: retrieves the name of a node
**----------------------------------------------------------------
*/
{
    strcpy(id, "");
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Nnodes) return 203;
    strcpy(id, p->network.Node[index].ID);
    return 0;
}
 
 
int DLLEXPORT EN_getnodecomment(EN_Project p, int index, char* id)
/*----------------------------------------------------------------
**  Input:   index = node index
**  Output:  id = node Comment
**  Returns: error code
**  Purpose: retrieves the name of a node
**----------------------------------------------------------------
*/
{
    strcpy(id, "");
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Nnodes) return 203;
    if(p->network.Node[index].Comment!=NULL) strcpy(id, p->network.Node[index].Comment);
    
    return 0;
}
 
int DLLEXPORT EN_setnodeid(EN_Project p, int index, char *newid)
/*----------------------------------------------------------------
**  Input:   index = node index
**           newid = new node ID name
**  Output:  none
**  Returns: error code
**  Purpose: sets the ID name of a node
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    // Check for valid arguments
    if (index <= 0 || index > net->Nnodes) return 203;
    if (!namevalid(newid)) return 252;
 
    // Check if another node with same name exists
    if (hashtable_find(net->NodeHashTable, newid) > 0)
        return 215;
 
    // Replace the existing node ID with the new value
    hashtable_delete(net->NodeHashTable, net->Node[index].ID);
    strncpy(net->Node[index].ID, newid, MAXID);
    hashtable_insert(net->NodeHashTable, net->Node[index].ID, index);
    return 0;
}
 
int DLLEXPORT EN_getnodetype(EN_Project p, int index, int *nodeType)
/*----------------------------------------------------------------
**  Input:   index = node index
**  Output:  nodeType  = node type (see EN_NodeType)
**  Returns: error code
**  Purpose: retrieves the type of a node
**----------------------------------------------------------------
*/
{
    *nodeType = -1;
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Nnodes) return 203;
    if (index <= p->network.Njuncs) *nodeType = EN_JUNCTION;
    else
    {
        if (p->network.Tank[index - p->network.Njuncs].A == 0.0)
        {
            *nodeType = EN_RESERVOIR;
        }
        else *nodeType = EN_TANK;
    }
    return 0;
}
 
int DLLEXPORT EN_getnodevalue(EN_Project p, int index, int property, double *value)
/*----------------------------------------------------------------
**  Input:   index = node index
**           property = node property code (see EN_NodeProperty)
**  Output:  value = node property value
**  Returns: error code
**  Purpose: retrieves a property value for a node
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Hydraul *hyd = &p->hydraul;
    Quality *qual = &p->quality;
 
    double v = 0.0;
    Psource source;
 
    Snode *Node = net->Node;
    Stank *Tank = net->Tank;
 
    int nJuncs = net->Njuncs;
 
    double *Ucf = p->Ucf;
    double *NodeHead = hyd->NodeHead;
    double *NodeQual = qual->NodeQual;
 
    // Check for valid arguments
    *value = 0.0;
    if (!p->Openflag) return 102;
    if (index <= 0 || index > net->Nnodes) return 203;
 
    // Retrieve requested property
    switch (property)
    {
    case EN_ELEVATION:
        v = Node[index].El * Ucf[ELEV];
        break;
 
    case EN_BASEDEMAND:
        // NOTE: primary demand category is first on demand list
        if (index <= nJuncs)
        {
            if (Node[index].D) v = Node[index].D->Base * Ucf[FLOW];
        }
        break;
 
    case EN_PATTERN:
        // NOTE: primary demand category is first on demand list
        if (index <= nJuncs)
        {
            if (Node[index].D) v = (double)(Node[index].D->Pat);
        }
        else v = (double)(Tank[index - nJuncs].Pat);
        break;
 
    case EN_EMITTER:
        v = 0.0;
        if (Node[index].Ke > 0.0)
        {
            v = Ucf[FLOW] / pow((Ucf[PRESSURE] * Node[index].Ke), (1.0 / hyd->Qexp));
        }
        break;
 
    case EN_INITQUAL:
        v = Node[index].C0 * Ucf[QUALITY];
        break;
 
    case EN_SOURCEQUAL:
    case EN_SOURCETYPE:
    case EN_SOURCEMASS:
    case EN_SOURCEPAT:
        source = Node[index].S;
        if (source == NULL) return 240;
        if (property == EN_SOURCEQUAL) v = source->C0;
        else if (property == EN_SOURCEMASS) v = source->Smass * 60.0;
        else if (property == EN_SOURCEPAT)  v = source->Pat;
        else v = source->Type;
        break;
 
    case EN_TANKLEVEL:
        if (index <= nJuncs) return 0;
        v = (Tank[index - nJuncs].H0 - Node[index].El) * Ucf[ELEV];
        break;
 
    case EN_INITVOLUME:
        v = 0.0;
        if (index > nJuncs) v = Tank[index - nJuncs].V0 * Ucf[VOLUME];
        break;
 
    case EN_MIXMODEL:
        v = MIX1;
        if (index > nJuncs) v = Tank[index - nJuncs].MixModel;
        break;
 
    case EN_MIXZONEVOL:
        v = 0.0;
        if (index > nJuncs) v = Tank[index - nJuncs].V1max * Ucf[VOLUME];
        break;
 
    case EN_DEMAND:
        v = hyd->NodeDemand[index] * Ucf[FLOW];
        break;
 
    case EN_HEAD:
        v = NodeHead[index] * Ucf[HEAD];
        break;
 
    case EN_PRESSURE:
        v = (NodeHead[index] - Node[index].El) * Ucf[PRESSURE];
        break;
 
    case EN_QUALITY:
        v = NodeQual[index] * Ucf[QUALITY];
        break;
 
    case EN_TANKDIAM:
        v = 0.0;
        if (index > nJuncs)
        {
            v = sqrt(4.0 / PI * Tank[index - nJuncs].A) * Ucf[ELEV];
        }
        break;
 
    case EN_MINVOLUME:
        v = 0.0;
        if (index > nJuncs) v = Tank[index - nJuncs].Vmin * Ucf[VOLUME];
        break;
 
    case EN_MAXVOLUME:
        v = 0.0;
        if (index > nJuncs) v = Tank[index - nJuncs].Vmax * Ucf[VOLUME];
        break;
 
    case EN_VOLCURVE:
        v = 0.0;
        if (index > nJuncs) v = Tank[index - nJuncs].Vcurve;
        break;
 
    case EN_MINLEVEL:
        v = 0.0;
        if (index > nJuncs)
        {
            v = (Tank[index - nJuncs].Hmin - Node[index].El) * Ucf[ELEV];
        }
        break;
 
    case EN_MAXLEVEL:
        v = 0.0;
        if (index > nJuncs)
        {
            v = (Tank[index - nJuncs].Hmax - Node[index].El) * Ucf[ELEV];
        }
        break;
 
    case EN_MIXFRACTION:
        v = 1.0;
        if (index > nJuncs && Tank[index - nJuncs].Vmax > 0.0)
        {
            v = Tank[index - nJuncs].V1max / Tank[index - nJuncs].Vmax;
        }
        break;
 
    case EN_TANK_KBULK:
        v = 0.0;
        if (index > nJuncs) v = Tank[index - nJuncs].Kb * SECperDAY;
        break;
 
    case EN_TANKVOLUME:
        if (index <= nJuncs) return 0;
        v = tankvolume(p, index - nJuncs, NodeHead[index]) * Ucf[VOLUME];
        break;
 
    case EN_CANOVERFLOW:
        if (Node[index].Type != TANK) return 0;
        v = Tank[index - nJuncs].CanOverflow;
        break;
        
    case EN_DEMANDDEFICIT:
        if (index > nJuncs) return 0;
        // After an analysis, DemandFlow contains node's required demand
        // while NodeDemand contains delivered demand + emitter flow
        if (hyd->DemandFlow[index] < 0.0) return 0;
        v = (hyd->DemandFlow[index] - 
            (hyd->NodeDemand[index] - hyd->EmitterFlow[index])) * Ucf[FLOW];
        break;
        
    default:
        return 251;
    }
    *value = v;
    return 0;
}
 
int DLLEXPORT EN_setnodevalue(EN_Project p, int index, int property, double value)
/*----------------------------------------------------------------
**  Input:   index = node index
**           property  = node property code (see EN_NodeProperty)
**           value = node property value
**  Output:  none
**  Returns: error code
**  Purpose: sets a property value for a node
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Hydraul *hyd = &p->hydraul;
    Quality *qual = &p->quality;
 
    Snode *Node = net->Node;
    Stank *Tank = net->Tank;
    Scurve *curve;
 
    const int nNodes = net->Nnodes;
    const int nJuncs = net->Njuncs;
    const int nPats = net->Npats;
 
    double *Ucf = p->Ucf;
 
    int i, j, n;
    Psource source;
    double hTmp;
    double vTmp;
 
    if (!p->Openflag) return 102;
    if (index <= 0 || index > nNodes) return 203;
    switch (property)
    {
    case EN_ELEVATION:
        if (index <= nJuncs) Node[index].El = value / Ucf[ELEV];
        else
        {
            value = (value / Ucf[ELEV]) - Node[index].El;
            j = index - nJuncs;
            Tank[j].H0 += value;
            Tank[j].Hmin += value;
            Tank[j].Hmax += value;
            Node[index].El += value;
            hyd->NodeHead[index] += value;
        }
        break;
 
    case EN_BASEDEMAND:
        // NOTE: primary demand category is first on demand list
        if (index <= nJuncs)
        {
            if (Node[index].D) Node[index].D->Base = value / Ucf[FLOW];
        }
        break;
 
    case EN_PATTERN:
        // NOTE: primary demand category is first on demand list
        j = ROUND(value);
        if (j < 0 || j > nPats) return 205;
        if (index <= nJuncs)
        {
            if (Node[index].D) Node[index].D->Pat = j;
        }
        else Tank[index - nJuncs].Pat = j;
        break;
 
    case EN_EMITTER:
        if (index > nJuncs) return 0;
        if (value < 0.0) return 209;
        if (value > 0.0) value = pow((Ucf[FLOW] / value), hyd->Qexp) / Ucf[PRESSURE];
        Node[index].Ke = value;
        break;
 
    case EN_INITQUAL:
        if (value < 0.0) return 209;
        Node[index].C0 = value / Ucf[QUALITY];
        if (index > nJuncs) Tank[index - nJuncs].C = Node[index].C0;
        break;
 
    case EN_SOURCEQUAL:
    case EN_SOURCETYPE:
    case EN_SOURCEPAT:
        if (value < 0.0) return 209;
        source = Node[index].S;
        if (source == NULL)
        {
            source = (struct Ssource *)malloc(sizeof(struct Ssource));
            if (source == NULL) return 101;
            source->Type = CONCEN;
            source->C0 = 0.0;
            source->Pat = 0;
            Node[index].S = source;
        }
        if (property == EN_SOURCEQUAL) source->C0 = value;
        else if (property == EN_SOURCEPAT)
        {
            j = ROUND(value);
            if (j < 0 || j > nPats) return 205;
            source->Pat = j;
        }
        else // property == EN_SOURCETYPE
        {
            j = ROUND(value);
            if (j < CONCEN || j > FLOWPACED) return 251;
            else source->Type = (SourceType)j;
        }
        break;
 
    case EN_TANKLEVEL:
        if (index <= nJuncs) return 0;
        j = index - nJuncs;
        if (Tank[j].A == 0.0) /* Tank is a reservoir */
        {
            Tank[j].H0 = value / Ucf[ELEV];
            Tank[j].Hmin = Tank[j].H0;
            Tank[j].Hmax = Tank[j].H0;
            Node[index].El = Tank[j].H0;
            hyd->NodeHead[index] = Tank[j].H0;
        }
        else
        {
            value = Node[index].El + value / Ucf[ELEV];
            if (value > Tank[j].Hmax || value < Tank[j].Hmin) return 225;
            Tank[j].H0 = value;
            Tank[j].V0 = tankvolume(p, j, Tank[j].H0);
            // Resetting Volume in addition to initial volume
            Tank[j].V = Tank[j].V0;
            hyd->NodeHead[index] = Tank[j].H0;
        }
        break;
 
    case EN_TANKDIAM:
        if (value <= 0.0) return 209;                  // invalid diameter
        if (index <= nJuncs) return 0;                 // node is not a tank
        j = index - nJuncs;                            // tank index
        if (Tank[j].A == 0.0) return 0;                // tank is a reservoir
        value /= Ucf[ELEV];                            // diameter in feet
        Tank[j].A = PI * SQR(value) / 4.0;             // new tank area
        if (Tank[j].Vcurve > 0)                        // tank has a volume curve
        {
            Tank[j].Vcurve = 0;                        // remove volume curve
 
            // Since the volume curve no longer applies we assume that the tank's
            // shape below Hmin is cylindrical and Vmin equals area times Hmin
            Tank[j].Vmin = Tank[j].A * Tank[j].Hmin;
        }
        // Since tank's area has changed its volumes must be updated
        // NOTE: For a non-volume curve tank we can't change the Vmin
        //       associated with a Hmin since we don't know the tank's
        //       shape below Hmin. Vmin can always be changed by setting
        //       EN_MINVOLUME in a subsequent function call.
        Tank[j].V0 = tankvolume(p, j, Tank[j].H0);     // new init. volume
        vTmp = Tank[j].Vmax;                           // old max. volume
        Tank[j].Vmax = tankvolume(p, j, Tank[j].Hmax); // new max. volume
        Tank[j].V1max *= Tank[j].Vmax / vTmp;          // new mix zone volume
        break;
 
    case EN_MINVOLUME:
        if (value < 0.0) return 209;               // invalid volume
        if (index <= nJuncs) return 0;             // node is not a tank
        j = index - nJuncs;                        // tank index
        if (Tank[j].A == 0.0) return 0;            // tank is a reservoir
        i = Tank[j].Vcurve;                        // volume curve index
        if (i > 0)                                 // tank has a volume curve
        {
            curve = &net->Curve[i];                // curve object
            if (value < curve->Y[0]) return 225;   // volume off of curve
            value /= Ucf[VOLUME];                  // volume in ft3
            hTmp = tankgrade(p, j, value);         // head at given volume
            if (hTmp > Tank[j].H0 ||
                hTmp > Tank[j].Hmax) return 225;   // invalid water levels
            Tank[j].Hmin = hTmp;                   // new min. head
            Tank[j].Vmin = value;                  // new min. volume
        }
        else                                       // tank has no volume curve
        {
            // If the volume supplied by the function is 0 then the tank shape
            // below Hmin is assumed to be cylindrical and a new Vmin value is
            // computed. Otherwise Vmin is set to the supplied value.
            if (value == 0.0) Tank[j].Vmin = Tank[j].A * Tank[j].Hmin;
            else Tank[j].Vmin = value / Ucf[VOLUME];
 
            // Since Vmin changes the other volumes need updating
            Tank[j].V0 = tankvolume(p, j, Tank[j].H0);     // new init. volume
            vTmp = Tank[j].Vmax;                           // old max. volume
            Tank[j].Vmax = tankvolume(p, j, Tank[j].Hmax); // new max. volume
            Tank[j].V1max *= Tank[j].Vmax / vTmp;          // new mix zone volume
        }
        break;
 
    case EN_VOLCURVE:
        // NOTE: Setting EN_VOLCURVE to 0 to remove a volume curve is not valid.
        //       One should instead set a value for EN_TANKDIAM.
        i = ROUND(value);                          // curve index
        if (i <= 0 ||
            i > net->Ncurves) return 205;          // invalid curve index
        if (index <= nJuncs) return 0;             // node not a tank
        j = index - nJuncs;                        // tank index
        if (Tank[j].A == 0.0) return 0;            // tank is a reservoir
        curve = &net->Curve[i];                    // curve object
 
        // Check that tank's min/max levels lie within curve
        value = (Tank[j].Hmin - Node[index].El) * Ucf[ELEV];
        if (value < curve->X[0]) return 225;
        value = (Tank[j].Hmax - Node[index].El) * Ucf[ELEV];
        n = curve->Npts - 1;
        if (value > curve->X[n]) return 225;
 
        Tank[j].Vcurve = i;                            // assign curve to tank
        Tank[j].Vmin = tankvolume(p, j, Tank[j].Hmin); // new min. volume
        Tank[j].V0 = tankvolume(p, j, Tank[j].H0);     // new init. volume
        vTmp = Tank[j].Vmax;                           // old max. volume
        Tank[j].Vmax = tankvolume(p, j, Tank[j].Hmax); // new max. volume
        Tank[j].V1max *= Tank[j].Vmax / vTmp;          // new mix zone volume
        Tank[j].A = (curve->Y[n] - curve->Y[0]) /      // nominal area 
            (curve->X[n] - curve->X[0]);
        break;
 
    case EN_MINLEVEL:
        if (value < 0.0) return 209;               // invalid water level
        if (index <= nJuncs) return 0;             // node not a tank
        j = index - nJuncs;                        // tank index
        if (Tank[j].A == 0.0) return  0;           // tank is a reservoir
        hTmp = value / Ucf[ELEV] + Node[index].El; // convert level to head
        if (hTmp >= Tank[j].Hmax ||
            hTmp > Tank[j].H0) return 225;         // invalid water levels
        i = Tank[j].Vcurve;                        // volume curve index
        if (i > 0)                                 // tank has a volume curve
        {
            curve = &net->Curve[i];
            if (value < curve->X[0]) return 225;   // new level is off curve
            Tank[j].Vmin = tankvolume(p, j, hTmp); // new min. volume
        }
        Tank[j].Hmin = hTmp;
        // NOTE: We assume that for non-volume curve tanks Vmin doesn't change
        //       with Hmin. If not the case then a subsequent call setting
        //       EN_MINVOLUME must be made.
        break;
 
    case EN_MAXLEVEL:
        if (value <= 0.0) return 209;              // invalid water level
        if (index <= nJuncs) return 0;             // node not a tank
        j = index - nJuncs;                        // tank index
        if (Tank[j].A == 0.0) return 0;            // tank is a reservoir
        hTmp = value / Ucf[ELEV] + Node[index].El; // convert level to head
        if (hTmp < Tank[j].Hmin ||
            hTmp < Tank[j].H0) return 225;         // invalid water levels
        i = Tank[j].Vcurve;                        // volume curve index
        if (i > 0)                                 // tank has a volume curve
        {
            curve = &net->Curve[i];
            n = curve->Npts - 1;                   // last point on curve
            if (value > curve->X[n]) return 225;   // new level is off curve
        }
        Tank[j].Hmax = hTmp;                       // new max. head
        vTmp = Tank[j].Vmax;                       // old max. volume
        Tank[j].Vmax = tankvolume(p, j, hTmp);     // new max. volume
        Tank[j].V1max *= Tank[j].Vmax / vTmp;      // new mix zone volume
        break;
 
    case EN_MIXMODEL:
        j = ROUND(value);
        if (index <= nJuncs) return 0;
        if (j < MIX1 || j > LIFO) return 251;
        if (Tank[index - nJuncs].A > 0.0)
        {
            Tank[index - nJuncs].MixModel = (MixType)j;
        }
        break;
 
    case EN_MIXFRACTION:
        if (index <= nJuncs) return 0;
        if (value < 0.0 || value > 1.0) return 209;
        j = index - nJuncs;
        if (Tank[j].A > 0.0)
        {
            Tank[j].V1max = value * Tank[j].Vmax;
        }
        break;
 
    case EN_TANK_KBULK:
        if (index <= nJuncs) return 0;
        j = index - nJuncs;
        if (Tank[j].A > 0.0)
        {
            Tank[j].Kb = value / SECperDAY;
            qual->Reactflag = 1;
        }
        break;
 
    case EN_CANOVERFLOW:
        if (Node[index].Type != TANK) return 0;
        Tank[index - nJuncs].CanOverflow = (value != 0.0);
        break;
 
    default:
        return 251;
    }
    return 0;
}
 
int DLLEXPORT EN_setjuncdata(EN_Project p, int index, double elev,
                             double dmnd, char *dmndpat)
/*----------------------------------------------------------------
**  Input:   index = junction node index
**           elev = junction elevation
**           dmnd = junction primary base demand
**           dmndpat = name of primary demand time pattern
**  Output:  none
**  Returns: error code
**  Purpose: sets several properties for a junction node
**----------------------------------------------------------------
*/
{
    int patIndex = 0;
    Snode *node;
 
    // Check that junction exists
    if (!p->Openflag) return 102;
    if (index <= 0 || index > p->network.Njuncs) return 203;
 
    // Check that demand pattern exists
    if (dmndpat && strlen(dmndpat) > 0)
    {
        if (EN_getpatternindex(p, dmndpat, &patIndex) > 0) return 205;
    }
 
    // Assign demand parameters to junction's primary demand category
    node = &(p->network.Node[index]);
    dmnd /= p->Ucf[FLOW];
    // Category exists - update its properties
    if (node->D)
    {
        (node->D)->Base = dmnd;
        (node->D)->Pat = patIndex;
    }
    // No demand categories exist -- create a new one
    else if (!adddemand(node, dmnd, patIndex, NULL)) return 101;
 
    // Assign new elevation value to junction
    node->El = elev / p->Ucf[ELEV];
    return 0;
}
 
int DLLEXPORT EN_settankdata(EN_Project p, int index, double elev,
                             double initlvl, double minlvl,
                             double maxlvl, double diam,
                             double minvol, char *volcurve)
/*----------------------------------------------------------------
**  Input:   index = tank node index
**           elev = tank bottom elevation
**           initlvl = initial water depth
**           minlvl = minimum water depth
**           maxlvl = maximum water depth
**           diam = tank diameter
**           minvol = tank volume at minimum level
**           volCurve = name of curve for volume v. level
**  Output:  none
**  Returns: error code
**  Purpose: sets several properties for a tank node
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    int i, j, n, curveIndex = 0;
    double area, elevation = elev;
    double *Ucf = p->Ucf;
    Stank *Tank = net->Tank;
    Scurve *curve;
 
    // Check that tank exists
    if (!p->Openflag) return 102;
    if (index <= net->Njuncs || index > net->Nnodes) return 203;
    j = index - net->Njuncs;
    if (Tank[j].A == 0) return 0;  // Tank is a Reservoir
 
    // Check for valid parameter values
    if (initlvl < 0.0 || minlvl < 0.0 || maxlvl < 0.0) return 209;
    if (minlvl > initlvl || minlvl > maxlvl || initlvl > maxlvl) return 225;
    if (diam < 0.0 || minvol < 0.0) return 209;
 
    // volume curve supplied
    if (strlen(volcurve) > 0)
    {
        for (i = 1; i <= net->Ncurves; i++)
        {
            if (strcmp(volcurve, net->Curve[i].ID) == 0)
            {
                curveIndex = i;
                break;
            }
        }
        if (curveIndex == 0) return 206;
        curve = &net->Curve[curveIndex];
        n = curve->Npts - 1;
        if (minlvl < curve->X[0] || maxlvl > curve->X[n]) return 225;
        area = (curve->Y[n] - curve->Y[0]) / (curve->X[n] - curve->X[0]);
    }
 
    // Tank diameter supplied
    else area = PI * diam * diam / 4.0;
 
    // Assign parameters to tank object
    net->Node[Tank[j].Node].El = elevation;
    Tank[j].A = area / Ucf[ELEV] / Ucf[ELEV];
    Tank[j].H0 = elevation + initlvl / Ucf[ELEV];
    Tank[j].Hmin = elevation + minlvl / Ucf[ELEV];
    Tank[j].Hmax = elevation + maxlvl / Ucf[ELEV];
    Tank[j].Vcurve = curveIndex;
    if (curveIndex == 0)
    {
        if (minvol > 0.0) Tank[j].Vmin = minvol / Ucf[VOLUME];
        else Tank[j].Vmin = Tank[j].A * Tank[j].Hmin;
    }
    else Tank[j].Vmin = tankvolume(p, j, Tank[j].Hmin);
    Tank[j].V0 = tankvolume(p, j, Tank[j].H0);
    Tank[j].Vmax = tankvolume(p, j, Tank[j].Hmax);
    return 0;
}
 
int DLLEXPORT EN_getcoord(EN_Project p, int index, double *x, double *y)
/*----------------------------------------------------------------
**  Input:   index = node index
**  Output:  x = node x-coordinate
**           y = node y-coordinate
**  Returns: error code
**  Purpose: retrieves the coordinates of a node
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Snode *node;
 
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Nnodes) return 203;
 
    // check if node has coords
    node = &net->Node[index];
    if (node->X == MISSING ||
        node->Y == MISSING) return 254;
 
    *x = (double)(node->X);
    *y = (double)(node->Y);
    return 0;
}
 
int DLLEXPORT EN_setcoord(EN_Project p, int index, double x, double y)
/*----------------------------------------------------------------
**  Input:   index = node index
**           x = node x-coordinate
**           y = node y-coordinate
**  Output:  none
**  Returns: error code
**  Purpose: sets the coordinates of a node
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Snode *node;
 
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Nnodes) return 203;
    node = &net->Node[index];
    node->X = x;
    node->Y = y;
    return 0;
}
 
/********************************************************************
 
    Nodal Demand Functions
 
********************************************************************/
 
int DLLEXPORT EN_getdemandmodel(EN_Project p, int *model, double *pmin,
                                double *preq, double *pexp)
/*----------------------------------------------------------------
**  Input:   none
**  Output:  model = type of demand model (see EN_DemandModel)
**           pmin = minimum pressure for any demand
**           preq = required pressure for full demand
**           pexp = exponent in pressure dependent demand formula
**  Returns: error code
**  Purpose: retrieves the parameters of a project's demand model
**----------------------------------------------------------------
*/
{
    *model = p->hydraul.DemandModel;
    *pmin = p->hydraul.Pmin * p->Ucf[PRESSURE];
    *preq = p->hydraul.Preq * p->Ucf[PRESSURE];
    *pexp = p->hydraul.Pexp;
    return 0;
}
 
int DLLEXPORT EN_setdemandmodel(EN_Project p, int model, double pmin,
                                double preq, double pexp)
/*----------------------------------------------------------------
**  Input:   model = type of demand model (see EN_DemandModel)
**           pmin = minimum pressure for any demand
**           preq = required pressure for full demand
**           pexp = exponent in pressure dependent demand formula
**  Output:  none
**  Returns: error code
**  Purpose: sets the parameters of a project's demand model
**----------------------------------------------------------------
*/
{
    if (model < 0 || model > EN_PDA) return 251;
    if (model == EN_PDA)
    {
        if (pexp <= 0.0) return 208;
        if (pmin < 0.0) return 208;
        if (preq - pmin < MINPDIFF) return 208;
    }
    p->hydraul.DemandModel = model;
    p->hydraul.Pmin = pmin / p->Ucf[PRESSURE];
    p->hydraul.Preq = preq / p->Ucf[PRESSURE];
    p->hydraul.Pexp = pexp;
    return 0;
}
 
int  DLLEXPORT EN_adddemand(EN_Project p, int nodeIndex, double baseDemand,
                            char *demandPattern, char *demandName)
/*----------------------------------------------------------------
**  Input:   nodeIndex = node index
**           baseDemand = baseline demand value
**           demandPattern = name of demand's time pattern (can be NULL or empty)
**           demandName = name of demand's category (can be NULL or empty)
**  Returns: error code
**  Purpose: adds a new demand category to a junction node
**----------------------------------------------------------------
*/
{
    int patIndex = 0;
    Snode *node;
 
    // Check for valid arguments
    if (!p->Openflag) return 102;
    if (nodeIndex <= 0 || nodeIndex > p->network.Nnodes) return 203;
    if (demandPattern && strlen(demandPattern) > 0)
    {
        if (EN_getpatternindex(p, demandPattern, &patIndex) > 0) return 205;
    }
 
    // Do nothing if node is not a junction
    if (nodeIndex > p->network.Njuncs) return 0;
 
    // Add the new demand to the node's demands list
    node = &(p->network.Node[nodeIndex]);
    if (!adddemand(node, baseDemand / p->Ucf[FLOW], patIndex, demandName)) return 101;
    return 0;
}
 
int DLLEXPORT EN_deletedemand(EN_Project p, int nodeIndex, int demandIndex)
/*----------------------------------------------------------------
**  Input:   nodeIndex = node index
**           demandIndex = index of node's demand to be deleted
**  Returns: error code
**  Purpose: deletes an existing demand category from a junction node
**----------------------------------------------------------------
*/
{
    Pdemand d, dprev;
    Snode *node;
    int n = 1;
 
    // Check for valid arguments
    if (!p->Openflag) return 102;
    if (nodeIndex <= 0 || nodeIndex > p->network.Nnodes) return 203;
 
    // Only junctions have demands
    if (nodeIndex <= p->network.Njuncs)
    {
        // Find head of node's list of demands
        node = &p->network.Node[nodeIndex];
        d = node->D;
        if (d == NULL) return 253;
        dprev = d;
 
        // Check if target demand is head of demand list
        if (demandIndex == 1)
        {
            node->D = d->next;
            free(d->Name);
            free(d);
            return 0;
        }
 
        // Otherwise locate target demand in demand list
        while (d != NULL && n < demandIndex)
        {
            dprev = d;
            d = d->next;
            n++;
        }
 
        // Return error if target demand not found
        if (d == NULL) return 253;
 
        // Link the demands that precede and follow the target
        dprev->next = d->next;
 
        // Delete the target demand
        free(d->Name);
        free(d);
    }
    return 0;
}
 
int DLLEXPORT EN_getdemandindex(EN_Project p, int nodeIndex, char *demandName,
                                int *demandIndex)
/*----------------------------------------------------------------
**  Input:   nodeIndex = node index
**           demandName = name of demand being sought
**  Output:  demandIndex  = index of demand being sought
**  Returns: error code
**  Purpose: retrieves the position of a named demand category
**           in a node's list of demands
**----------------------------------------------------------------
*/
{
    Pdemand d;
    int n = 0;
    int nameEmpty = FALSE;
    int found = FALSE;
 
    // Check for valid arguments
    *demandIndex = 0;
    if (!p->Openflag) return 102;
    if (nodeIndex <= 0 || nodeIndex > p->network.Nnodes) return 203;
    if (demandName == NULL) return 253;
 
    // Check if target name is empty
    if (strlen(demandName) == 0) nameEmpty = TRUE;
 
    // Locate target demand in node's demands list
    for (d = p->network.Node[nodeIndex].D; d != NULL; d = d->next)
    {
        n++;
        if (d->Name == NULL)
        {
            if (nameEmpty) found = TRUE;;
        }
        else if (strcmp(d->Name, demandName) == 0) found = TRUE;
        if (found) break;
    }
 
    // Return target demand's index
    if (!found) return 253;
    *demandIndex = n;
    return 0;
}
 
int DLLEXPORT EN_getnumdemands(EN_Project p, int nodeIndex, int *numDemands)
/*----------------------------------------------------------------
**  Input:   nodeIndex = node index
**  Output:  numDemands  = number of demand categories
**  Returns: error code
**  Purpose: retrieves the number of demand categories for a node
**----------------------------------------------------------------
*/
{
    Pdemand d;
    int n = 0;
 
    // Check for valid arguments
    if (!p->Openflag) return 102;
    if (nodeIndex <= 0 || nodeIndex > p->network.Nnodes) return 203;
 
    // Count the number of demand categories assigned to node
    for (d = p->network.Node[nodeIndex].D; d != NULL; d = d->next) n++;
    *numDemands = n;
    return 0;
}
 
//int DLLEXPORT EN_getTotalDemand(EN_Project pr, int p, double *value)
//{
//    Network* net = &pr->network;
//    Hydraul* hyd = &pr->hydraul;
//    Times* time = &pr->times;
//
//    int  i, j, n;
//    long k;
//    double djunc, sum,totaldemand;
//    Pdemand demand;
//
//    totaldemand = 0;
//    // Determine total elapsed number of pattern periods
//    //p = (time->Htime + time->Pstart) / time->Pstep;
//
//    // Update demand at each node according to its assigned pattern
//    //hyd->Dsystem = 0.0;          // System-wide demand
//    for (i = 1; i <= net->Njuncs; i++)
//    {
//        sum = 0.0;
//        for (demand = net->Node[i].D; demand != NULL; demand = demand->next)
//        {
//            if (net->Node[i].Type == JUNCTION)
//            {
//                // pattern period (k) = (elapsed periods) modulus (periods per pattern)
//                j = demand->Pat;
//                k = p % (long)net->Pattern[j].Length;
//                djunc = (demand->Base) * net->Pattern[j].F[k];
//                //if (djunc > 0.0) hyd->Dsystem += djunc;
//                sum += djunc;
//            }
//        }
//        //hyd->NodeDemand[i] = sum;
//        // Initialize pressure dependent demand
//        // hyd->DemandFlow[i] = sum;
//
//        totaldemand += sum;
//    }
//    *value = totaldemand * pr->Ucf[FLOW];
//    return 0;
//}
//ÄâÐ޸ģ¨Ôö¼Ó±£»¤£©
int DLLEXPORT EN_getTotalDemand(EN_Project pr, int p, double* value)
{
    Network* net = &pr->network;
    Hydraul* hyd = &pr->hydraul;
    Times* time = &pr->times;
 
    int  i, j, n;
    long k;
    double djunc, sum, totaldemand;
    Pdemand demand;
    if (p < 0) return 0;//Ôö¼Ó±£»¤
    totaldemand = 0;
 
    for (i = 1; i <= net->Njuncs; i++)
    {
        sum = 0.0;
        if (net->Node[i].Type == JUNCTION) {  // ¼ì²é½ÚµãÀàÐÍ
            for (demand = net->Node[i].D; demand != NULL; demand = demand->next)
            {
                j = demand->Pat;
                if (j >= 0 && j < net->Npats) {  // ¼ì²éģʽË÷ÒýÊÇ·ñÔ½½ç
                    k = p % (long)net->Pattern[j].Length;
                    djunc = (demand->Base) * net->Pattern[j].F[k];
                    sum += djunc;
                }
            }
        }
 
        totaldemand += sum;
    }
    *value = totaldemand * pr->Ucf[FLOW];
    return 0;
}
int DLLEXPORT EN_getbasedemand(EN_Project p, int nodeIndex, int demandIndex,
                               double *baseDemand)
/*----------------------------------------------------------------
**  Input:   nodeIndex = node index
**           demandIndex = demand category index
**  Output:  baseDemand = baseline demand value
**  Returns: error code
**  Purpose: retrieves the baseline value for a node's demand category
**----------------------------------------------------------------
*/
{
    Pdemand d;
 
    // Check for valid arguments
    *baseDemand = 0.0;
    if (!p->Openflag) return 102;
    if (nodeIndex <= 0 || nodeIndex > p->network.Nnodes) return 203;
 
    // Locate target demand in node's demands list
    d = finddemand(p->network.Node[nodeIndex].D, demandIndex);
    if (d == NULL) return 253;
 
    // Retrieve target demand's base value
    *baseDemand = d->Base * p->Ucf[FLOW];
    return 0;
}
 
int DLLEXPORT EN_setbasedemand(EN_Project p, int nodeIndex, int demandIndex,
                               double baseDemand)
/*----------------------------------------------------------------
**  Input:   nodeIndex = node index
**           demandIndex = demand category index
**           baseDemand = baseline demand value
**  Output:  none
**  Returns: error code
**  Purpose: sets the baseline value for a node's demand category
**----------------------------------------------------------------
*/
{
    Pdemand d;
 
    // Check for valid arguments
    if (!p->Openflag) return 102;
    if (nodeIndex <= 0 || nodeIndex > p->network.Nnodes) return 203;
 
    // Locate target demand in node's demands list
    d = finddemand(p->network.Node[nodeIndex].D, demandIndex);
    if (d == NULL) return 253;
 
    // Assign new base value to target demand
    d->Base = baseDemand / p->Ucf[FLOW];
    return 0;
}
 
int DLLEXPORT EN_getdemandname(EN_Project p, int nodeIndex, int demandIndex,
                               char *demandName)
/*----------------------------------------------------------------
**  Input:   nodeIndex = node index
**           demandIndex = demand category index
**  Output:  demandname = demand category name
**  Returns: error code
**  Purpose: retrieves the name assigned to a node's demand category
**----------------------------------------------------------------
*/
{
    Pdemand d;
 
    strcpy(demandName, "");
 
    // Check for valid arguments
    if (!p->Openflag) return 102;
    if (nodeIndex <= 0 || nodeIndex > p->network.Njuncs) return 203;
 
    // Locate target demand in node's demands list
    d = finddemand(p->network.Node[nodeIndex].D, demandIndex);
    if (d == NULL) return 253;
 
    // Retrieve target demand's category name
    if (d->Name) strcpy(demandName, d->Name);
    return 0;
}
 
int DLLEXPORT EN_setdemandname(EN_Project p, int nodeIndex, int demandIndex,
                               char *demandName)
/*----------------------------------------------------------------
**  Input:   nodeIndex = node index
**           demandIndex = demand category index
**           demandName = name of demand category
**  Output:  none
**  Returns: error code
**  Purpose: assigns a name to a node's demand category
**----------------------------------------------------------------
*/
{
    Pdemand d;
 
    // Check for valid arguments
    if (!p->Openflag) return 102;
    if (nodeIndex <= 0 || nodeIndex > p->network.Njuncs) return 203;
 
    // Locate target demand in node's demands list
    d = finddemand(p->network.Node[nodeIndex].D, demandIndex);
    if (d == NULL) return 253;
 
    // Assign category name to target demand
    d->Name = xstrcpy(&d->Name, demandName, MAXID);
    return 0;
}
 
int DLLEXPORT EN_getdemandpattern(EN_Project p, int nodeIndex, int demandIndex,
                                  int *patIndex)
/*----------------------------------------------------------------
**  Input:   nodeIndex = node index
**           demandIndex = demand category index
**  Output:  patIndex = time pattern index
**  Returns: error code
**  Purpose: retrieves the time pattern assigned to a node's
**           demand category
**----------------------------------------------------------------
*/
{
    Pdemand d;
 
    // Check for valid arguments
    *patIndex = 0;
    if (!p->Openflag) return 102;
    if (nodeIndex <= 0 || nodeIndex > p->network.Nnodes) return 203;
 
    // Locate target demand in node's demand list
    d = finddemand(p->network.Node[nodeIndex].D, demandIndex);
    if (d == NULL) return 253;
 
    // Retrieve that demand's pattern index
    *patIndex = d->Pat;
    return 0;
}
 
int  DLLEXPORT EN_setdemandpattern(EN_Project p, int nodeIndex, int demandIndex,
                                   int patIndex)
/*----------------------------------------------------------------
**  Input:   nodeIndex = node index
**           demandIndex = demand category index
**           patIndex = time pattern index
**  Output:  none
**  Returns: error code
**  Purpose: assigns a time pattern to a node's demand category
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    Pdemand d;
 
    // Check for valid arguments
    if (!p->Openflag) return 102;
    if (nodeIndex <= 0 || nodeIndex > net->Nnodes) return 203;
    if (patIndex < 0 || patIndex > net->Npats) return 205;
 
    // Locate target demand in node's demand list
    d = finddemand(p->network.Node[nodeIndex].D, demandIndex);
    if (d == NULL) return 253;
 
    // Assign new time pattern to target demand
    d->Pat = patIndex;
    return 0;
}
 
/********************************************************************
 
    Link Functions
 
********************************************************************/
 
int DLLEXPORT EN_addlink(EN_Project p, char *id, int linkType,
                         char *fromNode, char *toNode, int *index)
/*----------------------------------------------------------------
**  Input:   id = link ID name
**           type = link type (see EN_LinkType)
**           fromNode = name of link's starting node
**           toNode = name of link's ending node
**  Output:  index = position of new link in Link array
**  Returns: error code
**  Purpose: adds a new link to a project
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Hydraul *hyd = &p->hydraul;
 
    int i, n, size, errcode;
    int n1, n2;
    Slink *link;
    Spump *pump;
 
    // Cannot modify network structure while solvers are active
    *index = 0;
    if (!p->Openflag) return 102;
    if (p->hydraul.OpenHflag || p->quality.OpenQflag) return 262;
 
    // Check if id name contains invalid characters
    if (!namevalid(id)) return 252;
 
    // Check if a link with same id already exists
    if (EN_getlinkindex(p, id, &i) == 0) return 215;
 
    // Check for valid link type
    if (linkType < CVPIPE || linkType > GPV) return 251;
 
    // Lookup the link's from and to nodes
    n1 = hashtable_find(net->NodeHashTable, fromNode);
    n2 = hashtable_find(net->NodeHashTable, toNode);
    if (n1 == 0 || n2 == 0) return 203;
 
    // Check that valve link has legal connections
    if (linkType > PUMP)
    {
        errcode = valvecheck(p, 0, linkType, n1, n2);
        if (errcode) return errcode;
    }
 
    // Grow link-related arrays to accomodate the new link
    net->Nlinks++;
    p->parser.MaxLinks = net->Nlinks;
    n = net->Nlinks;
    size = (n + 1) * sizeof(Slink);
    net->Link = (Slink *)realloc(net->Link, size);
    size = (n + 1) * sizeof(double);
    hyd->LinkFlow = (double *)realloc(hyd->LinkFlow, size);
    hyd->LinkSetting = (double *)realloc(hyd->LinkSetting, size);
    size = (n + 1) * sizeof(StatusType);
    hyd->LinkStatus = (StatusType *)realloc(hyd->LinkStatus, size);
 
    // Set properties for the new link
    link = &net->Link[n];
    strncpy(link->ID, id, MAXID);
 
    if (linkType <= PIPE) net->Npipes++;
    else if (linkType == PUMP)
    {
        // Grow pump array to accomodate the new link
        net->Npumps++;
        size = (net->Npumps + 1) * sizeof(Spump);
        net->Pump = (Spump *)realloc(net->Pump, size);
        pump = &net->Pump[net->Npumps];
        pump->Link = n;
        pump->Ptype = NOCURVE;
        pump->Q0 = 0;
        pump->Qmax = 0;
        pump->Hmax = 0;
        pump->H0 = 0;
        pump->R = 0;
        pump->N = 0;
        pump->Hcurve = 0;
        pump->Ecurve = 0;
        pump->Upat = 0;
        pump->Epat = 0;
        pump->Ecost = 0;
        pump->Energy.TotalCost = MISSING;
    }
    else
    {
        // Grow valve array to accomodate the new link
        net->Nvalves++;
        size = (net->Nvalves + 1) * sizeof(Svalve);
        net->Valve = (Svalve *)realloc(net->Valve, size);
        net->Valve[net->Nvalves].Link = n;
    }
 
    link->Type =(LinkType) linkType;
    link->N1 = n1;
    link->N2 = n2;
    link->Status = OPEN;
 
    if (linkType == PUMP)
    {
        link->Kc = 1.0; // Speed factor
        link->Km = 0.0; // Horsepower
        link->Len = 0.0;
    }
    else if (linkType <= PIPE)  // pipe or cvpipe
    {
        // 10" diameter new ductile iron pipe with
        // length of average city block
        link->Diam = 10 / p->Ucf[DIAM];
        switch (hyd->Formflag)
        {
        case HW: link->Kc = 130;    break;
        case DW: link->Kc = 0.0005; break;
        case CM: link->Kc = 0.01;   break;
        default: link->Kc = 1.0;
        }
        link->Km = 0.0; // Loss coeff
        link->Len = 330.0;
    }
    else  // Valve
    {
        link->Diam = 10 / p->Ucf[DIAM];
        link->Kc = 0.0; // Valve setting.
        link->Km = 0.0; // Loss coeff
        link->Len = 0.0;
        link->Status = ACTIVE;
    }
    link->Kb = 0;
    link->Kw = 0;
    link->R = 0;
    link->Rc = 0;
    link->Rpt = 0;
    link->ResultIndex = 0;
    link->Comment = NULL;
    link->Vertices = NULL;
 
    hashtable_insert(net->LinkHashTable, link->ID, n);
    *index = n;
    return 0;
}
 
int DLLEXPORT EN_deletelink(EN_Project p, int index, int actionCode)
/*----------------------------------------------------------------
**  Input:   index  = index of the link to delete
**           actionCode = how to treat controls that contain the link:
**           EN_UNCONDITIONAL deletes all such controls plus the link,
**           EN_CONDITIONAL does not delete the link if it appears
**           in a control and returns an error code
**  Output:  none
**  Returns: error code
**  Purpose: deletes a link from a project
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    int i;
    int pumpindex;
    int valveindex;
    int linkType;
    Slink *link;
 
    // Cannot modify network structure while solvers are active
    if (!p->Openflag) return 102;
    if (p->hydraul.OpenHflag || p->quality.OpenQflag) return 262;
 
    // Check that link exists
    if (index <= 0 || index > net->Nlinks) return 204;
    if (actionCode < EN_UNCONDITIONAL || actionCode > EN_CONDITIONAL) return 251;
 
    // Deletion will be cancelled if link appears in any controls
    if (actionCode == EN_CONDITIONAL)
    {
        actionCode = incontrols(p, LINK, index);
        if (actionCode > 0) return 261;
    }
 
    // Get references to the link and its type
    link = &net->Link[index];
    EN_getlinktype(p, index, &linkType);
 
    // Remove link from its hash table
    hashtable_delete(net->LinkHashTable, link->ID);
 
    // Remove link's comment and vertices
    free(link->Comment);
    freelinkvertices(link);
 
    // Shift position of higher entries in Link array down one
    for (i = index; i <= net->Nlinks - 1; i++)
    {
        net->Link[i] = net->Link[i + 1];
        // ... update link's entry in the hash table
        hashtable_update(net->LinkHashTable, net->Link[i].ID, i);
    }
 
    // Adjust references to higher numbered links for pumps & valves
    for (i = 1; i <= net->Npumps; i++)
    {
        if (net->Pump[i].Link > index) net->Pump[i].Link -= 1;
    }
    for (i = 1; i <= net->Nvalves; i++)
    {
        if (net->Valve[i].Link > index) net->Valve[i].Link -= 1;
    }
 
    // Delete any pump associated with the deleted link
    if (linkType == PUMP)
    {
        pumpindex = findpump(net, index);
        for (i = pumpindex; i <= net->Npumps - 1; i++)
        {
            net->Pump[i] = net->Pump[i + 1];
        }
        net->Npumps--;
    }
 
    // Delete any valve (linkType > PUMP) associated with the deleted link
    if (linkType > PUMP)
    {
        valveindex = findvalve(net, index);
        for (i = valveindex; i <= net->Nvalves - 1; i++)
        {
            net->Valve[i] = net->Valve[i + 1];
        }
        net->Nvalves--;
    }
 
    // Delete any control containing the link
    for (i = net->Ncontrols; i >= 1; i--)
    {
        if (net->Control[i].Link == index) EN_deletecontrol(p, i);
    }
 
    // Adjust higher numbered link indices in remaining controls
    for (i = 1; i <= net->Ncontrols; i++)
    {
        if (net->Control[i].Link > index) net->Control[i].Link--;
    }
 
    // Make necessary adjustments to rule-based controls
    adjustrules(p, EN_R_LINK, index);  // see RULES.C
 
    // Reduce link count by one
    net->Nlinks--;
    return 0;
}
 
int DLLEXPORT EN_getlinkindex(EN_Project p, char *id, int *index)
/*----------------------------------------------------------------
**  Input:   id = link ID name
**  Output:  index = link index
**  Returns: error code
**  Purpose: retrieves the index of a link
**----------------------------------------------------------------
*/
{
    *index = 0;
    if (!p->Openflag) return 102;
    *index = findlink(&p->network, id);
    if (*index == 0) return 204;
    else return 0;
}
 
int DLLEXPORT EN_getlinkid(EN_Project p, int index, char *id)
/*----------------------------------------------------------------
**  Input:   index = link index
**  Output:  id = link ID name
**  Returns: error code
**  Purpose: retrieves the ID name of a link
**----------------------------------------------------------------
*/
{
    strcpy(id, "");
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Nlinks) return 204;
    strcpy(id, p->network.Link[index].ID);
    return 0;
}
 
 
int DLLEXPORT EN_getlinkcomment(EN_Project p, int index, char* id)
/*----------------------------------------------------------------
**  Input:   index = link index
**  Output:  id = link Comment
**  Returns: error code
**  Purpose: retrieves the ID name of a link
**----------------------------------------------------------------
*/
{
    strcpy(id, "");
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Nlinks) return 204;
    strcpy(id, p->network.Link[index].Comment);
    return 0;
}
 
int DLLEXPORT EN_setlinkid(EN_Project p, int index, char *newid)
/*----------------------------------------------------------------
**  Input:   index = link index
**           id = link ID name
**  Output:  none
**  Returns: error code
**  Purpose: sets the ID name of a link
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    // Check for valid arguments
    if (index <= 0 || index > net->Nlinks) return 204;
    if (!namevalid(newid)) return 252;
 
    // Check if another link with same name exists
    if (hashtable_find(net->LinkHashTable, newid) > 0) return 215;
 
    // Replace the existing link ID with the new value
    hashtable_delete(net->LinkHashTable, net->Link[index].ID);
    strncpy(net->Link[index].ID, newid, MAXID);
    hashtable_insert(net->LinkHashTable, net->Link[index].ID, index);
    return 0;
}
 
int DLLEXPORT EN_getlinktype(EN_Project p, int index, int *linkType)
/*----------------------------------------------------------------
**  Input:   index = link index
**  Output:  linkType = link type (see EN_LinkType)
**  Returns: error code
**  Purpose: retrieves the type code of a link
**----------------------------------------------------------------
*/
{
    *linkType = -1;
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Nlinks) return 204;
    *linkType = p->network.Link[index].Type;
    return 0;
}
 
int DLLEXPORT EN_setlinktype(EN_Project p, int *index, int linkType, int actionCode)
/*----------------------------------------------------------------
**  Input:   index = link index
**           linkType = new link type (see EN_LinkType)
**           actionCode = how to treat controls that contain the link:
**           EN_UNCONDITIONAL deletes all such controls,
**           EN_CONDITIONAL cancels the type change if the link appears
**           in a control and returns an error code
**  Output:  none
**  Returns: error code
**  Purpose: changes the type of a particular link (e.g. pipe to pump)
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    int i = *index, n1, n2;
    char id[MAXID + 1];
    char id1[MAXID + 1];
    char id2[MAXID + 1];
    int errcode;
    int oldType;
 
    // Cannot modify network structure while solvers are active
    if (!p->Openflag) return 102;
    if (p->hydraul.OpenHflag || p->quality.OpenQflag) return 262;
 
    // Check for valid input parameters
    if (linkType < 0 || linkType > GPV || actionCode < EN_UNCONDITIONAL ||
        actionCode > EN_CONDITIONAL)
    {
        return 251;
    }
 
    // Check for valid link index
    if (i <= 0 || i > net->Nlinks) return 204;
 
    // Check if current link type equals new type
    EN_getlinktype(p, i, &oldType);
    if (oldType == linkType) return 0;
 
    // Type change will be cancelled if link appears in any controls
    if (actionCode == EN_CONDITIONAL)
    {
        actionCode = incontrols(p, LINK, i);
        if (actionCode > 0) return 261;
    }
 
    // Pipe changing from or to having a check valve
    if (oldType <= PIPE && linkType <= PIPE)
    {
        net->Link[i].Type = (LinkType)linkType;
        if (linkType == CVPIPE) net->Link[i].Status = OPEN;
        return 0;
    }
 
    // Get ID's of link & its end nodes
    EN_getlinkid(p, i, id);
    EN_getlinknodes(p, i, &n1, &n2);
    EN_getnodeid(p, n1, id1);
    EN_getnodeid(p, n2, id2);
 
    // Check for illegal valve connections
    errcode = valvecheck(p, i, linkType, n1, n2);
    if (errcode) return errcode;
 
    // Delete the original link (and any controls containing it)
    EN_deletelink(p, i, actionCode);
 
    // Create a new link of new type and old id
    errcode = EN_addlink(p, id, linkType, id1, id2, index);
    return errcode;
}
 
int DLLEXPORT EN_getlinknodes(EN_Project p, int index, int *node1, int *node2)
/*----------------------------------------------------------------
**  Input:   index = link index
**  Output:  node1 = index of link's starting node
**           node2 = index of link's ending node
**  Returns: error code
**  Purpose: retrieves the start and end nodes of a link
**----------------------------------------------------------------
*/
{
    *node1 = 0;
    *node2 = 0;
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Nlinks) return 204;
    *node1 = p->network.Link[index].N1;
    *node2 = p->network.Link[index].N2;
    return 0;
}
 
int DLLEXPORT EN_setlinknodes(EN_Project p, int index, int node1, int node2)
/*----------------------------------------------------------------
**  Input:   index = link index
**           node1 = index of link's new starting node
**           node2 = index of link's new ending node
**  Returns: error code
**  Purpose: sets the start and end nodes of a link
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    int type, errcode;
 
    // Cannot modify network structure while solvers are active
    if (p->hydraul.OpenHflag || p->quality.OpenQflag) return 262;
 
    // Check for valid link index
    if (index <= 0 || index > net->Nlinks) return 204;
 
    // Check that nodes exist
    if (node1 < 0 || node1 > net->Nnodes) return 203;
    if (node2 < 0 || node2 > net->Nnodes) return 203;
 
    // Check that nodes are not the same
    if (node1 == node2) return 222;
 
    // Do nothing if the new nodes are the same as the old ones
    if (node1 == net->Link[index].N1 && node2 == net->Link[index].N2)
        return 0;
 
    // Check for illegal valve connection
    type = net->Link[index].Type;
    if (type > PUMP)
    {
        errcode = valvecheck(p, index, type, node1, node2);
        if (errcode) return errcode;
    }
 
    // Assign new end nodes to link
    net->Link[index].N1 = node1;
    net->Link[index].N2 = node2;
    return 0;
}
 
int DLLEXPORT EN_getlinkvalue(EN_Project p, int index, int property, double *value)
/*----------------------------------------------------------------
**  Input:   index = link index
**           property = link property code (see EN_LinkProperty)
**  Output:  value = link property value
**  Returns: error code
**  Purpose: retrieves a property value for a link
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Hydraul *hyd = &p->hydraul;
 
    double a, h, q, v = 0.0;
    int pmp;
    Slink *Link = net->Link;
    Spump *Pump = net->Pump;
    double *Ucf = p->Ucf;
    double *LinkFlow = hyd->LinkFlow;
    double *LinkSetting = hyd->LinkSetting;
 
    // Check for valid arguments
    *value = 0.0;
    if (!p->Openflag) return 102;
    if (index <= 0 || index > net->Nlinks) return 204;
 
    // Retrieve called-for property
    switch (property)
    {
    case EN_DIAMETER:
        if (Link[index].Type == PUMP) v = 0.0;
        else v = Link[index].Diam * Ucf[DIAM];
        break;
 
    case EN_LENGTH:
        v = Link[index].Len * Ucf[ELEV];
        break;
 
    case EN_ROUGHNESS:
        if (Link[index].Type <= PIPE)
        {
            if (hyd->Formflag == DW) v = Link[index].Kc * (1000.0 * Ucf[ELEV]);
            else v = Link[index].Kc;
        }
        else v = 0.0;
        break;
 
    case EN_MINORLOSS:
        if (Link[index].Type != PUMP)
        {
            v = Link[index].Km;
            v *= (SQR(Link[index].Diam) * SQR(Link[index].Diam) / 0.02517);
        }
        else v = 0.0;
        break;
 
    case EN_INITSTATUS:
        if (Link[index].Status <= CLOSED) v = 0.0;
        else v = 1.0;
        break;
 
    case EN_INITSETTING:
        if (Link[index].Type == PIPE || Link[index].Type == CVPIPE)
        {
            return EN_getlinkvalue(p, index, EN_ROUGHNESS, value);
        }
        v = Link[index].Kc;
        switch (Link[index].Type)
        {
        case PRV:
        case PSV:
        case PBV:
            v *= Ucf[PRESSURE];
            break;
        case FCV:
            v *= Ucf[FLOW];
        default:
            break;
        }
        break;
 
    case EN_KBULK:
        v = Link[index].Kb * SECperDAY;
        break;
 
    case EN_KWALL:
        v = Link[index].Kw * SECperDAY;
        break;
 
    case EN_FLOW:
        if (hyd->LinkStatus[index] <= CLOSED) v = 0.0;
        else v = LinkFlow[index] * Ucf[FLOW];
        break;
 
    case EN_VELOCITY:
        if (Link[index].Type == PUMP) v = 0.0;
        else if (hyd->LinkStatus[index] <= CLOSED) v = 0.0;
        else
        {
            q = ABS(LinkFlow[index]);
            a = PI * SQR(Link[index].Diam) / 4.0;
            v = q / a * Ucf[VELOCITY];
        }
        break;
 
    case EN_HEADLOSS:
        if (hyd->LinkStatus[index] <= CLOSED) v = 0.0;
        else
        {
            h = hyd->NodeHead[Link[index].N1] - hyd->NodeHead[Link[index].N2];
            if (Link[index].Type != PUMP) h = ABS(h);
            v = h * Ucf[HEADLOSS];
        }
        break;
 
    case EN_STATUS:
        if (hyd->LinkStatus[index] <= CLOSED) v = 0.0;
        else v = 1.0;
        break;
 
    case EN_SETTING:
        if (Link[index].Type == PIPE || Link[index].Type == CVPIPE)
        {
            return EN_getlinkvalue(p, index, EN_ROUGHNESS, value);
        }
        if (LinkSetting[index] == MISSING) v = 0.0;
        else v = LinkSetting[index];
        switch (Link[index].Type)
        {
        case PRV:
        case PSV:
        case PBV:
            v *= Ucf[PRESSURE];
            break;
        case FCV:
            v *= Ucf[FLOW];
        default:
            break;
        }
        break;
 
    case EN_ENERGY:
        getenergy(p, index, &v, &a);
        break;
 
    case EN_LINKQUAL:
        v = avgqual(p, index) * Ucf[LINKQUAL];
        break;
 
    case EN_LINKPATTERN:
        if (Link[index].Type == PUMP)
        {
            v = (double)Pump[findpump(&p->network, index)].Upat;
        }
        break;
 
    case EN_PUMP_STATE:
        v = hyd->LinkStatus[index];
 
        if (Link[index].Type == PUMP)
        {
            pmp = findpump(net, index);
            if (hyd->LinkStatus[index] >= OPEN)
            {
                if (hyd->LinkFlow[index] > hyd->LinkSetting[index] * Pump[pmp].Qmax)
                {
                    v = XFLOW;
                }
                if (hyd->LinkFlow[index] < 0.0) v = XHEAD;
            }
        }
        break;
 
    case EN_PUMP_EFFIC:
        getenergy(p, index, &a, &v);
        break;
 
    case EN_PUMP_POWER:
        v = 0;
        if (Link[index].Type == PUMP)
        {
            pmp = findpump(net, index);
            if (Pump[pmp].Ptype == CONST_HP) v = Link[index].Km; // Power in HP or KW
        }
        break;
 
    case EN_PUMP_HCURVE:
        if (Link[index].Type == PUMP)
        {
            v = (double)Pump[findpump(&p->network, index)].Hcurve;
        }
        break;
 
    case EN_PUMP_ECURVE:
        if (Link[index].Type == PUMP)
        {
            v = (double)Pump[findpump(&p->network, index)].Ecurve;
        }
        break;
 
    case EN_PUMP_ECOST:
        if  (Link[index].Type == PUMP)
        {
            v = (double)Pump[findpump(&p->network, index)].Ecost;
        }
        break;
 
    case EN_PUMP_EPAT:
        if (Link[index].Type == PUMP)
        {
            v = (double)Pump[findpump(&p->network, index)].Epat;
        }
        break;
     /*----------begin sh3h-------*/
#if W30
    case EN_MINORHEAD:
        {
            double q = ABS(hyd->LinkFlow[index]);                         /* Absolute flow       */
            double ml = Link[index].Km;             /* Minor loss coeff.   */
            double hpipe = ml*SQR(q);
            v = hpipe*Ucf[HEADLOSS];
            break ;
        }
    case EN_FRICTIONHEAD:
        {
            double q = ABS(hyd->LinkFlow[index]);                         /* Absolute flow       */
            double r = Link[index].R;                /* Resistance coeff.   */      
            double hpipe = 0;
            double f = 1.0;
            double r1;                               /* D-W friction factor */
            if (hyd->Formflag == DW)
            {
                hpipe = r * pow(q, hyd->Hexp);
            }
            else
            {
                hpipe = r * pow(q, hyd->Hexp);
            }
            v = hpipe * Ucf[HEADLOSS];
            break;
        }
    case EN_VOLUMN:
          v = 0.0;
          if ( index > net->Njuncs ) v =net->Tank[index-net->Njuncs].V*Ucf[VOLUME];
 
          break;
    case EN_SPEED:
        if (Link[index].Type == PUMP)
        {
            v = Link[index].Kc;
        }
        break;
    case EN_POWER:
          double v1, v2;
          EN_getnodevalue(p, Link[index].N1, EN_PRESSURE, &v1);
          EN_getnodevalue(p,Link[index].N2, EN_PRESSURE, &v2);
          if (hyd->LinkStatus[index] <= CLOSED) v = 0.0;
          else v = hyd->LinkFlow[index]*Ucf[FLOW];
          v = 1000 * v / 1000 * ABS(v1 - v2);
          break;
 
#endif
     /*----------end sh3h-------*/
    default:
        return 251;
    }
    *value = (double)v;
    return 0;
}
 
int DLLEXPORT EN_setlinkvalue(EN_Project p, int index, int property, double value)
/*----------------------------------------------------------------
**  Input:   index = link index
**           property  = link property code (see EN_LinkProperty)
**           value = property value
**  Output:  none
**  Returns: error code
**  Purpose: sets a property value for a link
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Hydraul *hyd = &p->hydraul;
    Quality *qual = &p->quality;
 
    Slink *Link = net->Link;
    double *Ucf = p->Ucf;
    double *LinkSetting = hyd->LinkSetting;
    char s;
    double r;
    int pumpIndex, patIndex, curveIndex;
 
    if (!p->Openflag) return 102;
    if (index <= 0 || index > net->Nlinks) return 204;
    switch (property)
    {
    case EN_DIAMETER:
        if (Link[index].Type != PUMP)
        {
            if (value <= 0.0) return 211;
            value /= Ucf[DIAM];                // Convert to feet
            r = Link[index].Diam / value;      // Ratio of old to new diam
            Link[index].Km *= SQR(r) * SQR(r); // Adjust minor loss factor
            Link[index].Diam = value;          // Update diameter
            resistcoeff(p, index);             // Update resistance coeff.
        }
        break;
 
    case EN_LENGTH:
        if (Link[index].Type <= PIPE)
        {
            if (value <= 0.0) return 211;
            Link[index].Len = value / Ucf[ELEV];
            resistcoeff(p, index);
        }
        break;
 
    case EN_ROUGHNESS:
        if (Link[index].Type <= PIPE)
        {
            if (value <= 0.0) return 211;
            Link[index].Kc = value;
            if (hyd->Formflag == DW) Link[index].Kc /= (1000.0 * Ucf[ELEV]);
            resistcoeff(p, index);
        }
        break;
 
    case EN_MINORLOSS:
        if (Link[index].Type != PUMP)
        {
            if (value <= 0.0) return 211;
            Link[index].Km = 0.02517 * value / SQR(Link[index].Diam) /
                             SQR(Link[index].Diam);
        }
        break;
 
    case EN_INITSTATUS:
    case EN_STATUS:
        // Cannot set status for a check valve
        if (Link[index].Type == CVPIPE) return 207;
        s = (char)ROUND(value);
        if (s < 0 || s > 1) return 211;
        if (property == EN_INITSTATUS)
        {
            setlinkstatus(p, index, s, &Link[index].Status, &Link[index].Kc);
        }
        else
        {
            setlinkstatus(p, index, s, &hyd->LinkStatus[index], &LinkSetting[index]);
        }
        break;
 
    case EN_INITSETTING:
    case EN_SETTING:
        if (value < 0.0) return 211;
        if (Link[index].Type == PIPE || Link[index].Type == CVPIPE)
        {
            return EN_setlinkvalue(p, index, EN_ROUGHNESS, value);
        }
        else
        {
            switch (Link[index].Type)
            {
            case PUMP:
                break;
            case PRV:
            case PSV:
            case PBV:
                value /= Ucf[PRESSURE];
                break;
            case FCV:
                value /= Ucf[FLOW];
                break;
            case TCV:
                break;
            case GPV:
                return 207; // Cannot modify setting for GPV
            default:
                return 0;
            }
            if (property == EN_INITSETTING)
            {
                setlinksetting(p, index, value, &Link[index].Status, &Link[index].Kc);
            }
            else
            {
                setlinksetting(p, index, value, &hyd->LinkStatus[index],
                               &LinkSetting[index]);
            }
        }
        break;
 
    case EN_KBULK:
        if (Link[index].Type <= PIPE)
        {
            Link[index].Kb = value / SECperDAY;
            qual->Reactflag = 1;
        }
        break;
 
    case EN_KWALL:
        if (Link[index].Type <= PIPE)
        {
            Link[index].Kw = value / SECperDAY;
            qual->Reactflag = 1;
        }
        break;
 
    case EN_LINKPATTERN:
        if (Link[index].Type == PUMP)
        {
            patIndex = ROUND(value);
            if (patIndex < 0 || patIndex > net->Npats) return 205;
            pumpIndex = findpump(&p->network, index);
            net->Pump[pumpIndex].Upat = patIndex;
        }
        break;
 
    case EN_PUMP_POWER:
        if (Link[index].Type == PUMP)
        {
            if (value <= 0.0) return 211;
            pumpIndex = findpump(&p->network, index);
            net->Pump[pumpIndex].Ptype = CONST_HP;
            net->Pump[pumpIndex].Hcurve = 0;
            net->Link[index].Km = value;
            updatepumpparams(p, pumpIndex);
            net->Pump[pumpIndex].R /= Ucf[POWER];
            net->Pump[pumpIndex].Q0 /= Ucf[FLOW];
            net->Pump[pumpIndex].Qmax /= Ucf[FLOW];
            net->Pump[pumpIndex].Hmax /= Ucf[HEAD];
        }
        break;
 
    case EN_PUMP_HCURVE:
        if (Link[index].Type == PUMP)
        {
            return EN_setheadcurveindex(p, index, ROUND(value));
        }
        break;
 
    case EN_PUMP_ECURVE:
        if (Link[index].Type == PUMP)
        {
            curveIndex = ROUND(value);
            if (curveIndex < 0 || curveIndex > net->Ncurves) return 205;
            pumpIndex = findpump(&p->network, index);
            net->Pump[pumpIndex].Ecurve = curveIndex;
        }
        break;
 
    case EN_PUMP_ECOST:
        if (Link[index].Type == PUMP)
        {
            if (value < 0.0) return 211;
            pumpIndex = findpump(&p->network, index);
            net->Pump[pumpIndex].Ecost = value;
        }
        break;
 
    case EN_PUMP_EPAT:
        if (Link[index].Type == PUMP)
        {
            patIndex = ROUND(value);
            if (patIndex < 0 || patIndex > net->Npats) return 205;
            pumpIndex = findpump(&p->network, index);
            net->Pump[pumpIndex].Epat = patIndex;
        }
        break;
    /*----------begin sh3h-------*/
#if W30
    case EN_SPEED:
          if (Link[index].Type == PUMP)
          {
              Link[index].Kc = value;
              hyd->LinkSetting[index] = value;
          }
          break;
#endif
     /*----------end sh3h-------*/
    default:
        return 251;
    }
    return 0;
}
 
int DLLEXPORT EN_setpipedata(EN_Project p, int index, double length,
                             double diam, double rough, double mloss)
/*----------------------------------------------------------------
**  Input:   index = pipe link index
**           length = pipe length
**           diam = pipe diameter
**           rough = pipe roughness coefficient
**           mloss = minor loss coefficient
**  Output:  none
**  Returns: error code
**  Purpose: sets several properties for a pipe link
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    Slink *Link = net->Link;
    double *Ucf = p->Ucf;
    double diameter = diam;
 
    // Check that pipe exists
    if (!p->Openflag) return 102;
    if (index <= 0 || index > net->Nlinks) return 204;
    if (Link[index].Type > PIPE) return 0;
 
    // Check for valid parameters
    if (length <= 0.0 || diam <= 0.0 || rough <= 0.0 || mloss < 0.0) return 211;
 
    // Assign parameters to pipe
    Link[index].Len = length / Ucf[ELEV];
    diameter /= Ucf[DIAM];
    Link[index].Diam = diameter;
    Link[index].Kc = rough;
    if (p->hydraul.Formflag == DW) Link[index].Kc /= (1000.0 * Ucf[ELEV]);
 
    // Update minor loss factor & pipe flow resistance
    Link[index].Km = 0.02517 * mloss / SQR(Link[index].Diam) / SQR(Link[index].Diam);
    resistcoeff(p, index);
    return 0;
}
 
int DLLEXPORT EN_getvertexcount(EN_Project p, int index, int *count)
/*----------------------------------------------------------------
**  Input:   index = link index
**  Output:  count = number of link's vertex points
**  Returns: error code
**  Purpose: retrieves number of vertex points in a link
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    
    Slink *Link = net->Link;
    Pvertices vertices;
    
    // Check that link exists
    *count = 0;
    if (!p->Openflag) return 102;
    if (index <= 0 || index > net->Nlinks) return 204;
    
    // Set count to number of vertices
    vertices = Link[index].Vertices;
    if (vertices) *count = vertices->Npts;
    return 0;
}    
 
int DLLEXPORT EN_getvertex(EN_Project p, int index, int vertex, double *x, double *y)
/*----------------------------------------------------------------
**  Input:   index = link index
**           vertex = index of a link vertex point
**  Output:  x = vertex point's X-coordinate
**           y = vertex point's Y-coordinate
**  Returns: error code
**  Purpose: retrieves the coordinates of a vertex point in a link
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    
    Slink *Link = net->Link;
    Pvertices vertices;
    
    // Check that link exists
    *x = MISSING;
    *y = MISSING;
    if (!p->Openflag) return 102;
    if (index <= 0 || index > net->Nlinks) return 204;
    
    // Check that vertex exists
    vertices = Link[index].Vertices;
    if (vertices == NULL) return 255;
    if (vertex <= 0 || vertex > vertices->Npts) return 255;
    *x = vertices->X[vertex - 1];
    *y = vertices->Y[vertex - 1];    
    return 0;
}
    
int DLLEXPORT EN_setvertices(EN_Project p, int index, double *x, double *y, int count)
/*----------------------------------------------------------------
**  Input:   index = link index
**           x = array of X-coordinates for vertex points
**           y = array of Y-coordinates for vertex points
**           count = number of vertex points
**  Returns: error code
**  Purpose: assigns a set of vertex points to a link
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    
    Slink *link;
    int i;
    int err = 0;
    
    // Check that link exists
    if (!p->Openflag) return 102;
    if (index <= 0 || index > net->Nlinks) return 204;
    link = &net->Link[index];
 
    // Delete existing set of vertices
    freelinkvertices(link);
    
    // Add each new vertex to the link
    for (i = 0; i < count; i++)
    {
        err = addlinkvertex(link, x[i], y[i]);
        if (err) break;
    }
    if (err) freelinkvertices(link);
    return err;
}    
 
/********************************************************************
 
    Pump Functions
 
********************************************************************/
 
int DLLEXPORT EN_getpumptype(EN_Project p, int linkIndex, int *pumpType)
/*----------------------------------------------------------------
**  Input:   linkIndex = index of a pump link
**  Output:  pumpType = type of pump head curve (see EN_PumpType)
**  Returns: error code
**  Purpose: retrieves the type of head curve used by a pump
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    Slink *Link = net->Link;
    Spump *Pump = net->Pump;
    const int Nlinks = net->Nlinks;
 
    *pumpType = -1;
    if (!p->Openflag) return 102;
    if (linkIndex < 1 || linkIndex > Nlinks) return 204;
    if (PUMP != Link[linkIndex].Type) return 216;
    *pumpType = Pump[findpump(&p->network, linkIndex)].Ptype;
    return 0;
}
 
int DLLEXPORT EN_getheadcurveindex(EN_Project p, int linkIndex, int *curveIndex)
/*----------------------------------------------------------------
**  Input:   linkIndex = index of a pump link
**  Output:  curveIndex = index of a pump's head curve
**  Returns: error code
**  Purpose: retrieves the index of a pump's head curve
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    Slink *Link = net->Link;
    Spump *Pump = net->Pump;
    const int Nlinks = net->Nlinks;
 
    *curveIndex = 0;
    if (!p->Openflag) return 102;
    if (linkIndex < 1 || linkIndex > Nlinks) return 204;
    if (PUMP != Link[linkIndex].Type) return 216;
    *curveIndex = Pump[findpump(net, linkIndex)].Hcurve;
    return 0;
}
 
int DLLEXPORT EN_setheadcurveindex(EN_Project p, int linkIndex, int curveIndex)
/*----------------------------------------------------------------
**  Input:   linkIndex = index of a pump link
**           curveIndex = index of a curve
**  Output:  none
**  Returns: error code
**  Purpose: assigns a new head curve to a pump
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    double *Ucf = p->Ucf;
    int pumpIndex;
    int oldCurveIndex;
    int newCurveType;
    int err = 0;
    Spump *pump;
 
    // Check for valid parameters
    if (!p->Openflag) return 102;
    if (linkIndex < 1 || linkIndex > net->Nlinks) return 204;
    if (PUMP != net->Link[linkIndex].Type) return 0;
    if (curveIndex < 0 || curveIndex > net->Ncurves) return 206;
 
    // Save values that need to be restored in case new curve is invalid
    pumpIndex = findpump(net, linkIndex);
    pump = &p->network.Pump[pumpIndex];
    oldCurveIndex = pump->Hcurve;
    newCurveType = p->network.Curve[curveIndex].Type;
    
    // Assign the new curve to the pump
    pump->Ptype = NOCURVE;
    pump->Hcurve = curveIndex;
    if (curveIndex == 0) return 0;
    
    // Update the pump's head curve parameters (which also changes
    // the new curve's Type to PUMP_CURVE)
    err = updatepumpparams(p, pumpIndex);
    
    // If the parameter updating failed (new curve was not a valid pump curve)
    // restore the pump's original curve and its parameters
    if (err > 0)
    {
        p->network.Curve[curveIndex].Type =(CurveType) newCurveType;
        pump->Ptype = NOCURVE;
        pump->Hcurve = oldCurveIndex;
        if (oldCurveIndex == 0) return err;
        updatepumpparams(p, pumpIndex);
    }    
    
    // Convert the units of the updated pump parameters to feet and cfs
    if (pump->Ptype == POWER_FUNC)
    {
        pump->H0 /= Ucf[HEAD];
        pump->R *= (pow(Ucf[FLOW], pump->N) / Ucf[HEAD]);
    }
    pump->Q0 /= Ucf[FLOW];
    pump->Qmax /= Ucf[FLOW];
    pump->Hmax /= Ucf[HEAD];
 
    return err;
}
 
/********************************************************************
 
    Time Pattern Functions
 
********************************************************************/
 
int DLLEXPORT EN_addpattern(EN_Project p, char *id)
/*----------------------------------------------------------------
**  Input:   id = time pattern ID name
**  Output:  none
**  Returns: error code
**  Purpose: adds a new time pattern to a project
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Parser  *parser = &p->parser;
 
    int i, n, err = 0;
    Spattern *pat;
 
    // Check if a pattern with same id already exists
    if (!p->Openflag) return 102;
    if (EN_getpatternindex(p, id, &i) == 0) return 215;
 
    // Check if id name contains invalid characters
    if (!namevalid(id)) return 252;
 
    // Expand the project's array of patterns
    n = net->Npats + 1;
    net->Pattern = (Spattern *)realloc(net->Pattern, (n + 1) * sizeof(Spattern));
 
    // Assign properties to the new pattern
    pat = &net->Pattern[n];
    strcpy(pat->ID, id);
    pat->Comment = NULL;
    pat->Length = 1;
    pat->F = (double *)calloc(1, sizeof(double));
    if (pat->F == NULL) err = 1;
    else pat->F[0] = 1.0;
 
    // Abort if memory allocation error
    if (err)
    {
        free(pat->F);
        return 101;
    }
 
    // Update the number of patterns
    net->Npats = n;
    parser->MaxPats = n;
    return 0;
}
 
int  DLLEXPORT EN_deletepattern(EN_Project p, int index)
/*----------------------------------------------------------------
**  Input:   index  = index of the pattern to delete
**  Output:  none
**  Returns: error code
**  Purpose: deletes a time pattern from a project
**----------------------------------------------------------------
*/
{
    int i;
 
    Network *net = &p->network;
    Parser  *parser = &p->parser;
    Hydraul *hyd = &p->hydraul;
 
    // Can't delete a pattern while a solver is active
    if (!p->Openflag)return 102;
    if (p->hydraul.OpenHflag || p->quality.OpenQflag) return 262;
 
    // Check that pattern exists
    if (index < 1 || index > p->network.Npats) return 205;
 
    // Adjust references by other objects to patterns
    adjustpatterns(net, index);
 
    // Modify global energy price pattern
    if (hyd->Epat == index)  hyd->Epat = 0;
    else if (hyd->Epat > index) hyd->Epat--;
 
    // Free the pattern's factor array
    FREE(net->Pattern[index].F);
    FREE(net->Pattern[index].Comment);
 
    // Shift the entries in the network's Pattern array
    for (i = index; i < net->Npats; i++) net->Pattern[i] = net->Pattern[i+1];
    net->Npats--;
    parser->MaxPats--;
    return 0;
}
 
int DLLEXPORT EN_getpatternindex(EN_Project p, char *id, int *index)
/*----------------------------------------------------------------
**  Input:   id = time pattern name
**  Output:  index = time pattern index
**  Returns: error code
**  Purpose: retrieves the index of a time pattern
**----------------------------------------------------------------
*/
{
    int i;
 
    *index = 0;
    if (!p->Openflag) return 102;
    for (i = 1; i <= p->network.Npats; i++)
    {
        if (strcmp(id, p->network.Pattern[i].ID) == 0)
        {
            *index = i;
            return 0;
        }
    }
    *index = 0;
    return 205;
}
 
int DLLEXPORT EN_getpatternid(EN_Project p, int index, char *id)
/*----------------------------------------------------------------
**  Input:   index = time pattern index
**  Output:  id = time pattern ID name
**  Returns: error code
**  Purpose: retrieves the ID name of a time pattern
**----------------------------------------------------------------
*/
{
    strcpy(id, "");
    if (!p->Openflag)return 102;
    if (index < 1 || index > p->network.Npats) return 205;
    strcpy(id, p->network.Pattern[index].ID);
    return 0;
}
 
int DLLEXPORT EN_setpatternid(EN_Project p, int index, char *id)
/*----------------------------------------------------------------
**  Input:   index = time pattern index
**           id = time pattern ID name
**  Returns: error code
**  Purpose: changes the ID name of a time pattern
**----------------------------------------------------------------
*/
{
    int i;
 
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Npats) return 205;
 
    // Check if id name contains invalid characters
    if (!namevalid(id)) return 252;
 
    for (i = 1; i <= p->network.Npats; i++)
    {
        if (i != index && strcmp(id, p->network.Pattern[i].ID) == 0) return 215;
    }
    strcpy(p->network.Pattern[index].ID, id);
    return 0;
}
 
int DLLEXPORT EN_getpatternlen(EN_Project p, int index, int *len)
/*----------------------------------------------------------------
**  Input:   index = time pattern index
**  Output:  len = number of periods in a time pattern
**  Returns: error code
**  Purpose: retrieves the number of time periods in a time pattern
**----------------------------------------------------------------
*/
{
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Npats) return 205;
    *len = p->network.Pattern[index].Length;
    return 0;
}
 
int DLLEXPORT EN_getpatternvalue(EN_Project p, int index, int period, double *value)
/*----------------------------------------------------------------
**  Input:   index = time pattern index
**           period = time pattern period
**  Output:  value = pattern factor for a particular time period
**  Returns: error code
**  Purpose: retrieves the pattern factor for a specific time period
**           in a time pattern
**----------------------------------------------------------------
*/
{
    *value = 0.0;
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Npats) return 205;
    if (period < 1 || period > p->network.Pattern[index].Length) return 251;
    *value = (double)p->network.Pattern[index].F[period - 1];
    return 0;
}
 
int DLLEXPORT EN_setpatternvalue(EN_Project p, int index, int period, double value)
/*----------------------------------------------------------------
**  Input:   index = time pattern index
**           period = time pattern period
**           value = pattern factor for a particular time period
**  Output:  none
**  Returns: error code
**  Purpose: sets the pattern factor for a specific time period
**           in a time pattern
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Spattern *Pattern = net->Pattern;
 
    if (!p->Openflag) return  102;
    if (index <= 0 || index > net->Npats) return 205;
    if (period <= 0 || period > Pattern[index].Length) return 251;
    Pattern[index].F[period - 1] = value;
    return 0;
}
 
int DLLEXPORT EN_getaveragepatternvalue(EN_Project p, int index, double *value)
/*----------------------------------------------------------------
**  Input:   index = time pattern index
**  Output:  value = average of a time pattern's factors
**  Returns: error code
**  Purpose: retrieves the average of all pattern factors for a time pattern
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    Spattern *Pattern = net->Pattern;
    int i;
 
    *value = 0.0;
    if (!p->Openflag) return 102;
    if (index < 1 || index > net->Npats) return 205;
    for (i = 0; i < Pattern[index].Length; i++)
    {
        *value += (double)Pattern[index].F[i];
    }
    *value /= (double)Pattern[index].Length;
    return 0;
}
 
int DLLEXPORT EN_setpattern(EN_Project p, int index, double *values, int len)
/*----------------------------------------------------------------
**  Input:   index = time pattern index
**           values = an array of pattern factor values
**           len = number of time periods contained in f
**  Output:  none
**  Returns: error code
**  Purpose: replaces the pattern factors in a time pattern
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    int j;
    Spattern *Pattern = net->Pattern;
 
    // Check for valid arguments
    if (!p->Openflag) return 102;
    if (index <= 0 || index > net->Npats) return 205;
    if (values == NULL) return 205;
    if (len <= 0) return 202;
 
    // Re-set number of time periods & reallocate memory for multipliers
    Pattern[index].Length = len;
    Pattern[index].F = (double *)realloc(Pattern[index].F, len * sizeof(double));
    if (Pattern[index].F == NULL) return 101;
 
    // Load multipliers into pattern
    for (j = 0; j < len; j++) Pattern[index].F[j] = values[j];
    return 0;
}
 
/********************************************************************
 
    Data Curve Functions
 
********************************************************************/
 
int DLLEXPORT EN_addcurve(EN_Project p, char *id)
/*----------------------------------------------------------------
**  Input:   id = data curve ID name
**  Output:  none
**  Returns: error code
**  Purpose: adds a new data curve to a project
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    int i, n, err = 0;
    Scurve *curve;
 
    // Check if a curve with same id already exists
    if (!p->Openflag) return 102;
    if (EN_getcurveindex(p, id, &i) == 0) return 215;
 
    // Check if id name contains invalid characters
    if (!namevalid(id)) return 252;
 
    // Expand the array of curves
    n = net->Ncurves + 1;
    net->Curve = (Scurve *) realloc(net->Curve, (n + 1) * sizeof(Scurve));
 
    // Set the properties of the new curve
    curve = &net->Curve[n];
    strcpy(curve->ID, id);
    curve->Comment = NULL;
    curve->Capacity = 1;
    curve->Npts = 1;
    curve->Type = GENERIC_CURVE;
    curve->X = (double *)calloc(1, sizeof(double));
    curve->Y = (double *)calloc(1, sizeof(double));
    if (curve->X == NULL) err = 1;
    else if (curve->Y == NULL) err = 1;
    else
    {
        curve->X[0] = 1.0;
        curve->Y[0] = 1.0;
    }
 
    // Abort if memory allocation error
    if (err)
    {
        free(curve->X);
        free(curve->Y);
        return 101;
    }
 
    // Update the number of curves
    net->Ncurves = n;
    p->parser.MaxCurves = n;
    return 0;
}
 
int  DLLEXPORT EN_deletecurve(EN_Project p, int index)
/*----------------------------------------------------------------
**  Input:   index  = index of the curve to delete
**  Output:  none
**  Returns: error code
**  Purpose: deletes a data curve from a project
**----------------------------------------------------------------
*/
{
    int i;
 
    Network *net = &p->network;
    Parser  *parser = &p->parser;
 
    // Can't delete a curve while a solver is active
    if (!p->Openflag)return 102;
    if (p->hydraul.OpenHflag || p->quality.OpenQflag) return 262;
 
    // Check that curve exists
    if (index < 1 || index > p->network.Ncurves) return 205;
 
    // Adjust references by other objects to curves
    adjustcurves(net, index);
 
    // Free the curve's data arrays
    FREE(net->Curve[index].X);
    FREE(net->Curve[index].Y);
    FREE(net->Curve[index].Comment);
 
    // Shift the entries in the network's Curve array
    for (i = index; i < net->Ncurves; i++) net->Curve[i] = net->Curve[i + 1];
    net->Ncurves--;
    parser->MaxCurves--;
    return 0;
}
 
int DLLEXPORT EN_getcurveindex(EN_Project p, char *id, int *index)
/*----------------------------------------------------------------
**  Input:   id = data curve name
**  Output:  index = data curve index
**  Returns: error code
**  Purpose: retrieves the index of a data curve
**----------------------------------------------------------------
*/
{
    *index = 0;
    if (!p->Openflag) return 102;
    *index = findcurve(&p->network, id);
    if (*index == 0) return 206;
    return 0;
}
 
int DLLEXPORT EN_getcurveid(EN_Project p, int index, char *id)
/*----------------------------------------------------------------
**  Input:   index = data curve index
**  Output:  id = data curve ID name
**  Returns: error code
**  Purpose: retrieves the name of a data curve
**----------------------------------------------------------------
*/
{
    strcpy(id, "");
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Ncurves) return 206;
    strcpy(id, p->network.Curve[index].ID);
    return 0;
}
 
int DLLEXPORT EN_setcurveid(EN_Project p, int index, char *id)
/*----------------------------------------------------------------
**  Input:   index = data curve index
**           id = data curve ID name
**  Returns: error code
**  Purpose: changes the ID name of a data curve
**----------------------------------------------------------------
*/
{
    int i;
 
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Ncurves) return 205;
 
    // Check if id name contains invalid characters
    if (!namevalid(id)) return 252;
 
    for (i = 1; i <= p->network.Ncurves; i++)
    {
        if (i != index && strcmp(id, p->network.Curve[i].ID) == 0) return 215;
    }
    strcpy(p->network.Curve[index].ID, id);
    return 0;
}
 
int DLLEXPORT EN_getcurvelen(EN_Project p, int index, int *len)
/*----------------------------------------------------------------
**  Input:   index = data curve index
**  Output:  len = number of points in a data curve
**  Returns: error code
**  Purpose: retrieves the number of points in a data curve
**----------------------------------------------------------------
*/
{
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Ncurves) return 206;
    *len = p->network.Curve[index].Npts;
    return 0;
}
 
int DLLEXPORT EN_getcurvetype(EN_Project p, int index, int *type)
/*----------------------------------------------------------------
**  Input:   index = data curve index
**  Output:  type = type of data curve (see EN_CurveType)
**  Returns: error code
**  Purpose: retrieves the type assigned to a data curve
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    if (!p->Openflag) return 102;
    if (index < 1 || index > net->Ncurves) return 206;
    *type = net->Curve[index].Type;
    return 0;
}
 
int DLLEXPORT EN_getcurvevalue(EN_Project p, int curveIndex, int pointIndex,
                               double *x, double *y)
/*----------------------------------------------------------------
**  Input:   curveIndex = data curve index
**           pointIndex = index of a data point on the curve
**  Output:  x = x-value of the point on the curve
**           y = y-value of the point on the curve
**  Returns: error code
**  Purpose: retrieves the value of a specific point on a data curve
**----------------------------------------------------------------
*/
{
    *x = 0.0;
    *y = 0.0;
    if (!p->Openflag) return 102;
    if (curveIndex < 1 || curveIndex > p->network.Ncurves) return 206;
    if (pointIndex < 1 || pointIndex > p->network.Curve[curveIndex].Npts) return 251;
    *x = p->network.Curve[curveIndex].X[pointIndex - 1];
    *y = p->network.Curve[curveIndex].Y[pointIndex - 1];
    return 0;
}
 
int DLLEXPORT EN_setcurvevalue(EN_Project p, int curveIndex, int pointIndex,
                               double x, double y)
/*----------------------------------------------------------------
**  Input:   curveIndex = data curve index
**           pointIndex = index of a data point on the curve
**           x = new x-value for the point on the curve
**           y = new y-value for the point on the curve
**  Output:  none
**  Returns: error code
**  Purpose: sets the value of a specific point on a data curve
**  Note:    if pointIndex exceeds the curve's length a new point is added.
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Scurve *curve;
    double x1 = -1.e37, x2 = 1.e37;
    int n = pointIndex - 1;
 
    // Check for valid input
    if (!p->Openflag) return 102;
    if (curveIndex <= 0 || curveIndex > net->Ncurves) return 206;
    curve = &net->Curve[curveIndex];
    if (pointIndex <= 0) return 251;
 
    // Check that new point maintains increasing x values
    if (n - 1 >= 0) x1 = curve->X[n-1];
    if (n + 1 < curve->Npts) x2 = curve->X[n+1];
    if (x <= x1 || x >= x2) return 230;
 
    // Expand curve if need be
    if (pointIndex > curve->Npts) pointIndex = curve->Npts + 1;
    if (pointIndex >= curve->Capacity)
    {
        if (resizecurve(curve, curve->Capacity + 10) > 0) return 101;
    }
 
    // Increase curve's number of points if need be
    if (pointIndex > curve->Npts)
    {
        curve->Npts++;
        n = curve->Npts - 1;
    }
 
    // Insert new point into curve
    curve->X[n] = x;
    curve->Y[n] = y;
    
    // Adjust parameters for pumps using curve as a head curve
    return adjustpumpparams(p, curveIndex);
}
 
int DLLEXPORT EN_getcurve(EN_Project p, int index, char *id, int *nPoints,
                          double *xValues, double *yValues)
/*----------------------------------------------------------------
**  Input:   index = data curve index
**  Output:  id = ID name of data curve
**           nPoints = number of data points on the curve
**           xValues = array of x-values for each data point
**           yValues = array of y-values for each data point
**  Returns: error code
**  Purpose: retrieves the data associated with a data curve
**
**  The calling program is responsible for making xValues and
**  yValues large enough to hold nPoints data points.
**----------------------------------------------------------------
*/
{
    int i;
    Scurve *curve;
 
    if (!p->Openflag) return 102;
    if (index <= 0 || index > p->network.Ncurves) return 206;
    if (xValues == NULL || yValues == NULL) return 206;
    curve = &p->network.Curve[index];
    strncpy(id, curve->ID, MAXID);
    *nPoints = curve->Npts;
    for (i = 0; i < curve->Npts; i++)
    {
        xValues[i] = curve->X[i];
        yValues[i] = curve->Y[i];
    }
    return 0;
}
 
int DLLEXPORT EN_setcurve(EN_Project p, int index, double *xValues,
                          double *yValues, int nPoints)
/*----------------------------------------------------------------
**  Input:   index = data curve index
**           xValues = array of x-values
**           yValues = array of y-values
**           nPoints = number of data points in the x and y arrays
**  Returns: error code
**  Purpose: replaces a curve's set of data points
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Scurve *curve;
    int j;
 
    // Check for valid arguments
    if (!p->Openflag) return 102;
    if (index <= 0 || index > net->Ncurves) return 206;
    if (xValues == NULL || yValues == NULL) return 206;
    if (nPoints <= 0) return 202;
 
    // Check that x values are increasing
    for (j = 1; j < nPoints; j++) if (xValues[j-1] >= xValues[j]) return 230;
 
    // Expand size of curve's data arrays if need be
    curve = &net->Curve[index];
    if (resizecurve(curve, nPoints) > 0) return 101;
 
    // Load values into curve
    curve->Npts = nPoints;
    for (j = 0; j < nPoints; j++)
    {
        curve->X[j] = xValues[j];
        curve->Y[j] = yValues[j];
    }
    
    // Adjust parameters for pumps using curve as a head curve
    return adjustpumpparams(p, index);
}
 
/********************************************************************
 
    Simple Controls Functions
 
********************************************************************/
 
int DLLEXPORT EN_addcontrol(EN_Project p, int type, int linkIndex, double setting,
              int nodeIndex, double level, int *index)
/*----------------------------------------------------------------
**  Input:   type = type of control (see EN_ControlType)
**           linkIndex = index of link being controlled
**           setting = link control setting (e.g., pump speed)
**           nodeIndex = index of node controlling a link (for level controls)
**           level = control activation level (pressure for junction nodes,
**                   water level for tank nodes or time value for time-based
**                   control)
**  Output:  index = the index of the new control
**  Returns: error code
**  Purpose: adds a new simple control to a project
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Parser *parser = &p->parser;
 
    StatusType status = ACTIVE;
    int  n;
    long t = 0;
    double s = setting, lvl = level;
    double *Ucf = p->Ucf;
    Scontrol *control;
 
 
    // Check that project exists
    if (!p->Openflag) return 102;
 
    // Check that controlled link exists
    if (linkIndex <= 0 || linkIndex > net->Nlinks) return 204;
 
    // Cannot control check valve
    if (net->Link[linkIndex].Type == CVPIPE) return 207;
 
    // Check for valid parameters
    if (type < 0 || type > EN_TIMEOFDAY) return 251;
    if (type == EN_LOWLEVEL || type == EN_HILEVEL)
    {
        if (nodeIndex < 1 || nodeIndex > net->Nnodes) return 203;
    }
    else nodeIndex = 0;
    if (s < 0.0 || lvl < 0.0) return 202;
 
    // Adjust units of control parameters
    switch (net->Link[linkIndex].Type)
    {
    case PRV:
    case PSV:
    case PBV:
        s /= Ucf[PRESSURE];
        break;
    case FCV:
        s /= Ucf[FLOW];
        break;
    case GPV:
        if (s == 0.0) status = CLOSED;
        else if (s == 1.0) status = OPEN;
        else return 202;
        s = net->Link[linkIndex].Kc;
        break;
    case PIPE:
    case PUMP:
        status = OPEN;
        if (s == 0.0) status = CLOSED;
    default:
        break;
    }
 
    if (type == LOWLEVEL || type == HILEVEL)
    {
        if (nodeIndex > net->Njuncs) lvl = net->Node[nodeIndex].El + level / Ucf[ELEV];
        else lvl = net->Node[nodeIndex].El + level / Ucf[PRESSURE];
    }
    if (type == TIMER) t = (long)ROUND(lvl);
    if (type == TIMEOFDAY) t = (long)ROUND(lvl) % SECperDAY;
 
    // Expand project's array of controls
    n = net->Ncontrols + 1;
    net->Control = (Scontrol *)realloc(net->Control, (n + 1) * sizeof(Scontrol));
 
    // Set properties of the new control
    control = &net->Control[n];
    control->Type = (ControlType)type;
    control->Link = linkIndex;
    control->Node = nodeIndex;
    control->Status = status;
    control->Setting = s;
    control->Grade = lvl;
    control->Time = t;
 
    // Update number of controls
    net->Ncontrols = n;
    parser->MaxControls = n;
 
    // Replace the control's index
    *index = n;
    return 0;
}
 
int DLLEXPORT EN_deletecontrol(EN_Project p, int index)
/*----------------------------------------------------------------
**  Input:   index  = index of the control
**  Output:  none
**  Returns: error code
**  Purpose: deletes a simple control from a project
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    int i;
 
    if (index <= 0 || index > net->Ncontrols) return 241;
    for (i = index; i <= net->Ncontrols - 1; i++)
    {
        net->Control[i] = net->Control[i + 1];
    }
    net->Ncontrols--;
    return 0;
}
 
int DLLEXPORT EN_getcontrol(EN_Project p, int index, int *type, int *linkIndex,
                            double *setting, int *nodeIndex, double *level)
/*----------------------------------------------------------------
**  Input:   index  = index of the control
**  Output:  type = type of control (see EN_ControlType)
**           linkIndex = index of link being controlled
**           setting = link control setting (e.g., pump speed)
**           nodeIndex = index of node that triggers a level control
**           level = trigger level that activates the control (pressure for junction nodes,
**                   water level for tank nodes or time value for time-based control)
**  Returns: error code
**  Purpose: Retrieves the properties of a simple control
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    double s, lvl;
    double *Ucf = p->Ucf;
    Scontrol *control;
    Snode *node;
 
    // Set default return values
    s = 0.0;
    lvl = 0.0;
    *type = 0;
    *linkIndex = 0;
    *nodeIndex = 0;
 
    // Check for valid arguments
    if (!p->Openflag) return 102;
    if (index <= 0 || index > net->Ncontrols) return 241;
 
    // Retrieve control's type and link index
    control = &net->Control[index];
    *type = control->Type;
    *linkIndex = control->Link;
 
    // Retrieve control's setting
    s = control->Setting;
    if (control->Setting != MISSING)
    {
        switch (net->Link[*linkIndex].Type)
        {
        case PRV:
        case PSV:
        case PBV:
            s *= Ucf[PRESSURE];
            break;
        case FCV:
            s *= Ucf[FLOW];
        default:
            break;
        }
    }
    else if (control->Status == OPEN) s = 1.0;
    else s = 0.0;
 
    // Retrieve level value for a node level control
    *nodeIndex = control->Node;
    if (*nodeIndex > 0)
    {
        node = &net->Node[*nodeIndex];
        if (*nodeIndex > net->Njuncs)  // Node is a tank
        {
             lvl = (control->Grade - node->El) * Ucf[ELEV];
        }
        else  // Node is a junction
        {
            lvl = (control->Grade - node->El) * Ucf[PRESSURE];
        }
    }
 
    // Retrieve level value for a time-based control
    else
    {
        lvl = (double)control->Time;
    }
    *setting = (double)s;
    *level = (double)lvl;
    return 0;
}
 
int DLLEXPORT EN_setcontrol(EN_Project p, int index, int type, int linkIndex,
                            double setting, int nodeIndex, double level)
/*----------------------------------------------------------------
**  Input:   index  = index of the control
**           type = type of control (see EN_ControlType)
**           linkIndex = index of link being controlled
**           setting = link control setting (e.g., pump speed)
**           nodeIndex = index of node that triggers the control (for level controls)
**           level = trigger level that activates the control (pressure for junction nodes,
**                   water level for tank nodes or time value for time-based control)
**  Output:  none
**  Returns: error code
**  Purpose: Sets the properties of a simple control
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    StatusType status = ACTIVE;
    long t = 0;
    double s = setting, lvl = level;
    double *Ucf = p->Ucf;
    Slink *link;
    Scontrol *control;
 
    // Check that project exists
    if (!p->Openflag) return 102;
 
    // Check that control exists
    if (index <= 0 || index > net->Ncontrols) return 241;
    control = &net->Control[index];
 
    // Check that controlled link exists (0 index de-activates the control)
    if (linkIndex == 0)
    {
        control->Link = 0;
        return 0;
    }
    if (linkIndex < 0 || linkIndex > net->Nlinks) return 204;
 
    // Cannot control check valve
    if (net->Link[linkIndex].Type == CVPIPE) return 207;
 
    // Check for valid control properties
    if (type < 0 || type > EN_TIMEOFDAY) return 251;
    if (type == EN_LOWLEVEL || type == EN_HILEVEL)
    {
        if (nodeIndex < 1 || nodeIndex > net->Nnodes) return 203;
    }
    else nodeIndex = 0;
    if (s < 0.0 || lvl < 0.0) return 202;
 
    // Adjust units of control's properties
    link = &net->Link[linkIndex];
    switch (link->Type)
    {
    case PRV:
    case PSV:
    case PBV:
        s /= Ucf[PRESSURE];
        break;
    case FCV:
        s /= Ucf[FLOW];
        break;
    case GPV:
        if (s == 0.0)  status = CLOSED;
        else if (s == 1.0) status = OPEN;
        else return 202;
        s = link->Kc;
        break;
    case PIPE:
    case PUMP:
        status = OPEN;
        if (s == 0.0) status = CLOSED;
    default:
        break;
    }
    if (type == LOWLEVEL || type == HILEVEL)
    {
        if (nodeIndex > net->Njuncs) lvl = net->Node[nodeIndex].El + level / Ucf[ELEV];
        else lvl = net->Node[nodeIndex].El + level / Ucf[PRESSURE];
    }
    if (type == TIMER) t = (long)ROUND(lvl);
    if (type == TIMEOFDAY) t = (long)ROUND(lvl) % SECperDAY;
 
    /* Reset control's parameters */
    control->Type = (ControlType)type;
    control->Link = linkIndex;
    control->Node = nodeIndex;
    control->Status = status;
    control->Setting = s;
    control->Grade = lvl;
    control->Time = t;
    return 0;
}
 
/********************************************************************
 
    Rule-Based Controls Functions
 
********************************************************************/
 
int DLLEXPORT EN_addrule(EN_Project p, char *rule)
/*----------------------------------------------------------------
**  Input:   rule = text of rule being added in the format
**           used for the [RULES] section of an HYDRAULIC input file
**  Output:  none
**  Returns: error code
**  Purpose: adds a new rule to a project
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
    Parser  *parser = &p->parser;
    Rules   *rules = &p->rules;
 
    char *line;
    char *nextline;
    char line2[MAXLINE+1];
 
    // Resize rules array
    net->Rule = (Srule *)realloc(net->Rule, (net->Nrules + 2)*sizeof(Srule));
    rules->Errcode = 0;
    rules->RuleState = 6;  // = r_PRIORITY
 
    // Extract each line of the rule statement
    line = rule;
    while (line)
    {
        // Find where current line ends and next one begins
        nextline = strchr(line, '\n');
        if (nextline) *nextline = '\0';
 
        // Copy and tokenize the current line
        strcpy(line2, line);
        strcat(line2, "\n");  // Tokenizer won't work without this
        parser->Ntokens = gettokens(line2, parser->Tok, MAXTOKS, parser->Comment);
 
        // Process the line to build up the rule's contents
        if (parser->Ntokens > 0 && *parser->Tok[0] != ';')
        {
            ruledata(p);  // Nrules gets updated in ruledata()
            if (rules->Errcode) break;
        }
 
        // Extract next line from the rule statement
        if (nextline) *nextline = '\n';
        line = nextline ? (nextline + 1) : NULL;
    }
 
    // Delete new rule entry if there was an error
    if (rules->Errcode) deleterule(p, net->Nrules);
 
    // Re-assign error code 201 (syntax error) to 250 (invalid format)
    if (rules->Errcode == 201) rules->Errcode = 250;
    return rules->Errcode;
}
 
int DLLEXPORT EN_deleterule(EN_Project p, int index)
/*----------------------------------------------------------------
**  Input:   index = rule index
**  Output:  none
**  Returns: error code
**  Purpose: deletes a rule from a project
**----------------------------------------------------------------
*/
{
    if (index < 1 || index > p->network.Nrules) return 257;
    deleterule(p, index);
    return 0;
}
 
int DLLEXPORT EN_getrule(EN_Project p, int index, int *nPremises,
                         int *nThenActions, int *nElseActions,
                         double *priority)
/*----------------------------------------------------------------
**  Input:   index  = rule index
**  Output:  nPremises  = number of premises conditions (IF AND OR)
**           nThenActions = number of actions in THEN portion of rule
**           nElseActions = number of actions in ELSE portion of rule
**           priority = rule priority
**  Returns: error code
**  Purpose: gets information about a particular rule
**----------------------------------------------------------------
*/
{
    Network *net = &p->network;
 
    int count;
    Spremise *premise;
    Saction *action;
 
    if (index < 1 || index > net->Nrules) return 257;
    *priority = (double)p->network.Rule[index].priority;
 
    count = 0;
    premise = net->Rule[index].Premises;
    while (premise != NULL)
    {
        count++;
        premise = premise->next;
    }
    *nPremises = count;
 
    count = 0;
    action = net->Rule[index].ThenActions;
    while (action != NULL)
    {
        count++;
        action = action->next;
    }
    *nThenActions = count;
 
    count = 0;
    action = net->Rule[index].ElseActions;
    while (action != NULL)
    {
        count++;
        action = action->next;
    }
    *nElseActions = count;
    return 0;
}
 
int DLLEXPORT EN_getruleID(EN_Project p, int index, char *id)
/*----------------------------------------------------------------
**  Input:   index = rule index
**  Output:  id = rule ID label
**  Returns: error code
**  Purpose: retrieves the ID label of a rule
**----------------------------------------------------------------
*/
{
    strcpy(id, "");
    if (!p->Openflag) return 102;
    if (index < 1 || index > p->network.Nrules) return 257;
    strcpy(id, p->network.Rule[index].label);
    return 0;
}
 
int DLLEXPORT EN_getpremise(EN_Project p, int ruleIndex, int premiseIndex,
                           int *logop, int *object, int *objIndex, int *variable,
                           int *relop, int *status, double *value)
/*----------------------------------------------------------------
**  Input:   ruleIndex = rule index
**           premiseIndex = premise index
**  Output:  logop = logical operator (IF = 1, AND = 2, OR = 3)
**           object = type of object appearing in the premise (see EN_RuleObject)
**           objIndex = object's index in Node or Link array
**           variable = object variable being tested (see EN_RuleVariable)
**           relop = relational operator (see EN_RuleOperator)
**           status = object status being tested against (see EN_RuleStatus))
**           value = variable value being tested against
**  Returns: error code
**  Purpose: retrieves the properties of a rule's premise
**----------------------------------------------------------------
*/
{
    Spremise *premises;
    Spremise *premise;
 
    if (ruleIndex < 1 || ruleIndex > p->network.Nrules) return 257;
 
    premises = p->network.Rule[ruleIndex].Premises;
    premise = getpremise(premises, premiseIndex);
    if (premise == NULL)  return 258;
 
    *logop = premise->logop;
    *object = premise->object;
    *objIndex = premise->index;
    *variable = premise->variable;
    *relop = premise->relop;
    *status = premise->status;
    *value = (double)premise->value;
    return 0;
}
 
 
int DLLEXPORT EN_setpremise(EN_Project p, int ruleIndex, int premiseIndex,
                            int logop, int object, int objIndex, int variable,
                            int relop, int status, double value)
/*----------------------------------------------------------------
**  Input:   ruleIndex = rule index
**           premiseIndex = premise index
**           logop = logical operator (IF = 1, AND = 2, OR = 3)
**           object = type of object appearing in the premise (see EN_RuleObject)
**           objIndex = object's index in Node or Link array
**           variable = object variable being tested (see EN_RuleVariable)
**           relop = relational operator (see EN_RuleOperator)
**           status = object status being tested against (see EN_RuleStatus))
**           value = variable value being tested against
**  Output:  none
**  Returns: error code
**  Purpose: sets the properties of a rule's premise
**----------------------------------------------------------------
*/
{
    Spremise *premises;
    Spremise *premise;
 
    if (ruleIndex < 1 || ruleIndex > p->network.Nrules) return 257;
 
    premises = p->network.Rule[ruleIndex].Premises;
    premise = getpremise(premises, premiseIndex);
    if (premise == NULL)  return 258;
 
    premise->logop = logop;
    premise->object = object;
    premise->index = objIndex;
    premise->variable = variable;
    premise->relop = relop;
    premise->status = status;
    premise->value = value;
    return 0;
}
 
int DLLEXPORT EN_setpremiseindex(EN_Project p, int ruleIndex, int premiseIndex,
                                 int objIndex)
/*----------------------------------------------------------------
**  Input:   ruleIndex = rule index
**           premiseIndex = premise index
**           objIndex = object's index in Node or Link array
**  Output:  none
**  Returns: error code
**  Purpose: sets the index of an object referred to in a rule's premise
**----------------------------------------------------------------
*/
{
    Spremise *premises;
    Spremise *premise;
 
    if (ruleIndex < 1 || ruleIndex > p->network.Nrules) return 257;
 
    premises = p->network.Rule[ruleIndex].Premises;
    premise = getpremise(premises, premiseIndex);
    if (premise == NULL)  return 258;
 
    premise->index = objIndex;
    return 0;
}
 
int DLLEXPORT EN_setpremisestatus(EN_Project p, int ruleIndex, int premiseIndex, int status)
/*----------------------------------------------------------------
**  Input:   ruleIndex = rule index
**           premiseIndex = premise index
**           status = object status being tested against
**                    (see EN_RuleStatus))
**  Output:  none
**  Returns: error code
**  Purpose: sets the status of an object being tested against
**           in a rule's premise
**----------------------------------------------------------------
*/
{
    Spremise *premises;
    Spremise *premise;
 
    if (ruleIndex < 1 || ruleIndex > p->network.Nrules) return 257;
 
    premises = p->network.Rule[ruleIndex].Premises;
    premise = getpremise(premises, premiseIndex);
    if (premise == NULL) return 258;
 
    premise->status = status;
    return 0;
}
 
int DLLEXPORT EN_setpremisevalue(EN_Project p, int ruleIndex, int premiseIndex, double value)
/*----------------------------------------------------------------
**  Input:   ruleIndex = rule index
**           premiseIndex = premise index
**           value = value of object variable being tested against
**  Output:  none
**  Returns: error code
**  Purpose: sets the value of object's variable being tested against
**           in a rule's premise
**----------------------------------------------------------------
*/
{
    Spremise *premises;
    Spremise *premise;
 
    if (ruleIndex < 1 || ruleIndex > p->network.Nrules) return 257;
 
    premises = p->network.Rule[ruleIndex].Premises;
    premise = getpremise(premises, premiseIndex);
    if (premise == NULL) return 258;
 
    premise->value = value;
    return 0;
}
 
int DLLEXPORT EN_getthenaction(EN_Project p, int ruleIndex, int actionIndex,
                               int *linkIndex, int *status, double *setting)
/*----------------------------------------------------------------
**  Input:   ruleIndex = rule index
**           actionIndex = index of a rule's THEN actions
**  Output:  linkIndex = index of link appearing in the action
**           status = status assigned to the link (see EN_RuleStatus))
**           setting = setting assigned to the link
**  Returns: error code
**  Purpose: retrieves the properties of a rule's THEN action
**----------------------------------------------------------------
*/
{
    Saction *actions;
    Saction *action;
 
    if (ruleIndex < 1 || ruleIndex > p->network.Nrules) return 257;
 
    actions = p->network.Rule[ruleIndex].ThenActions;
    action = getaction(actions, actionIndex);
    if (action == NULL) return 258;
 
    *linkIndex = action->link;
    *status = action->status;
    *setting = (double)action->setting;
    return 0;
}
 
int DLLEXPORT EN_setthenaction(EN_Project p, int ruleIndex, int actionIndex,
                               int linkIndex,  int status, double setting)
/*----------------------------------------------------------------
**  Input:   ruleIndex = rule index
**           actionIndex = index of a rule's THEN actions
**           linkIndex = index of link appearing in the action
**           status = status assigned to the link (see EN_RuleStatus))
**           setting = setting assigned to the link
**  Returns: error code
**  Purpose: sets the properties of a rule's THEN action
**----------------------------------------------------------------
*/
{
    Saction *actions;
    Saction *action;
 
    if (ruleIndex < 1 || ruleIndex > p->network.Nrules) return 257;
 
    actions = p->network.Rule[ruleIndex].ThenActions;
    action = getaction(actions, actionIndex);
    if (action == NULL) return 258;
 
    action->link = linkIndex;
    action->status = status;
    action->setting = setting;
    return 0;
}
 
int DLLEXPORT EN_getelseaction(EN_Project p, int ruleIndex, int actionIndex,
                               int *linkIndex, int *status, double *setting)
/*----------------------------------------------------------------
**  Input:   ruleIndex = rule index
**           actionIndex = index of a rule's ELSE actions
**  Output:  linkIndex = index of link appearing in the action
**           status = status assigned to the link (see EN_RuleStatus))
**           setting = setting assigned to the link
**  Returns: error code
**  Purpose: retrieves the properties of a rule's ELSE action
**----------------------------------------------------------------
*/
{
  Saction *actions;
  Saction *action;
 
  if (ruleIndex < 1 || ruleIndex > p->network.Nrules) return 257;
 
  actions = p->network.Rule[ruleIndex].ElseActions;
  action = getaction(actions, actionIndex);
  if (action == NULL) return 258;
 
  *linkIndex = action->link;
  *status = action->status;
  *setting = (double)action->setting;
  return 0;
}
 
int DLLEXPORT EN_setelseaction(EN_Project p, int ruleIndex, int actionIndex,
                               int linkIndex,  int status, double setting)
/*----------------------------------------------------------------
**  Input:   ruleIndex = rule index
**           actionIndex = index of a rule's ELSE actions
**           linkIndex = index of link appearing in the action
**           status = status assigned to the link (see EN_RuleStatus))
**           setting = setting assigned to the link
**  Returns: error code
**  Purpose: sets the properties of a rule's ELSE action
**----------------------------------------------------------------
*/
{
  Saction *actions;
  Saction *action;
 
  if (ruleIndex < 1 || ruleIndex > p->network.Nrules) return 257;
 
  actions = p->network.Rule[ruleIndex].ElseActions;
  action = getaction(actions, actionIndex);
  if (action == NULL) return 258;
 
  action->link = linkIndex;
  action->status = status;
  action->setting = setting;
  return 0;
}
 
int DLLEXPORT EN_setrulepriority(EN_Project p, int index, double priority)
/*-----------------------------------------------------------------------------
**  Input:   index  = rule index
**           priority = rule priority level
**  Output:  none
**  Returns: error code
**  Purpose: sets the priority level for a rule
**-----------------------------------------------------------------------------
*/
{
    if (index <= 0 || index > p->network.Nrules)  return 257;
    p->network.Rule[index].priority = priority;
    return 0;
}
 
 
 
 
int DLLEXPORT EN_setinistatus(EN_Project p, char* id, char* value)
{
    if (setinistatus(p,id, value)) {
        return(200);
    }
    return (0);
}
 
 
int DLLEXPORT EN_test(Sdemand d)
{
    return 0;
}
 
//
//int DLLEXPORT ENaddjunc(EN_Project p, char* line)
//{
//    int  errcode = 0;
//    ERRCODE(addjunc(p, line));
//    return errcode;
//}
//
//int DLLEXPORT ENaddtank(EN_Project p, char* line)
//{
//    int  errcode = 0;
//    ERRCODE(addtank(p, line));
//    return errcode;
//}
//
//int DLLEXPORT ENaddpipe(EN_Project p, char* line, char* node1, char* node2)
//{
//    int  errcode = 0;
//    ERRCODE(addpipe(p, line, node1, node2));
//    return errcode;
//}
//
//int DLLEXPORT ENaddvalve(EN_Project p, char* line)
//{
//    int errcode = 0;
//    ERRCODE(addvalve(p, line));
//    return(errcode);
//}
//
//int DLLEXPORT ENaddpump(EN_Project p, char* line)
//{
//    int errcode = 0;
//    ERRCODE(addpump(p, line));
//    return(errcode);
//}
//
//int DLLEXPORT ENopenStart(EN_Project p,char* f1, char* f2, char* f3)
///*----------------------------------------------------------------
//**  Input:   f1 = pointer to name of input file
//**           f2 = pointer to name of report file
//**           f3 = pointer to name of binary output file
//**  Output:  none
//**  Returns: error code
//**  Purpose: opens HYDRAULIC input file & reads in network data
//**----------------------------------------------------------------
//*/
//{
//    int  errcode = 0;
//
//    /*** Updated 9/7/00 ***/
//    /* Reset math coprocessor */
//#ifdef DLL
//    _fpreset();
//#endif
//
//    /* Set system flags */
//    p->Openflag = FALSE;
//    p->hydraul.OpenHflag = FALSE;
//    p->quality.OpenQflag = FALSE;
//    p->outfile.SaveHflag = FALSE;
//    p->outfile.SaveQflag = FALSE;
//    p->Warnflag = FALSE;
//
//    /*** Updated 9/7/00 ***/
//    p->report.Messageflag = TRUE;
//
//    /* If binary output file being used, then   */
//    /* do not write full results to Report file */
//    /* (use it only for status reports).        */
//    p->report.Rptflag = 0;
//    if (strlen(f3) == 0) p->report.Rptflag = 1;
//
//    /*** Updated 9/7/00 ***/
//    /*** Previous code segment ignored. ***/
//    /*** Rptflag now always set to 1.   ***/
//    p->report.Rptflag = 1;
//
//    /* Initialize global pointers to NULL. */
//    initpointers(p);
//
//    /* Open input & report files */
//    ERRCODE(openfiles(p,f1, f2, f3));
//    if (errcode > 0)
//    {
//        errmsg(p, errcode);
//        return(errcode);
//    }
//    writelogo(p);
//
//    /* Find network size & allocate memory for data */
//    //writecon(p->viewprog,FMT02);
//    writewin(p->viewprog, FMT100);
//    ERRCODE(netsize(p));
//    ERRCODE(allocdata(p));
//
//    /* Retrieve input data */
//    ERRCODE(getdataonly(p));
//
//    return errcode;
//}
//
//int DLLEXPORT ENopenEnd(EN_Project p) {
//    int errcode = 0;
//
//    ERRCODE(adjustdataonly(p));
//
//    /* Free temporary linked lists used for Patterns & Curves */
//    /*freeTmplist(Patlist);
//    freeTmplist(Curvelist);*/
//
//    /* If using previously saved hydraulics then open its file */
//    if (p->outfile.Hydflag == USE) ERRCODE(openhydfile(p));
//
//    /* Write input summary to report file */
//    if (!errcode)
//    {
//        if (p->report.Summaryflag) writesummary(p);
//        writetime(p, FMT104);
//        p->Openflag = TRUE;
//    }
//    else errmsg(p, errcode);
//    return(errcode);
//}
//
//int  DLLEXPORT ENsetlinknodes(EN_Project p,char* linkID, char* node1, char* node2)
//{
//    int errcode = 0;
//    ERRCODE(setlinknodes(p,linkID, node1, node2));
//    return(errcode);
//}
//
//int   DLLEXPORT ENsetlinklength(EN_Project p, char* linkID, float length) {
//    int errcode = 0;
//    ERRCODE(setlinklength(p,linkID, length));
//    return(errcode);
//}