Sharp7.cs 147 KB
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
/*=============================================================================|
|  PROJECT Sharp7                                                        1.0.7 |
|==============================================================================|
|  Copyright (C) 2016 Davide Nardella                                          |
|  All rights reserved.                                                        |
|==============================================================================|
|  Sharp7 is free software: you can redistribute it and/or modify              |
|  it under the terms of the Lesser GNU General Public License as published by |
|  the Free Software Foundation, either version 3 of the License, or           |
|  (at your option) any later version.                                         |
|                                                                              |
|  It means that you can distribute your commercial software which includes    |
|  Sharp7 without the requirement to distribute the source code of your        |
|  application and without the requirement that your application be itself     |
|  distributed under LGPL.                                                     |
|                                                                              |
|  Sharp7 is distributed in the hope that it will be useful,                   |
|  but WITHOUT ANY WARRANTY; without even the implied warranty of              |
|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               |
|  Lesser GNU General Public License for more details.                         |
|                                                                              |
|  You should have received a copy of the GNU General Public License and a     |
|  copy of Lesser GNU General Public License along with Sharp7.                |
|  If not, see  http://www.gnu.org/licenses/                                   |
|==============================================================================|
History:
 * 1.0.0 2016/10/09 First Release
 * 1.0.1 2016/10/22 Added CoreCLR compatibility (CORE_CLR symbol must be 
					defined in Build options).
					Thanks to Dirk-Jan Wassink.
 * 1.0.2 2016/11/13 Fixed a bug in CLR compatibility
 * 1.0.3 2017/01/25 Fixed a bug in S7.GetIntAt(). Thanks to lupal1
					Added S7Timer Read/Write. Thanks to Lukas Palkovic 
 * 1.0.4 2018/06/12 Fixed the last bug in S7.GetIntAt(). Thanks to Jérémy HAURAY
					Get/Set LTime. Thanks to Jérémy HAURAY
					Get/Set 1500 WString. Thanks to Jérémy HAURAY
					Get/Set 1500 Array of WChar. Thanks to Jérémy HAURAY
 * 1.0.5 2018/11/21 Implemented ListBlocks and ListBlocksOfType (by Jos Koenis, TEB Engineering)
 * 1.0.6 2019/05/25 Implemented Force Jobs by Bart Swister
 * 1.0.7 2019/10/05 Bugfix in List in ListBlocksOfType. Thanks to Cosimo Ladiana 
*/
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.IO;
//------------------------------------------------------------------------------
// If you are compiling for UWP verify that WINDOWS_UWP or NETFX_CORE are 
// defined into Project Properties->Build->Conditional compilation symbols
//------------------------------------------------------------------------------
#if WINDOWS_UWP || NETFX_CORE
using System.Threading.Tasks;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
#else // <-- Including MONO
using System.Net.Sockets;
#endif

namespace Sharp7
{


    #region [Async Sockets UWP(W10,IoT,Phone)/Windows 8/Windows 8 Phone]
#if WINDOWS_UWP || NETFX_CORE
	class MsgSocket
	{
		private DataReader Reader = null;
		private DataWriter Writer = null;
		private StreamSocket TCPSocket;

		private bool _Connected;

		private int _ReadTimeout = 2000;
		private int _WriteTimeout = 2000;
		private int _ConnectTimeout = 1000;

		public static int LastError = 0;


		private void CreateSocket()
		{
			TCPSocket = new StreamSocket();
			TCPSocket.Control.NoDelay = true;
			_Connected = false;
		}

		public MsgSocket()
		{
		}

		public void Close()
		{
			if (Reader != null)
			{
				Reader.Dispose();
				Reader = null;
			}
			if (Writer != null)
			{
				Writer.Dispose();
				Writer = null;
			}
			if (TCPSocket != null)
			{
				TCPSocket.Dispose();
				TCPSocket = null;
			}
			_Connected = false;
		}

		private async Task AsConnect(string Host, string port, CancellationTokenSource cts)
		{
			HostName ServerHost = new HostName(Host);
			try
			{
				await TCPSocket.ConnectAsync(ServerHost, port).AsTask(cts.Token);
				_Connected = true;
			}
			catch (TaskCanceledException)
			{
				LastError = S7Consts.errTCPConnectionTimeout;
			}
			catch
			{
				LastError = S7Consts.errTCPConnectionFailed; // Maybe unreachable peer
			}
		}

		public int Connect(string Host, int Port)
		{
			LastError = 0;
			if (!Connected)
			{
				CreateSocket();
				CancellationTokenSource cts = new CancellationTokenSource();
				try
				{
					try
					{
						cts.CancelAfter(_ConnectTimeout);
						Task.WaitAny(Task.Run(async () => await AsConnect(Host, Port.ToString(), cts)));
					}
					catch
					{
						LastError = S7Consts.errTCPConnectionFailed;
					}
				}
				finally
				{
					if (cts != null)
					{
						try
						{
							cts.Cancel();
							cts.Dispose();
							cts = null;
						}
						catch { }
					}

				}
				if (LastError == 0)
				{
					Reader = new DataReader(TCPSocket.InputStream);
					Reader.InputStreamOptions = InputStreamOptions.Partial;
					Writer = new DataWriter(TCPSocket.OutputStream);
					_Connected = true;
				}
				else
					Close();
			}
			return LastError;
		}

		private async Task AsReadBuffer(byte[] Buffer, int Size, CancellationTokenSource cts)
		{
			try
			{
				await Reader.LoadAsync((uint)Size).AsTask(cts.Token);
				Reader.ReadBytes(Buffer);
			}
			catch
			{
				LastError = S7Consts.errTCPDataReceive;
			}
		}

		public int Receive(byte[] Buffer, int Start, int Size)
		{
			byte[] InBuffer = new byte[Size];
			CancellationTokenSource cts = new CancellationTokenSource();
			LastError = 0;
			try
			{
				try
				{
					cts.CancelAfter(_ReadTimeout);
					Task.WaitAny(Task.Run(async () => await AsReadBuffer(InBuffer, Size, cts)));
				}
				catch
				{
					LastError = S7Consts.errTCPDataReceive;
				}
			}
			finally
			{
				if (cts != null)
				{
					try
					{
						cts.Cancel();
						cts.Dispose();
						cts = null;
					}
					catch { }
				}
			}
			if (LastError == 0)
				Array.Copy(InBuffer, 0, Buffer, Start, Size);
			else
				Close();
			return LastError;
		}

		private async Task WriteBuffer(byte[] Buffer, CancellationTokenSource cts)
		{
			try
			{
				Writer.WriteBytes(Buffer);
				await Writer.StoreAsync().AsTask(cts.Token);
			}
			catch
			{
				LastError = S7Consts.errTCPDataSend;
			}
		}

		public int Send(byte[] Buffer, int Size)
		{
			byte[] OutBuffer = new byte[Size];
			CancellationTokenSource cts = new CancellationTokenSource();
			Array.Copy(Buffer, 0, OutBuffer, 0, Size);
			LastError = 0;
			try
			{
				try
				{
					cts.CancelAfter(_WriteTimeout);
					Task.WaitAny(Task.Run(async () => await WriteBuffer(OutBuffer, cts)));
				}
				catch
				{
					LastError = S7Consts.errTCPDataSend;
				}
			}
			finally
			{
				if (cts != null)
				{
					try
					{
						cts.Cancel();
						cts.Dispose();
						cts = null;
					}
					catch { }
				}
			}
			if (LastError != 0)
				Close();
			return LastError;
		}

		~MsgSocket()
		{
			Close();
		}

		public bool Connected
		{
			get
			{
				return (TCPSocket != null) && _Connected;
			}
		}

		public int ReadTimeout
		{
			get
			{
				return _ReadTimeout;
			}
			set
			{
				_ReadTimeout = value;
			}
		}

		public int WriteTimeout
		{
			get
			{
				return _WriteTimeout;
			}
			set
			{
				_WriteTimeout = value;
			}
		}
		public int ConnectTimeout
		{
			get
			{
				return _ConnectTimeout;
			}
			set
			{
				_ConnectTimeout = value;
			}
		}
	}
#endif
    #endregion

    #region [Sync Sockets Win32/Win64 Desktop Application]
#if !WINDOWS_UWP && !NETFX_CORE
    class MsgSocket
    {
        private Socket TCPSocket;
        private int _ReadTimeout = 2000;
        private int _WriteTimeout = 2000;
        private int _ConnectTimeout = 1000;
        public int LastError = 0;

        public MsgSocket()
        {
        }

        ~MsgSocket()
        {
            Close();
        }

        public void Close()
        {
            if (TCPSocket != null)
            {
                TCPSocket.Dispose();
                TCPSocket = null;
            }
        }

        private void CreateSocket()
        {
            TCPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            TCPSocket.NoDelay = true;
        }

        private void TCPPing(string Host, int Port)
        {
            // To Ping the PLC an Asynchronous socket is used rather then an ICMP packet.
            // This allows the use also across Internet and Firewalls (obviously the port must be opened)           
            LastError = 0;
            Socket PingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {

#if CORE_CLR
				var task = PingSocket.ConnectAsync(Host, Port);
				task.Wait(_ConnectTimeout);
				bool success = task.IsCompleted;
#else
                IAsyncResult result = PingSocket.BeginConnect(Host, Port, null, null);
                bool success = result.AsyncWaitHandle.WaitOne(_ConnectTimeout, true);
#endif
                if (!success)
                {
                    LastError = S7Consts.errTCPConnectionFailed;
                }
            }
            catch
            {
                LastError = S7Consts.errTCPConnectionFailed;
            };
#if CORE_CLR
			PingSocket.Dispose();
#else
            PingSocket.Close();
#endif
        }

        public int Connect(string Host, int Port)
        {
            LastError = 0;
            if (!Connected)
            {
                TCPPing(Host, Port);
                if (LastError == 0)
                    try
                    {
                        CreateSocket();
                        TCPSocket.Connect(Host, Port);
                    }
                    catch
                    {
                        LastError = S7Consts.errTCPConnectionFailed;
                    }
            }
            return LastError;
        }

        private int WaitForData(int Size, int Timeout)
        {
            bool Expired = false;
            int SizeAvail;
            int Elapsed = Environment.TickCount;
            LastError = 0;
            try
            {
                SizeAvail = TCPSocket.Available;
                while ((SizeAvail < Size) && (!Expired))
                {
                    Thread.Sleep(2);
                    SizeAvail = TCPSocket.Available;
                    Expired = Environment.TickCount - Elapsed > Timeout;
                    // If timeout we clean the buffer
                    if (Expired && (SizeAvail > 0))
                        try
                        {
                            byte[] Flush = new byte[SizeAvail];
                            TCPSocket.Receive(Flush, 0, SizeAvail, SocketFlags.None);
                        }
                        catch { }
                }
            }
            catch
            {
                LastError = S7Consts.errTCPDataReceive;
            }
            if (Expired)
            {
                LastError = S7Consts.errTCPDataReceive;
            }
            return LastError;
        }

        public int Receive(byte[] Buffer, int Start, int Size)
        {

            int BytesRead = 0;
            LastError = WaitForData(Size, _ReadTimeout);
            if (LastError == 0)
            {
                try
                {
                    BytesRead = TCPSocket.Receive(Buffer, Start, Size, SocketFlags.None);
                }
                catch
                {
                    LastError = S7Consts.errTCPDataReceive;
                }
                if (BytesRead == 0) // Connection Reset by the peer
                {
                    LastError = S7Consts.errTCPDataReceive;
                    Close();
                }
            }
            return LastError;
        }

        public int Send(byte[] Buffer, int Size)
        {
            LastError = 0;
            try
            {
                int BytesSent = TCPSocket.Send(Buffer, Size, SocketFlags.None);
            }
            catch
            {
                LastError = S7Consts.errTCPDataSend;
                Close();
            }
            return LastError;
        }

        public bool Connected
        {
            get
            {
                return (TCPSocket != null) && (TCPSocket.Connected);
            }
        }

        public int ReadTimeout
        {
            get
            {
                return _ReadTimeout;
            }
            set
            {
                _ReadTimeout = value;
            }
        }

        public int WriteTimeout
        {
            get
            {
                return _WriteTimeout;
            }
            set
            {
                _WriteTimeout = value;
            }

        }
        public int ConnectTimeout
        {
            get
            {
                return _ConnectTimeout;
            }
            set
            {
                _ConnectTimeout = value;
            }
        }
    }
#endif
    #endregion

    public static class S7Consts
    {
        #region [Exported Consts]
        // Error codes
        //------------------------------------------------------------------------------
        //                                     ERRORS                 
        //------------------------------------------------------------------------------
        public const int errTCPSocketCreation = 0x00000001;
        public const int errTCPConnectionTimeout = 0x00000002;
        public const int errTCPConnectionFailed = 0x00000003;
        public const int errTCPReceiveTimeout = 0x00000004;
        public const int errTCPDataReceive = 0x00000005;
        public const int errTCPSendTimeout = 0x00000006;
        public const int errTCPDataSend = 0x00000007;
        public const int errTCPConnectionReset = 0x00000008;
        public const int errTCPNotConnected = 0x00000009;
        public const int errTCPUnreachableHost = 0x00002751;

        public const int errIsoConnect = 0x00010000; // Connection error
        public const int errIsoInvalidPDU = 0x00030000; // Bad format
        public const int errIsoInvalidDataSize = 0x00040000; // Bad Datasize passed to send/recv : buffer is invalid

        public const int errCliNegotiatingPDU = 0x00100000;
        public const int errCliInvalidParams = 0x00200000;
        public const int errCliJobPending = 0x00300000;
        public const int errCliTooManyItems = 0x00400000;
        public const int errCliInvalidWordLen = 0x00500000;
        public const int errCliPartialDataWritten = 0x00600000;
        public const int errCliSizeOverPDU = 0x00700000;
        public const int errCliInvalidPlcAnswer = 0x00800000;
        public const int errCliAddressOutOfRange = 0x00900000;
        public const int errCliInvalidTransportSize = 0x00A00000;
        public const int errCliWriteDataSizeMismatch = 0x00B00000;
        public const int errCliItemNotAvailable = 0x00C00000;
        public const int errCliInvalidValue = 0x00D00000;
        public const int errCliCannotStartPLC = 0x00E00000;
        public const int errCliAlreadyRun = 0x00F00000;
        public const int errCliCannotStopPLC = 0x01000000;
        public const int errCliCannotCopyRamToRom = 0x01100000;
        public const int errCliCannotCompress = 0x01200000;
        public const int errCliAlreadyStop = 0x01300000;
        public const int errCliFunNotAvailable = 0x01400000;
        public const int errCliUploadSequenceFailed = 0x01500000;
        public const int errCliInvalidDataSizeRecvd = 0x01600000;
        public const int errCliInvalidBlockType = 0x01700000;
        public const int errCliInvalidBlockNumber = 0x01800000;
        public const int errCliInvalidBlockSize = 0x01900000;
        public const int errCliNeedPassword = 0x01D00000;
        public const int errCliInvalidPassword = 0x01E00000;
        public const int errCliNoPasswordToSetOrClear = 0x01F00000;
        public const int errCliJobTimeout = 0x02000000;
        public const int errCliPartialDataRead = 0x02100000;
        public const int errCliBufferTooSmall = 0x02200000;
        public const int errCliFunctionRefused = 0x02300000;
        public const int errCliDestroying = 0x02400000;
        public const int errCliInvalidParamNumber = 0x02500000;
        public const int errCliCannotChangeParam = 0x02600000;
        public const int errCliFunctionNotImplemented = 0x02700000;
        //------------------------------------------------------------------------------
        //        PARAMS LIST FOR COMPATIBILITY WITH Snap7.net.cs           
        //------------------------------------------------------------------------------
        public const Int32 p_u16_LocalPort = 1;  // Not applicable here
        public const Int32 p_u16_RemotePort = 2;
        public const Int32 p_i32_PingTimeout = 3;
        public const Int32 p_i32_SendTimeout = 4;
        public const Int32 p_i32_RecvTimeout = 5;
        public const Int32 p_i32_WorkInterval = 6;  // Not applicable here
        public const Int32 p_u16_SrcRef = 7;  // Not applicable here
        public const Int32 p_u16_DstRef = 8;  // Not applicable here
        public const Int32 p_u16_SrcTSap = 9;  // Not applicable here
        public const Int32 p_i32_PDURequest = 10;
        public const Int32 p_i32_MaxClients = 11; // Not applicable here
        public const Int32 p_i32_BSendTimeout = 12; // Not applicable here
        public const Int32 p_i32_BRecvTimeout = 13; // Not applicable here
        public const Int32 p_u32_RecoveryTime = 14; // Not applicable here
        public const Int32 p_u32_KeepAliveTime = 15; // Not applicable here
                                                     // Area ID
        public const byte S7AreaPE = 0x81;
        public const byte S7AreaPA = 0x82;
        public const byte S7AreaMK = 0x83;
        public const byte S7AreaDB = 0x84;
        public const byte S7AreaCT = 0x1C;
        public const byte S7AreaTM = 0x1D;
        // Word Length
        public const int S7WLBit = 0x01;
        public const int S7WLByte = 0x02;
        public const int S7WLChar = 0x03;
        public const int S7WLWord = 0x04;
        public const int S7WLInt = 0x05;
        public const int S7WLDWord = 0x06;
        public const int S7WLDInt = 0x07;
        public const int S7WLReal = 0x08;
        public const int S7WLCounter = 0x1C;
        public const int S7WLTimer = 0x1D;
        // PLC Status
        public const int S7CpuStatusUnknown = 0x00;
        public const int S7CpuStatusRun = 0x08;
        public const int S7CpuStatusStop = 0x04;

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct S7Tag
        {
            public Int32 Area;
            public Int32 DBNumber;
            public Int32 Start;
            public Int32 Elements;
            public Int32 WordLen;
        }
        #endregion
    }

    public class S7Timer
    {
        #region S7Timer
        TimeSpan pt;
        TimeSpan et;
        bool input = false;
        bool q = false;
        public S7Timer(byte[] buff, int position)
        {
            if (position + 12 < buff.Length)
            {
                return;
            }
            else
            {
                SetTimer(new List<byte>(buff).GetRange(position, 16).ToArray());
            }
        }

        public S7Timer(byte[] buff)
        {
            SetTimer(buff);
        }

        private void SetTimer(byte[] buff)
        {
            if (buff.Length != 12)
            {
                this.pt = new TimeSpan(0);
                this.et = new TimeSpan(0);
            }
            else
            {
                Int32 resPT;
                resPT = buff[0]; resPT <<= 8;
                resPT += buff[1]; resPT <<= 8;
                resPT += buff[2]; resPT <<= 8;
                resPT += buff[3];
                this.pt = new TimeSpan(0, 0, 0, 0, resPT);

                Int32 resET;
                resET = buff[4]; resET <<= 8;
                resET += buff[5]; resET <<= 8;
                resET += buff[6]; resET <<= 8;
                resET += buff[7];
                this.et = new TimeSpan(0, 0, 0, 0, resET);

                this.input = (buff[8] & 0x01) == 0x01;
                this.q = (buff[8] & 0x02) == 0x02;
            }
        }
        public TimeSpan PT
        {
            get
            {
                return pt;
            }
        }
        public TimeSpan ET
        {
            get
            {
                return et;
            }
        }
        public bool IN
        {
            get
            {
                return input;
            }
        }
        public bool Q
        {
            get
            {
                return q;
            }
        }
        #endregion
    }

    public static class S7
    {
        #region [Help Functions]

        private static Int64 bias = 621355968000000000; // "decimicros" between 0001-01-01 00:00:00 and 1970-01-01 00:00:00

        private static int BCDtoByte(byte B)
        {
            return ((B >> 4) * 10) + (B & 0x0F);
        }

        private static byte ByteToBCD(int Value)
        {
            return (byte)(((Value / 10) << 4) | (Value % 10));
        }

        private static byte[] CopyFrom(byte[] Buffer, int Pos, int Size)
        {
            byte[] Result = new byte[Size];
            Array.Copy(Buffer, Pos, Result, 0, Size);
            return Result;
        }

        public static int DataSizeByte(int WordLength)
        {
            switch (WordLength)
            {
                case S7Consts.S7WLBit: return 1;  // S7 sends 1 byte per bit
                case S7Consts.S7WLByte: return 1;
                case S7Consts.S7WLChar: return 1;
                case S7Consts.S7WLWord: return 2;
                case S7Consts.S7WLDWord: return 4;
                case S7Consts.S7WLInt: return 2;
                case S7Consts.S7WLDInt: return 4;
                case S7Consts.S7WLReal: return 4;
                case S7Consts.S7WLCounter: return 2;
                case S7Consts.S7WLTimer: return 2;
                default: return 0;
            }
        }

        #region Get/Set the bit at Pos.Bit
        public static bool GetBitAt(byte[] Buffer, int Pos, int Bit)
        {
            byte[] Mask = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
            if (Bit < 0) Bit = 0;
            if (Bit > 7) Bit = 7;
            return (Buffer[Pos] & Mask[Bit]) != 0;
        }
        public static void SetBitAt(ref byte[] Buffer, int Pos, int Bit, bool Value)
        {
            byte[] Mask = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
            if (Bit < 0) Bit = 0;
            if (Bit > 7) Bit = 7;

            if (Value)
                Buffer[Pos] = (byte)(Buffer[Pos] | Mask[Bit]);
            else
                Buffer[Pos] = (byte)(Buffer[Pos] & ~Mask[Bit]);
        }
        #endregion

        #region Get/Set 8 bit signed value (S7 SInt) -128..127
        public static int GetSIntAt(byte[] Buffer, int Pos)
        {
            int Value = Buffer[Pos];
            if (Value < 128)
                return Value;
            else
                return (int)(Value - 256);
        }
        public static void SetSIntAt(byte[] Buffer, int Pos, int Value)
        {
            if (Value < -128) Value = -128;
            if (Value > 127) Value = 127;
            Buffer[Pos] = (byte)Value;
        }
        #endregion

        #region Get/Set 16 bit signed value (S7 int) -32768..32767
        public static short GetIntAt(byte[] Buffer, int Pos)
        {
            return (short)((Buffer[Pos] << 8) | Buffer[Pos + 1]);
        }
        public static void SetIntAt(byte[] Buffer, int Pos, Int16 Value)
        {
            Buffer[Pos] = (byte)(Value >> 8);
            Buffer[Pos + 1] = (byte)(Value & 0x00FF);
        }
        #endregion

        #region Get/Set 32 bit signed value (S7 DInt) -2147483648..2147483647
        public static int GetDIntAt(byte[] Buffer, int Pos)
        {
            int Result;
            Result = Buffer[Pos]; Result <<= 8;
            Result += Buffer[Pos + 1]; Result <<= 8;
            Result += Buffer[Pos + 2]; Result <<= 8;
            Result += Buffer[Pos + 3];
            return Result;
        }
        public static void SetDIntAt(byte[] Buffer, int Pos, int Value)
        {
            Buffer[Pos + 3] = (byte)(Value & 0xFF);
            Buffer[Pos + 2] = (byte)((Value >> 8) & 0xFF);
            Buffer[Pos + 1] = (byte)((Value >> 16) & 0xFF);
            Buffer[Pos] = (byte)((Value >> 24) & 0xFF);
        }
        #endregion

        #region Get/Set 64 bit signed value (S7 LInt) -9223372036854775808..9223372036854775807
        public static Int64 GetLIntAt(byte[] Buffer, int Pos)
        {
            Int64 Result;
            Result = Buffer[Pos]; Result <<= 8;
            Result += Buffer[Pos + 1]; Result <<= 8;
            Result += Buffer[Pos + 2]; Result <<= 8;
            Result += Buffer[Pos + 3]; Result <<= 8;
            Result += Buffer[Pos + 4]; Result <<= 8;
            Result += Buffer[Pos + 5]; Result <<= 8;
            Result += Buffer[Pos + 6]; Result <<= 8;
            Result += Buffer[Pos + 7];
            return Result;
        }
        public static void SetLIntAt(byte[] Buffer, int Pos, Int64 Value)
        {
            Buffer[Pos + 7] = (byte)(Value & 0xFF);
            Buffer[Pos + 6] = (byte)((Value >> 8) & 0xFF);
            Buffer[Pos + 5] = (byte)((Value >> 16) & 0xFF);
            Buffer[Pos + 4] = (byte)((Value >> 24) & 0xFF);
            Buffer[Pos + 3] = (byte)((Value >> 32) & 0xFF);
            Buffer[Pos + 2] = (byte)((Value >> 40) & 0xFF);
            Buffer[Pos + 1] = (byte)((Value >> 48) & 0xFF);
            Buffer[Pos] = (byte)((Value >> 56) & 0xFF);
        }
        #endregion

        #region Get/Set 8 bit unsigned value (S7 USInt) 0..255
        public static byte GetUSIntAt(byte[] Buffer, int Pos)
        {
            return Buffer[Pos];
        }
        public static void SetUSIntAt(byte[] Buffer, int Pos, byte Value)
        {
            Buffer[Pos] = Value;
        }
        #endregion

        #region Get/Set 16 bit unsigned value (S7 UInt) 0..65535
        public static UInt16 GetUIntAt(byte[] Buffer, int Pos)
        {
            return (UInt16)((Buffer[Pos] << 8) | Buffer[Pos + 1]);
        }
        public static void SetUIntAt(byte[] Buffer, int Pos, UInt16 Value)
        {
            Buffer[Pos] = (byte)(Value >> 8);
            Buffer[Pos + 1] = (byte)(Value & 0x00FF);
        }
        #endregion

        #region Get/Set 32 bit unsigned value (S7 UDInt) 0..4294967296
        public static UInt32 GetUDIntAt(byte[] Buffer, int Pos)
        {
            UInt32 Result;
            Result = Buffer[Pos]; Result <<= 8;
            Result |= Buffer[Pos + 1]; Result <<= 8;
            Result |= Buffer[Pos + 2]; Result <<= 8;
            Result |= Buffer[Pos + 3];
            return Result;
        }
        public static void SetUDIntAt(byte[] Buffer, int Pos, UInt32 Value)
        {
            Buffer[Pos + 3] = (byte)(Value & 0xFF);
            Buffer[Pos + 2] = (byte)((Value >> 8) & 0xFF);
            Buffer[Pos + 1] = (byte)((Value >> 16) & 0xFF);
            Buffer[Pos] = (byte)((Value >> 24) & 0xFF);
        }
        #endregion

        #region Get/Set 64 bit unsigned value (S7 ULint) 0..18446744073709551616
        public static UInt64 GetULIntAt(byte[] Buffer, int Pos)
        {
            UInt64 Result;
            Result = Buffer[Pos]; Result <<= 8;
            Result |= Buffer[Pos + 1]; Result <<= 8;
            Result |= Buffer[Pos + 2]; Result <<= 8;
            Result |= Buffer[Pos + 3]; Result <<= 8;
            Result |= Buffer[Pos + 4]; Result <<= 8;
            Result |= Buffer[Pos + 5]; Result <<= 8;
            Result |= Buffer[Pos + 6]; Result <<= 8;
            Result |= Buffer[Pos + 7];
            return Result;
        }
        public static void SetULintAt(byte[] Buffer, int Pos, UInt64 Value)
        {
            Buffer[Pos + 7] = (byte)(Value & 0xFF);
            Buffer[Pos + 6] = (byte)((Value >> 8) & 0xFF);
            Buffer[Pos + 5] = (byte)((Value >> 16) & 0xFF);
            Buffer[Pos + 4] = (byte)((Value >> 24) & 0xFF);
            Buffer[Pos + 3] = (byte)((Value >> 32) & 0xFF);
            Buffer[Pos + 2] = (byte)((Value >> 40) & 0xFF);
            Buffer[Pos + 1] = (byte)((Value >> 48) & 0xFF);
            Buffer[Pos] = (byte)((Value >> 56) & 0xFF);
        }
        #endregion

        #region Get/Set 8 bit word (S7 Byte) 16#00..16#FF
        public static byte GetByteAt(byte[] Buffer, int Pos)
        {
            return Buffer[Pos];
        }
        public static void SetByteAt(byte[] Buffer, int Pos, byte Value)
        {
            Buffer[Pos] = Value;
        }
        #endregion

        #region Get/Set 16 bit word (S7 Word) 16#0000..16#FFFF
        public static UInt16 GetWordAt(byte[] Buffer, int Pos)
        {
            return GetUIntAt(Buffer, Pos);
        }
        public static void SetWordAt(byte[] Buffer, int Pos, UInt16 Value)
        {
            SetUIntAt(Buffer, Pos, Value);
        }
        #endregion

        #region Get/Set 32 bit word (S7 DWord) 16#00000000..16#FFFFFFFF
        public static UInt32 GetDWordAt(byte[] Buffer, int Pos)
        {
            return GetUDIntAt(Buffer, Pos);
        }
        public static void SetDWordAt(byte[] Buffer, int Pos, UInt32 Value)
        {
            SetUDIntAt(Buffer, Pos, Value);
        }
        #endregion

        #region Get/Set 64 bit word (S7 LWord) 16#0000000000000000..16#FFFFFFFFFFFFFFFF
        public static UInt64 GetLWordAt(byte[] Buffer, int Pos)
        {
            return GetULIntAt(Buffer, Pos);
        }
        public static void SetLWordAt(byte[] Buffer, int Pos, UInt64 Value)
        {
            SetULintAt(Buffer, Pos, Value);
        }
        #endregion

        #region Get/Set 32 bit floating point number (S7 Real) (Range of Single)
        public static Single GetRealAt(byte[] Buffer, int Pos)
        {
            UInt32 Value = GetUDIntAt(Buffer, Pos);
            byte[] bytes = BitConverter.GetBytes(Value);
            return BitConverter.ToSingle(bytes, 0);
        }
        public static void SetRealAt(byte[] Buffer, int Pos, Single Value)
        {
            byte[] FloatArray = BitConverter.GetBytes(Value);
            Buffer[Pos] = FloatArray[3];
            Buffer[Pos + 1] = FloatArray[2];
            Buffer[Pos + 2] = FloatArray[1];
            Buffer[Pos + 3] = FloatArray[0];
        }
        #endregion

        #region Get/Set 64 bit floating point number (S7 LReal) (Range of Double)
        public static Double GetLRealAt(byte[] Buffer, int Pos)
        {
            UInt64 Value = GetULIntAt(Buffer, Pos);
            byte[] bytes = BitConverter.GetBytes(Value);
            return BitConverter.ToDouble(bytes, 0);
        }
        public static void SetLRealAt(byte[] Buffer, int Pos, Double Value)
        {
            byte[] FloatArray = BitConverter.GetBytes(Value);
            Buffer[Pos] = FloatArray[7];
            Buffer[Pos + 1] = FloatArray[6];
            Buffer[Pos + 2] = FloatArray[5];
            Buffer[Pos + 3] = FloatArray[4];
            Buffer[Pos + 4] = FloatArray[3];
            Buffer[Pos + 5] = FloatArray[2];
            Buffer[Pos + 6] = FloatArray[1];
            Buffer[Pos + 7] = FloatArray[0];
        }
        #endregion

        #region Get/Set DateTime (S7 DATE_AND_TIME)
        public static DateTime GetDateTimeAt(byte[] Buffer, int Pos)
        {
            int Year, Month, Day, Hour, Min, Sec, MSec;

            Year = BCDtoByte(Buffer[Pos]);
            if (Year < 90)
                Year += 2000;
            else
                Year += 1900;

            Month = BCDtoByte(Buffer[Pos + 1]);
            Day = BCDtoByte(Buffer[Pos + 2]);
            Hour = BCDtoByte(Buffer[Pos + 3]);
            Min = BCDtoByte(Buffer[Pos + 4]);
            Sec = BCDtoByte(Buffer[Pos + 5]);
            MSec = (BCDtoByte(Buffer[Pos + 6]) * 10) + (BCDtoByte(Buffer[Pos + 7]) / 10);
            try
            {
                return new DateTime(Year, Month, Day, Hour, Min, Sec, MSec);
            }
            catch (System.ArgumentOutOfRangeException)
            {
                return new DateTime(0);
            }
        }
        public static void SetDateTimeAt(byte[] Buffer, int Pos, DateTime Value)
        {
            int Year = Value.Year;
            int Month = Value.Month;
            int Day = Value.Day;
            int Hour = Value.Hour;
            int Min = Value.Minute;
            int Sec = Value.Second;
            int Dow = (int)Value.DayOfWeek + 1;
            // MSecH = First two digits of miliseconds 
            int MsecH = Value.Millisecond / 10;
            // MSecL = Last digit of miliseconds
            int MsecL = Value.Millisecond % 10;
            if (Year > 1999)
                Year -= 2000;

            Buffer[Pos] = ByteToBCD(Year);
            Buffer[Pos + 1] = ByteToBCD(Month);
            Buffer[Pos + 2] = ByteToBCD(Day);
            Buffer[Pos + 3] = ByteToBCD(Hour);
            Buffer[Pos + 4] = ByteToBCD(Min);
            Buffer[Pos + 5] = ByteToBCD(Sec);
            Buffer[Pos + 6] = ByteToBCD(MsecH);
            Buffer[Pos + 7] = ByteToBCD(MsecL * 10 + Dow);
        }
        #endregion

        #region Get/Set DATE (S7 DATE) 
        public static DateTime GetDateAt(byte[] Buffer, int Pos)
        {
            try
            {
                return new DateTime(1990, 1, 1).AddDays(GetIntAt(Buffer, Pos));
            }
            catch (System.ArgumentOutOfRangeException)
            {
                return new DateTime(0);
            }
        }
        public static void SetDateAt(byte[] Buffer, int Pos, DateTime Value)
        {
            SetIntAt(Buffer, Pos, (Int16)(Value - new DateTime(1990, 1, 1)).Days);
        }

        #endregion

        #region Get/Set TOD (S7 TIME_OF_DAY)
        public static DateTime GetTODAt(byte[] Buffer, int Pos)
        {
            try
            {
                return new DateTime(0).AddMilliseconds(S7.GetDIntAt(Buffer, Pos));
            }
            catch (System.ArgumentOutOfRangeException)
            {
                return new DateTime(0);
            }
        }
        public static void SetTODAt(byte[] Buffer, int Pos, DateTime Value)
        {
            TimeSpan Time = Value.TimeOfDay;
            SetDIntAt(Buffer, Pos, (Int32)Math.Round(Time.TotalMilliseconds));
        }
        #endregion

        #region Get/Set LTOD (S7 1500 LONG TIME_OF_DAY)
        public static DateTime GetLTODAt(byte[] Buffer, int Pos)
        {
            // .NET Tick = 100 ns, S71500 Tick = 1 ns
            try
            {
                return new DateTime(Math.Abs(GetLIntAt(Buffer, Pos) / 100));
            }
            catch (System.ArgumentOutOfRangeException)
            {
                return new DateTime(0);
            }
        }
        public static void SetLTODAt(byte[] Buffer, int Pos, DateTime Value)
        {
            TimeSpan Time = Value.TimeOfDay;
            SetLIntAt(Buffer, Pos, (Int64)Time.Ticks * 100);
        }
        #endregion

        #region GET/SET LDT (S7 1500 Long Date and Time)
        public static DateTime GetLDTAt(byte[] Buffer, int Pos)
        {
            try
            {
                return new DateTime((GetLIntAt(Buffer, Pos) / 100) + bias);
            }
            catch (System.ArgumentOutOfRangeException)
            {
                return new DateTime(0);
            }
        }
        public static void SetLDTAt(byte[] Buffer, int Pos, DateTime Value)
        {
            SetLIntAt(Buffer, Pos, (Value.Ticks - bias) * 100);
        }
        #endregion

        #region Get/Set DTL (S71200/1500 Date and Time)
        // Thanks to Johan Cardoen for GetDTLAt
        public static DateTime GetDTLAt(byte[] Buffer, int Pos)
        {
            int Year, Month, Day, Hour, Min, Sec, MSec;

            Year = Buffer[Pos] * 256 + Buffer[Pos + 1];
            Month = Buffer[Pos + 2];
            Day = Buffer[Pos + 3];
            Hour = Buffer[Pos + 5];
            Min = Buffer[Pos + 6];
            Sec = Buffer[Pos + 7];
            MSec = (int)GetUDIntAt(Buffer, Pos + 8) / 1000000;

            try
            {
                return new DateTime(Year, Month, Day, Hour, Min, Sec, MSec);
            }
            catch (System.ArgumentOutOfRangeException)
            {
                return new DateTime(0);
            }
        }
        public static void SetDTLAt(byte[] Buffer, int Pos, DateTime Value)
        {
            short Year = (short)Value.Year;
            byte Month = (byte)Value.Month;
            byte Day = (byte)Value.Day;
            byte Hour = (byte)Value.Hour;
            byte Min = (byte)Value.Minute;
            byte Sec = (byte)Value.Second;
            byte Dow = (byte)(Value.DayOfWeek + 1);

            Int32 NanoSecs = Value.Millisecond * 1000000;

            var bytes_short = BitConverter.GetBytes(Year);

            Buffer[Pos] = bytes_short[1];
            Buffer[Pos + 1] = bytes_short[0];
            Buffer[Pos + 2] = Month;
            Buffer[Pos + 3] = Day;
            Buffer[Pos + 4] = Dow;
            Buffer[Pos + 5] = Hour;
            Buffer[Pos + 6] = Min;
            Buffer[Pos + 7] = Sec;
            SetDIntAt(Buffer, Pos + 8, NanoSecs);
        }

        #endregion

        #region Get/Set String (S7 String)
        // Thanks to Pablo Agirre 
        public static string GetStringAt(byte[] Buffer, int Pos)
        {
            int size = (int)Buffer[Pos + 1];
            return Encoding.UTF8.GetString(Buffer, Pos + 2, size);
        }

        public static void SetStringAt(byte[] Buffer, int Pos, int MaxLen, string Value)
        {
            int size = Value.Length;
            Buffer[Pos] = (byte)MaxLen;
            Buffer[Pos + 1] = (byte)size;
            Encoding.UTF8.GetBytes(Value, 0, size, Buffer, Pos + 2);
        }

        #endregion

        #region Get/Set WString (S7-1500 String)
        public static string GetWStringAt(byte[] Buffer, int Pos)
        {
            //WString size = n characters + 2 Words (first for max length, second for real length)
            //Get the real length in Words
            int size = GetIntAt(Buffer, Pos + 2);
            //Extract string in UTF-16 unicode Big Endian.
            return Encoding.BigEndianUnicode.GetString(Buffer, Pos + 4, size * 2);
        }

        public static void SetWStringAt(byte[] Buffer, int Pos, int MaxCharNb, string Value)
        {
            //Get the length in words from number of characters
            int size = Value.Length;
            //Set the Max length in Words 
            SetIntAt(Buffer, Pos, (short)MaxCharNb);
            //Set the real length in words
            SetIntAt(Buffer, Pos + 2, (short)size);
            //Set the UTF-16 unicode Big endian String (after max length and length)
            Encoding.BigEndianUnicode.GetBytes(Value, 0, size, Buffer, Pos + 4);
        }

        #endregion

        #region Get/Set Array of char (S7 ARRAY OF CHARS)
        public static string GetCharsAt(byte[] Buffer, int Pos, int Size)
        {
            return Encoding.UTF8.GetString(Buffer, Pos, Size);
        }

        public static void SetCharsAt(byte[] Buffer, int Pos, string Value)
        {
            int MaxLen = Buffer.Length - Pos;
            // Truncs the string if there's no room enough        
            if (MaxLen > Value.Length) MaxLen = Value.Length;
            Encoding.UTF8.GetBytes(Value, 0, MaxLen, Buffer, Pos);
        }

        #endregion

        #region Get/Set Array of WChar (S7-1500 ARRAY OF CHARS)

        public static String GetWCharsAt(byte[] Buffer, int Pos, int SizeInCharNb)
        {
            //Extract Unicode UTF-16 Big-Endian character from the buffer. To use with WChar Datatype.
            //Size to read is in byte. Be careful, 1 char = 2 bytes
            return Encoding.BigEndianUnicode.GetString(Buffer, Pos, SizeInCharNb * 2);
        }

        public static void SetWCharsAt(byte[] Buffer, int Pos, string Value)
        {
            //Compute Max length in char number
            int MaxLen = (Buffer.Length - Pos) / 2;
            // Truncs the string if there's no room enough        
            if (MaxLen > Value.Length) MaxLen = Value.Length;
            Encoding.BigEndianUnicode.GetBytes(Value, 0, MaxLen, Buffer, Pos);
        }

        #endregion

        #region Get/Set Counter
        public static int GetCounter(ushort Value)
        {
            return BCDtoByte((byte)Value) * 100 + BCDtoByte((byte)(Value >> 8));
        }

        public static int GetCounterAt(ushort[] Buffer, int Index)
        {
            return GetCounter(Buffer[Index]);
        }

        public static ushort ToCounter(int Value)
        {
            return (ushort)(ByteToBCD(Value / 100) + (ByteToBCD(Value % 100) << 8));
        }

        public static void SetCounterAt(ushort[] Buffer, int Pos, int Value)
        {
            Buffer[Pos] = ToCounter(Value);
        }
        #endregion

        #region Get/Set Timer

        public static S7Timer GetS7TimerAt(byte[] Buffer, int Pos)
        {
            return new S7Timer(new List<byte>(Buffer).GetRange(Pos, 12).ToArray());
        }

        public static void SetS7TimespanAt(byte[] Buffer, int Pos, TimeSpan Value)
        {
            SetDIntAt(Buffer, Pos, (Int32)Value.TotalMilliseconds);
        }

        public static TimeSpan GetS7TimespanAt(byte[] Buffer, int pos)
        {
            if (Buffer.Length < pos + 4)
            {
                return new TimeSpan();
            }

            Int32 a;
            a = Buffer[pos + 0]; a <<= 8;
            a += Buffer[pos + 1]; a <<= 8;
            a += Buffer[pos + 2]; a <<= 8;
            a += Buffer[pos + 3];
            TimeSpan sp = new TimeSpan(0, 0, 0, 0, a);

            return sp;
        }

        public static TimeSpan GetLTimeAt(byte[] Buffer, int pos)
        {
            //LTime size : 64 bits (8 octets)
            //Case if the buffer is too small
            if (Buffer.Length < pos + 8) return new TimeSpan();

            try
            {
                // Extract and Convert number of nanoseconds to tick (1 tick = 100 nanoseconds)
                return TimeSpan.FromTicks(GetLIntAt(Buffer, pos) / 100);
            }
            catch (Exception)
            {
                return new TimeSpan();
            }
        }

        public static void SetLTimeAt(byte[] Buffer, int Pos, TimeSpan Value)
        {
            SetLIntAt(Buffer, Pos, (long)(Value.Ticks * 100));
        }

        #endregion

        #endregion [Help Functions]
    }

    public class S7MultiVar
    {
        #region [MultiRead/Write Helper]
        private S7Client FClient;
        private GCHandle[] Handles = new GCHandle[S7Client.MaxVars];
        private int Count = 0;
        private S7Client.S7DataItem[] Items = new S7Client.S7DataItem[S7Client.MaxVars];


        public int[] Results = new int[S7Client.MaxVars];

        private bool AdjustWordLength(int Area, ref int WordLen, ref int Amount, ref int Start)
        {
            // Calc Word size          
            int WordSize = S7.DataSizeByte(WordLen);
            if (WordSize == 0)
                return false;

            if (Area == S7Consts.S7AreaCT)
                WordLen = S7Consts.S7WLCounter;
            if (Area == S7Consts.S7AreaTM)
                WordLen = S7Consts.S7WLTimer;

            if (WordLen == S7Consts.S7WLBit)
                Amount = 1;  // Only 1 bit can be transferred at time
            else
            {
                if ((WordLen != S7Consts.S7WLCounter) && (WordLen != S7Consts.S7WLTimer))
                {
                    Amount = Amount * WordSize;
                    Start = Start * 8;
                    WordLen = S7Consts.S7WLByte;
                }
            }
            return true;
        }

        public S7MultiVar(S7Client Client)
        {
            FClient = Client;
            for (int c = 0; c < S7Client.MaxVars; c++)
                Results[c] = (int)S7Consts.errCliItemNotAvailable;
        }
        ~S7MultiVar()
        {
            Clear();
        }

        public bool Add<T>(S7Consts.S7Tag Tag, ref T[] Buffer, int Offset)
        {
            return Add(Tag.Area, Tag.WordLen, Tag.DBNumber, Tag.Start, Tag.Elements, ref Buffer, Offset);
        }

        public bool Add<T>(S7Consts.S7Tag Tag, ref T[] Buffer)
        {
            return Add(Tag.Area, Tag.WordLen, Tag.DBNumber, Tag.Start, Tag.Elements, ref Buffer);
        }

        public bool Add<T>(Int32 Area, Int32 WordLen, Int32 DBNumber, Int32 Start, Int32 Amount, ref T[] Buffer)
        {
            return Add(Area, WordLen, DBNumber, Start, Amount, ref Buffer, 0);
        }

        public bool Add<T>(Int32 Area, Int32 WordLen, Int32 DBNumber, Int32 Start, Int32 Amount, ref T[] Buffer, int Offset)
        {
            if (Count < S7Client.MaxVars)
            {
                if (AdjustWordLength(Area, ref WordLen, ref Amount, ref Start))
                {
                    Items[Count].Area = Area;
                    Items[Count].WordLen = WordLen;
                    Items[Count].Result = (int)S7Consts.errCliItemNotAvailable;
                    Items[Count].DBNumber = DBNumber;
                    Items[Count].Start = Start;
                    Items[Count].Amount = Amount;
                    GCHandle handle = GCHandle.Alloc(Buffer, GCHandleType.Pinned);
#if WINDOWS_UWP || NETFX_CORE
					if (IntPtr.Size == 4)
						Items[Count].pData = (IntPtr)(handle.AddrOfPinnedObject().ToInt32() + Offset * Marshal.SizeOf<T>());
					else
						Items[Count].pData = (IntPtr)(handle.AddrOfPinnedObject().ToInt64() + Offset * Marshal.SizeOf<T>());
#else
                    if (IntPtr.Size == 4)
                        Items[Count].pData = (IntPtr)(handle.AddrOfPinnedObject().ToInt32() + Offset * Marshal.SizeOf(typeof(T)));
                    else
                        Items[Count].pData = (IntPtr)(handle.AddrOfPinnedObject().ToInt64() + Offset * Marshal.SizeOf(typeof(T)));
#endif
                    Handles[Count] = handle;
                    Count++;
                    return true;
                }
                else
                    return false;
            }
            else
                return false;
        }

        public int Read()
        {
            int FunctionResult;
            int GlobalResult = (int)S7Consts.errCliFunctionRefused;
            try
            {
                if (Count > 0)
                {
                    FunctionResult = FClient.ReadMultiVars(Items, Count);
                    if (FunctionResult == 0)
                        for (int c = 0; c < S7Client.MaxVars; c++)
                            Results[c] = Items[c].Result;
                    GlobalResult = FunctionResult;
                }
                else
                    GlobalResult = (int)S7Consts.errCliFunctionRefused;
            }
            finally
            {
                Clear(); // handles are no more needed and MUST be freed
            }
            return GlobalResult;
        }

        public int Write()
        {
            int FunctionResult;
            int GlobalResult = (int)S7Consts.errCliFunctionRefused;
            try
            {
                if (Count > 0)
                {
                    FunctionResult = FClient.WriteMultiVars(Items, Count);
                    if (FunctionResult == 0)
                        for (int c = 0; c < S7Client.MaxVars; c++)
                            Results[c] = Items[c].Result;
                    GlobalResult = FunctionResult;
                }
                else
                    GlobalResult = (int)S7Consts.errCliFunctionRefused;
            }
            finally
            {
                Clear(); // handles are no more needed and MUST be freed
            }
            return GlobalResult;
        }

        public void Clear()
        {
            for (int c = 0; c < Count; c++)
            {
                if (Handles[c] != null)
                    Handles[c].Free();
            }
            Count = 0;
        }
        #endregion
    }

    public class S7Client
    {
        #region [Constants and TypeDefs]

        // Block type
        public const int Block_OB = 0x38;
        public const int Block_DB = 0x41;
        public const int Block_SDB = 0x42;
        public const int Block_FC = 0x43;
        public const int Block_SFC = 0x44;
        public const int Block_FB = 0x45;
        public const int Block_SFB = 0x46;

        // Sub Block Type 
        public const byte SubBlk_OB = 0x08;
        public const byte SubBlk_DB = 0x0A;
        public const byte SubBlk_SDB = 0x0B;
        public const byte SubBlk_FC = 0x0C;
        public const byte SubBlk_SFC = 0x0D;
        public const byte SubBlk_FB = 0x0E;
        public const byte SubBlk_SFB = 0x0F;

        // Block languages
        public const byte BlockLangAWL = 0x01;
        public const byte BlockLangKOP = 0x02;
        public const byte BlockLangFUP = 0x03;
        public const byte BlockLangSCL = 0x04;
        public const byte BlockLangDB = 0x05;
        public const byte BlockLangGRAPH = 0x06;

        // Max number of vars (multiread/write)
        public static readonly int MaxVars = 20;

        // Result transport size
        const byte TS_ResBit = 0x03;
        const byte TS_ResByte = 0x04;
        const byte TS_ResInt = 0x05;
        const byte TS_ResReal = 0x07;
        const byte TS_ResOctet = 0x09;

        const ushort Code7Ok = 0x0000;
        const ushort Code7AddressOutOfRange = 0x0005;
        const ushort Code7InvalidTransportSize = 0x0006;
        const ushort Code7WriteDataSizeMismatch = 0x0007;
        const ushort Code7ResItemNotAvailable = 0x000A;
        const ushort Code7ResItemNotAvailable1 = 0xD209;
        const ushort Code7InvalidValue = 0xDC01;
        const ushort Code7NeedPassword = 0xD241;
        const ushort Code7InvalidPassword = 0xD602;
        const ushort Code7NoPasswordToClear = 0xD604;
        const ushort Code7NoPasswordToSet = 0xD605;
        const ushort Code7FunNotAvailable = 0x8104;
        const ushort Code7DataOverPDU = 0x8500;

        // Client Connection Type
        public static readonly UInt16 CONNTYPE_PG = 0x01;  // Connect to the PLC as a PG
        public static readonly UInt16 CONNTYPE_OP = 0x02;  // Connect to the PLC as an OP
        public static readonly UInt16 CONNTYPE_BASIC = 0x03;  // Basic connection 

        public int _LastError = 0;

        public struct S7DataItem
        {
            public int Area;
            public int WordLen;
            public int Result;
            public int DBNumber;
            public int Start;
            public int Amount;
            public IntPtr pData;
        }

        // Order Code + Version
        public struct S7OrderCode
        {
            public string Code; // such as "6ES7 151-8AB01-0AB0"
            public byte V1;     // Version 1st digit
            public byte V2;     // Version 2nd digit
            public byte V3;     // Version 3th digit
        };

        // CPU Info
        public struct S7CpuInfo
        {
            public string ModuleTypeName;
            public string SerialNumber;
            public string ASName;
            public string Copyright;
            public string ModuleName;
        }

        public struct S7CpInfo
        {
            public int MaxPduLength;
            public int MaxConnections;
            public int MaxMpiRate;
            public int MaxBusRate;
        };

        // Block List
        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct S7BlocksList
        {
            public Int32 OBCount;
            public Int32 FBCount;
            public Int32 FCCount;
            public Int32 SFBCount;
            public Int32 SFCCount;
            public Int32 DBCount;
            public Int32 SDBCount;
        };

        // Managed Block Info
        public struct S7BlockInfo
        {
            public int BlkType;
            public int BlkNumber;
            public int BlkLang;
            public int BlkFlags;
            public int MC7Size;  // The real size in bytes
            public int LoadSize;
            public int LocalData;
            public int SBBLength;
            public int CheckSum;
            public int Version;
            // Chars info
            public string CodeDate;
            public string IntfDate;
            public string Author;
            public string Family;
            public string Header;
        };

        // See §33.1 of "System Software for S7-300/400 System and Standard Functions"
        // and see SFC51 description too
        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct SZL_HEADER
        {
            public UInt16 LENTHDR;
            public UInt16 N_DR;
        };

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct S7SZL
        {
            public SZL_HEADER Header;
            [MarshalAs(UnmanagedType.ByValArray)]
            public byte[] Data;
        };

        // SZL List of available SZL IDs : same as SZL but List items are big-endian adjusted
        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct S7SZLList
        {
            public SZL_HEADER Header;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x2000 - 2)]
            public UInt16[] Data;
        };

        // S7 Protection
        // See §33.19 of "System Software for S7-300/400 System and Standard Functions"
        public struct S7Protection
        {
            public ushort sch_schal;
            public ushort sch_par;
            public ushort sch_rel;
            public ushort bart_sch;
            public ushort anl_sch;
        };

        #endregion

        #region [S7 Telegrams]

        // ISO Connection Request telegram (contains also ISO Header and COTP Header)
        byte[] ISO_CR = {
			// TPKT (RFC1006 Header)
			0x03, // RFC 1006 ID (3) 
			0x00, // Reserved, always 0
			0x00, // High part of packet lenght (entire frame, payload and TPDU included)
			0x16, // Low part of packet lenght (entire frame, payload and TPDU included)
			// COTP (ISO 8073 Header)
			0x11, // PDU Size Length
			0xE0, // CR - Connection Request ID
			0x00, // Dst Reference HI
			0x00, // Dst Reference LO
			0x00, // Src Reference HI
			0x01, // Src Reference LO
			0x00, // Class + Options Flags
			0xC0, // PDU Max Length ID
			0x01, // PDU Max Length HI
			0x0A, // PDU Max Length LO
			0xC1, // Src TSAP Identifier
			0x02, // Src TSAP Length (2 bytes)
			0x01, // Src TSAP HI (will be overwritten)
			0x00, // Src TSAP LO (will be overwritten)
			0xC2, // Dst TSAP Identifier
			0x02, // Dst TSAP Length (2 bytes)
			0x01, // Dst TSAP HI (will be overwritten)
			0x02  // Dst TSAP LO (will be overwritten)
		};

        // TPKT + ISO COTP Header (Connection Oriented Transport Protocol)
        byte[] TPKT_ISO = { // 7 bytes
			0x03,0x00,
            0x00,0x1f,      // Telegram Length (Data Size + 31 or 35)
			0x02,0xf0,0x80  // COTP (see above for info)
		};

        // S7 PDU Negotiation Telegram (contains also ISO Header and COTP Header)
        byte[] S7_PN = {
            0x03, 0x00, 0x00, 0x19,
            0x02, 0xf0, 0x80, // TPKT + COTP (see above for info)
			0x32, 0x01, 0x00, 0x00,
            0x04, 0x00, 0x00, 0x08,
            0x00, 0x00, 0xf0, 0x00,
            0x00, 0x01, 0x00, 0x01,
            0x00, 0x1e        // PDU Length Requested = HI-LO Here Default 480 bytes
		};

        // S7 Read/Write Request Header (contains also ISO Header and COTP Header)
        byte[] S7_RW = { // 31-35 bytes
			0x03,0x00,
            0x00,0x1f,       // Telegram Length (Data Size + 31 or 35)
			0x02,0xf0, 0x80, // COTP (see above for info)
			0x32,            // S7 Protocol ID 
			0x01,            // Job Type
			0x00,0x00,       // Redundancy identification
			0x05,0x00,       // PDU Reference
			0x00,0x0e,       // Parameters Length
			0x00,0x00,       // Data Length = Size(bytes) + 4      
			0x04,            // Function 4 Read Var, 5 Write Var  
			0x01,            // Items count
			0x12,            // Var spec.
			0x0a,            // Length of remaining bytes
			0x10,            // Syntax ID 
			(byte)S7Consts.S7WLByte,  // Transport Size idx=22                       
			0x00,0x00,       // Num Elements                          
			0x00,0x00,       // DB Number (if any, else 0)            
			0x84,            // Area Type                            
			0x00,0x00,0x00,  // Area Offset                     
			// WR area
			0x00,            // Reserved 
			0x04,            // Transport size
			0x00,0x00,       // Data Length * 8 (if not bit or timer or counter) 
		};
        private static int Size_RD = 31; // Header Size when Reading 
        private static int Size_WR = 35; // Header Size when Writing

        // S7 Variable MultiRead Header
        byte[] S7_MRD_HEADER = {
            0x03,0x00,
            0x00,0x1f,       // Telegram Length 
			0x02,0xf0, 0x80, // COTP (see above for info)
			0x32,            // S7 Protocol ID 
			0x01,            // Job Type
			0x00,0x00,       // Redundancy identification
			0x05,0x00,       // PDU Reference
			0x00,0x0e,       // Parameters Length
			0x00,0x00,       // Data Length = Size(bytes) + 4      
			0x04,            // Function 4 Read Var, 5 Write Var  
			0x01             // Items count (idx 18)
		};

        // S7 Variable MultiRead Item
        byte[] S7_MRD_ITEM = {
            0x12,            // Var spec.
			0x0a,            // Length of remaining bytes
			0x10,            // Syntax ID 
			(byte)S7Consts.S7WLByte,  // Transport Size idx=3                   
			0x00,0x00,       // Num Elements                          
			0x00,0x00,       // DB Number (if any, else 0)            
			0x84,            // Area Type                            
			0x00,0x00,0x00   // Area Offset                     
		};

        // S7 Variable MultiWrite Header
        byte[] S7_MWR_HEADER = {
            0x03,0x00,
            0x00,0x1f,       // Telegram Length 
			0x02,0xf0, 0x80, // COTP (see above for info)
			0x32,            // S7 Protocol ID 
			0x01,            // Job Type
			0x00,0x00,       // Redundancy identification
			0x05,0x00,       // PDU Reference
			0x00,0x0e,       // Parameters Length (idx 13)
			0x00,0x00,       // Data Length = Size(bytes) + 4 (idx 15)     
			0x05,            // Function 5 Write Var  
			0x01             // Items count (idx 18)
		};

        // S7 Variable MultiWrite Item (Param)
        byte[] S7_MWR_PARAM = {
            0x12,            // Var spec.
			0x0a,            // Length of remaining bytes
			0x10,            // Syntax ID 
			(byte)S7Consts.S7WLByte,  // Transport Size idx=3                      
			0x00,0x00,       // Num Elements                          
			0x00,0x00,       // DB Number (if any, else 0)            
			0x84,            // Area Type                            
			0x00,0x00,0x00,  // Area Offset                     
		};

        // SZL First telegram request   
        byte[] S7_SZL_FIRST = {
            0x03, 0x00, 0x00, 0x21,
            0x02, 0xf0, 0x80, 0x32,
            0x07, 0x00, 0x00,
            0x05, 0x00, // Sequence out
			0x00, 0x08, 0x00,
            0x08, 0x00, 0x01, 0x12,
            0x04, 0x11, 0x44, 0x01,
            0x00, 0xff, 0x09, 0x00,
            0x04,
            0x00, 0x00, // ID (29)
			0x00, 0x00  // Index (31)
		};

        // SZL Next telegram request 
        byte[] S7_SZL_NEXT = {
            0x03, 0x00, 0x00, 0x21,
            0x02, 0xf0, 0x80, 0x32,
            0x07, 0x00, 0x00, 0x06,
            0x00, 0x00, 0x0c, 0x00,
            0x04, 0x00, 0x01, 0x12,
            0x08, 0x12, 0x44, 0x01,
            0x01, // Sequence
			0x00, 0x00, 0x00, 0x00,
            0x0a, 0x00, 0x00, 0x00
        };

        // Get Date/Time request
        byte[] S7_GET_DT = {
            0x03, 0x00, 0x00, 0x1d,
            0x02, 0xf0, 0x80, 0x32,
            0x07, 0x00, 0x00, 0x38,
            0x00, 0x00, 0x08, 0x00,
            0x04, 0x00, 0x01, 0x12,
            0x04, 0x11, 0x47, 0x01,
            0x00, 0x0a, 0x00, 0x00,
            0x00
        };

        // Set Date/Time command
        byte[] S7_SET_DT = {
            0x03, 0x00, 0x00, 0x27,
            0x02, 0xf0, 0x80, 0x32,
            0x07, 0x00, 0x00, 0x89,
            0x03, 0x00, 0x08, 0x00,
            0x0e, 0x00, 0x01, 0x12,
            0x04, 0x11, 0x47, 0x02,
            0x00, 0xff, 0x09, 0x00,
            0x0a, 0x00,
            0x19, // Hi part of Year (idx=30)
			0x13, // Lo part of Year
			0x12, // Month
			0x06, // Day
			0x17, // Hour
			0x37, // Min
			0x13, // Sec
			0x00, 0x01 // ms + Day of week   
		};

        // S7 Set Session Password 
        byte[] S7_SET_PWD = {
            0x03, 0x00, 0x00, 0x25,
            0x02, 0xf0, 0x80, 0x32,
            0x07, 0x00, 0x00, 0x27,
            0x00, 0x00, 0x08, 0x00,
            0x0c, 0x00, 0x01, 0x12,
            0x04, 0x11, 0x45, 0x01,
            0x00, 0xff, 0x09, 0x00,
            0x08, 
			// 8 Char Encoded Password
			0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00
        };

        // S7 Clear Session Password 
        byte[] S7_CLR_PWD = {
            0x03, 0x00, 0x00, 0x1d,
            0x02, 0xf0, 0x80, 0x32,
            0x07, 0x00, 0x00, 0x29,
            0x00, 0x00, 0x08, 0x00,
            0x04, 0x00, 0x01, 0x12,
            0x04, 0x11, 0x45, 0x02,
            0x00, 0x0a, 0x00, 0x00,
            0x00
        };

        // S7 STOP request
        byte[] S7_STOP = {
            0x03, 0x00, 0x00, 0x21,
            0x02, 0xf0, 0x80, 0x32,
            0x01, 0x00, 0x00, 0x0e,
            0x00, 0x00, 0x10, 0x00,
            0x00, 0x29, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x09,
            0x50, 0x5f, 0x50, 0x52,
            0x4f, 0x47, 0x52, 0x41,
            0x4d
        };

        // S7 HOT Start request
        byte[] S7_HOT_START = {
            0x03, 0x00, 0x00, 0x25,
            0x02, 0xf0, 0x80, 0x32,
            0x01, 0x00, 0x00, 0x0c,
            0x00, 0x00, 0x14, 0x00,
            0x00, 0x28, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0xfd, 0x00, 0x00, 0x09,
            0x50, 0x5f, 0x50, 0x52,
            0x4f, 0x47, 0x52, 0x41,
            0x4d
        };

        // S7 COLD Start request
        byte[] S7_COLD_START = {
            0x03, 0x00, 0x00, 0x27,
            0x02, 0xf0, 0x80, 0x32,
            0x01, 0x00, 0x00, 0x0f,
            0x00, 0x00, 0x16, 0x00,
            0x00, 0x28, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0xfd, 0x00, 0x02, 0x43,
            0x20, 0x09, 0x50, 0x5f,
            0x50, 0x52, 0x4f, 0x47,
            0x52, 0x41, 0x4d
        };
        const byte pduStart = 0x28;   // CPU start
        const byte pduStop = 0x29;   // CPU stop
        const byte pduAlreadyStarted = 0x02;   // CPU already in run mode
        const byte pduAlreadyStopped = 0x07;   // CPU already in stop mode

        // S7 Get PLC Status 
        byte[] S7_GET_STAT = {
            0x03, 0x00, 0x00, 0x21,
            0x02, 0xf0, 0x80, 0x32,
            0x07, 0x00, 0x00, 0x2c,
            0x00, 0x00, 0x08, 0x00,
            0x08, 0x00, 0x01, 0x12,
            0x04, 0x11, 0x44, 0x01,
            0x00, 0xff, 0x09, 0x00,
            0x04, 0x04, 0x24, 0x00,
            0x00
        };

        // S7 Get Block Info Request Header (contains also ISO Header and COTP Header)
        byte[] S7_BI = {
            0x03, 0x00, 0x00, 0x25,
            0x02, 0xf0, 0x80, 0x32,
            0x07, 0x00, 0x00, 0x05,
            0x00, 0x00, 0x08, 0x00,
            0x0c, 0x00, 0x01, 0x12,
            0x04, 0x11, 0x43, 0x03,
            0x00, 0xff, 0x09, 0x00,
            0x08, 0x30,
            0x41, // Block Type
			0x30, 0x30, 0x30, 0x30, 0x30, // ASCII Block Number
			0x41
        };

        // S7 List Blocks Request Header
        byte[] S7_LIST_BLOCKS = {
            0x03, 0x00, 0x00, 0x1d,
            0x02, 0xf0, 0x80, 0x32,
            0x07, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x08, 0x00,
            0x04, 0x00, 0x01, 0x12,
            0x04, 0x11, 0x43, 0x01, // 0x43 0x01 = ListBlocks
			0x00, 0x0a, 0x00, 0x00,
            0x00
        };

        // S7 List Blocks Of Type Request Header
        byte[] S7_LIST_BLOCKS_OF_TYPE = {
            0x03, 0x00, 0x00, 0x1f,
            0x02, 0xf0, 0x80, 0x32,
            0x07, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x08, 0x00,
            0x06, 0x00, 0x01, 0x12,
            0x04, 0x11, 0x43, 0x02, // 0x43 0x02 = ListBlocksOfType
			0x00 // ... append ReqData
		};

        #endregion

        #region [Internals]

        // Defaults
        private static int ISOTCP = 102; // ISOTCP Port
        private static int MinPduSize = 16;
        private static int MinPduSizeToRequest = 240;
        private static int MaxPduSizeToRequest = 960;
        private static int DefaultTimeout = 2000;
        private static int IsoHSize = 7; // TPKT+COTP Header Size

        // Properties
        private int _PDULength = 0;
        private int _PduSizeRequested = 480;
        private int _PLCPort = ISOTCP;
        private int _RecvTimeout = DefaultTimeout;
        private int _SendTimeout = DefaultTimeout;
        private int _ConnTimeout = DefaultTimeout;

        // Privates
        private string IPAddress;
        private byte LocalTSAP_HI;
        private byte LocalTSAP_LO;
        private byte RemoteTSAP_HI;
        private byte RemoteTSAP_LO;
        private byte LastPDUType;
        private ushort ConnType = CONNTYPE_PG;
        private byte[] PDU = new byte[2048];
        private MsgSocket Socket = null;
        private int Time_ms = 0;
        private ushort cntword = 0;

        private void CreateSocket()
        {
            try
            {
                Socket = new MsgSocket();
                Socket.ConnectTimeout = _ConnTimeout;
                Socket.ReadTimeout = _RecvTimeout;
                Socket.WriteTimeout = _SendTimeout;
            }
            catch
            {
            }
        }

        private int TCPConnect()
        {
            if (_LastError == 0)
                try
                {
                    _LastError = Socket.Connect(IPAddress, _PLCPort);
                }
                catch
                {
                    _LastError = S7Consts.errTCPConnectionFailed;
                }
            return _LastError;
        }

        private void RecvPacket(byte[] Buffer, int Start, int Size)
        {
            if (Connected)
                _LastError = Socket.Receive(Buffer, Start, Size);
            else
                _LastError = S7Consts.errTCPNotConnected;
        }

        private void SendPacket(byte[] Buffer, int Len)
        {
            _LastError = Socket.Send(Buffer, Len);
        }

        private void SendPacket(byte[] Buffer)
        {
            if (Connected)
                SendPacket(Buffer, Buffer.Length);
            else
                _LastError = S7Consts.errTCPNotConnected;
        }

        private int RecvIsoPacket()
        {
            Boolean Done = false;
            int Size = 0;
            while ((_LastError == 0) && !Done)
            {
                // Get TPKT (4 bytes)
                RecvPacket(PDU, 0, 4);
                if (_LastError == 0)
                {
                    Size = S7.GetWordAt(PDU, 2);
                    // Check 0 bytes Data Packet (only TPKT+COTP = 7 bytes)
                    if (Size == IsoHSize)
                        RecvPacket(PDU, 4, 3); // Skip remaining 3 bytes and Done is still false
                    else
                    {
                        if ((Size > _PduSizeRequested + IsoHSize) || (Size < MinPduSize))
                            _LastError = S7Consts.errIsoInvalidPDU;
                        else
                            Done = true; // a valid Length !=7 && >16 && <247
                    }
                }
            }
            if (_LastError == 0)
            {
                RecvPacket(PDU, 4, 3); // Skip remaining 3 COTP bytes
                LastPDUType = PDU[5];   // Stores PDU Type, we need it 
                                        // Receives the S7 Payload          
                RecvPacket(PDU, 7, Size - IsoHSize);
            }
            if (_LastError == 0)
                return Size;
            else
                return 0;
        }

        private int ISOConnect()
        {
            int Size;
            ISO_CR[16] = LocalTSAP_HI;
            ISO_CR[17] = LocalTSAP_LO;
            ISO_CR[20] = RemoteTSAP_HI;
            ISO_CR[21] = RemoteTSAP_LO;

            // Sends the connection request telegram      
            SendPacket(ISO_CR);
            if (_LastError == 0)
            {
                // Gets the reply (if any)
                Size = RecvIsoPacket();
                if (_LastError == 0)
                {
                    if (Size == 22)
                    {
                        if (LastPDUType != (byte)0xD0) // 0xD0 = CC Connection confirm
                            _LastError = S7Consts.errIsoConnect;
                    }
                    else
                        _LastError = S7Consts.errIsoInvalidPDU;
                }
            }
            return _LastError;
        }

        private int NegotiatePduLength()
        {
            int Length;
            // Set PDU Size Requested
            S7.SetWordAt(S7_PN, 23, (ushort)_PduSizeRequested);
            // Sends the connection request telegram
            SendPacket(S7_PN);
            if (_LastError == 0)
            {
                Length = RecvIsoPacket();
                if (_LastError == 0)
                {
                    // check S7 Error
                    if ((Length == 27) && (PDU[17] == 0) && (PDU[18] == 0))  // 20 = size of Negotiate Answer
                    {
                        // Get PDU Size Negotiated
                        _PDULength = S7.GetWordAt(PDU, 25);
                        if (_PDULength <= 0)
                            _LastError = S7Consts.errCliNegotiatingPDU;
                    }
                    else
                        _LastError = S7Consts.errCliNegotiatingPDU;
                }
            }
            return _LastError;
        }

        private int CpuError(ushort Error)
        {
            switch (Error)
            {
                case 0: return 0;
                case Code7AddressOutOfRange: return S7Consts.errCliAddressOutOfRange;
                case Code7InvalidTransportSize: return S7Consts.errCliInvalidTransportSize;
                case Code7WriteDataSizeMismatch: return S7Consts.errCliWriteDataSizeMismatch;
                case Code7ResItemNotAvailable:
                case Code7ResItemNotAvailable1: return S7Consts.errCliItemNotAvailable;
                case Code7DataOverPDU: return S7Consts.errCliSizeOverPDU;
                case Code7InvalidValue: return S7Consts.errCliInvalidValue;
                case Code7FunNotAvailable: return S7Consts.errCliFunNotAvailable;
                case Code7NeedPassword: return S7Consts.errCliNeedPassword;
                case Code7InvalidPassword: return S7Consts.errCliInvalidPassword;
                case Code7NoPasswordToSet:
                case Code7NoPasswordToClear: return S7Consts.errCliNoPasswordToSetOrClear;
                default:
                    return S7Consts.errCliFunctionRefused;
            };
        }

        private ushort GetNextWord()
        {
            return cntword++;
        }

        #endregion

        #region [Class Control]

        public S7Client()
        {
            CreateSocket();
        }

        ~S7Client()
        {
            Disconnect();
        }

        public int Connect()
        {
            _LastError = 0;
            Time_ms = 0;
            int Elapsed = Environment.TickCount;
            if (!Connected)
            {
                TCPConnect(); // First stage : TCP Connection
                if (_LastError == 0)
                {
                    ISOConnect(); // Second stage : ISOTCP (ISO 8073) Connection
                    if (_LastError == 0)
                    {
                        _LastError = NegotiatePduLength(); // Third stage : S7 PDU negotiation
                    }
                }
            }
            if (_LastError != 0)
                Disconnect();
            else
                Time_ms = Environment.TickCount - Elapsed;

            return _LastError;
        }

        public int ConnectTo(string Address, int Rack, int Slot)
        {
            UInt16 RemoteTSAP = (UInt16)((ConnType << 8) + (Rack * 0x20) + Slot);
            SetConnectionParams(Address, 0x0100, RemoteTSAP);
            return Connect();
        }

        public int SetConnectionParams(string Address, ushort LocalTSAP, ushort RemoteTSAP)
        {
            int LocTSAP = LocalTSAP & 0x0000FFFF;
            int RemTSAP = RemoteTSAP & 0x0000FFFF;
            IPAddress = Address;
            LocalTSAP_HI = (byte)(LocTSAP >> 8);
            LocalTSAP_LO = (byte)(LocTSAP & 0x00FF);
            RemoteTSAP_HI = (byte)(RemTSAP >> 8);
            RemoteTSAP_LO = (byte)(RemTSAP & 0x00FF);
            return 0;
        }

        public int SetConnectionType(ushort ConnectionType)
        {
            ConnType = ConnectionType;
            return 0;
        }

        public int Disconnect()
        {
            Socket.Close();
            return 0;
        }

        public int GetParam(Int32 ParamNumber, ref int Value)
        {
            int Result = 0;
            switch (ParamNumber)
            {
                case S7Consts.p_u16_RemotePort:
                    {
                        Value = PLCPort;
                        break;
                    }
                case S7Consts.p_i32_PingTimeout:
                    {
                        Value = ConnTimeout;
                        break;
                    }
                case S7Consts.p_i32_SendTimeout:
                    {
                        Value = SendTimeout;
                        break;
                    }
                case S7Consts.p_i32_RecvTimeout:
                    {
                        Value = RecvTimeout;
                        break;
                    }
                case S7Consts.p_i32_PDURequest:
                    {
                        Value = PduSizeRequested;
                        break;
                    }
                default:
                    {
                        Result = S7Consts.errCliInvalidParamNumber;
                        break;
                    }
            }
            return Result;
        }

        // Set Properties for compatibility with Snap7.net.cs
        public int SetParam(Int32 ParamNumber, ref int Value)
        {
            int Result = 0;
            switch (ParamNumber)
            {
                case S7Consts.p_u16_RemotePort:
                    {
                        PLCPort = Value;
                        break;
                    }
                case S7Consts.p_i32_PingTimeout:
                    {
                        ConnTimeout = Value;
                        break;
                    }
                case S7Consts.p_i32_SendTimeout:
                    {
                        SendTimeout = Value;
                        break;
                    }
                case S7Consts.p_i32_RecvTimeout:
                    {
                        RecvTimeout = Value;
                        break;
                    }
                case S7Consts.p_i32_PDURequest:
                    {
                        PduSizeRequested = Value;
                        break;
                    }
                default:
                    {
                        Result = S7Consts.errCliInvalidParamNumber;
                        break;
                    }
            }
            return Result;
        }

        public delegate void S7CliCompletion(IntPtr usrPtr, int opCode, int opResult);
        public int SetAsCallBack(S7CliCompletion Completion, IntPtr usrPtr)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        #endregion

        #region [Data I/O main functions]

        public int ReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)
        {
            int BytesRead = 0;
            return ReadArea(Area, DBNumber, Start, Amount, WordLen, Buffer, ref BytesRead);
        }

        public int ReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer, ref int BytesRead)
        {
            int Address;
            int NumElements;
            int MaxElements;
            int TotElements;
            int SizeRequested;
            int Length;
            int Offset = 0;
            int WordSize = 1;

            _LastError = 0;
            Time_ms = 0;
            int Elapsed = Environment.TickCount;
            // Some adjustment
            if (Area == S7Consts.S7AreaCT)
                WordLen = S7Consts.S7WLCounter;
            if (Area == S7Consts.S7AreaTM)
                WordLen = S7Consts.S7WLTimer;

            // Calc Word size          
            WordSize = S7.DataSizeByte(WordLen);
            if (WordSize == 0)
                return S7Consts.errCliInvalidWordLen;

            if (WordLen == S7Consts.S7WLBit)
                Amount = 1;  // Only 1 bit can be transferred at time
            else
            {
                if ((WordLen != S7Consts.S7WLCounter) && (WordLen != S7Consts.S7WLTimer))
                {
                    Amount = Amount * WordSize;
                    WordSize = 1;
                    WordLen = S7Consts.S7WLByte;
                }
            }

            MaxElements = (_PDULength - 18) / WordSize; // 18 = Reply telegram header
            TotElements = Amount;

            while ((TotElements > 0) && (_LastError == 0))
            {
                NumElements = TotElements;
                if (NumElements > MaxElements)
                    NumElements = MaxElements;

                SizeRequested = NumElements * WordSize;

                // Setup the telegram
                Array.Copy(S7_RW, 0, PDU, 0, Size_RD);
                // Set DB Number
                PDU[27] = (byte)Area;
                // Set Area
                if (Area == S7Consts.S7AreaDB)
                    S7.SetWordAt(PDU, 25, (ushort)DBNumber);

                // Adjusts Start and word length
                if ((WordLen == S7Consts.S7WLBit) || (WordLen == S7Consts.S7WLCounter) || (WordLen == S7Consts.S7WLTimer))
                {
                    Address = Start;
                    PDU[22] = (byte)WordLen;
                }
                else
                    Address = Start << 3;

                // Num elements
                S7.SetWordAt(PDU, 23, (ushort)NumElements);

                // Address into the PLC (only 3 bytes)           
                PDU[30] = (byte)(Address & 0x0FF);
                Address = Address >> 8;
                PDU[29] = (byte)(Address & 0x0FF);
                Address = Address >> 8;
                PDU[28] = (byte)(Address & 0x0FF);

                SendPacket(PDU, Size_RD);
                if (_LastError == 0)
                {
                    Length = RecvIsoPacket();
                    if (_LastError == 0)
                    {
                        if (Length < 25)
                            _LastError = S7Consts.errIsoInvalidDataSize;
                        else
                        {
                            if (PDU[21] != 0xFF)
                                _LastError = CpuError(PDU[21]);
                            else
                            {
                                Array.Copy(PDU, 25, Buffer, Offset, SizeRequested);
                                Offset += SizeRequested;
                            }
                        }
                    }
                }
                TotElements -= NumElements;
                Start += NumElements * WordSize;
            }

            if (_LastError == 0)
            {
                BytesRead = Offset;
                Time_ms = Environment.TickCount - Elapsed;
            }
            else
                BytesRead = 0;
            return _LastError;
        }

        public int WriteArea(int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)
        {
            int BytesWritten = 0;
            return WriteArea(Area, DBNumber, Start, Amount, WordLen, Buffer, ref BytesWritten);
        }

        public int WriteArea(int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer, ref int BytesWritten)
        {
            int Address;
            int NumElements;
            int MaxElements;
            int TotElements;
            int DataSize;
            int IsoSize;
            int Length;
            int Offset = 0;
            int WordSize = 1;

            _LastError = 0;
            Time_ms = 0;
            int Elapsed = Environment.TickCount;
            // Some adjustment
            if (Area == S7Consts.S7AreaCT)
                WordLen = S7Consts.S7WLCounter;
            if (Area == S7Consts.S7AreaTM)
                WordLen = S7Consts.S7WLTimer;

            // Calc Word size          
            WordSize = S7.DataSizeByte(WordLen);
            if (WordSize == 0)
                return S7Consts.errCliInvalidWordLen;

            if (WordLen == S7Consts.S7WLBit) // Only 1 bit can be transferred at time
                Amount = 1;
            else
            {
                if ((WordLen != S7Consts.S7WLCounter) && (WordLen != S7Consts.S7WLTimer))
                {
                    Amount = Amount * WordSize;
                    WordSize = 1;
                    WordLen = S7Consts.S7WLByte;
                }
            }

            MaxElements = (_PDULength - 35) / WordSize; // 35 = Reply telegram header
            TotElements = Amount;

            while ((TotElements > 0) && (_LastError == 0))
            {
                NumElements = TotElements;
                if (NumElements > MaxElements)
                    NumElements = MaxElements;

                DataSize = NumElements * WordSize;
                IsoSize = Size_WR + DataSize;

                // Setup the telegram
                Array.Copy(S7_RW, 0, PDU, 0, Size_WR);
                // Whole telegram Size
                S7.SetWordAt(PDU, 2, (ushort)IsoSize);
                // Data Length
                Length = DataSize + 4;
                S7.SetWordAt(PDU, 15, (ushort)Length);
                // Function
                PDU[17] = (byte)0x05;
                // Set DB Number
                PDU[27] = (byte)Area;
                if (Area == S7Consts.S7AreaDB)
                    S7.SetWordAt(PDU, 25, (ushort)DBNumber);


                // Adjusts Start and word length
                if ((WordLen == S7Consts.S7WLBit) || (WordLen == S7Consts.S7WLCounter) || (WordLen == S7Consts.S7WLTimer))
                {
                    Address = Start;
                    Length = DataSize;
                    PDU[22] = (byte)WordLen;
                }
                else
                {
                    Address = Start << 3;
                    Length = DataSize << 3;
                }

                // Num elements
                S7.SetWordAt(PDU, 23, (ushort)NumElements);
                // Address into the PLC
                PDU[30] = (byte)(Address & 0x0FF);
                Address = Address >> 8;
                PDU[29] = (byte)(Address & 0x0FF);
                Address = Address >> 8;
                PDU[28] = (byte)(Address & 0x0FF);

                // Transport Size
                switch (WordLen)
                {
                    case S7Consts.S7WLBit:
                        PDU[32] = TS_ResBit;
                        break;
                    case S7Consts.S7WLCounter:
                    case S7Consts.S7WLTimer:
                        PDU[32] = TS_ResOctet;
                        break;
                    default:
                        PDU[32] = TS_ResByte; // byte/word/dword etc.
                        break;
                };
                // Length
                S7.SetWordAt(PDU, 33, (ushort)Length);

                // Copies the Data
                Array.Copy(Buffer, Offset, PDU, 35, DataSize);

                SendPacket(PDU, IsoSize);
                if (_LastError == 0)
                {
                    Length = RecvIsoPacket();
                    if (_LastError == 0)
                    {
                        if (Length == 22)
                        {
                            if (PDU[21] != (byte)0xFF)
                                _LastError = CpuError(PDU[21]);
                        }
                        else
                            _LastError = S7Consts.errIsoInvalidPDU;
                    }
                }
                Offset += DataSize;
                TotElements -= NumElements;
                Start += NumElements * WordSize;
            }

            if (_LastError == 0)
            {
                BytesWritten = Offset;
                Time_ms = Environment.TickCount - Elapsed;
            }
            else
                BytesWritten = 0;

            return _LastError;
        }

        public int ReadMultiVars(S7DataItem[] Items, int ItemsCount)
        {
            int Offset;
            int Length;
            int ItemSize;
            byte[] S7Item = new byte[12];
            byte[] S7ItemRead = new byte[1024];

            _LastError = 0;
            Time_ms = 0;
            int Elapsed = Environment.TickCount;

            // Checks items
            if (ItemsCount > MaxVars)
                return S7Consts.errCliTooManyItems;

            // Fills Header
            Array.Copy(S7_MRD_HEADER, 0, PDU, 0, S7_MRD_HEADER.Length);
            S7.SetWordAt(PDU, 13, (ushort)(ItemsCount * S7Item.Length + 2));
            PDU[18] = (byte)ItemsCount;
            // Fills the Items
            Offset = 19;
            for (int c = 0; c < ItemsCount; c++)
            {
                Array.Copy(S7_MRD_ITEM, S7Item, S7Item.Length);
                S7Item[3] = (byte)Items[c].WordLen;
                S7.SetWordAt(S7Item, 4, (ushort)Items[c].Amount);
                if (Items[c].Area == S7Consts.S7AreaDB)
                    S7.SetWordAt(S7Item, 6, (ushort)Items[c].DBNumber);
                S7Item[8] = (byte)Items[c].Area;

                // Address into the PLC
                int Address = Items[c].Start;
                S7Item[11] = (byte)(Address & 0x0FF);
                Address = Address >> 8;
                S7Item[10] = (byte)(Address & 0x0FF);
                Address = Address >> 8;
                S7Item[09] = (byte)(Address & 0x0FF);

                Array.Copy(S7Item, 0, PDU, Offset, S7Item.Length);
                Offset += S7Item.Length;
            }

            if (Offset > _PDULength)
                return S7Consts.errCliSizeOverPDU;

            S7.SetWordAt(PDU, 2, (ushort)Offset); // Whole size
            SendPacket(PDU, Offset);

            if (_LastError != 0)
                return _LastError;
            // Get Answer
            Length = RecvIsoPacket();
            if (_LastError != 0)
                return _LastError;
            // Check ISO Length
            if (Length < 22)
            {
                _LastError = S7Consts.errIsoInvalidPDU; // PDU too Small
                return _LastError;
            }
            // Check Global Operation Result
            _LastError = CpuError(S7.GetWordAt(PDU, 17));
            if (_LastError != 0)
                return _LastError;
            // Get true ItemsCount
            int ItemsRead = S7.GetByteAt(PDU, 20);
            if ((ItemsRead != ItemsCount) || (ItemsRead > MaxVars))
            {
                _LastError = S7Consts.errCliInvalidPlcAnswer;
                return _LastError;
            }
            // Get Data
            Offset = 21;
            for (int c = 0; c < ItemsCount; c++)
            {
                // Get the Item
                Array.Copy(PDU, Offset, S7ItemRead, 0, Length - Offset);
                if (S7ItemRead[0] == 0xff)
                {
                    ItemSize = (int)S7.GetWordAt(S7ItemRead, 2);
                    if ((S7ItemRead[1] != TS_ResOctet) && (S7ItemRead[1] != TS_ResReal) && (S7ItemRead[1] != TS_ResBit))
                        ItemSize = ItemSize >> 3;
                    Marshal.Copy(S7ItemRead, 4, Items[c].pData, ItemSize);
                    Items[c].Result = 0;
                    if (ItemSize % 2 != 0)
                        ItemSize++; // Odd size are rounded
                    Offset = Offset + 4 + ItemSize;
                }
                else
                {
                    Items[c].Result = CpuError(S7ItemRead[0]);
                    Offset += 4; // Skip the Item header                           
                }
            }
            Time_ms = Environment.TickCount - Elapsed;
            return _LastError;
        }

        public int WriteMultiVars(S7DataItem[] Items, int ItemsCount)
        {
            int Offset;
            int ParLength;
            int DataLength;
            int ItemDataSize;
            byte[] S7ParItem = new byte[S7_MWR_PARAM.Length];
            byte[] S7DataItem = new byte[1024];

            _LastError = 0;
            Time_ms = 0;
            int Elapsed = Environment.TickCount;

            // Checks items
            if (ItemsCount > MaxVars)
                return S7Consts.errCliTooManyItems;
            // Fills Header
            Array.Copy(S7_MWR_HEADER, 0, PDU, 0, S7_MWR_HEADER.Length);
            ParLength = ItemsCount * S7_MWR_PARAM.Length + 2;
            S7.SetWordAt(PDU, 13, (ushort)ParLength);
            PDU[18] = (byte)ItemsCount;
            // Fills Params
            Offset = S7_MWR_HEADER.Length;
            for (int c = 0; c < ItemsCount; c++)
            {
                Array.Copy(S7_MWR_PARAM, 0, S7ParItem, 0, S7_MWR_PARAM.Length);
                S7ParItem[3] = (byte)Items[c].WordLen;
                S7ParItem[8] = (byte)Items[c].Area;
                S7.SetWordAt(S7ParItem, 4, (ushort)Items[c].Amount);
                S7.SetWordAt(S7ParItem, 6, (ushort)Items[c].DBNumber);
                // Address into the PLC
                int Address = Items[c].Start;
                S7ParItem[11] = (byte)(Address & 0x0FF);
                Address = Address >> 8;
                S7ParItem[10] = (byte)(Address & 0x0FF);
                Address = Address >> 8;
                S7ParItem[09] = (byte)(Address & 0x0FF);
                Array.Copy(S7ParItem, 0, PDU, Offset, S7ParItem.Length);
                Offset += S7_MWR_PARAM.Length;
            }
            // Fills Data
            DataLength = 0;
            for (int c = 0; c < ItemsCount; c++)
            {
                S7DataItem[0] = 0x00;
                switch (Items[c].WordLen)
                {
                    case S7Consts.S7WLBit:
                        S7DataItem[1] = TS_ResBit;
                        break;
                    case S7Consts.S7WLCounter:
                    case S7Consts.S7WLTimer:
                        S7DataItem[1] = TS_ResOctet;
                        break;
                    default:
                        S7DataItem[1] = TS_ResByte; // byte/word/dword etc.
                        break;
                };
                if ((Items[c].WordLen == S7Consts.S7WLTimer) || (Items[c].WordLen == S7Consts.S7WLCounter))
                    ItemDataSize = Items[c].Amount * 2;
                else
                    ItemDataSize = Items[c].Amount;

                if ((S7DataItem[1] != TS_ResOctet) && (S7DataItem[1] != TS_ResBit))
                    S7.SetWordAt(S7DataItem, 2, (ushort)(ItemDataSize * 8));
                else
                    S7.SetWordAt(S7DataItem, 2, (ushort)ItemDataSize);

                Marshal.Copy(Items[c].pData, S7DataItem, 4, ItemDataSize);
                if (ItemDataSize % 2 != 0)
                {
                    S7DataItem[ItemDataSize + 4] = 0x00;
                    ItemDataSize++;
                }
                Array.Copy(S7DataItem, 0, PDU, Offset, ItemDataSize + 4);
                Offset = Offset + ItemDataSize + 4;
                DataLength = DataLength + ItemDataSize + 4;
            }

            // Checks the size
            if (Offset > _PDULength)
                return S7Consts.errCliSizeOverPDU;

            S7.SetWordAt(PDU, 2, (ushort)Offset); // Whole size
            S7.SetWordAt(PDU, 15, (ushort)DataLength); // Whole size
            SendPacket(PDU, Offset);

            RecvIsoPacket();
            if (_LastError == 0)
            {
                // Check Global Operation Result
                _LastError = CpuError(S7.GetWordAt(PDU, 17));
                if (_LastError != 0)
                    return _LastError;
                // Get true ItemsCount
                int ItemsWritten = S7.GetByteAt(PDU, 20);
                if ((ItemsWritten != ItemsCount) || (ItemsWritten > MaxVars))
                {
                    _LastError = S7Consts.errCliInvalidPlcAnswer;
                    return _LastError;
                }

                for (int c = 0; c < ItemsCount; c++)
                {
                    if (PDU[c + 21] == 0xFF)
                        Items[c].Result = 0;
                    else
                        Items[c].Result = CpuError((ushort)PDU[c + 21]);
                }
                Time_ms = Environment.TickCount - Elapsed;
            }
            return _LastError;
        }

        #endregion

        #region [Data I/O lean functions]

        public int DBRead(int DBNumber, int Start, int Size, byte[] Buffer)
        {
            return ReadArea(S7Consts.S7AreaDB, DBNumber, Start, Size, S7Consts.S7WLByte, Buffer);
        }

        public int DBWrite(int DBNumber, int Start, int Size, byte[] Buffer)
        {
            return WriteArea(S7Consts.S7AreaDB, DBNumber, Start, Size, S7Consts.S7WLByte, Buffer);
        }

        public int MBRead(int Start, int Size, byte[] Buffer)
        {
            return ReadArea(S7Consts.S7AreaMK, 0, Start, Size, S7Consts.S7WLByte, Buffer);
        }

        public int MBWrite(int Start, int Size, byte[] Buffer)
        {
            return WriteArea(S7Consts.S7AreaMK, 0, Start, Size, S7Consts.S7WLByte, Buffer);
        }

        public int EBRead(int Start, int Size, byte[] Buffer)
        {
            return ReadArea(S7Consts.S7AreaPE, 0, Start, Size, S7Consts.S7WLByte, Buffer);
        }

        public int EBWrite(int Start, int Size, byte[] Buffer)
        {
            return WriteArea(S7Consts.S7AreaPE, 0, Start, Size, S7Consts.S7WLByte, Buffer);
        }

        public int ABRead(int Start, int Size, byte[] Buffer)
        {
            return ReadArea(S7Consts.S7AreaPA, 0, Start, Size, S7Consts.S7WLByte, Buffer);
        }

        public int ABWrite(int Start, int Size, byte[] Buffer)
        {
            return WriteArea(S7Consts.S7AreaPA, 0, Start, Size, S7Consts.S7WLByte, Buffer);
        }

        public int TMRead(int Start, int Amount, ushort[] Buffer)
        {
            byte[] sBuffer = new byte[Amount * 2];
            int Result = ReadArea(S7Consts.S7AreaTM, 0, Start, Amount, S7Consts.S7WLTimer, sBuffer);
            if (Result == 0)
            {
                for (int c = 0; c < Amount; c++)
                {
                    Buffer[c] = (ushort)((sBuffer[c * 2 + 1] << 8) + (sBuffer[c * 2]));
                }
            }
            return Result;
        }

        public int TMWrite(int Start, int Amount, ushort[] Buffer)
        {
            byte[] sBuffer = new byte[Amount * 2];
            for (int c = 0; c < Amount; c++)
            {
                sBuffer[c * 2 + 1] = (byte)((Buffer[c] & 0xFF00) >> 8);
                sBuffer[c * 2] = (byte)(Buffer[c] & 0x00FF);
            }
            return WriteArea(S7Consts.S7AreaTM, 0, Start, Amount, S7Consts.S7WLTimer, sBuffer);
        }

        public int CTRead(int Start, int Amount, ushort[] Buffer)
        {
            byte[] sBuffer = new byte[Amount * 2];
            int Result = ReadArea(S7Consts.S7AreaCT, 0, Start, Amount, S7Consts.S7WLCounter, sBuffer);
            if (Result == 0)
            {
                for (int c = 0; c < Amount; c++)
                {
                    Buffer[c] = (ushort)((sBuffer[c * 2 + 1] << 8) + (sBuffer[c * 2]));
                }
            }
            return Result;
        }

        public int CTWrite(int Start, int Amount, ushort[] Buffer)
        {
            byte[] sBuffer = new byte[Amount * 2];
            for (int c = 0; c < Amount; c++)
            {
                sBuffer[c * 2 + 1] = (byte)((Buffer[c] & 0xFF00) >> 8);
                sBuffer[c * 2] = (byte)(Buffer[c] & 0x00FF);
            }
            return WriteArea(S7Consts.S7AreaCT, 0, Start, Amount, S7Consts.S7WLCounter, sBuffer);
        }

        #endregion

        #region [Directory functions]

        public int ListBlocks(ref S7BlocksList List)
        {
            _LastError = 0;
            Time_ms = 0;
            int Elapsed = Environment.TickCount;

            ushort Sequence = GetNextWord();

            Array.Copy(S7_LIST_BLOCKS, 0, PDU, 0, S7_LIST_BLOCKS.Length);
            PDU[0x0b] = (byte)(Sequence & 0xff);
            PDU[0x0c] = (byte)(Sequence >> 8);

            SendPacket(PDU, S7_LIST_BLOCKS.Length);

            if (_LastError != 0) return _LastError;
            int Length = RecvIsoPacket();
            if (Length <= 32)// the minimum expected
            {
                _LastError = S7Consts.errIsoInvalidPDU;
                return _LastError;
            }

            ushort Result = S7.GetWordAt(PDU, 27);
            if (Result != 0)
            {
                _LastError = CpuError(Result);
                return _LastError;
            }

            List = default(S7BlocksList);
            int BlocksSize = S7.GetWordAt(PDU, 31);

            if (Length <= 32 + BlocksSize)
            {
                _LastError = S7Consts.errIsoInvalidPDU;
                return _LastError;
            }

            int BlocksCount = BlocksSize >> 2;
            for (int blockNum = 0; blockNum < BlocksCount; blockNum++)
            {
                int Count = S7.GetWordAt(PDU, (blockNum << 2) + 35);

                switch (S7.GetByteAt(PDU, (blockNum << 2) + 34)) //BlockType
                {
                    case Block_OB:
                        List.OBCount = Count;
                        break;
                    case Block_DB:
                        List.DBCount = Count;
                        break;
                    case Block_SDB:
                        List.SDBCount = Count;
                        break;
                    case Block_FC:
                        List.FCCount = Count;
                        break;
                    case Block_SFC:
                        List.SFCCount = Count;
                        break;
                    case Block_FB:
                        List.FBCount = Count;
                        break;
                    case Block_SFB:
                        List.SFBCount = Count;
                        break;
                    default:
                        //Unknown block type. Ignore
                        break;
                }
            }

            Time_ms = Environment.TickCount - Elapsed;
            return _LastError; // 0
        }

        private string SiemensTimestamp(long EncodedDate)
        {
            DateTime DT = new DateTime(1984, 1, 1).AddSeconds(EncodedDate * 86400);
#if WINDOWS_UWP || NETFX_CORE || CORE_CLR
			return DT.ToString(System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern);
#else
            return DT.ToShortDateString();
            //  return DT.ToString();
#endif
        }

        public int GetAgBlockInfo(int BlockType, int BlockNum, ref S7BlockInfo Info)
        {
            _LastError = 0;
            Time_ms = 0;
            int Elapsed = Environment.TickCount;

            S7_BI[30] = (byte)BlockType;
            // Block Number
            S7_BI[31] = (byte)((BlockNum / 10000) + 0x30);
            BlockNum = BlockNum % 10000;
            S7_BI[32] = (byte)((BlockNum / 1000) + 0x30);
            BlockNum = BlockNum % 1000;
            S7_BI[33] = (byte)((BlockNum / 100) + 0x30);
            BlockNum = BlockNum % 100;
            S7_BI[34] = (byte)((BlockNum / 10) + 0x30);
            BlockNum = BlockNum % 10;
            S7_BI[35] = (byte)((BlockNum / 1) + 0x30);

            SendPacket(S7_BI);

            if (_LastError == 0)
            {
                int Length = RecvIsoPacket();
                if (Length > 32) // the minimum expected
                {
                    ushort Result = S7.GetWordAt(PDU, 27);
                    if (Result == 0)
                    {
                        Info.BlkFlags = PDU[42];
                        Info.BlkLang = PDU[43];
                        Info.BlkType = PDU[44];
                        Info.BlkNumber = S7.GetWordAt(PDU, 45);
                        Info.LoadSize = S7.GetDIntAt(PDU, 47);
                        Info.CodeDate = SiemensTimestamp(S7.GetWordAt(PDU, 59));
                        Info.IntfDate = SiemensTimestamp(S7.GetWordAt(PDU, 65));
                        Info.SBBLength = S7.GetWordAt(PDU, 67);
                        Info.LocalData = S7.GetWordAt(PDU, 71);
                        Info.MC7Size = S7.GetWordAt(PDU, 73);
                        Info.Author = S7.GetCharsAt(PDU, 75, 8).Trim(new char[] { (char)0 });
                        Info.Family = S7.GetCharsAt(PDU, 83, 8).Trim(new char[] { (char)0 });
                        Info.Header = S7.GetCharsAt(PDU, 91, 8).Trim(new char[] { (char)0 });
                        Info.Version = PDU[99];
                        Info.CheckSum = S7.GetWordAt(PDU, 101);
                    }
                    else
                        _LastError = CpuError(Result);
                }
                else
                    _LastError = S7Consts.errIsoInvalidPDU;
            }
            if (_LastError == 0)
                Time_ms = Environment.TickCount - Elapsed;

            return _LastError;

        }

        public int GetPgBlockInfo(ref S7BlockInfo Info, byte[] Buffer, int Size)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int ListBlocksOfType(int BlockType, ushort[] List, ref int ItemsCount)
        {
            var First = true;
            bool Done = false;
            byte In_Seq = 0;
            int Count = 0; //Block 1...n
            int PduLength;
            int Elapsed = Environment.TickCount;

            //Consequent packets have a different ReqData
            byte[] ReqData = new byte[] { 0xff, 0x09, 0x00, 0x02, 0x30, (byte)BlockType };
            byte[] ReqDataContinue = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00 };

            _LastError = 0;
            Time_ms = 0;

            do
            {
                PduLength = S7_LIST_BLOCKS_OF_TYPE.Length + ReqData.Length;
                ushort Sequence = GetNextWord();

                Array.Copy(S7_LIST_BLOCKS_OF_TYPE, 0, PDU, 0, S7_LIST_BLOCKS_OF_TYPE.Length);
                S7.SetWordAt(PDU, 0x02, (ushort)PduLength);
                PDU[0x0b] = (byte)(Sequence & 0xff);
                PDU[0x0c] = (byte)(Sequence >> 8);
                if (!First)
                {
                    S7.SetWordAt(PDU, 0x0d, 12); //ParLen
                    S7.SetWordAt(PDU, 0x0f, 4); //DataLen
                    PDU[0x14] = 8; //PLen
                    PDU[0x15] = 0x12; //Uk
                }
                PDU[0x17] = 0x02;
                PDU[0x18] = In_Seq;
                Array.Copy(ReqData, 0, PDU, 0x19, ReqData.Length);

                SendPacket(PDU, PduLength);
                if (_LastError != 0) return _LastError;

                PduLength = RecvIsoPacket();
                if (_LastError != 0) return _LastError;

                if (PduLength <= 32)// the minimum expected
                {
                    _LastError = S7Consts.errIsoInvalidPDU;
                    return _LastError;
                }

                ushort Result = S7.GetWordAt(PDU, 0x1b);
                if (Result != 0)
                {
                    _LastError = CpuError(Result);
                    return _LastError;
                }

                if (PDU[0x1d] != 0xFF)
                {
                    _LastError = S7Consts.errCliItemNotAvailable;
                    return _LastError;
                }

                Done = PDU[0x1a] == 0;
                In_Seq = PDU[0x18];

                int CThis = S7.GetWordAt(PDU, 0x1f) >> 2; //Amount of blocks in this message


                for (int c = 0; c < CThis; c++)
                {
                    if (Count >= ItemsCount) //RoomError
                    {
                        _LastError = S7Consts.errCliPartialDataRead;
                        return _LastError;
                    }
                    List[Count++] = S7.GetWordAt(PDU, 0x21 + 4 * c);
                    Done |= Count == 0x8000; //but why?
                }

                if (First)
                {
                    ReqData = ReqDataContinue;
                    First = false;
                }
            } while (_LastError == 0 && !Done);

            if (_LastError == 0)
                ItemsCount = Count;

            Time_ms = Environment.TickCount - Elapsed;
            return _LastError; // 0
        }

        #endregion

        #region [Blocks functions]

        public int Upload(int BlockType, int BlockNum, byte[] UsrData, ref int Size)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int FullUpload(int BlockType, int BlockNum, byte[] UsrData, ref int Size)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int Download(int BlockNum, byte[] UsrData, int Size)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int Delete(int BlockType, int BlockNum)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int DBGet(int DBNumber, byte[] UsrData, ref int Size)
        {
            S7BlockInfo BI = new S7BlockInfo();
            int Elapsed = Environment.TickCount;
            Time_ms = 0;

            _LastError = GetAgBlockInfo(Block_DB, DBNumber, ref BI);

            if (_LastError == 0)
            {
                int DBSize = BI.MC7Size;
                if (DBSize <= UsrData.Length)
                {
                    Size = DBSize;
                    _LastError = DBRead(DBNumber, 0, DBSize, UsrData);
                    if (_LastError == 0)
                        Size = DBSize;
                }
                else
                    _LastError = S7Consts.errCliBufferTooSmall;
            }
            if (_LastError == 0)
                Time_ms = Environment.TickCount - Elapsed;
            return _LastError;
        }

        public int DBFill(int DBNumber, int FillChar)
        {
            S7BlockInfo BI = new S7BlockInfo();
            int Elapsed = Environment.TickCount;
            Time_ms = 0;

            _LastError = GetAgBlockInfo(Block_DB, DBNumber, ref BI);

            if (_LastError == 0)
            {
                byte[] Buffer = new byte[BI.MC7Size];
                for (int c = 0; c < BI.MC7Size; c++)
                    Buffer[c] = (byte)FillChar;
                _LastError = DBWrite(DBNumber, 0, BI.MC7Size, Buffer);
            }
            if (_LastError == 0)
                Time_ms = Environment.TickCount - Elapsed;
            return _LastError;
        }

        #endregion

        #region [Date/Time functions]

        public int GetPlcDateTime(ref DateTime DT)
        {
            int Length;
            _LastError = 0;
            Time_ms = 0;
            int Elapsed = Environment.TickCount;

            SendPacket(S7_GET_DT);
            if (_LastError == 0)
            {
                Length = RecvIsoPacket();
                if (Length > 30) // the minimum expected
                {
                    if ((S7.GetWordAt(PDU, 27) == 0) && (PDU[29] == 0xFF))
                    {
                        DT = S7.GetDateTimeAt(PDU, 35);
                    }
                    else
                        _LastError = S7Consts.errCliInvalidPlcAnswer;
                }
                else
                    _LastError = S7Consts.errIsoInvalidPDU;
            }

            if (_LastError == 0)
                Time_ms = Environment.TickCount - Elapsed;

            return _LastError;
        }

        public int SetPlcDateTime(DateTime DT)
        {
            int Length;
            _LastError = 0;
            Time_ms = 0;
            int Elapsed = Environment.TickCount;

            S7.SetDateTimeAt(S7_SET_DT, 31, DT);
            SendPacket(S7_SET_DT);
            if (_LastError == 0)
            {
                Length = RecvIsoPacket();
                if (Length > 30) // the minimum expected
                {
                    if (S7.GetWordAt(PDU, 27) != 0)
                        _LastError = S7Consts.errCliInvalidPlcAnswer;
                }
                else
                    _LastError = S7Consts.errIsoInvalidPDU;
            }
            if (_LastError == 0)
                Time_ms = Environment.TickCount - Elapsed;

            return _LastError;
        }

        public int SetPlcSystemDateTime()
        {
            return SetPlcDateTime(DateTime.Now);
        }

        #endregion

        #region [System Info functions]

        public int GetOrderCode(ref S7OrderCode Info)
        {
            S7SZL SZL = new S7SZL();
            int Size = 1024;
            SZL.Data = new byte[Size];
            int Elapsed = Environment.TickCount;
            _LastError = ReadSZL(0x0011, 0x000, ref SZL, ref Size);
            if (_LastError == 0)
            {
                Info.Code = S7.GetCharsAt(SZL.Data, 2, 20);
                Info.V1 = SZL.Data[Size - 3];
                Info.V2 = SZL.Data[Size - 2];
                Info.V3 = SZL.Data[Size - 1];
            }
            if (_LastError == 0)
                Time_ms = Environment.TickCount - Elapsed;
            return _LastError;
        }

        public int GetCpuInfo(ref S7CpuInfo Info)
        {
            S7SZL SZL = new S7SZL();
            int Size = 1024;
            SZL.Data = new byte[Size];
            int Elapsed = Environment.TickCount;
            _LastError = ReadSZL(0x001C, 0x000, ref SZL, ref Size);
            if (_LastError == 0)
            {
                Info.ModuleTypeName = S7.GetCharsAt(SZL.Data, 172, 32);
                Info.SerialNumber = S7.GetCharsAt(SZL.Data, 138, 24);
                Info.ASName = S7.GetCharsAt(SZL.Data, 2, 24);
                Info.Copyright = S7.GetCharsAt(SZL.Data, 104, 26);
                Info.ModuleName = S7.GetCharsAt(SZL.Data, 36, 24);
            }
            if (_LastError == 0)
                Time_ms = Environment.TickCount - Elapsed;
            return _LastError;
        }

        public int GetCpInfo(ref S7CpInfo Info)
        {
            S7SZL SZL = new S7SZL();
            int Size = 1024;
            SZL.Data = new byte[Size];
            int Elapsed = Environment.TickCount;
            _LastError = ReadSZL(0x0131, 0x001, ref SZL, ref Size);
            if (_LastError == 0)
            {
                Info.MaxPduLength = S7.GetIntAt(PDU, 2);
                Info.MaxConnections = S7.GetIntAt(PDU, 4);
                Info.MaxMpiRate = S7.GetDIntAt(PDU, 6);
                Info.MaxBusRate = S7.GetDIntAt(PDU, 10);
            }
            if (_LastError == 0)
                Time_ms = Environment.TickCount - Elapsed;
            return _LastError;
        }

        public int ReadSZL(int ID, int Index, ref S7SZL SZL, ref int Size)
        {
            int Length;
            int DataSZL;
            int Offset = 0;
            bool Done = false;
            bool First = true;
            byte Seq_in = 0x00;
            ushort Seq_out = 0x0000;

            _LastError = 0;
            Time_ms = 0;
            int Elapsed = Environment.TickCount;
            SZL.Header.LENTHDR = 0;

            do
            {
                if (First)
                {
                    S7.SetWordAt(S7_SZL_FIRST, 11, ++Seq_out);
                    S7.SetWordAt(S7_SZL_FIRST, 29, (ushort)ID);
                    S7.SetWordAt(S7_SZL_FIRST, 31, (ushort)Index);
                    SendPacket(S7_SZL_FIRST);
                }
                else
                {
                    S7.SetWordAt(S7_SZL_NEXT, 11, ++Seq_out);
                    PDU[24] = (byte)Seq_in;
                    SendPacket(S7_SZL_NEXT);
                }
                if (_LastError != 0)
                    return _LastError;

                Length = RecvIsoPacket();
                if (_LastError == 0)
                {
                    if (First)
                    {
                        if (Length > 32) // the minimum expected
                        {
                            if ((S7.GetWordAt(PDU, 27) == 0) && (PDU[29] == (byte)0xFF))
                            {
                                // Gets Amount of this slice
                                DataSZL = S7.GetWordAt(PDU, 31) - 8; // Skips extra params (ID, Index ...)
                                Done = PDU[26] == 0x00;
                                Seq_in = (byte)PDU[24]; // Slice sequence
                                SZL.Header.LENTHDR = S7.GetWordAt(PDU, 37);
                                SZL.Header.N_DR = S7.GetWordAt(PDU, 39);
                                Array.Copy(PDU, 41, SZL.Data, Offset, DataSZL);
                                //                                SZL.Copy(PDU, 41, Offset, DataSZL);
                                Offset += DataSZL;
                                SZL.Header.LENTHDR += SZL.Header.LENTHDR;
                            }
                            else
                                _LastError = S7Consts.errCliInvalidPlcAnswer;
                        }
                        else
                            _LastError = S7Consts.errIsoInvalidPDU;
                    }
                    else
                    {
                        if (Length > 32) // the minimum expected
                        {
                            if ((S7.GetWordAt(PDU, 27) == 0) && (PDU[29] == (byte)0xFF))
                            {
                                // Gets Amount of this slice
                                DataSZL = S7.GetWordAt(PDU, 31);
                                Done = PDU[26] == 0x00;
                                Seq_in = (byte)PDU[24]; // Slice sequence
                                Array.Copy(PDU, 37, SZL.Data, Offset, DataSZL);
                                Offset += DataSZL;
                                SZL.Header.LENTHDR += SZL.Header.LENTHDR;
                            }
                            else
                                _LastError = S7Consts.errCliInvalidPlcAnswer;
                        }
                        else
                            _LastError = S7Consts.errIsoInvalidPDU;
                    }
                }
                First = false;
            }
            while (!Done && (_LastError == 0));
            if (_LastError == 0)
            {
                Size = SZL.Header.LENTHDR;
                Time_ms = Environment.TickCount - Elapsed;
            }
            return _LastError;
        }

        public int ReadSZLList(ref S7SZLList List, ref Int32 ItemsCount)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        #endregion

        #region [Control functions]

        public int PlcHotStart()
        {
            _LastError = 0;
            int Elapsed = Environment.TickCount;

            SendPacket(S7_HOT_START);
            if (_LastError == 0)
            {
                int Length = RecvIsoPacket();
                if (Length > 18) // 18 is the minimum expected
                {
                    if (PDU[19] != pduStart)
                        _LastError = S7Consts.errCliCannotStartPLC;
                    else
                    {
                        if (PDU[20] == pduAlreadyStarted)
                            _LastError = S7Consts.errCliAlreadyRun;
                        else
                            _LastError = S7Consts.errCliCannotStartPLC;
                    }
                }
                else
                    _LastError = S7Consts.errIsoInvalidPDU;
            }
            if (_LastError == 0)
                Time_ms = Environment.TickCount - Elapsed;
            return _LastError;
        }

        public int PlcColdStart()
        {
            _LastError = 0;
            int Elapsed = Environment.TickCount;

            SendPacket(S7_COLD_START);
            if (_LastError == 0)
            {
                int Length = RecvIsoPacket();
                if (Length > 18) // 18 is the minimum expected
                {
                    if (PDU[19] != pduStart)
                        _LastError = S7Consts.errCliCannotStartPLC;
                    else
                    {
                        if (PDU[20] == pduAlreadyStarted)
                            _LastError = S7Consts.errCliAlreadyRun;
                        else
                            _LastError = S7Consts.errCliCannotStartPLC;
                    }
                }
                else
                    _LastError = S7Consts.errIsoInvalidPDU;
            }
            if (_LastError == 0)
                Time_ms = Environment.TickCount - Elapsed;
            return _LastError;
        }

        public int PlcStop()
        {
            _LastError = 0;
            int Elapsed = Environment.TickCount;

            SendPacket(S7_STOP);
            if (_LastError == 0)
            {
                int Length = RecvIsoPacket();
                if (Length > 18) // 18 is the minimum expected
                {
                    if (PDU[19] != pduStop)
                        _LastError = S7Consts.errCliCannotStopPLC;
                    else
                    {
                        if (PDU[20] == pduAlreadyStopped)
                            _LastError = S7Consts.errCliAlreadyStop;
                        else
                            _LastError = S7Consts.errCliCannotStopPLC;
                    }
                }
                else
                    _LastError = S7Consts.errIsoInvalidPDU;
            }
            if (_LastError == 0)
                Time_ms = Environment.TickCount - Elapsed;
            return _LastError;
        }

        public int PlcCopyRamToRom(UInt32 Timeout)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int PlcCompress(UInt32 Timeout)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int PlcGetStatus(ref Int32 Status)
        {
            _LastError = 0;
            int Elapsed = Environment.TickCount;

            SendPacket(S7_GET_STAT);
            if (_LastError == 0)
            {
                int Length = RecvIsoPacket();
                if (Length > 30) // the minimum expected
                {
                    ushort Result = S7.GetWordAt(PDU, 27);
                    if (Result == 0)
                    {
                        switch (PDU[44])
                        {
                            case S7Consts.S7CpuStatusUnknown:
                            case S7Consts.S7CpuStatusRun:
                            case S7Consts.S7CpuStatusStop:
                                {
                                    Status = PDU[44];
                                    break;
                                }
                            default:
                                {
                                    // Since RUN status is always 0x08 for all CPUs and CPs, STOP status
                                    // sometime can be coded as 0x03 (especially for old cpu...)
                                    Status = S7Consts.S7CpuStatusStop;
                                    break;
                                }
                        }
                    }
                    else
                        _LastError = CpuError(Result);
                }
                else
                    _LastError = S7Consts.errIsoInvalidPDU;
            }
            if (_LastError == 0)
                Time_ms = Environment.TickCount - Elapsed;
            return _LastError;
        }

        #endregion

        #region [Security functions]
        public int SetSessionPassword(string Password)
        {
            byte[] pwd = { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
            int Length;
            _LastError = 0;
            int Elapsed = Environment.TickCount;
            // Encodes the Password
            S7.SetCharsAt(pwd, 0, Password);
            pwd[0] = (byte)(pwd[0] ^ 0x55);
            pwd[1] = (byte)(pwd[1] ^ 0x55);
            for (int c = 2; c < 8; c++)
            {
                pwd[c] = (byte)(pwd[c] ^ 0x55 ^ pwd[c - 2]);
            }
            Array.Copy(pwd, 0, S7_SET_PWD, 29, 8);
            // Sends the telegrem
            SendPacket(S7_SET_PWD);
            if (_LastError == 0)
            {
                Length = RecvIsoPacket();
                if (Length > 32) // the minimum expected
                {
                    ushort Result = S7.GetWordAt(PDU, 27);
                    if (Result != 0)
                        _LastError = CpuError(Result);
                }
                else
                    _LastError = S7Consts.errIsoInvalidPDU;
            }
            if (_LastError == 0)
                Time_ms = Environment.TickCount - Elapsed;
            return _LastError;
        }

        public int ClearSessionPassword()
        {
            int Length;
            _LastError = 0;
            int Elapsed = Environment.TickCount;
            SendPacket(S7_CLR_PWD);
            if (_LastError == 0)
            {
                Length = RecvIsoPacket();
                if (Length > 30) // the minimum expected
                {
                    ushort Result = S7.GetWordAt(PDU, 27);
                    if (Result != 0)
                        _LastError = CpuError(Result);
                }
                else
                    _LastError = S7Consts.errIsoInvalidPDU;
            }
            return _LastError;
        }

        public int GetProtection(ref S7Protection Protection)
        {
            S7Client.S7SZL SZL = new S7Client.S7SZL();
            int Size = 256;
            SZL.Data = new byte[Size];
            _LastError = ReadSZL(0x0232, 0x0004, ref SZL, ref Size);
            if (_LastError == 0)
            {
                Protection.sch_schal = S7.GetWordAt(SZL.Data, 2);
                Protection.sch_par = S7.GetWordAt(SZL.Data, 4);
                Protection.sch_rel = S7.GetWordAt(SZL.Data, 6);
                Protection.bart_sch = S7.GetWordAt(SZL.Data, 8);
                Protection.anl_sch = S7.GetWordAt(SZL.Data, 10);
            }
            return _LastError;
        }
        #endregion

        #region [Low Level]

        public int IsoExchangeBuffer(byte[] Buffer, ref Int32 Size)
        {
            _LastError = 0;
            Time_ms = 0;
            int Elapsed = Environment.TickCount;
            Array.Copy(TPKT_ISO, 0, PDU, 0, TPKT_ISO.Length);
            S7.SetWordAt(PDU, 2, (ushort)(Size + TPKT_ISO.Length));
            try
            {
                Array.Copy(Buffer, 0, PDU, TPKT_ISO.Length, Size);
            }
            catch
            {
                return S7Consts.errIsoInvalidPDU;
            }
            SendPacket(PDU, TPKT_ISO.Length + Size);
            if (_LastError == 0)
            {
                int Length = RecvIsoPacket();
                if (_LastError == 0)
                {
                    Array.Copy(PDU, TPKT_ISO.Length, Buffer, 0, Length - TPKT_ISO.Length);
                    Size = Length - TPKT_ISO.Length;
                }
            }
            if (_LastError == 0)
                Time_ms = Environment.TickCount - Elapsed;
            else
                Size = 0;
            return _LastError;
        }

        #endregion

        #region [Async functions (not implemented)]

        public int AsReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsWriteArea(int Area, int DBNumber, int Start, int Amount, int WordLen, byte[] Buffer)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsDBRead(int DBNumber, int Start, int Size, byte[] Buffer)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsDBWrite(int DBNumber, int Start, int Size, byte[] Buffer)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsMBRead(int Start, int Size, byte[] Buffer)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsMBWrite(int Start, int Size, byte[] Buffer)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsEBRead(int Start, int Size, byte[] Buffer)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsEBWrite(int Start, int Size, byte[] Buffer)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsABRead(int Start, int Size, byte[] Buffer)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsABWrite(int Start, int Size, byte[] Buffer)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsTMRead(int Start, int Amount, ushort[] Buffer)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsTMWrite(int Start, int Amount, ushort[] Buffer)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsCTRead(int Start, int Amount, ushort[] Buffer)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsCTWrite(int Start, int Amount, ushort[] Buffer)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsListBlocksOfType(int BlockType, ushort[] List)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsReadSZL(int ID, int Index, ref S7SZL Data, ref Int32 Size)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsReadSZLList(ref S7SZLList List, ref Int32 ItemsCount)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsUpload(int BlockType, int BlockNum, byte[] UsrData, ref int Size)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsFullUpload(int BlockType, int BlockNum, byte[] UsrData, ref int Size)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int ASDownload(int BlockNum, byte[] UsrData, int Size)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsPlcCopyRamToRom(UInt32 Timeout)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsPlcCompress(UInt32 Timeout)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsDBGet(int DBNumber, byte[] UsrData, ref int Size)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public int AsDBFill(int DBNumber, int FillChar)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        public bool CheckAsCompletion(ref int opResult)
        {
            opResult = 0;
            return false;
        }

        public int WaitAsCompletion(int Timeout)
        {
            return S7Consts.errCliFunctionNotImplemented;
        }

        #endregion

        #region [Info Functions / Properties]

        public string ErrorText(int Error)
        {
            switch (Error)
            {
                case 0: return "OK";
                case S7Consts.errTCPSocketCreation: return "SYS : Error creating the Socket";
                case S7Consts.errTCPConnectionTimeout: return "TCP : Connection Timeout";
                case S7Consts.errTCPConnectionFailed: return "TCP : Connection Error";
                case S7Consts.errTCPReceiveTimeout: return "TCP : Data receive Timeout";
                case S7Consts.errTCPDataReceive: return "TCP : Error receiving Data";
                case S7Consts.errTCPSendTimeout: return "TCP : Data send Timeout";
                case S7Consts.errTCPDataSend: return "TCP : Error sending Data";
                case S7Consts.errTCPConnectionReset: return "TCP : Connection reset by the Peer";
                case S7Consts.errTCPNotConnected: return "CLI : Client not connected";
                case S7Consts.errTCPUnreachableHost: return "TCP : Unreachable host";
                case S7Consts.errIsoConnect: return "ISO : Connection Error";
                case S7Consts.errIsoInvalidPDU: return "ISO : Invalid PDU received";
                case S7Consts.errIsoInvalidDataSize: return "ISO : Invalid Buffer passed to Send/Receive";
                case S7Consts.errCliNegotiatingPDU: return "CLI : Error in PDU negotiation";
                case S7Consts.errCliInvalidParams: return "CLI : invalid param(s) supplied";
                case S7Consts.errCliJobPending: return "CLI : Job pending";
                case S7Consts.errCliTooManyItems: return "CLI : too may items (>20) in multi read/write";
                case S7Consts.errCliInvalidWordLen: return "CLI : invalid WordLength";
                case S7Consts.errCliPartialDataWritten: return "CLI : Partial data written";
                case S7Consts.errCliSizeOverPDU: return "CPU : total data exceeds the PDU size";
                case S7Consts.errCliInvalidPlcAnswer: return "CLI : invalid CPU answer";
                case S7Consts.errCliAddressOutOfRange: return "CPU : Address out of range";
                case S7Consts.errCliInvalidTransportSize: return "CPU : Invalid Transport size";
                case S7Consts.errCliWriteDataSizeMismatch: return "CPU : Data size mismatch";
                case S7Consts.errCliItemNotAvailable: return "CPU : Item not available";
                case S7Consts.errCliInvalidValue: return "CPU : Invalid value supplied";
                case S7Consts.errCliCannotStartPLC: return "CPU : Cannot start PLC";
                case S7Consts.errCliAlreadyRun: return "CPU : PLC already RUN";
                case S7Consts.errCliCannotStopPLC: return "CPU : Cannot stop PLC";
                case S7Consts.errCliCannotCopyRamToRom: return "CPU : Cannot copy RAM to ROM";
                case S7Consts.errCliCannotCompress: return "CPU : Cannot compress";
                case S7Consts.errCliAlreadyStop: return "CPU : PLC already STOP";
                case S7Consts.errCliFunNotAvailable: return "CPU : Function not available";
                case S7Consts.errCliUploadSequenceFailed: return "CPU : Upload sequence failed";
                case S7Consts.errCliInvalidDataSizeRecvd: return "CLI : Invalid data size received";
                case S7Consts.errCliInvalidBlockType: return "CLI : Invalid block type";
                case S7Consts.errCliInvalidBlockNumber: return "CLI : Invalid block number";
                case S7Consts.errCliInvalidBlockSize: return "CLI : Invalid block size";
                case S7Consts.errCliNeedPassword: return "CPU : Function not authorized for current protection level";
                case S7Consts.errCliInvalidPassword: return "CPU : Invalid password";
                case S7Consts.errCliNoPasswordToSetOrClear: return "CPU : No password to set or clear";
                case S7Consts.errCliJobTimeout: return "CLI : Job Timeout";
                case S7Consts.errCliFunctionRefused: return "CLI : function refused by CPU (Unknown error)";
                case S7Consts.errCliPartialDataRead: return "CLI : Partial data read";
                case S7Consts.errCliBufferTooSmall: return "CLI : The buffer supplied is too small to accomplish the operation";
                case S7Consts.errCliDestroying: return "CLI : Cannot perform (destroying)";
                case S7Consts.errCliInvalidParamNumber: return "CLI : Invalid Param Number";
                case S7Consts.errCliCannotChangeParam: return "CLI : Cannot change this param now";
                case S7Consts.errCliFunctionNotImplemented: return "CLI : Function not implemented";
                default: return "CLI : Unknown error (0x" + Convert.ToString(Error, 16) + ")";
            };
        }

        public int LastError()
        {
            return _LastError;
        }

        public int RequestedPduLength()
        {
            return _PduSizeRequested;
        }

        public int NegotiatedPduLength()
        {
            return _PDULength;
        }

        public int ExecTime()
        {
            return Time_ms;
        }

        public int ExecutionTime
        {
            get
            {
                return Time_ms;
            }
        }

        public int PduSizeNegotiated
        {
            get
            {
                return _PDULength;
            }
        }

        public int PduSizeRequested
        {
            get
            {
                return _PduSizeRequested;
            }
            set
            {
                if (value < MinPduSizeToRequest)
                    value = MinPduSizeToRequest;
                if (value > MaxPduSizeToRequest)
                    value = MaxPduSizeToRequest;
                _PduSizeRequested = value;
            }
        }

        public int PLCPort
        {
            get
            {
                return _PLCPort;
            }
            set
            {
                _PLCPort = value;
            }
        }

        public int ConnTimeout
        {
            get
            {
                return _ConnTimeout;
            }
            set
            {
                _ConnTimeout = value;
            }
        }

        public int RecvTimeout
        {
            get
            {
                return _RecvTimeout;
            }
            set
            {
                _RecvTimeout = value;
            }
        }

        public int SendTimeout
        {
            get
            {
                return _SendTimeout;
            }
            set
            {
                _SendTimeout = value;
            }
        }

        public bool Connected
        {
            get
            {
                return (Socket != null) && (Socket.Connected);
            }
        }
        #endregion

        #region forcejob

        public class S7Forces
        {
            public List<ForceJob> Forces;
        }


        internal int GetActiveForces(List<ForceJob> forces, byte[] forceframe)
        {


            // sending second package only if there are force jobs active 
            SendPacket(forceframe);
            var length = RecvIsoPacket();

            switch (WordFromByteArr(PDU, 27))
            {
                default:
                    _LastError = S7Consts.errTCPDataReceive;
                    break;
                case 0x000:

                    // creating byte [] with length of useful data (first 67 bytes aren't useful data )
                    byte[] forceData = new byte[length - 67];
                    // copy pdu to other byte[] and remove the unused data 
                    Array.Copy(PDU, 67, forceData, 0, length - 67);
                    // check array transition definition > value's 
                    byte[] splitDefData = new byte[] { 0x00, 0x09, 0x00 };
                    int Splitposition = 0;
                    for (int x = 0; x < forceData.Length - 3; x = x + 6)
                    {
                        // checking when the definitions go to data (the data starts with split definition data and the amount of bytes before should always be a plural of 6)
                        if (forceData[x] == splitDefData[0] && forceData[x + 1] == splitDefData[1] && forceData[x + 2] == splitDefData[2] && x % 6 == 0)
                        {
                            Splitposition = x;
                            break;
                        }

                    }
                    // calculating amount of forces 
                    int amountForces = Splitposition / 6;
                    // setting first byte from data
                    int dataposition = Splitposition;
                    for (int x = 0; x < amountForces; x++)
                    {
                        ForceJob force = new ForceJob
                        {
                            // bit value
                            BitAdress = (forceData[(1 + (6 * x))]),

                            // byte value

                            ByteAdress = ((forceData[(4 + (6 * x))]) * 256) + (forceData[(5 + (6 * x))])
                        };
                        // foce identity
                        switch (forceData[0 + (6 * x)])
                        {

                            case 0x0:
                                force.ForceType = "M";
                                break;

                            case 0x1:
                                force.ForceType = "MB";
                                force.BitAdress = null;
                                break;
                            case 0x2:
                                force.ForceType = "MW";
                                force.BitAdress = null;
                                break;
                            case 0x3:
                                force.ForceType = "MD";
                                force.BitAdress = null;
                                break;

                            case 0x10:
                                force.ForceType = "I";
                                break;

                            case 0x11:
                                force.ForceType = "IB";
                                force.BitAdress = null;
                                break;

                            case 0x12:
                                force.ForceType = "IW";
                                force.BitAdress = null;
                                break;

                            case 0x13:
                                force.ForceType = "ID";
                                force.BitAdress = null;
                                break;


                            case 0x20:
                                force.ForceType = "Q";
                                break;

                            case 0x21:
                                force.ForceType = "QB";
                                force.BitAdress = null;
                                break;

                            case 0x22:
                                force.ForceType = "QW";
                                force.BitAdress = null;
                                break;

                            case 0x23:
                                force.ForceType = "QD";
                                force.BitAdress = null;
                                break;

                            // if you get this code You can add it in the list above.
                            default:
                                force.ForceType = forceData[0 + (6 * x)].ToString() + " unknown";
                                break;
                        }

                        // setting force value depending on the data length
                        switch (forceData[dataposition + 3])// Data length from force
                        {

                            case 0x01:
                                force.ForceValue = forceData[dataposition + 4];
                                break;

                            case 0x02:
                                force.ForceValue = WordFromByteArr(forceData, dataposition + 4);
                                break;

                            case 0x04:
                                force.ForceValue = DoubleFromByteArr(forceData, dataposition + 4);
                                break;

                            default:
                                break;


                        }

                        // calculating when the next force start 

                        var nextForce = 0x04 + (forceData[dataposition + 3]);
                        if (nextForce < 6)
                        {
                            nextForce = 6;
                        }
                        dataposition += nextForce;
                        // adding force to list 
                        forces.Add(force);
                    }
                    break;
            }
            return _LastError;
        }

        public int GetForceValues300(ref S7Forces forces)
        {
            _LastError = 00;
            int Elapsed = Environment.TickCount;
            List<ForceJob> forcedValues = new List<ForceJob>();
            SendPacket(S7_FORCE_VAL1);
            var Length = RecvIsoPacket();

            // when response is 45 there are no force jobs active or no correct response from plc

            switch (WordFromByteArr(PDU, 27))
            {
                case 0x0000:// no error code

                    if (WordFromByteArr(PDU, 31) >= 16)
                    {
                        _LastError = GetActiveForces(forcedValues, S7_FORCE_VAL300);
                    }
                    break;

                default:
                    _LastError = S7Consts.errTCPDataReceive;
                    break;
            }

            forces.Forces = forcedValues;

            Time_ms = Environment.TickCount - Elapsed;
            return _LastError;
        }

        public int GetForceValues400(ref S7Forces forces)
        {
            _LastError = 00;
            int Elapsed = Environment.TickCount;
            List<ForceJob> forcedValues = new List<ForceJob>();
            SendPacket(S7_FORCE_VAL1);
            var Length = RecvIsoPacket();

            // when response is 45 there are no force jobs active or no correct response from PLC

            switch (WordFromByteArr(PDU, 27))
            {
                case 0x0000:

                    if (WordFromByteArr(PDU, 31) >= 12)
                    {
                        _LastError = GetActiveForces(forcedValues, S7_FORCE_VAL400);
                    }
                    break;

                default:
                    _LastError = S7Consts.errTCPDataReceive;
                    break;
            }

            forces.Forces = forcedValues;
            Time_ms = Environment.TickCount - Elapsed;
            return _LastError;
        }

        public int WordFromByteArr(byte[] data, int position)
        {
            int result = Convert.ToInt32((data[position] << 8) + data[position + 1]);
            return result;
        }

        public int DoubleFromByteArr(byte[] data, int position)
        {
            int result = Convert.ToInt32((data[position] << 24) + (data[position + 1] << 16) + (data[position + 2] << 8) + (data[position + 3]));
            return result;
        }


        // S7 Get Force Values frame 1
        byte[] S7_FORCE_VAL1 = {
            0x03, 0x00, 0x00, 0x3d,
            0x02, 0xf0 ,0x80, 0x32,
            0x07, 0x00, 0x00, 0x07,
            0x00, 0x00, 0x0c, 0x00,
            0x20, 0x00, 0x01, 0x12,
            0x08, 0x12, 0x41, 0x10,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0xff, 0x09, 0x00,
            0x1c, 0x00, 0x14, 0x00,
            0x04, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x01, 0x00,
            0x00, 0x00, 0x01, 0x00,
            0x01, 0x00, 0x01, 0x00,
            0x01, 0x00, 0x01, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00

        };

        // S7 Get Force Values frame 2 (300 series )
        byte[] S7_FORCE_VAL300 = {
            0x03, 0x00, 0x00, 0x3b,
            0x02, 0xf0, 0x80, 0x32,
            0x07, 0x00, 0x00, 0x0c,
            0x00, 0x00, 0x0c, 0x00,
            0x1e, 0x00, 0x01, 0x12,
            0x08, 0x12, 0x41, 0x11,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0xff, 0x09, 0x00,
            0x1a, 0x00, 0x14, 0x00,
            0x02, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x01, 0x00,
            0x00, 0x00, 0x01, 0x00,
            0x01, 0x00, 0x01, 0x00,
            0x01, 0x00, 0x01, 0x00,
            0x00, 0x09, 0x03

        };

        // S7 Get Force Values frame 2 (400 series )
        byte[] S7_FORCE_VAL400 = {
            0x03, 0x00, 0x00, 0x3b,
            0x02, 0xf0, 0x80, 0x32,
            0x07, 0x00, 0x00, 0x0c,
            0x00, 0x00, 0x0c, 0x00,
            0x1e, 0x00, 0x01, 0x12,
            0x08, 0x12, 0x41, 0x11,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0xff, 0x09, 0x00,
            0x1a, 0x00, 0x14, 0x00,
            0x02, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x01, 0x00,
            0x00, 0x00, 0x01, 0x00,
            0x01, 0x00, 0x01, 0x00,
            0x01, 0x00, 0x01, 0x00,
            0x00, 0x09, 0x05
        };
    }

    public class ForceJob
    {
        public string FullAdress
        {
            get
            {
                if (BitAdress == null)
                {
                    return $"{ForceType} {ByteAdress}";
                }
                else
                {
                    return $"{ForceType} {ByteAdress}.{BitAdress}";
                }
            }
        }
        public int ForceValue { get; set; }
        public string ForceType { get; set; }
        public int ByteAdress { get; set; }
        public int? BitAdress { get; set; }
        public string Symbol { get; set; }
        public string Comment { get; set; }

    }

    #region CommentedForce
    public class CommentForces
    {
        // Only symbol table's with.seq extension
        public List<ForceJob> AddForceComments(string filepath, List<ForceJob> actualForces)
        {
            if (Path.GetExtension(filepath).ToLower() == ".seq")
            {
                var SymbolTableDataText = ReadSymbolTable(filepath);
                if (SymbolTableDataText.Length >= 1)
                {
                    var SymbolTableDataList = ConvertDataArrToList(SymbolTableDataText);
                    var CommentedForceList = AddCommentToForce(actualForces, SymbolTableDataList);
                    return CommentedForceList;
                }
            }
            return ErrorSymbTableProces(actualForces);
        }

        private List<ForceJob> AddCommentToForce(List<ForceJob> forceringen, List<SymbolTableRecord> symbolTable)
        {
            List<ForceJob> commentedforces = new List<ForceJob>();

            foreach (ForceJob force in forceringen)
            {

                var found = symbolTable.Where(s => s.Address == force.FullAdress).FirstOrDefault();
                ForceJob commentedforce = new ForceJob();
                commentedforce = force;


                if (found != null)
                {
                    commentedforce.Symbol = found.Symbol;
                    commentedforce.Comment = found.Comment;
                }
                else
                {
                    commentedforce.Symbol = "NOT SET";
                    commentedforce.Comment = "not in variable table";
                }
                commentedforces.Add(commentedforce);

            }

            return commentedforces;

        }

        private List<SymbolTableRecord> ConvertDataArrToList(string[] text)
        {
            List<SymbolTableRecord> Symbollist = new List<SymbolTableRecord>();

            foreach (var line in text)
            {
                SymbolTableRecord temp = new SymbolTableRecord();
                string[] splited = new string[10];
                splited = line.Split('\t');
                temp.Address = splited[1];
                temp.Symbol = splited[2];
                temp.Comment = splited[3];

                Symbollist.Add(temp);
            }
            return Symbollist;
        }

        private string[] ReadSymbolTable(string Filepath)
        {

            string[] lines = System.IO.File.ReadAllLines(Filepath);
            return lines;
        }



        private List<ForceJob> ErrorSymbTableProces(List<ForceJob> actualForces)
        {
            var errorForceTable = actualForces;
            foreach (var forcerecord in errorForceTable)
            {
                forcerecord.Comment = "Force Table could not be processed";
                forcerecord.Symbol = "ERROR";

            }
            return errorForceTable;
        }
    }


    public class SymbolTableRecord
    {
        public string Symbol { get; set; }
        public string Address { get; set; }
        public string Comment { get; set; }
    }


    #endregion
    #endregion
}