All files / js cmd.js

84.03% Statements 3457/4114
73.08% Branches 774/1059
77.5% Functions 62/80
84.03% Lines 3457/4114

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 411573x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 73x 73x 73x                                           73x 73x 27x 27x 294x 294x 21x 27x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 1526x 1526x 1526x 1526x 1526x 73x 73x 73x           73x 1758x 1758x 1758x 1526x 1526x 1758x 1758x 73x 73x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x   1x     2x 2x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x                                                         73x                               73x                         73x                     73x 47x 47x 47x 47x 47x 47x 47x         47x 7x 7x 7x 7x 7x 7x 7x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 47x 73x 49x 49x 49x 49x 49x 49x 49x 49x 49x 32x 32x 32x 49x 49x 49x 49x 1x 1x 1x 47x 47x 47x 47x 49x 73x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 3711x 3711x 4140x           4140x 4140x 4140x 4140x 4140x 4140x 4140x 4140x 73x 73x 226x 226x 226x 73x                                 73x             73x 164x 164x 164x 164x 164x 164x 164x 164x 73x         73x                                                                     73x 73x 73x 73x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 73x 73x 73x 73x 73x 73x 73x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 192x 192x 8x 8x 112x 112x 112x 112x         112x 8x 8x 8x 8x 8x 8x 8x         8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 40x 40x 40x 40x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 73x 73x 73x 73x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 70x 70x 70x 1680x 1680x 70x 1545x 1545x 1539x 1539x 1539x 1539x 1539x 1539x 1539x 1545x 1545x 1545x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 70x 66x 53x 53x 53x 70x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 73x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 73x 73x 73x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x             6x           6x 6x 5x 6x 6x 5x 6x 6x 6x 73x 4x 4x 4x 4x 4x 73x 3x 3x 3x 3x 3x 3x 73x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 73x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 73x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 73x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 73x           73x 73x 73x 2x 2x 2x 2x 73x 73x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 73x 73x 2x 2x 8x 8x 2x 2x 73x                                           73x 73x 73x 8x 8x 8x 8x 8x 8x 7x 3x 3x 3x 3x 6x 2x 8x 8x 2x 8x 73x 8x 8x 8x 8x 8x 8x 4x 8x 73x 5x 5x 5x 5x 3x 1x 1x 1x 1x 1x 1x   5x 73x                           73x               73x                                           73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 5082x 5082x 5082x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 5084x 5084x 5084x 5084x 73x 73x 73x     73x 73x 73x 5082x 5082x 73x 73x 73x 1x 1x 6x 6x   1x 73x 73x 73x 73x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 73x 73x 73x         73x 73x 73x 73x 73x 71x 71x 71x 71x 71x 71x 4615x 4615x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 73x 73x 73x                           73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 9x 9x 9x 9x 9x 745x 745x 745x 273x 273x 472x 9x 9x 27x 27x 27x 9x 9x 22x 22x 9x 9x 2x 2x     2x 9x 9x 3x 3x 3x 3x 3x 3x 3x 3x 3x 45x 45x 45x 45x 45x 45x 45x 45x 45x   45x 45x 45x 45x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x     3x 3x       3x 3x 45x 3x 45x 3x 9x 9x 9x 9x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 2x 36x   34x 3x 34x 1x 31x 3x 30x   27x 4x 27x 1x 23x 1x 22x   21x   21x   21x   21x 1x 21x     20x     20x     20x     20x 3x 3x 19x 2x 2x 17x 1x 1x 15x 1x 1x 14x 3x 3x 3x 12x 1x 1x 1x 1x 36x 36x 36x 36x 36x 9x 9x 9x 9x 9x 9x 9x 73x 73x 73x 73x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 5138x 8x 7x 7x 7x 7x 7x 7x 4x 4x       4x 6x 2x 2x 6x 6x 8x 8x 5131x 5131x 5124x 5124x 5124x 5124x 5124x 5124x 5124x 5124x 5124x 5075x 5075x 5075x 5124x 47x 47x 47x 47x 47x 5075x 5075x 5124x 36x 36x 36x 5075x 5124x 47x 47x 5075x 5123x 5075x 5075x 5082x 5082x 5082x 5082x 5082x 5082x 5082x 5138x 1575x 1575x 1575x 1575x 1575x 5082x 5082x 5082x 5082x 5082x 5138x 5082x 5082x 5138x                 5082x 5138x                 5082x 5082x 5082x 5082x 5136x 2907x 2907x 2907x 2907x 2907x 2907x 2907x 2907x 2907x 2907x 2907x 2907x 2907x 2907x 2907x 2907x 2907x 2907x 2907x 280x 280x 280x 280x 280x 280x 280x 280x 2907x 2905x 2905x 2905x 2905x 2175x 2175x 2175x 2175x 5138x                                                                               2175x 2175x 5119x 18x 18x 18x 18x 5138x 44x 44x 44x 44x 44x 44x 5138x 102x 102x             102x 102x 102x 102x 5138x 3x 3x           3x 3x 3x 3x 5138x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5138x 1x 1x 1x 1x 1x                                   1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5138x 1x 1x 1x 1x 1x 1x 1x 5138x 30x 30x 30x 30x 30x 30x 30x 5138x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 5138x 195x         195x 195x 195x 195x 5138x                                     5138x 2x 2x 2x 2x 5138x 181x 181x 20x 180x 161x 161x 181x 5138x 321x 321x 321x 25x 25x 321x 321x 5138x 17x 17x 17x 17x 5138x 228x 228x 228x 228x 228x 2x 2x 2x 226x 226x 226x 226x 226x 228x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 228x 1x 1x 224x 223x 223x 10x 10x 10x 10x 223x 1x 1x 1x 1x 1x 213x 119x 23x 23x 23x 23x 96x 96x 103x 7x 7x 7x 103x 3x 3x 3x 3x 89x 3x 3x 3x 86x 6x 6x 6x 83x 1x 1x 1x 77x 5x 5x 5x 76x 9x 9x 9x 71x 1x 1x 1x 62x 9x 9x 9x 61x 2x 2x 2x 52x 27x 27x 27x 50x 6x 6x 6x 23x 12x 12x 12x 17x 4x 4x 4x 5x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   212x 2x 2x 2x 2x 1x 93x         91x 4x 4x 4x 91x 2x 2x 87x 18x 18x 85x 3x 3x 67x 14x 14x         14x 14x 64x 13x 13x         13x 13x 50x 6x         6x 6x 37x 17x 17x 31x 14x 12x 12x 12x 12x 12x 14x 14x 94x 94x 5138x 26x 26x 26x 26x 5138x 47x 47x 47x 47x 47x 5138x 13x 13x 13x 13x 13x 13x 5138x 36x 36x 36x 36x 36x 36x 5138x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 2x 2x 2x 2x 2x 5138x 49x 49x 49x 49x 5138x 22x 22x 22x 22x 5138x 30x 30x 30x 30x 5138x 17x 17x 17x 17x 5138x 3x 3x 3x 3x 5138x 25x 25x 25x 25x 5138x 13x 13x 13x 13x 5138x 2x 2x 2x 2x 5138x 35x 35x 35x 35x 5138x 11x 11x 11x 11x 5138x 4x 4x 4x 4x 5138x 94x 94x 94x 94x 94x 94x 5138x 21x 21x 21x 21x 21x 5138x 28x 28x 28x 28x 5138x                   5138x                       5138x                           5138x                   5138x                                           5138x 27x 27x 27x 27x 27x 27x 27x 27x 14x 14x 26x 13x 13x 13x 27x 27x 27x 5138x 49x 49x 49x 49x 49x 5138x 5138x 5138x 5138x 18x 18x 18x 13x 13x 18x 18x 18x 18x 18x 18x 18x 10x 10x 10x 10x 10x 1x 1x 1x 1x 10x 10x 10x 9x 9x 9x 9x 9x 10x 10x 10x 8x 8x 10x 18x 4x 18x 18x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 18x 8x 8x 8x 8x 8x 8x 5138x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x             4x 5x 1x 1x 5x 5x 5138x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5138x 13x 13x 13x 13x 13x 13x 13x 13x 13x 3x 12x 1x 1x 1x 1x 1x 1x         10x 9x 9x 9x 13x 13x 13x 5138x 7x 7x 7x 6x 6x 5138x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x     1x 1x 5138x         5138x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 210x 210x 14x 14x 14x 14x 14x 1x 14x 1x 13x 1x 12x 1x 11x 1x 10x 2x 9x 1x 7x   6x 1x 1x 1x 1x 6x 1x 5x   4x 1x 4x 1x 1x 1x 1x 3x 1x 1x 1x 1x 14x 14x 5138x 12x 12x 12x 12x 12x 5138x 1x 1x 1x 1x 5138x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 24x 11544x 11544x 938x 938x 938x 11544x 11544x 581x 581x 85x 85x 24x 118x 118x 118x 118x 118x 24x 24x 11x 24x 85x 85x 85x 85x 85x 81x 64x 61x 59x 85x 85x 85x 85x 11x 2x     2x 2x 1x 1x 1x 5138x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 11x 13x 13x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5138x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 11x 13x 13x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5138x 3x 3x 3x 3x 3x 5138x 3x 3x 3x 3x 3x 5138x 7x 7x 7x 7x 7x 5138x 9x 9x 9x 9x 9x 5138x 36x 36x 36x 36x 5138x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 5138x 1805x 1805x 1805x 1805x 4967x 893x 893x 893x 457x 457x 457x 893x 893x 5088x 912x 912x 912x 912x 912x 912x 5138x 73x 73x 73x 922x 922x 922x 922x 922x 922x 922x 922x 922x 922x 922x 922x 922x 10x 10x 10x 922x 922x 922x 73x 73x 15x 15x 15x 15x 15x 2x 2x 2x 15x 73x 73x 4924x 4924x 4924x 4924x 4924x 4924x 4924x 9848x 9848x 9848x 9848x 9848x 9848x 9788x 9788x 9788x 9833x 4924x 4924x 4924x 4924x 4924x 4924x 4924x 4924x 4924x 4924x 4924x 4924x 4924x 4924x 4924x 4924x     4924x 4924x 4924x 4924x 4924x 15x 15x 15x 15x 15x         15x 15x 15x 15x 15x 15x 4909x 4924x 73x 73x 73x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 7x 7x 7x 7x   7x 7x 7x 7x 7x 7x 7x 7x 1x 1x   1x 1x 1x 1x 1x 1x 7x 7x 21x 10x 10x     10x 10x 21x 4x 4x         4x 3x 3x 3x   3x 3x 3x 3x 4x 1x   1x 1x 1x 1x 4x 21x                                                 21x 21x                                                                                           21x   21x 21x 21x 73x 73x 5160x 5160x 5160x 5160x 5160x 72x 5160x 5160x 11x 5x 5x 11x 6x 6x 11x 11x 11x 5149x 5160x 73x 73x 73x 73x 73x 73x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5158x 5158x 5158x 5160x 1995x 1995x 1995x 1995x 5160x 5160x 5160x 5160x 5160x 2861x 2861x 2861x 5160x 5158x 5158x 5160x 2298x 335x 335x 335x 335x           335x 2298x 5160x 73x 73x 73x 73x 73x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 5160x 1122x 1122x 13x 13x 1122x 1122x 5160x 5160x 5160x 11x 11x 5149x 5149x 5149x 5149x 5149x 5149x 5160x 8x 8x 17x       17x 17x 17x 8x 8x 5149x 5160x 9x 9x 9x 9x 9x 5160x 1x 1x 5139x 5160x 133x 133x 133x 133x 133x 133x     133x 133x 133x 133x 133x 133x 133x 5139x 5139x 5160x 117x 117x 117x 117x 117x 2x 2x 2x 117x 2x 2x 2x 2x 2x 117x 5137x 5160x 180x 180x 180x 180x 180x 180x 120x 120x 120x 120x 59x 59x 5160x 4957x 4957x 4957x 4957x 4957x 4957x 4957x 4957x 9x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 4948x 4948x 4957x 4948x 4948x 4948x 4948x 4948x 4x 4x 4x 4x 3x 3x 3x 3x 3x 4x 4948x 4945x 4957x 21x 21x 5x 5x 5x 21x 21x 4924x 4957x 15x 15x 15x 15x 15x 4909x 4909x 4957x 828x 776x 776x 776x 776x 828x 828x 4081x 4081x 4081x 4081x 4081x 4081x 4957x 4957x 4957x 4957x 4957x 71x 71x 4948x 96x 96x 96x 4081x 4081x 4080x 4948x 37x 37x 37x 37x 37x 4080x 4080x 4080x 4080x 4957x 1995x 1995x 5160x 5160x 5160x 73x 73x 5140x 5140x 5140x 5138x 5138x 2x 2x 647x   647x       2x 2x 2x         2x 2x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 2x 2x 1x 5140x 73x 73x 73x 73x 73x 73x 73x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x         59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 59x 73x 73x 73x 73x 73x 13x 13x 13x 13x 13x 13x 13x 13x 1x 1x 13x 13x 13x 13x 13x 4x 4x 4x     4x 13x 13x 13x 13x 13x 308x         308x 13x 13x 13x 13x 13x 13x 13x               13x 13x 13x 13x 13x 13x 13x 13x 6x 6x 13x 73x 73x 73x 73x 73x 73x 73x 73x 73x 697x 697x 697x 697x 697x 697x 697x 697x 697x 697x 697x 697x 697x 697x 2091x 6273x 6273x 5546x 5546x 6273x 5546x 6273x 39x 7x 7x 7x 7x 7x 7x 7x 6273x 3x 2x 2x 2x 2x 2x 2x 2x 5507x 5504x 5504x 3116x 3116x 43x 43x     43x 3116x 5504x 5504x 5504x 1x 1x         1x 1x 1x 1x 5504x 6273x 6273x 2091x 697x 697x 697x 73x 73x 511x 511x 511x 511x 114x 114x 511x 511x 73x 73x 73x 73x 73x 73x 190x 190x 190x 190x 190x 190x 184x 184x 190x 190x 190x 190x 73x 73x 73x 73x 73x 74x 74x 74x 25x 25x 73x 49x 49x 74x 74x 74x 74x 74x 73x 73x 73x 73x 73x 73x 73x 73x 73x 28x 28x 1x 1x 1x 27x 27x 28x 2x 2x 25x 26x 4x 4x 28x 73x 73x 73x 73x 73x 1579x 1579x 1568x 1568x 1568x 1568x 1568x 1579x 1490x 1490x 1568x 1568x 1579x 73x 73x 73x 73x 165x 165x 165x 165x 165x 165x 165x 165x 162x 162x 162x 165x 165x 14x 14x 14x 14x 164x       159x 2x 2x 2x 146x 146x 147x 135x 135x 135x 135x 135x 135x 11x 11x 11x 11x 11x 11x 11x 11x 165x 8x 8x 8x 8x 8x 8x 8x 8x     8x 11x 11x 165x 73x 73x 73x 73x 73x 73x 170x 170x 17x 17x 17x 17x 17x 170x 73x 73x 72x 72x  
// cmd.js — Command dispatch (port of cmd.c)
// rhack() dispatches player keystrokes to command functions.
// For basic movement (hjklyubn), dispatches to domove().
 
import { game } from './gstate.js';
import { TELEPORT_BUILD_DATE } from './version.js';
import { doengrave } from './engrave.js';
import { ShellEscape, GameQuit, GameInterrupt } from './signals.js';
import { itemactions } from './iactions.js';
import { cmdq_add_key, cmdq_clear, cmdq_pop, getCount, nhgetch, more, ynFunction, getlin } from './input.js';
import { pushRngLogEntry, pushCtxMoveLog, pushMultiLog, rn2, rnd, rn2_raw, rne, rnl } from './rng.js';
import { bot, canspotmon, cls, curs_on_u, delay_output, docorner, docrt, erase_menu_or_text, feel_location, feel_newsym, flush_screen, mon_visible, newsym, NHW_TEXT, recalc_block_point, render_screen_output_to_display, rendered_ch, sensemon, setBotl, setBotlx, status_initialize, tty_clear_nhwindow, tty_create_nhwindow, tty_destroy_nhwindow, tty_dismiss_nhwindow, unblock_point, unmap_object } from './display.js';
import { assertNotInModal, enterModal, exitModal } from './modal_guard.js';
import { A_CHA, A_CHAOTIC, A_CON, A_DEX, A_INT, A_LAWFUL, A_NEUTRAL, A_STR, A_WIS, ALTAR, AUTOUNLOCK_APPLY_KEY, CMDQ_EXTCMD, CMDQ_KEY, COLNO, CORR, CQ_CANNED, CQ_REPEAT, D_BROKEN, D_CLOSED, D_ISOPEN, D_LOCKED, D_NODOOR, DO_MOVE, DOMOVE_RUSH, DOMOVE_WALK, DOOR, ECMD_TIME, FOUNTAIN, GRAVE, IS_DOOR, IS_FURNITURE, IS_OBSTRUCTED, IS_WALL, IS_WATERWALL, is_hole, is_pit, isok, LAVAPOOL, LAVAWALL, M_AP_FURNITURE, M_AP_OBJECT, MENU_ITEMFLAGS_SELECTED, MENU_ITEMFLAGS_SKIPINVERT, N_DIRS, NHW_MENU, OBJ_AT, OVERLOADED, PARANOID_SWIM, PARANOID_TRAP, PICK_ANY, PICK_ONE, POOL, P_BASIC, P_EXPERT, P_GRAND_MASTER, P_ISRESTRICTED, P_MASTER, P_NONE, P_SKILLED, P_UNSKILLED, ROOM, ROWNO, RUN_CRAWL, RUN_LEAP, RUN_TPORT, SCORR, SDOOR, SINK, SLT_ENCUMBER, STAIRS, STATUE_TRAP, STONE, TELEDS_TELEPORT, TELEP_TRAP, TER_MAP, TER_OBJ, TER_TRP, TEST_MOVE, THRONE, TIP_SWIM, TOPLINE_EMPTY, TOPLINE_NEED_MORE, TOPLINE_NON_EMPTY, TOPLINE_SPECIAL_PROMPT, TRAVP_GUESS, TRAVP_TRAVEL, TT_BEARTRAP, TT_BURIEDBALL, TT_INFLOOR, TT_LAVA, TT_PIT, TT_WEB, W_ARM, W_ARMC, W_ARMF, W_ARMG, W_ARMH, W_ARMS, W_ARMU, WATER, WEB, WT_SQUEEZABLE_INV, W_SADDLE, W_SWAPWEP, W_TOOL, W_WEP, WAND_WREST_CHANCE, xdir, ydir } from './const.js';
import { next_ident, obj_extract_self, place_object, remove_object, sobj_at } from './mkobj.js';
import { goto_level } from './allmain.js';
import { AT_WEAP, mons } from './monsters.js';
import { dodrink, dodip } from './potion.js';
import { dozap } from './zap.js';
import { find_roll_to_hit, passive, do_attack } from './uhitm.js';
import { Blind, Confusion, Conflict, Fire_resistance, Flying, Hallucination, Is_airlevel, Levitation, Passes_walls, Punished, Stunned, Underwater, Upolyd, u_locomotion } from './macros.js';
import { read_engr_at } from './engrave.js';
import { bad_rock, end_running, findtravelpath, helpless, is_safemon, maybe_smudge_engr, money_cnt, mundisplaceable, NODIAG, spoteffects, test_move, u_maybe_impaired } from './hack.js';
import { dokick } from './dokick.js';
import { vision_recalc } from './vision.js';
import { dotakeoff, doputon, doremring, dowear } from './do_wear.js';
import { ACURR, exercise } from './attrib.js';
import { an, doname, doname_with_price, makeplural, the, xname } from './objnam.js';
import { ATR_INVERSE, NO_COLOR } from './terminal.js';
import { is_lava, is_pool } from './dbridge.js';
import { m_at, t_at } from './map_access.js';
import { WEAPON_CLASS, ARMOR_CLASS, RING_CLASS, AMULET_CLASS, TOOL_CLASS, FOOD_CLASS, POTION_CLASS, SCROLL_CLASS, SPBOOK_CLASS, WAND_CLASS, COIN_CLASS, GEM_CLASS, BULLWHIP, LEASH, LENSES, POT_OIL, CREAM_PIE, EUCALYPTUS_LEAF, LUMP_OF_ROYAL_JELLY, MAGIC_MARKER, TOUCHSTONE, NODIR, WAN_STASIS, BOULDER, WATER_WALKING_BOOTS, is_ammo } from './objects.js';
import { dotwoweapon, dowield, doswapweapon, setuqwep, setuswapwep, setuwep } from './wield.js';
import { enhance_weapon_skill, P_SKILL, skill_name, weapon_type } from './weapon.js';
import { doeat, is_edible } from './eat.js';
import { dothrow, dofire } from './dothrow.js';
import { You, You_cant, custompline, pline, pline_The, set_msg_xy, There, get_message_history } from './pline.js';
import { docast, dovspell } from './spell.js';
import { wiz_genesis, wiz_intrinsic, wiz_level_change, wiz_level_tele, wiz_map, wiz_wish } from './wizcmds.js';
import { dopray, dosacrifice, doturn } from './pray.js';
import { dosit } from './sit.js';
import { check_leash, doapply, dorub } from './apply.js';
import { doclose, doforce, doopen } from './lock.js';
// import { doread } from './read.js'; // TODO: wire when getobj events fixed (#265)
import { dodrop, dowipe, cmd_safety_prevention, Norep } from './do.js';
import { doloot, dopickup, inv_weight, near_capacity, pickup, weight_cap } from './pickup.js';
import { dojump } from './apply.js';
import { add_menu, add_menu_heading, add_menu_str, create_nhwindow_menu, destroy_nhwindow_menu, end_menu, select_menu, start_menu } from './menu.js';
import { getpos } from './getpos.js';
import { m_next2u, set_ustuck, y_monnam } from './mon.js';
import { doride, place_monster, remove_monster_steed } from './steed.js';
import { addinv, currency, getobj, let_to_name, display_inventory, doorganize } from './invent.js';
import { doread } from './read.js';
import { dopay } from './shk.js';
import { dowhatis, doquickwhatis, dowhatdoes, docontact, waterbody_name } from './pager.js';
import { dist2, ing_suffix, surface, upstart } from './hacklib.js';
import { cvt_sdoor_to_door, find_trap, mfind0, reveal_terrain } from './detect.js';
import { activate_statue_trap, climb_pit, into_vs_onto, reset_utrap, trapname } from './trap.js';
import { is_hider, noattacks, sticks, throws_rocks } from './mondata.js';
import { grounded } from './mondata.js';
import { docallcmd, hliquid } from './do_name.js';
import { align_gname } from './pray.js';
import { buried_ball, buried_ball_to_punishment } from './dig.js';
import { drag_ball, move_bc } from './ball.js';
import { retouch_object, u_wield_art } from './artifact.js';
import { ART_STING } from './artifacts.js';
import { onscary } from './monmove.js';
import { dotele } from './teleport.js';
import { dotalk } from './sounds.js';
import { domonability, dopolyself } from './polyself.js';
import { applyOptions, parseoption } from './options.js';
import { def_char_to_objclass } from './drawing.js';
import { def_oc_syms } from './symbols.js';
 
function cmdSkillLevelNameFromValue(sklvl) {
    switch (sklvl) {
    case P_UNSKILLED: return 'Unskilled';
    case P_BASIC: return 'Basic';
    case P_SKILLED: return 'Skilled';
    case P_EXPERT: return 'Expert';
    case P_MASTER: return 'Master';
    case P_GRAND_MASTER: return 'Grand Master';
    default: return '(unknown)';
    }
}
 
// Simple object name for "You see here..." messages.
// C ref: objnam.c doname(obj) → xname + article
function simple_obj_name(obj) {
    if (!obj) return 'an object';
    const od = game.objects[obj.otyp];
    // Corpse: "a <monster> corpse" (xname doesn't handle corpsenm yet)
    if (od?.oc_name === 'corpse' && obj.corpsenm != null && obj.corpsenm >= 0) {
        const mdata = mons[obj.corpsenm];
        if (mdata) return `a ${mdata.mname} corpse`;
    }
    // Gold: xname handles quantity but not the "piece" wording
    if (od?.oc_class === COIN_CLASS) {
        const qty = obj.quan || 1;
        return qty === 1 ? '1 gold piece' : `${qty} gold pieces`;
    }
    // C ref: doname(obj) — xname handles description + pluralization
    const name = xname(obj);
    const qty = obj.quan || 1;
    if (qty > 1) return `${qty} ${name}`;
    const vowelSet = 'aeiou';
    const article = vowelSet.includes(name[0]?.toLowerCase()) ? 'an' : 'a';
    return `${article} ${name}`;
}
 
export function find_inventory_obj_by_letter(letter) {
    const ch = typeof letter === 'number' ? String.fromCharCode(letter) : letter;
    for (let obj = game.invent; obj; obj = obj.nobj) {
        if (obj.invlet === ch) return obj;
    }
    return null;
}
 
// C ref: cmd.c extcmdlist[] — entries with the AUTOCOMPLETE flag. Only
// these are considered by ext_cmd_getlin_hook during typing to extend
// the prompt when a prefix is unique. Non-AUTOCOMPLETE commands (shell,
// twoweapon, pay, pickup, perminv, ...) still dispatch — but only on an
// exact full-name match after Enter (ECM_IGNOREAC at dispatch time).
const BASE_EXTCMDS = [
    '?', 'adjust', 'annotate', 'chat', 'chronicle', 'conduct', 'dip',
    'enhance', 'force', 'genocided', 'herecmdmenu', 'invoke', 'jump', 'loot', 'monster',
    'name', 'offer', 'overview', 'pray',
    'quit', 'ride', 'rub', 'sit',
    'terrain', 'therecmdmenu', 'tip', 'turn', 'untrap', 'vanquished', 'version', 'wipe',
];
// Non-AUTOCOMPLETE user-facing extcmds: dispatch-only, not in the hook's
// match list. Typing '#shell' or '#twoweapon' requires the full name.
const NON_AUTOCOMPLETE_EXTCMDS = ['shell', 'twoweapon'];
// C ref: WIZMODECMD autocomplete entries — only in wizard/debug mode
const WIZ_EXTCMDS = [
    'levelchange', 'lightsources', 'migratemons', 'panic', 'polyself', 'seenv',
    'stats', 'timeout', 'vision', 'where',
    'wizmap',
    'wizbury', 'wizdispmacros', 'wizintrinsic', 'wizkill', 'wizmondiff',
    'wizrumorcheck', 'wizseenv', 'wizsmell', 'wiztelekinesis', 'wizwhere',
    'wizwish',
    'wmode',
];
function getAutocompleteExtcmds() {
    const cmds = [...BASE_EXTCMDS];
    if (game.flags?.debug) cmds.push(...WIZ_EXTCMDS);
    return cmds.sort();
}
// Full dispatch-time list (AUTOCOMPLETE + non-AUTOCOMPLETE user extcmds).
// C ref: tty_get_ext_cmd uses ECM_IGNOREAC | ECM_EXACTMATCH so the full
// name matches any user-facing extcmd, autocomplete or not.
function getAllDispatchExtcmds() {
    const cmds = [...BASE_EXTCMDS, ...NON_AUTOCOMPLETE_EXTCMDS];
    if (game.flags?.debug) cmds.push(...WIZ_EXTCMDS);
    return cmds.sort();
}
 
function extcmdAutocomplete(prefix) {
    const normalized = String(prefix || '').toLowerCase();
    if (!normalized) return '';
    const cmds = getAutocompleteExtcmds();
    const matches = cmds.filter((cmd) => cmd.startsWith(normalized));
    return matches.length === 1 ? matches[0] : normalized;
}
 
// C ref: cmd.c:1766-1861 doterrain()
async function doterrain_cmd() {
    const men = create_nhwindow_menu();
    start_menu(men);
    add_menu(men, 1, 0, 0, 0, NO_COLOR,
        'known map without monsters, objects, and traps',
        MENU_ITEMFLAGS_SELECTED);
    add_menu(men, 2, 0, 0, 0, NO_COLOR,
        'known map without monsters and objects',
        0);
    add_menu(men, 3, 0, 0, 0, NO_COLOR,
        'known map without monsters',
        0);
    end_menu(men, 'View which?');
    const picked = await select_menu(men, PICK_ONE);
    destroy_nhwindow_menu(men);
    const which = Number(picked?.items?.[0]?.identifier || 0);
    if (which === 1) {
        await reveal_terrain(TER_MAP);
    } else if (which === 2) {
        await reveal_terrain(TER_MAP | TER_TRP);
    } else if (which === 3) {
        await reveal_terrain(TER_MAP | TER_TRP | TER_OBJ);
    }
    return 0;
}
 
const GETPOS_TIP_LINES = [
    'Tip: Farlooking or selecting a map location',
    '',
    'You are now in a "farlook" mode - the movement keys move the cursor,',
    'not your character.  Game time does not advance.  This mode is used',
    'to look around the map, or to select a location on it.',
    '',
    'When in this mode, you can press ESC to return to normal game mode,',
    'and pressing ? will show the key help.',
    '(end)',
];
 
const GETPOS_PROMPT_LINE = "(For instructions type a '?')  Move cursor to the desired destination:";
 
async function renderGetposTip(display) {
    if (!display?.grid) return;
    const rows = display.rows || 24;
    const cols = display.cols || 80;
    const maxWidth = GETPOS_TIP_LINES.reduce((m, line) => Math.max(m, line.length), 0);
    const offx = Math.max(0, cols - maxWidth - 3);
    const startCol = offx + 1;
    const maxrow = Math.min(GETPOS_TIP_LINES.length, rows - 1);
    for (let row = 0; row <= maxrow; row++) {
        display.clearRow(row);
    }
    if (!Number.isInteger(game._getpos_tip_win)) {
        const tipwin = tty_create_nhwindow(NHW_MENU);
        if (tipwin >= 0 && game.wins[tipwin]) game.wins[tipwin].active = true;
        game._getpos_tip_win = tipwin;
    }
    for (let row = 0; row < GETPOS_TIP_LINES.length; row++) {
        const line = GETPOS_TIP_LINES[row];
        if (!line) continue;
        display.putstr(startCol, row, line);
    }
    if (typeof display.setCursor === 'function') {
        display.setCursor(startCol + '(end)'.length + 1, Math.max(0, maxrow - 1));
    }
    game._getpos_tip_offx = offx;
    game._getpos_tip_maxrow = maxrow;
    game._menuActive = true;
}
 
async function dismissGetposTipWindow() {
    const tipwin = game._getpos_tip_win;
    if (!Number.isInteger(tipwin) || tipwin < 0) return;
    const offx = Number.isInteger(game._getpos_tip_offx) ? game._getpos_tip_offx : 0;
    const maxrow = Number.isInteger(game._getpos_tip_maxrow)
        ? game._getpos_tip_maxrow
        : GETPOS_TIP_LINES.length;
    tty_destroy_nhwindow(tipwin);
    erase_menu_or_text(tipwin, offx, maxrow);
    await docorner(offx, maxrow + 1);
    game._getpos_tip_win = null;
    game._getpos_tip_offx = null;
    game._getpos_tip_maxrow = null;
    game._menuActive = false;
}
 
async function restoreGetposPrompt(display) {
    game.iflags.getloc_tip_active = false;
    game._pending_message = '';
    if (!display?.grid || !game.level) return;
    await dismissGetposTipWindow();
    // C ref: getpos() calls two plines that get concatenated by update_topl
    await pline("(For instructions type a '?')");
    await pline('Move cursor to the desired destination:');
    if (typeof display.setCursor === 'function' && game.u) {
        display.setCursor(game.u.ux - 1, game.u.uy + 1);
    }
}
 
async function dismissGetposOverlay(display) {
    game._menuActive = false;
    game.iflags.getloc_travelmode = false;
    game.iflags.getloc_tip_active = false;
    game._pending_message = '';
    await dismissGetposTipWindow();
    if (!display?.grid || !game.level) return;
    await docrt(false, true);
    render_screen_output_to_display(display);
}
 
async function dotravel_target() {
    const g = game;
    if (!g.iflags.travelcc) g.iflags.travelcc = { x: 0, y: 0 };
    const tx = g.iflags?.travelcc?.x ?? 0;
    const ty = g.iflags?.travelcc?.y ?? 0;
 
    if (!isok(tx, ty)) {
        g.iflags.getloc_travelmode = false;
        g.iflags.getloc_tip_active = false;
        await pline('No travel destination set.');
        return 0;
    } else if (g.u && g.u.ux === tx && g.u.uy === ty) {
        g.iflags.getloc_travelmode = false;
        g.iflags.getloc_tip_active = false;
        await You('are already here.');
        g.iflags.travelcc.x = 0;
        g.iflags.travelcc.y = 0;
        return 0;
    }
 
    g.iflags.getloc_travelmode = false;
    g.context.travel = 1;
    g.context.travel1 = 1;
    g.context.run = 8;
    g.context.nopick = 1;
    g.domove_attempting |= DOMOVE_RUSH;
 
    if (!g.multi) {
        g.multi = Math.max(COLNO, ROWNO);
        pushMultiLog('dotravel_target', g.multi);
    }
    g.u.last_str_turn = 0;
    g.context.mv = true;
 
    await domove();
    return ECMD_TIME;
}
 
async function dotravel_cmd() {
    const g = game;
    if (!g.iflags.travelcc) g.iflags.travelcc = { x: 0, y: 0 };
    const cc = {
        x: g.iflags?.travelcc?.x ?? 0,
        y: g.iflags?.travelcc?.y ?? 0,
    };
 
    if (cc.x === 0 && cc.y === 0) {
        cc.x = g.u.ux;
        cc.y = g.u.uy;
    }
 
    g.iflags.getloc_travelmode = true;
    await pline('Where do you want to travel to?');
    if ((await getpos(cc, true, 'the desired destination')) < 0) {
        g.iflags.getloc_travelmode = false;
        return 0;
    }
 
    g.iflags.travelcc.x = g.u.tx = cc.x;
    g.iflags.travelcc.y = g.u.ty = cc.y;
    return await dotravel_target();
}
 
async function finishHeroMove(newx, newy) {
    // C ref: hack.c domove_core() common moved-hero tail.
    // After the hero position changes, C recomputes visibility before
    // spoteffects() can enter a message-owned --More-- boundary.
    // C uses vision_recalc(1) for hero-moved updates.
    // C ref: hack.c:2982 — newsym old position before vision update
    newsym(game.u.ux0, game.u.uy0);
    vision_recalc(1);
    // invocation_message() — empty stub, no-op
    {
        // C ref: hack.c domove_core() uses flush_screen for display update.
        // In browser mode: full docrt + grid render.
        // In headless mode: newsym the hero's old and new positions so that
        // the gbuf render cell reflects the movement (C's show_glyph writes
        // to the terminal buffer during domove, so the buffer is always current).
        const display = game?.nhDisplay || null;
        const holdPromptFrame = !!(display?.grid && display.toplin === TOPLINE_NEED_MORE);
        if (display?.grid) {
            await docrt(false, true);
            if (!holdPromptFrame) {
                render_screen_output_to_display(display);
            }
        } else {
            // Headless: update gbuf render cell for hero old/new positions
            const u = game.u;
            if (u.ux0 != null && u.uy0 != null) newsym(u.ux0, u.uy0);
            newsym(newx, newy);
        }
    }
 
    // C ref: hack.c domove_core → spoteffects(TRUE)
    // spoteffects handles switch_terrain, check_special_room, autopickup,
    // check_here (look_here), traps (including teleport), and engravings.
    game.u.umoved = true;
    await spoteffects(true);
}
 
// C ref: win/tty/getline.c tty_get_ext_cmd() calls mungspaces() after getlin.
function normalizeExtcmdInput(raw) {
    return String(raw || '').replace(/\s+/g, ' ').trim().toLowerCase();
}
 
async function unlink_inventory_obj(obj) {
    if (!obj) return false;
    let prev = null;
    for (let cur = game.invent; cur; prev = cur, cur = cur.nobj) {
        if (cur !== obj) continue;
        if (prev) prev.nobj = cur.nobj || null;
        else game.invent = cur.nobj || null;
        cur.nobj = null;
        cur.where = 0;
        if (game.u.uwep === cur) await setuwep(null);
        if (game.u.uquiver === cur) setuqwep(null);
        if (game.u.uswapwep === cur) setuswapwep(null);
        return true;
    }
    return false;
}
 
function find_floor_object_at(x, y) {
    for (const obj of (game.level?.objects || [])) {
        if (obj?.where === 1 && obj.ox === x && obj.oy === y) return obj;
    }
    return null;
}
 
function direction_from_key(dirKey) {
    const key = typeof dirKey === 'number' ? String.fromCharCode(dirKey) : dirKey;
    const dirMap = {
        h: [-1, 0], j: [0, 1], k: [0, -1], l: [1, 0],
        y: [-1, -1], u: [1, -1], b: [-1, 1], n: [1, 1],
    };
    return dirMap[key] || null;
}
 
function is_getdir_special_key(dirKey) {
    const key = typeof dirKey === 'number' ? String.fromCharCode(dirKey) : String(dirKey || '');
    return key === '.' || key === 's' || key === '<' || key === '>';
}
 
async function read_direction_like_getdir(prompt = 'In what direction?') {
    const dirKey = await prompt_inventory_char(prompt, 'dir-prompt');
    if (dirKey === 27) {
        // C ref: cmd.c:4617 — ESC clears direction
        game.u.dx = game.u.dy = game.u.dz = 0;
        return { ok: false, canceled: true, dirKey };
    }
    const dir = direction_from_key(dirKey);
    if (dir) {
        // C ref: cmd.c:4485-4487 — set u.dx/u.dy/u.dz from direction
        game.u.dx = dir[0];
        game.u.dy = dir[1];
        game.u.dz = 0;
        return { ok: true, canceled: false, dirKey };
    }
    if (is_getdir_special_key(dirKey)) {
        // C ref: cmd.c:4490 — special keys (., <, >)
        const key = typeof dirKey === 'number' ? String.fromCharCode(dirKey) : String(dirKey || '');
        game.u.dx = 0;
        game.u.dy = 0;
        game.u.dz = (key === '<') ? -1 : (key === '>') ? 1 : 0;
        return { ok: true, canceled: false, dirKey };
    }
    // C ref: cmd.c:4689 — invalid direction in getdir
    const sym = typeof dirKey === 'number' ? String.fromCharCode(dirKey) : String(dirKey || '');
    if (sym !== '\x1b' && sym !== ' ' && sym !== '\n' && sym !== 'q') {
        if (game.iflags?.cmdassist) {
            await help_dir('\0', 'Invalid direction key!');
        } else {
            await pline('What a strange direction!');
        }
    }
    return { ok: false, canceled: false, dirKey };
}
 
// C ref: cmd.c:4765 help_dir() — display direction help as NHW_TEXT window
// Creates a text window with cmdassist content, displays it, waits for
// user to dismiss, then restores the game screen via docrt+flush_screen.
async function help_dir(sym, msg) {
    const lines = [];
    if (msg) {
        lines.push(`cmdassist: ${msg}`);
        lines.push('');
    }
    // C ref: cmd.c:4858 — direction key diagram
    // Non-numpad, diagonal movement allowed (NODIAG not checked)
    lines.push('Valid direction keys are:');
    lines.push('          y  k  u');
    lines.push('           \\ | / ');
    lines.push('          h- . -l');
    lines.push('           / | \\ ');
    lines.push('          b  j  n');
    lines.push('');
    lines.push('          <  up');
    lines.push('          >  down');
    lines.push('          .  direct at yourself');
    if (msg) {
        lines.push('');
        lines.push('(Suppress this message with !cmdassist in config file.)');
    }
    await display_text_window(lines);
    return true;
}
 
// C ref: wintty.c tty_display_nhwindow(NHW_TEXT) + process_text_window + erase_menu_or_text
// Renders text lines to the terminal grid, waits for dismiss key (space/enter/esc),
// then restores the game screen via docrt + flush_screen.
// With H2344_BROKEN, text windows are non-fullscreen overlays for small content.
// The dismiss path: erase_menu_or_text → docrt() → cls() → flush_screen(1).
export async function display_text_window(lines) {
    const display = game?.nhDisplay || null;
    // C ref: create_nhwindow(NHW_TEXT) + display_nhwindow + destroy_nhwindow
    const textWin = tty_create_nhwindow(NHW_TEXT);
    if (game.wins[textWin]) game.wins[textWin].active = true;
 
    // Render text to terminal grid
    // C ref: process_text_window renders lines, then dmore(quitchars) at the end
    if (display) {
        const rows = display.rows || 24;
        const cols = display.cols || 80;
        // Clear the display area (non-fullscreen: overlay from top)
        for (let r = 0; r < rows; r++) {
            if (typeof display.clearRow === 'function') display.clearRow(r);
        }
        // Render text lines
        for (let i = 0; i < lines.length && i < rows - 1; i++) {
            const line = lines[i].slice(0, cols);
            if (typeof display.putstr === 'function') {
                display.putstr(0, i, line);
            } else if (typeof display.setCell === 'function') {
                for (let j = 0; j < line.length; j++) {
                    display.setCell(j, i, line[j], 7/*CLR_GRAY*/, 0);
                }
            }
        }
        // Show "(end)" prompt at the bottom of text
        // C ref: dmore() in process_text_window — shows morestr at end
        const endLine = rows - 1;
        const endStr = '--More--';
        if (typeof display.putstr === 'function') {
            display.putstr(0, endLine, endStr);
        } else if (typeof display.setCell === 'function') {
            for (let j = 0; j < endStr.length; j++) {
                display.setCell(j, endLine, endStr[j], 7, 0);
            }
        }
        if (typeof display.setCursor === 'function') {
            display.setCursor(endStr.length, endLine);
        }
    }
    // Keep overlay contents stable at nhgetch capture boundaries while this
    // modal text window owns input.
    game._menuActive = true;
 
    // C ref: dmore → xwaitforspace(quitchars)
    // Wait for dismiss key: space, enter, or ESC
    // Keys that aren't quit chars are silently consumed (with nhbell in C)
    enterModal('text-window');
    try {
        while (true) {
            const ch = await nhgetch();
            if (ch === 32 || ch === 13 || ch === 10 || ch === 27) break;
            // C: tty_nhbell() for invalid key — silently ignore in JS
        }
    } finally {
        exitModal('text-window');
    }
 
    // C ref: destroy_nhwindow → tty_dismiss_nhwindow → erase_menu_or_text
    // For fullscreen text windows (offx=0), C's erase_menu_or_text calls
    // docrt which chains: cls → display_nhwindow(WIN_MESSAGE) + SET_BOTLX +
    // clear_nhwindow(WIN_MAP) → term_clear_screen → erase_tty_screen
    {
        // C ref: tty_destroy_nhwindow → tty_dismiss_nhwindow (if active)
        // Dismiss first (emits event), but keep the slot occupied so
        // subsequent window allocations get the correct IDs.
        tty_dismiss_nhwindow(textWin);
        // C: erase_menu_or_text for fullscreen (offx=0) text window
        erase_menu_or_text(textWin, 0, lines.length);
        // NOW free the slot (matching C's destroy timing)
        if (textWin >= 0 && game.wins[textWin]) game.wins[textWin] = null;
    }
    game._menuActive = false;
    // C: cls() → display_nhwindow(WIN_MESSAGE) + SET_BOTLX + clear_nhwindow(WIN_MAP)
    await cls();
    setBotlx('docrt_flags');
    // C: docrt() repaints the map after cls. JS's docrt_cls + docrt
    // handles the newsym loop to set gnew on all map cells.
    await docrt(false, true);
    await flush_screen(1);
    // Note: this produces the exact C event sequence for text window
    // dismiss. The RNG regression at dog_goal position 2369 is a
    // pre-existing hero position drift bug (issue #214) that was
    // previously masked by more() consuming extra keys due to the
    // missing '\n' accept (more() only accepted CR, not LF).
    // Cardinal Rule 4: don't revert C-faithful fixes for regressions.
}
 
// C ref: wintty.c process_text_window() paging behavior for NHW_TEXT.
// Renders a multi-page text window with --More-- at the bottom:
// Space/Enter => next page, ESC => exit early.
async function display_text_window_pages(lines, options = {}) {
    const display = game?.nhDisplay || null;
    const textWin = tty_create_nhwindow(NHW_TEXT);
    if (game.wins[textWin]) game.wins[textWin].active = true;
    const rows = display?.rows || 24;
    const cols = display?.cols || 80;
    const pageRows = Math.max(1, rows - 1);
    let start = 0;
    let shownRows = 0;
 
    game._menuActive = true;
    enterModal('text-window');
    try {
        while (true) {
            shownRows = 0;
            if (display) {
                for (let r = 0; r < rows; r++) {
                    if (typeof display.clearRow === 'function') display.clearRow(r);
                }
                for (let i = 0; i < pageRows; i++) {
                    const line = lines[start + i];
                    if (line == null) break;
                    shownRows++;
                    if (typeof display.putstr === 'function') {
                        // Convert ANSI cursor-forward \x1b[NC to N spaces
                        const expanded = String(line).replace(/\x1b\[(\d+)C/g,
                            (_, n) => ' '.repeat(parseInt(n)));
                        display.putstr(0, i, expanded.slice(0, cols));
                    }
                }
                const endLine = rows - 1;
                const endStr = '--More--';
                if (typeof display.putstr === 'function') {
                    display.putstr(0, endLine, endStr);
                }
                if (typeof display.setCursor === 'function') {
                    display.setCursor(endStr.length, endLine);
                }
            }
 
            const ch = await nhgetch();
            if (ch === 27) break;
            if (ch === 32 || ch === 13 || ch === 10) {
                if (start + pageRows >= lines.length) break;
                start += pageRows;
                continue;
            }
        }
    } finally {
        exitModal('text-window');
    }
 
    tty_dismiss_nhwindow(textWin);
    const dismissRows = Number.isInteger(options.dismissRows)
        ? options.dismissRows
        : shownRows;
    erase_menu_or_text(textWin, 0, dismissRows);
    if (textWin >= 0 && game.wins[textWin]) game.wins[textWin] = null;
    game._menuActive = false;
    // C ref: after text window dismiss, docrt() repaints the map.
    await cls();
    setBotlx('docrt_flags');
    await docrt(false, true);
    await flush_screen(1);
}
 
function build_doextversion_lines() {
    const buildDate = TELEPORT_BUILD_DATE.split(' ').slice(0, 3).join(' ');
    return [
        `MacOS NetHack Version 3.7.0-134 Work-in-progress - last build ${buildDate}`,
        '12:41:29.',
        '',
        'Options compiled into this edition:',
        '    I32LP64 data model, color, data file compression, deferred handling of',
        '    hangup signal, insurance files for recovering from crashes, live logging',
        '    support, log file, extended log file, errors and warnings log file, mail',
        '    daemon, news file, internal pager used for viewing help files, pattern',
        '    matching via posixregex, pseudo random numbers generated by ISAAC64,',
        '    strong PRNG seed from /dev/random, restore saved games via menu, screen',
        '    clipping, shell command, traditional status display, status via',
        '    windowport with highlighting, suspend command, terminal info library,',
        '    system configuration at run-time, show stack trace on error, launch',
        '    browser to report issues, save and bones files accepted from version',
        '    3.7.0 only, and basic NetHack features.',
        '',
        'Supported windowing system:',
        '    "tty" (traditional text with optional line-drawing).',
        '',
        'Supported soundlib:',
        '    "nosound".',
        '',
        "NetHack 3.7.* uses the 'Lua' interpreter to process some data:",
        '    Lua 5.4.8  Copyright (C) 1994-2025 Lua.org, PUC-Rio',
        '    "Permission is hereby granted, free of charge, to any person obtaining',
        '     a copy of this software and associated documentation files (the',
        '     "Software"), to deal in the Software without restriction including',
        '     without limitation the rights to use, copy, modify, merge, publish,',
        '     distribute, sublicense, and/or sell copies of the Software, and to',
        '     permit persons to whom the Software is furnished to do so, subject to',
        '     the following conditions:',
        '     The above copyright notice and this permission notice shall be',
        '     included in all copies or substantial portions of the Software."',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
        '',
    ];
}
 
const _helpFileCache = new Map();
 
async function load_help_file_lines(filename) {
    if (_helpFileCache.has(filename)) return _helpFileCache.get(filename);
    let text = null;
 
    // Try bundled help files first (works in browser without fetch)
    try {
        const { helpFiles } = await import('./helpfiles.js'); // lazy // lazy
        if (helpFiles[filename]) text = helpFiles[filename];
    } catch (_) {}
 
    // Fallback: read from filesystem (node) or fetch (dev server)
    if (text == null && typeof process !== 'undefined' && process?.versions?.node) {
        try {
            const fs = await import('node:fs/promises'); // lazy // lazy
            const relPath = `../nethack-c/patched/dat/${filename}`;
            text = await fs.readFile(new URL(relPath, import.meta.url), 'utf8');
        } catch (_) {}
    }
    if (text == null && typeof fetch === 'function') {
        try {
            const res = await fetch(`nethack-c/patched/dat/${filename}`);
            if (res.ok) text = await res.text();
        } catch (_) {}
    }
    const lines = (text == null) ? [] : text.replace(/\r\n/g, '\n').split('\n');
    if (filename !== 'usagehlp') {
        while (lines.length > 0 && lines[lines.length - 1] === '') {
            lines.pop();
        }
    }
    _helpFileCache.set(filename, lines);
    return lines;
}
 
async function display_help_file(filename) {
    const lines = await load_help_file_lines(filename);
    if (!lines.length) return;
    await display_text_window_pages(lines);
}
 
async function doextversion_helpitem() {
    // C harness logs this as nhlib.lua shuffle RNG during this help path.
    rn2(3);
    rn2(2);
    await display_text_window_pages(build_doextversion_lines(), { dismissRows: 10 });
}
 
function build_option_help_lines() {
    // C ref: options.c option_help(); this text mirrors current C harness output
    // for tty option-help paging (NHW_TEXT) used by '?' -> 'g'.
    return [
        "",
        "\u001b[17CNetHack Options Help:",
        "",
        "Set options as OPTIONS=<options> in",
        "/Users/davidbau/git/mazesofmenace/teleport/maud/test/comparison/c-harness/resul",
        "or use `NETHACKOPTIONS=\"<options>\"' in your environment",
        "(<options> is a list of options separated by commas)",
        "or press \"O\" while playing and use the menu.",
        "",
        "Boolean options (which can be negated by prefixing them with '!' or \"no\"):",
        "accessiblemsg, acoustics, altmeta, autodescribe, autodig, autoopen,",
        "autopickup, autoquiver, bgcolors, blind, bones, checkpoint, cmdassist, color,",
        "confirm, customcolors, customsymbols, dark_room, deaf, dropped_nopick,",
        "eight_bit_tty, extmenu, female, fireassist, fixinv, force_invmenu, goldX,",
        "help, herecmd_menu, hilite_pet, hilite_pile, hitpointbar, ignintr,",
        "implicit_uncursed, legacy, lit_corridor, lootabc, mail, mention_decor,",
        "mention_map, mention_walls, menu_overlay, menucolors, mon_movement, news,",
        "nudist, null, pauper, pickup_stolen, pickup_thrown, price_quotes, pushweapon,",
        "query_menu, quick_farsight, reroll, rest_on_space, safe_pet, safe_wait,",
        "selectsaved, showdamage, showexp, showrace, showvers, silent, sortpack,",
        "sounds, sparkle, spot_monsters, standout, status_updates, time, tips,",
        "tombstone, toptenwin, travel, tutorial, use_darkgray, use_inverse,",
        "use_truecolor, verbose, voices, whatis_menu, whatis_moveskip.",
        "",
        "Compound options:",
        "`windowtype'\u001b[9C- windowing system to use (should be specified first),",
        "`playmode'\u001b[11C- normal play, non-scoring explore mode, or debug mode,",
        "`name'\u001b[15C- your character's name (e.g., name:Merlin-W),",
        "`role'\u001b[15C- your starting role (e.g., Barbarian, Valkyrie),",
        "`race'\u001b[15C- your starting race (e.g., Human, Elf),",
        "`gender'\u001b[13C- your starting gender (male or female),",
        "`alignment'\u001b[10C- your starting alignment (lawful, neutral, or chaotic),",
        "`altkeyhandling'\u001b[5C- (not applicable),",
        "`autounlock'\u001b[9C- action to take when encountering locked door or chest,",
        "`boulder'\u001b[12C- deprecated (use S_boulder in sym file instead),",
        "`catname'\u001b[12C- name of your starting pet if it is a kitten,",
        "`crash_email'\u001b[8C- email address for reporting,",
        "`crash_name'\u001b[9C- your name for reporting,",
        "`crash_urlmax'\u001b[7C- length of longest url we can generate,",
        "`DECgraphics'\u001b[8C- load DECGraphics display symbols into symset,",
        "`disclose'\u001b[11C- the kinds of information to disclose at end of game,",
        "`dogname'\u001b[12C- name of your starting pet if it is a little dog,",
        "`dungeon'\u001b[12C- list of symbols to use in drawing the dungeon map,",
        "`effects'\u001b[12C- list of symbols to use in drawing special effects,",
        "`fruit'\u001b[14C- name of a fruit you enjoy eating,",
        "`glyph' - set representation of a glyph to a unicode value and color,",
        "`hilite_status'\u001b[6C- a status highlighting rule (can occur multiple times),",
        "`horsename'\u001b[10C- name of your starting pet if it is a pony,",
        "`IBMgraphics'\u001b[8C- load IBMGraphics display symbols into symset,",
        "`menu_deselect_all'  - deselect all items in a menu,",
        "`menu_deselect_page' - deselect all items on this page of a menu,",
        "`menu_first_page'    - jump to the first page in a menu,",
        "`menu_headings'\u001b[6C- display style for menu headings,",
        "`menu_invert_all'    - invert all items in a menu,",
        "`menu_invert_page'   - invert all items on this page of a menu,",
        "`menu_last_page'\u001b[5C- jump to the last page in a menu,",
        "`menu_next_page'\u001b[5C- go to the next menu page,",
        "`menu_objsyms'\u001b[7C- show object symbols in menus,",
        "`menu_previous_page' - go to the previous menu page,",
        "`menu_search'\u001b[8C- search for a menu item,",
        "`menu_select_all'    - select all items in a menu,",
        "`menu_select_page'   - select all items on this page of a menu,",
        "`menu_shift_left'    - pan current menu page left,",
        "`menu_shift_right'   - pan current menu page right,",
        "`menuinvertmode'\u001b[5C- experimental behavior of menu inverts,",
        "`menustyle'\u001b[10C- user interface for object selection,",
        "`monsters'\u001b[11C- list of symbols to use for monsters,",
        "`msg_window'\u001b[9C- control of \"view previous message(s)\" (^P) behavior,",
        "`msghistory'\u001b[9C- number of top line messages to save,",
        "`number_pad'\u001b[9C- use the number pad for movement,",
        "`objects'\u001b[12C- list of symbols to use for objects,",
        "`packorder'\u001b[10C- the inventory order of the items in your pack,",
        "`paranoid_confirmation' - extra prompting in certain situations,",
        "`petattr'\u001b[12C- attributes for highlighting pets,",
        "`pettype'\u001b[12C- your preferred initial pet type,",
        "`pickup_burden'\u001b[6C- maximum burden picked up before prompt,",
        "`pickup_types'\u001b[7C- types of objects to pick up automatically,",
        "`pile_limit'\u001b[9C- threshold for \"there are many objects here\",",
        "`roguesymset'\u001b[8C- load a set of rogue display symbols from symbols file,",
        "`runmode'\u001b[12C- display frequency when `running' or `travelling',",
        "`scores'\u001b[13C- the parts of the score list you wish to see,",
        "`sortdiscoveries'    - preferred order when displaying discovered objects,",
        "`sortloot'\u001b[11C- sort object selection lists by description,",
        "`sortvanquished'\u001b[5C- preferred order when displaying vanquished monsters,",
        "`soundlib'\u001b[11C- soundlib interface to use (if any),",
        "`statushilites'\u001b[6C- 0=no status highlighting, N=show highlights for N turns,",
        "`statuslines'\u001b[8C- 2 or 3 lines for status display,",
        "`suppress_alert'\u001b[5C- suppress alerts about version-specific features,",
        "`symset'\u001b[13C- load a set of display symbols from symbols file,",
        "`traps'\u001b[14C- list of symbols to use in drawing traps,",
        "`versinfo'\u001b[11C- extra information for 'showvers',",
        "`warnings'\u001b[11C- display characters for warnings,",
        "`whatis_coord'\u001b[7C- show coordinates when auto-describing cursor position,",
        "`whatis_filter' - filter coordinate locations when targeting next or previous,",
        "`cond_'\u001b[14C- prefix for cond_ options,",
        "`font'\u001b[15C- prefix for font options.",
        "",
        "Other settings:",
        " autocompletions",
        " autopickup exceptions",
        " bind keys",
        " menu colors",
        " message types",
        " status condition fields",
        " status highlight rules",
        "",
        "",
        "Some of the options can only be set before the game is started;",
        "those items will not be selectable in the 'O' command's menu.",
        "Some options are stored in a game's save file, and will keep saved",
        "values when restoring that game even if you have updated your config-",
        "uration file to change them.  Such changes will matter for new games.",
        "The \"other settings\" can be set with 'O', but when set within the",
        "configuration file they use their own directives rather than OPTIONS.",
        "See NetHack's \"Guidebook\" for details.",
    ];
}
 
function build_key_bindings_help_lines() {
    return [
        "",
        "\u001b[12CFull Current Key Bindings List",
        "\u001b[8C(also commands with no key assignment)",
        "",
        "Directional keys:",
        "\u001b[10Cy  k  u",
        "\u001b[11C\\ | /",
        "\u001b[10Ch- . -l",
        "\u001b[11C/ | \\",
        "\u001b[10Cb  j  n",
        "",
        "Ctrl+<direction> will run in specified direction until something very",
        "\u001b[8Cinteresting is seen.",
        "Shift+<direction> will run in specified direction until you encounter",
        "\u001b[8Can obstacle.",
        "",
        "Miscellaneous keys:",
        "<esc>   cancel current prompt or pending prefix",
        "^C\u001b[6Cinterrupt: break out of NetHack (SIGINT)",
        "",
        "Menu control keys:",
        ">\u001b[7CGo to next page",
        "<\u001b[7CGo to previous page",
        "^\u001b[7CGo to first page",
        "|\u001b[7CGo to last page",
        ".\u001b[7CSelect all items in entire menu",
        "@\u001b[7CInvert selection for all items",
        "-\u001b[7CUnselect all items in entire menu",
        ",\u001b[7CSelect all items on current page",
        "~\u001b[7CInvert current page's selections",
        "\\\u001b[7CUnselect all items on current page",
        ":\u001b[7CSearch and invert matching items",
        "Return  Accept current choice(s) and dismiss menu",
        "Enter   Same as Return",
        "Space   If not on last page, advance one page;",
        "\u001b[8Cwhen on last page, treat like Return",
        "Escape  Cancel menu without making any choice(s)",
        "",
        "General commands:",
        "^A\u001b[6Crepeat\u001b[8Crepeat a previous command",
        "^O\u001b[6Coverview\u001b[6Cshow a summary of the explored dungeon",
        "^P\u001b[6Cprevmsg\u001b[7Cview recent game messages",
        "^R\u001b[6Credraw\u001b[8Credraw screen",
        "^X\u001b[6Cattributes    show your attributes",
        "^Z\u001b[6Csuspend\u001b[7Cpush game to background ('fg' to come back)",
        "!\u001b[7Cshell\u001b[9Cleave game to enter a sub-shell ('exit' to come back)",
        "\"\u001b[7Cseeamulet\u001b[5Cshow the amulet currently worn",
        "#\u001b[7C#\u001b[13Center and perform an extended command",
        "$\u001b[7Cshowgold\u001b[6Cshow gold, possibly shop credit or debt",
        "&\u001b[7Cwhatdoes\u001b[6Ctell what a command does",
        "(\u001b[7Cseetools\u001b[6Cshow the tools currently in use",
        ")\u001b[7Cseeweapon\u001b[5Cshow the weapon currently wielded",
        "*\u001b[7Cseeall\u001b[8Cshow all equipment in use",
        "+\u001b[7Cshowspells    list and reorder known spells",
        "/\u001b[7Cwhatis\u001b[8Cshow what type of thing a symbol corresponds to",
        ";\u001b[7Cglance\u001b[8Cshow what type of thing a map symbol corresponds to",
        "=\u001b[7Cseerings\u001b[6Cshow the ring(s) currently worn",
        "?\u001b[7Chelp\u001b[10Cgive a help message",
        "@\u001b[7Cautopickup    toggle the 'autopickup' option on/off",
        "C\u001b[7Ccall\u001b[10Cname a monster, specific object, or type of object",
        "I\u001b[7Cinventtype    show inventory of one specific item class",
        "O\u001b[7Coptions\u001b[7Cshow option settings",
        "S\u001b[7Csave\u001b[10Csave the game and exit",
        "V\u001b[7Cversionshort  show version and date+time program was built",
        "[\u001b[7Cseearmor\u001b[6Cshow the armor currently worn",
        "\\\u001b[7Cknown\u001b[9Cshow what object types have been discovered",
        "^\u001b[7Cshowtrap\u001b[6Cdescribe an adjacent, discovered trap",
        "`\u001b[7Cknownclass    show discovered types for one class of objects",
        "i\u001b[7Cinventory\u001b[5Cshow your inventory",
        "v\u001b[7Cchronicle\u001b[5Cshow journal of major events",
        "|\u001b[7Cperminv\u001b[7Cscroll persistent inventory display",
        "<del>   terrain\u001b[7Cview map without monsters or objects obstructing it",
        "M-?\u001b[5C?\u001b[13Clist all extended commands",
        "M-A\u001b[5Cannotate\u001b[6Cname current level",
        "M-C\u001b[5Cconduct\u001b[7Clist voluntary challenges you have maintained",
        "M-N\u001b[5Cname\u001b[10Csame as call; name a monster or object or object type",
        "M-O\u001b[5Coverview\u001b[6Cshow a summary of the explored dungeon",
        "M-V\u001b[5Cvanquished    list vanquished monsters",
        "M-X\u001b[5Cexploremode   enter explore (discovery) mode",
        "M-a\u001b[5Cadjust\u001b[8Cadjust inventory letters",
        "M-e\u001b[5Cenhance\u001b[7Cadvance or check weapon and spell skills",
        "M-g\u001b[5Cgenocided\u001b[5Clist monsters that have been genocided or become extinct",
        "M-n\u001b[5Cname\u001b[10Csame as call; name a monster or object or object type",
        "M-v\u001b[5Cversion\u001b[7Clist compile time options for this version of NetHack",
        "#bugreport\u001b[12Cfile a bug report",
        "#herecmdmenu\u001b[10Cshow menu of commands you can do here",
        "#history\u001b[14Cshow long version and game history",
        "#lookaround\u001b[11Cdescribe what you can see",
        "#optionsfull\u001b[10Cshow all option settings, possibly change them",
        "#quit\u001b[17Cexit without saving current game",
        "#saveoptions\u001b[10Csave the game configuration",
        "#therecmdmenu\u001b[9Cmenu of commands you can do from here to adjacent spot",
        "#toggle\u001b[15Ctoggle boolean option",
        "",
        "Game commands:",
        "^D\u001b[6Ckick\u001b[10Ckick something",
        "^T\u001b[6Cteleport\u001b[6Cteleport around the level",
        "^_\u001b[6Cretravel\u001b[6Ctravel to previously selected travel location",
        ",\u001b[7Cpickup\u001b[8Cpick up things at the current location",
        "-\u001b[7Cfight\u001b[9Cprefix: force fight even if you don't see a monster",
        ".\u001b[7Cwait\u001b[10Crest one move while doing nothing",
        "5\u001b[7Crun\u001b[11Cprefix: run until something interesting is seen",
        ":\u001b[7Clook\u001b[10Clook at what is here",
        "<\u001b[7Cup\u001b[12Cgo up a staircase",
        ">\u001b[7Cdown\u001b[10Cgo down a staircase",
        "A\u001b[7Ctakeoffall    remove all armor",
        "D\u001b[7Cdroptype\u001b[6Cdrop specific item types",
        "E\u001b[7Cengrave\u001b[7Cengrave writing on the floor",
        "F\u001b[7Cfight\u001b[9Cprefix: force fight even if you don't see a monster",
        "G\u001b[7Crun\u001b[11Cprefix: run until something interesting is seen",
        "P\u001b[7Cputon\u001b[9Cput on an accessory (ring, amulet, etc)",
        "Q\u001b[7Cquiver\u001b[8Cselect ammunition for quiver",
        "R\u001b[7Cremove\u001b[8Cremove an accessory (ring, amulet, etc)",
        "T\u001b[7Ctakeoff\u001b[7Ctake off one piece of armor",
        "W\u001b[7Cwear\u001b[10Cwear a piece of armor",
        "X\u001b[7Ctwoweapon\u001b[5Ctoggle two-weapon combat",
        "Z\u001b[7Ccast\u001b[10Czap (cast) a spell",
        "_\u001b[7Ctravel\u001b[8Ctravel to a specific location on the map",
        "a\u001b[7Capply\u001b[9Capply (use) a tool (pick-axe, key, lamp...)",
        "c\u001b[7Cclose\u001b[9Cclose a door",
        "d\u001b[7Cdrop\u001b[10Cdrop an item",
        "e\u001b[7Ceat\u001b[11Ceat something",
        "f\u001b[7Cfire\u001b[10Cfire ammunition from quiver",
        "g\u001b[7Crush\u001b[10Cprefix: rush until something interesting is seen",
        "m\u001b[7Creqmenu\u001b[7Cprefix: request menu or modify command",
        "o\u001b[7Copen\u001b[10Copen a door",
        "p\u001b[7Cpay\u001b[11Cpay your shopping bill",
        "q\u001b[7Cquaff\u001b[9Cquaff (drink) something",
        "r\u001b[7Cread\u001b[10Cread a scroll or spellbook",
        "s\u001b[7Csearch\u001b[8Csearch for traps and secret doors",
        "t\u001b[7Cthrow\u001b[9Cthrow something",
        "w\u001b[7Cwield\u001b[9Cwield (put in use) a weapon",
        "x\u001b[7Cswap\u001b[10Cswap wielded and secondary weapons",
        "z\u001b[7Czap\u001b[11Czap a wand",
        "M-2\u001b[5Ctwoweapon\u001b[5Ctoggle two-weapon combat",
        "M-5\u001b[5Crush\u001b[10Cprefix: rush until something interesting is seen",
        "M-R\u001b[5Cride\u001b[10Cmount or dismount a saddled steed",
        "M-T\u001b[5Ctip\u001b[11Cempty a container",
        "M-c\u001b[5Cchat\u001b[10Ctalk to someone",
        "M-d\u001b[5Cdip\u001b[11Cdip an object into something",
        "M-f\u001b[5Cforce\u001b[9Cforce a lock",
        "M-i\u001b[5Cinvoke\u001b[8Cinvoke an object's special powers",
        "M-j\u001b[5Cjump\u001b[10Cjump to another location",
        "M-l\u001b[5Cloot\u001b[10Cloot a box on the floor",
        "M-m\u001b[5Cmonster\u001b[7Cuse monster's special ability",
        "M-o\u001b[5Coffer\u001b[9Coffer a sacrifice to the gods",
        "M-p\u001b[5Cpray\u001b[10Cpray to the gods for help",
        "M-r\u001b[5Crub\u001b[11Crub a lamp or a stone",
        "M-s\u001b[5Csit\u001b[11Csit down",
        "M-t\u001b[5Cturn\u001b[10Cturn undead away",
        "M-u\u001b[5Cuntrap\u001b[8Cuntrap something",
        "M-w\u001b[5Cwipe\u001b[10Cwipe off your face",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
    ];
}
 
function build_menu_controls_help_lines() {
    return [
        "Menu control keys:",
        "",
        "\u001b[11CWhole  Current",
        "\u001b[12CMenu   Page",
        "  Select\u001b[5C.\u001b[6C,",
        "  Invert\u001b[5C@\u001b[6C~",
        "Deselect\u001b[5C-\u001b[6C\\",
        "",
        "   Go to\u001b[5C>\u001b[6CNext page",
        "\u001b[13C<\u001b[6CPrevious page",
        "\u001b[13C^\u001b[6CFirst page",
        "\u001b[13C|\u001b[6CLast page",
        "",
        "  Search\u001b[5C:\u001b[6CExter a target string and invert all matching entries",
        "",
        "   Other   Return   Accept current choice(s) and dismiss menu",
        "\u001b[11CEnter    Same as Return",
        "\u001b[11CSpace    If not on last page, advance one page;",
        "\u001b[20Cwhen on last page, treat like Return",
        "\u001b[11CEscape   Cancel menu without making any choice(s)",
        "",
        "",
        "",
    ];
}
 
function build_contact_help_lines() {
    return [
        "To contact the NetHack development team directly,",
        "see the 'Contact' form on our website or email <devteam@nethack.org>.",
        "",
        "For more information on NetHack, or to report a bug,",
        "visit our website \"https://www.nethack.org/\".",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
    ];
}
 
function pluralize_name(name) {
    if (name.endsWith('s')) return name;
    if (name.endsWith('y') && !/[aeiou]y$/i.test(name)) return `${name.slice(0, -1)}ies`;
    return `${name}s`;
}
 
// apply_ok moved to iactions.js
 
async function prinv_like(obj) {
    // C ref: invent.c prinv() — uses doname() for inventory line display
    await pline(`${obj.invlet} - ${doname(obj)}.`);
}
 
export async function prompt_inventory_char(prompt, modalOwner) {
    const display = game?.nhDisplay || null;
    const isYnPrompt = modalOwner === 'dir-prompt' || modalOwner === 'item-prompt';
    const isItemPrompt = modalOwner === 'item-prompt';
    const pendingMore = !!(isYnPrompt && display?.toplin === TOPLINE_NEED_MORE);
    if (display) {
        if (!pendingMore && display.grid && game.level) {
            await docrt(false, true);
            render_screen_output_to_display(display);
        }
        if (isYnPrompt) {
            if (pendingMore) {
                await more(display);
            } else if (isItemPrompt && display.toplin === TOPLINE_NON_EMPTY) {
                pushRngLogEntry('^toplin[tty_clear_nhwindow=0]');
            }
            pushRngLogEntry('^toplin[tty_yn_function=3]');
            if (game?.u?.ux) await flush_screen(1);
            pushRngLogEntry('^toplin[addtopl=1]');
            game._pending_message = prompt;
            // C ref: addtopl() always sets toplin = NEED_MORE after printing
            display.toplin = TOPLINE_NEED_MORE;
            display.topMessage = prompt;
            display.toplines = prompt;
        }
        display.clearRow(0);
        display.putstr(0, 0, prompt);
        if (typeof display.setCursor === 'function') {
            const cols = Number.isInteger(display.cols) ? display.cols : 80;
            display.setCursor(Math.min(prompt.length + 1, cols - 1), 0);
        }
    }
    enterModal(modalOwner);
    try {
        const ch = await nhgetch();
        if (isYnPrompt) {
            // C ref: tty_yn_function sets toplin=NON_EMPTY after reading key
            if (display) display.toplin = TOPLINE_NON_EMPTY;
            pushRngLogEntry('^toplin[tty_yn_function=2]');
            // C ref: getobj only sets botl when a valid item is selected,
            // not when cancelled with a quitchar (ESC, space, enter)
            if (isItemPrompt && ch !== 27 && ch !== 32 && ch !== 10 && ch !== 13) {
                setBotl('getobj');
            }
            if (!isItemPrompt) {
                // C ref: non-item yn prompts call tty_clear_nhwindow(WIN_MESSAGE)
                await tty_clear_nhwindow('message');
            } else if (display) {
                // C ref: item prompts leave toplin=NON_EMPTY for parse() to clear
                game._pending_message = prompt;
                display.topMessage = prompt;
                display.toplines = prompt;
            }
        }
        return ch;
    } finally {
        exitModal(modalOwner);
    }
}
 
export function inventory_letters(filterFn) {
    const letters = [];
    for (let obj = game.invent; obj; obj = obj.nobj) {
        if (filterFn(obj)) letters.push(obj.invlet);
    }
    return letters.join('');
}
 
function compact_invlet_spec(letters) {
    const chars = Array.from(new Set((letters || '').split(''))).sort();
    if (!chars.length) return '';
    if (chars.length <= 5) return chars.join('');
    const out = [];
    let i = 0;
    while (i < chars.length) {
        const start = chars[i];
        let j = i;
        while (j + 1 < chars.length
            && chars[j + 1].charCodeAt(0) === chars[j].charCodeAt(0) + 1) {
            j++;
        }
        const runLen = j - i + 1;
        if (runLen >= 3) out.push(`${start}-${chars[j]}`);
        else if (runLen === 2) out.push(`${start}${chars[j]}`);
        else out.push(start);
        i = j + 1;
    }
    return out.join('');
}
 
// C ref: wield.c ready_ok — returns true for items that should appear
// in the quiver prompt letter list (GETOBJ_SUGGEST in C).
function quiver_ok_suggest(obj) {
    if (!obj) return false;
    const g = game;
    // Wielded items: downplay unless quantity > 1
    if (obj === g.u?.uwep || (obj === g.u?.uswapwep && g.u?.twoweap))
        return obj.quan > 1;
    if (is_ammo(obj)) {
        // Suggest if ammo matches wielded or swap launcher
        return (g.u?.uwep && ammo_matches_launcher(obj, g.u.uwep))
            || (g.u?.uswapwep && ammo_matches_launcher(obj, g.u.uswapwep));
    }
    if (launcher_name(obj)) return false; // downplay launchers
    // Weapons and coins: suggest
    if (obj.oclass === WEAPON_CLASS || obj.oclass === COIN_CLASS)
        return true;
    return false;
}
 
function launcher_name(obj) {
    const name = (game.objects[obj?.otyp]?.oc_name || '').toLowerCase();
    if (name.includes('crossbow')) return 'crossbow';
    if (name.includes('yumi')) return 'bow';
    if (name.includes('bow')) return 'bow';
    if (name.includes('sling')) return 'sling';
    return null;
}
 
function ammo_matches_launcher(obj, launcher) {
    const ammoName = (game.objects[obj?.otyp]?.oc_name || '').toLowerCase();
    const launcherType = launcher_name(launcher);
    if (!launcherType) return false;
    if (launcherType === 'bow') return ammoName.includes('arrow');
    if (launcherType === 'crossbow') return ammoName.includes('crossbow bolt');
    if (launcherType === 'sling') {
        return ammoName.includes('rock') || ammoName.includes('flint')
            || ammoName.includes('loadstone') || ammoName.includes('luckstone')
            || ammoName.includes('gem');
    }
    return false;
}
 
function quiver_prompt_ok(obj) {
    if (!obj) return false;
    if (obj === game.u.uwep) return (obj.quan || 1) > 1;
    if (obj === game.u.uswapwep && game.u?.twoweap) return (obj.quan || 1) > 1;
    if (launcher_name(obj)) return false;
    if (obj.oclass === WEAPON_CLASS) {
        if (ammo_matches_launcher(obj, game.u.uwep) || ammo_matches_launcher(obj, game.u.uswapwep)) {
            return true;
        }
        return true;
    }
    return obj.oclass === COIN_CLASS;
}
 
function wield_prompt_letters() {
    const letters = [];
    for (let obj = game.invent; obj; obj = obj.nobj) {
        if (obj?.oclass === WEAPON_CLASS) letters.push(obj.invlet);
    }
    return letters.join('');
}
 
async function doswapweapon_like() {
    game.multi = 0;
    pushMultiLog('doswapweapon', game.multi);
    const oldwep = game.u.uwep;
    const oldswap = game.u.uswapwep;

    setuswapwep(null);
    if (oldswap) {
        const oldmask = oldswap.owornmask;
        oldswap.owornmask = oldmask | W_WEP;
        await prinv_like(oldswap);
        oldswap.owornmask = oldmask;
        await setuwep(oldswap);
    }
    if (oldwep) {
        setuswapwep(oldwep);
        await prinv_like(oldwep);
    } else {
        await You('have no secondary weapon readied.');
    }
}
 
// dothrow_like removed — now using real dothrow() from dothrow.js
 
// Direction deltas for vi keys (hjkl mode, the default)
// C ref: cmd.c sdir[] = "hykulnjb><"
const vikeys_hjkl = {
    'h': { dx: -1, dy: 0 },  // west
    'j': { dx: 0, dy: 1 },   // south
    'k': { dx: 0, dy: -1 },  // north
    'l': { dx: 1, dy: 0 },   // east
    'y': { dx: -1, dy: -1 }, // northwest
    'u': { dx: 1, dy: -1 },  // northeast
    'b': { dx: -1, dy: 1 },  // southwest
    'n': { dx: 1, dy: 1 },   // southeast
    // Capital = run (C ref: cmd.c MV_RUN mode, context.run=1)
    'H': { dx: -1, dy: 0, run: true },
    'J': { dx: 0, dy: 1, run: true },
    'K': { dx: 0, dy: -1, run: true },
    'L': { dx: 1, dy: 0, run: true },
    'Y': { dx: -1, dy: -1, run: true },
    'U': { dx: 1, dy: -1, run: true },
    'B': { dx: -1, dy: 1, run: true },
    'N': { dx: 1, dy: 1, run: true },
    // Ctrl+direction = rush (C ref: cmd.c MV_RUSH mode, context.run=2)
    '\x08': { dx: -1, dy: 0, rush: true },  // Ctrl-H = rush west
    '\x0a': { dx: 0, dy: 1, rush: true },   // Ctrl-J = rush south
    '\x0b': { dx: 0, dy: -1, rush: true },  // Ctrl-K = rush north
    '\x0c': { dx: 1, dy: 0, rush: true },   // Ctrl-L = rush east
    '\x19': { dx: -1, dy: -1, rush: true }, // Ctrl-Y = rush northwest
    '\x15': { dx: 1, dy: -1, rush: true },  // Ctrl-U = rush northeast
    '\x02': { dx: -1, dy: 1, rush: true },  // Ctrl-B = rush southwest
    '\x0e': { dx: 1, dy: 1, rush: true },   // Ctrl-N = rush southeast
};
 
// Direction deltas for number_pad mode
// C ref: cmd.c ndir[] = "47896321><"
// When num_pad is ON, digits 1-9 are movement. Meta+digit = run.
const vikeys_numpad = {
    '4': { dx: -1, dy: 0 },  // west
    '2': { dx: 0, dy: 1 },   // south
    '8': { dx: 0, dy: -1 },  // north
    '6': { dx: 1, dy: 0 },   // east
    '7': { dx: -1, dy: -1 }, // northwest
    '9': { dx: 1, dy: -1 },  // northeast
    '1': { dx: -1, dy: 1 },  // southwest
    '3': { dx: 1, dy: 1 },   // southeast
    // Meta+digit = run (C ref: cmd.c M('4') etc.)
    '\xb4': { dx: -1, dy: 0, run: true },  // M('4') = 0xB4
    '\xb2': { dx: 0, dy: 1, run: true },   // M('2') = 0xB2
    '\xb8': { dx: 0, dy: -1, run: true },  // M('8') = 0xB8
    '\xb6': { dx: 1, dy: 0, run: true },   // M('6') = 0xB6
    '\xb7': { dx: -1, dy: -1, run: true }, // M('7') = 0xB7
    '\xb9': { dx: 1, dy: -1, run: true },  // M('9') = 0xB9
    '\xb1': { dx: -1, dy: 1, run: true },  // M('1') = 0xB1
    '\xb3': { dx: 1, dy: 1, run: true },   // M('3') = 0xB3
};
 
// Get the active movement key table based on num_pad setting
function getVikeys() {
    return game.iflags?.num_pad ? vikeys_numpad : vikeys_hjkl;
}
 
// Legacy alias — non-movement code that references vikeys directly
const vikeys = vikeys_hjkl;
 
// ═══════════════════════════════════════════════════════════════════
// Command table — C-faithful key→command dispatch
// C ref: cmd.c struct ext_func_tab, commands[], Cmd_bind linked list
//
// Each entry: { name, handler, flags }
//   name:    command name (matches C ef_txt, used for BIND= lookup)
//   handler: async function returning ECMD_* flags
//   flags:   AUTOCOMPLETE, WIZMODECMD, etc.
//
// The table is populated at module load with default bindings. At game
// startup, reset_commands() adjusts bindings based on num_pad mode.
// Users can override via BIND=key:command in .nethackrc.
// ═══════════════════════════════════════════════════════════════════
 
const AUTOCOMPLETE = 1;
const WIZMODECMD = 2;
const GENERALCMD = 4;
const CMD_M_PREFIX = 8;
 
// The command table: key (char code) → { name, handler, flags }
// Stored on game object for per-session lifecycle.
// C ref: gc.Cmd.cmdbinds — linked list of key→command bindings.
 
// Get or initialize the command table
function getCommandTable() {
    if (!game._cmdTable) initCommandTable();
    return game._cmdTable;
}
 
// Reset the command table (called by decl_globals_init via game object reset)
export function resetCommandTable() {
    if (game) game._cmdTable = null;
}
 
// Look up a command by key
export function cmdByKey(key) {
    return getCommandTable().get(typeof key === 'string' ? key.charCodeAt(0) : key);
}
 
// Look up a command by name (for BIND= support)
export function cmdByName(name) {
    const table = getCommandTable();
    for (const entry of table.values()) {
        if (entry.name === name) return entry;
    }
    return null;
}
 
// Bind a key to a command (by name)
// C ref: cmd.c bind_key(key, cmdname, user)
export function bind_key(key, cmdname) {
    const table = getCommandTable();
    const keyCode = typeof key === 'string' ? key.charCodeAt(0) : key;
    const entry = cmdByName(cmdname);
    if (!entry) return false;
    // Remove any existing binding for this key
    table.delete(keyCode);
    // Add new binding
    table.set(keyCode, { ...entry, boundKey: keyCode });
    return true;
}
 
// Unbind a key
export function unbind_key(key) {
    const table = getCommandTable();
    const keyCode = typeof key === 'string' ? key.charCodeAt(0) : key;
    table.delete(keyCode);
}
 
// Initialize command table with default bindings
// C ref: cmd.c extcmdlist[] + commands_init()
// Movement commands are handled separately via getVikeys() before
// the table is consulted. The table handles all non-movement commands.
function initCommandTable() {
    game._cmdTable = new Map();
    const cmdTable = game._cmdTable;
 
    // Helper to add a command entry
    const add = (key, name, flags = 0) => {
        const keyCode = typeof key === 'string' ? key.charCodeAt(0) : key;
        cmdTable.set(keyCode, { name, flags, boundKey: keyCode });
    };
 
    // C ref: cmd.c extcmdlist[] — default key bindings
    // Commands that have handlers in the switch statement below.
    // The handler is still in the switch; the table provides metadata
    // for lookup, rebinding, and num_pad support.
    add('a', 'apply');
    add('c', 'close');
    add('d', 'drop');
    add('e', 'eat');
    add('f', 'fire');
    add('i', 'inventory');
    add('o', 'open');
    add('p', 'pay');
    add('q', 'quaff');
    add('r', 'read');
    add('s', 'search');
    add('t', 'throw');
    add('w', 'wield');
    add('x', 'swap');
    add('z', 'zap');
    add('A', 'takeoffall');
    add('C', 'call');
    add('D', 'dropmany');
    add('E', 'engrave');
    add('I', 'typeinv');
    add('P', 'puton');
    add('Q', 'quiver');
    add('R', 'remove');
    add('S', 'save');
    add('T', 'takeoff');
    add('W', 'wear');
    add('Z', 'cast');
    add(',', 'pickup');
    add('.', 'wait');
    add(':', 'look');
    add(';', 'farlook');
    add('<', 'up');
    add('>', 'down');
    add('@', 'togglepickup');
    add('+', 'showspells');
    add('#', 'extcommand');
    add('\\', 'discoveries');
    add('?', 'help');
    add('/', 'whatis');
    add(127, 'terrain');
    add('^', 'idtrap');
    add('_', 'pray', CMD_M_PREFIX);
    // Ctrl commands
    add(0x04, 'kick');         // Ctrl-D
    add(0x06, 'wizmap', WIZMODECMD); // Ctrl-F
    add(0x0f, 'overview');     // Ctrl-O
    add(0x10, 'prevmsg');      // Ctrl-P
    add(0x12, 'redraw');       // Ctrl-R
    add(0x14, 'teleport');     // Ctrl-T
    add(0x17, 'wizwish', WIZMODECMD); // Ctrl-W
    add(0x18, 'attributes');   // Ctrl-X
    // Meta commands
    add('a'.charCodeAt(0) | 0x80, 'adjust');
    add('c'.charCodeAt(0) | 0x80, 'chat');
    add('d'.charCodeAt(0) | 0x80, 'dip');
    add('e'.charCodeAt(0) | 0x80, 'enhance');
    add('i'.charCodeAt(0) | 0x80, 'invoke');
    add('j'.charCodeAt(0) | 0x80, 'jump', AUTOCOMPLETE);
    add('l'.charCodeAt(0) | 0x80, 'loot', AUTOCOMPLETE);
    add('n'.charCodeAt(0) | 0x80, 'name', AUTOCOMPLETE);
    add('o'.charCodeAt(0) | 0x80, 'offer', AUTOCOMPLETE);
    add('p'.charCodeAt(0) | 0x80, 'pray', AUTOCOMPLETE);
    add('r'.charCodeAt(0) | 0x80, 'rub', AUTOCOMPLETE);
    add('s'.charCodeAt(0) | 0x80, 'sit', AUTOCOMPLETE);
    add('t'.charCodeAt(0) | 0x80, 'turn', AUTOCOMPLETE);
    add('u'.charCodeAt(0) | 0x80, 'untrap', AUTOCOMPLETE);
    add('w'.charCodeAt(0) | 0x80, 'wipe', AUTOCOMPLETE);
 
    // num_pad-specific commands (not bound by default, bound by reset_commands)
    // h=help, j=jump, k=kick, l=loot, u=untrap, N=name
    // These are registered as named commands for bind_key() lookup.
    // Their handlers are defined below.
}
 
// C ref: cmd.c reset_commands() — called at startup and when num_pad changes
export function reset_commands() {
    const table = getCommandTable();
    const numPad = !!game.iflags?.num_pad;

    if (numPad) {
        // C ref: cmd.c:3351-3362 — num_pad rebindings
        // These override the default letter-key bindings
        bind_key('h', 'help');
        bind_key('j', 'jump');
        bind_key('k', 'kick');
        bind_key('l', 'loot');
        bind_key('u', 'untrap');
    }
}
 
// Map command names to the canonical dispatch key used by rhack() switch.
// This lets BIND=key:command remap arbitrary keys without duplicating
// command handlers for every bound key.
const COMMAND_DISPATCH_KEY = {
    apply: 'a',
    close: 'c',
    drop: 'd',
    eat: 'e',
    fire: 'f',
    inventory: 'i',
    open: 'o',
    pay: 'p',
    quaff: 'q',
    read: 'r',
    search: 's',
    throw: 't',
    wield: 'w',
    swap: 'x',
    zap: 'z',
    takeoffall: 'A',
    call: 'C',
    dropmany: 'D',
    engrave: 'E',
    typeinv: 'I',
    puton: 'P',
    quiver: 'Q',
    remove: 'R',
    save: 'S',
    takeoff: 'T',
    wear: 'W',
    cast: 'Z',
    pickup: ',',
    wait: '.',
    look: ':',
    farlook: ';',
    up: '<',
    down: '>',
    togglepickup: '@',
    showspells: '+',
    extcommand: '#',
    discoveries: '\\',
    help: '?',
    whatis: '/',
    terrain: '\x7f',
    idtrap: '^',
    pray: '_',
    kick: '\u0004',      // Ctrl-D
    wizmap: '\u0006',    // Ctrl-F
    overview: '\u000f',  // Ctrl-O
    prevmsg: '\u0010',   // Ctrl-P
    redraw: '\u0012',    // Ctrl-R
    teleport: '\u0014',  // Ctrl-T
    wizwish: '\u0017',   // Ctrl-W
    attributes: '\u0018' // Ctrl-X
};
 
// C ref: options.c doset_simple()
// Minimal options menu path used by 'O' command in normal play.
// This preserves tty menu lifecycle/event ownership (open, page, dismiss),
// and the post-dismiss bot() call that C performs in doset_simple().
async function doset_simple() {
    const g = game;
    const defaultPickupClassOrder = '$")[%?+!=/(*`0_';
    const boolMark = (v) => (v ? 'X' : ' ');
    const getPath = (path, def = false) => {
        const [ns, key] = path.split('.');
        const value = g?.[ns]?.[key];
        if (value === undefined) {
            return !!def;
        }
        return !!value;
    };
    const applyOptionExpr = (expr) => {
        const parsed = [];
        parseoption(expr, parsed);
        applyOptions(parsed, g);
    };
    const toggleBoolOption = (name, path, def = false) => {
        const current = getPath(path, def);
        applyOptionExpr(current ? `!${name}` : name);
    };
    const promptAndSetOption = async (name, prompt) => {
        const buf = await getlin(prompt);
        if (!buf || buf.charCodeAt(0) === 27) {
            return;
        }
        applyOptionExpr(`${name}:${buf}`);
    };
    const promptAndSetPickupTypes = async () => {
        const order = (g.flags?.inv_order && g.flags.inv_order.length > 0)
            ? g.flags.inv_order
            : defaultPickupClassOrder;
        const current = g.flags?.pickup_types || '';
        const win = create_nhwindow_menu();
        start_menu(win);
        const seen = new Set();
        let accelCode = 'a'.charCodeAt(0);
        for (const sym of order) {
            if (seen.has(sym)) continue;
            seen.add(sym);
            if (def_char_to_objclass(sym) <= 1) continue;
            const idx = def_char_to_objclass(sym);
            const explain = def_oc_syms[idx]?.explain || 'objects';
            const selected = current.includes(sym) ? MENU_ITEMFLAGS_SELECTED : 0;
            const accel = String.fromCharCode(accelCode);
            add_menu(win, `opt:pickup_types:${sym}`, accel, sym, 0, NO_COLOR, `${sym}  ${explain}`, selected);
            if (accelCode === 'z'.charCodeAt(0)) {
                accelCode = 'A'.charCodeAt(0);
            } else {
                accelCode++;
            }
        }
        add_menu_str(win, '');
        add_menu(win, 'opt:pickup_types: ', 'A', 0, 0, NO_COLOR, '   All classes of objects', MENU_ITEMFLAGS_SKIPINVERT);
        add_menu_str(win, 'Note: when no choices are selected, "all" is implied.');
        add_menu_str(win, getPath('flags.pickup')
            ? "Toggle off 'autopickup' to not pick up anything."
            : "Toggle on 'autopickup' to automatically pick these things up.");
        end_menu(win, 'Autopickup what?');
        // C ref: choose_classes_menu() uses a large centered menu footprint
        // in tty; keep geometry aligned so dismiss/docorner events match.
        win.fixedOffx = 16;
        win.maxrow = 22;
        win.skipOverlayBackdropRedraw = true;
        const picked = await select_menu(win, PICK_ANY);
        destroy_nhwindow_menu(win);
        if (!picked || (picked.count || 0) <= 0) {
            return;
        }
        const selectedSet = new Set((picked.items || []).map((it) => String(it.identifier || '').split(':').pop()));
        if (selectedSet.has(' ')) {
            applyOptionExpr('pickup_types:');
            return;
        }
        let out = '';
        for (const sym of order) {
            if (!selectedSet.has(sym)) continue;
            if (!out.includes(sym)) out += sym;
        }
        applyOptionExpr(`pickup_types:${out}`);
    };
 
    let pickedCount = 0;
    do {
        const win = create_nhwindow_menu();
        start_menu(win);
 
        add_menu_heading(win, 'Options');
        add_menu_str(win, '');
        add_menu_str(win, '? - show help');
        add_menu_str(win, '');
        add_menu_heading(win, ' General                        ');
        add_menu(win, 'opt:fruit', 'a', 0, 0, NO_COLOR, `fruit                   [${g.flags?.fruit || 'slime mold'}]`, 0);
        add_menu(win, 'opt:number_pad', 'b', 0, 0, NO_COLOR, `number_pad              [${g.iflags?.num_pad || 0}=off]`, 0);
        add_menu(win, 'opt:price_quotes', 'c', 0, 0, NO_COLOR, `price_quotes            [${boolMark(!!g.flags?.pricequotes)}]`, 0);
        add_menu_str(win, '');
        add_menu_heading(win, ' Behavior                       ');
        add_menu(win, 'opt:autodig', 'd', 0, 0, NO_COLOR, `autodig                 [${boolMark(getPath('flags.autodig'))}]`, 0);
        add_menu(win, 'opt:autoopen', 'e', 0, 0, NO_COLOR, `autoopen                [${boolMark(getPath('flags.autoopen', true))}]`, 0);
        add_menu(win, 'opt:autopickup', 'f', 0, 0, NO_COLOR, `autopickup              [${boolMark(getPath('flags.pickup'))}]`, 0);
        add_menu_str(win, `g - autopickup exceptions   [(${g.iflags?.autopickup_exceptions?.length || 0} currently set)]`);
        add_menu(win, 'opt:autoquiver', 'h', 0, 0, NO_COLOR, `autoquiver              [${boolMark(getPath('flags.autoquiver'))}]`, 0);
        const autounlock = g.flags?.autounlock;
        const autounlockLabel = (autounlock === AUTOUNLOCK_APPLY_KEY)
            ? 'apply-key'
            : String(autounlock ?? 'apply-key');
        add_menu_str(win, `i - autounlock              [${autounlockLabel}]`);
        add_menu(win, 'opt:cmdassist', 'j', 0, 0, NO_COLOR, `cmdassist               [${boolMark(getPath('iflags.cmdassist', true))}]`, 0);
        add_menu(win, 'opt:dropped_nopick', 'k', 0, 0, NO_COLOR, `dropped_nopick          [${boolMark(getPath('flags.nopick_dropped', true))}]  (for autopickup)`, 0);
        add_menu(win, 'opt:fireassist', 'l', 0, 0, NO_COLOR, `fireassist              [${boolMark(getPath('iflags.fireassist', true))}]`, 0);
        add_menu(win, 'opt:pickup_stolen', 'm', 0, 0, NO_COLOR, `pickup_stolen           [${boolMark(getPath('flags.pickup_stolen', true))}]  (for autopickup)`, 0);
        add_menu(win, 'opt:pickup_thrown', 'n', 0, 0, NO_COLOR, `pickup_thrown           [${boolMark(getPath('flags.pickup_thrown', true))}]  (for autopickup)`, 0);
        add_menu(win, 'opt:pickup_types', 'o', 0, 0, NO_COLOR, `pickup_types            [${g.flags?.pickup_types || 'all'}]  (for autopickup)`, 0);
        add_menu(win, 'opt:pushweapon', 'p', 0, 0, NO_COLOR, `pushweapon              [${boolMark(getPath('flags.pushweapon'))}]`, 0);
 
        add_menu_str(win, '');
        add_menu_heading(win, ' Map                            ');
        add_menu(win, 'opt:bgcolors', 'a', 0, 0, NO_COLOR, `bgcolors                [${boolMark(getPath('iflags.bgcolors', true))}]`, 0);
        add_menu(win, 'opt:color', 'b', 0, 0, NO_COLOR, `color                   [${boolMark(getPath('iflags.wc_color', true))}]`, 0);
        add_menu(win, 'opt:customcolors', 'c', 0, 0, NO_COLOR, `customcolors            [${boolMark(getPath('iflags.customcolors', true))}]`, 0);
        add_menu(win, 'opt:customsymbols', 'd', 0, 0, NO_COLOR, `customsymbols           [${boolMark(getPath('iflags.customsymbols', true))}]`, 0);
        add_menu(win, 'opt:hilite_pet', 'e', 0, 0, NO_COLOR, `hilite_pet              [${boolMark(getPath('iflags.wc_hilite_pet'))}]`, 0);
        add_menu(win, 'opt:hilite_pile', 'f', 0, 0, NO_COLOR, `hilite_pile             [${boolMark(getPath('iflags.hilite_pile'))}]`, 0);
        add_menu(win, 'opt:showrace', 'g', 0, 0, NO_COLOR, `showrace                [${boolMark(getPath('flags.showrace'))}]`, 0);
        add_menu_str(win, 'h - sparkle                 [X]');
        add_menu_str(win, 'i - symset                  [DECgraphics, active, handler=DEC]');
        add_menu_str(win, '');
        add_menu_heading(win, ' Status                         ');
        add_menu(win, 'opt:hitpointbar', 'j', 0, 0, NO_COLOR, `hitpointbar             [${boolMark(getPath('iflags.wc2_hitpointbar'))}]`, 0);
        add_menu_str(win, 'k - menu colors             [(0 currently set)]');
        add_menu(win, 'opt:showexp', 'l', 0, 0, NO_COLOR, `showexp                 [${boolMark(getPath('flags.showexp'))}]`, 0);
        add_menu_str(win, 'm - status condition fields [(16 currently set)]');
        add_menu_str(win, 'n - status highlight rules  [(0 currently set)]');
        add_menu_str(win, `o - statuslines             [${g.iflags?.wc2_statuslines ?? 2}]`);
        add_menu(win, 'opt:time', 'p', 0, 0, NO_COLOR, `time                    [${boolMark(getPath('flags.time'))}]`, 0);
 
        end_menu(win, null);
        const picked = await select_menu(win, PICK_ONE);
        pickedCount = picked?.count || 0;
        const sel = picked?.items?.[0]?.identifier || '';
 
        if (sel === 'opt:fruit') {
            await promptAndSetOption('fruit', 'Set fruit to what?');
        } else if (sel === 'opt:number_pad') {
            await promptAndSetOption('number_pad', 'Set number_pad to what?');
        } else if (sel === 'opt:pickup_types') {
            await promptAndSetPickupTypes();
        } else if (sel === 'opt:price_quotes') {
            toggleBoolOption('price_quotes', 'flags.pricequotes');
        } else if (sel === 'opt:autodig') {
            toggleBoolOption('autodig', 'flags.autodig');
        } else if (sel === 'opt:autoopen') {
            toggleBoolOption('autoopen', 'flags.autoopen', true);
        } else if (sel === 'opt:autopickup') {
            toggleBoolOption('autopickup', 'flags.pickup');
        } else if (sel === 'opt:autoquiver') {
            toggleBoolOption('autoquiver', 'flags.autoquiver');
        } else if (sel === 'opt:cmdassist') {
            toggleBoolOption('cmdassist', 'iflags.cmdassist', true);
        } else if (sel === 'opt:dropped_nopick') {
            toggleBoolOption('dropped_nopick', 'flags.nopick_dropped', true);
        } else if (sel === 'opt:fireassist') {
            toggleBoolOption('fireassist', 'iflags.fireassist', true);
        } else if (sel === 'opt:pickup_stolen') {
            toggleBoolOption('pickup_stolen', 'flags.pickup_stolen', true);
        } else if (sel === 'opt:pickup_thrown') {
            toggleBoolOption('pickup_thrown', 'flags.pickup_thrown', true);
        } else if (sel === 'opt:pushweapon') {
            toggleBoolOption('pushweapon', 'flags.pushweapon');
        } else if (sel === 'opt:bgcolors') {
            toggleBoolOption('bgcolors', 'iflags.bgcolors', true);
            setBotlx('docrt_flags');
        } else if (sel === 'opt:color') {
            toggleBoolOption('color', 'iflags.wc_color', true);
            setBotlx('docrt_flags');
        } else if (sel === 'opt:customcolors') {
            toggleBoolOption('customcolors', 'iflags.customcolors', true);
            setBotlx('docrt_flags');
        } else if (sel === 'opt:customsymbols') {
            toggleBoolOption('customsymbols', 'iflags.customsymbols', true);
            setBotlx('docrt_flags');
        } else if (sel === 'opt:hilite_pet') {
            toggleBoolOption('hilite_pet', 'iflags.wc_hilite_pet');
            setBotlx('docrt_flags');
        } else if (sel === 'opt:hilite_pile') {
            toggleBoolOption('hilite_pile', 'iflags.hilite_pile');
            setBotlx('docrt_flags');
        } else if (sel === 'opt:showrace') {
            toggleBoolOption('showrace', 'flags.showrace');
            setBotlx('docrt_flags');
        } else if (sel === 'opt:hitpointbar') {
            toggleBoolOption('hitpointbar', 'iflags.wc2_hitpointbar');
            setBotlx('docrt_flags');
        } else if (sel === 'opt:showexp') {
            toggleBoolOption('showexp', 'flags.showexp');
            status_initialize();
            setBotl('optfn_boolean');
        } else if (sel === 'opt:time') {
            toggleBoolOption('time', 'flags.time');
            status_initialize();
            setBotl('optfn_boolean');
        }
 
        destroy_nhwindow_menu(win);
 
        // C ref: options.c doset_simple() updates status line each cycle.
        await bot();
    } while (pickedCount > 0);
 
    if (g?.disp) {
        g.disp.time_botl = !!g.flags?.time;
    }
    return 0;
}
 
// C ref: cmd.c:3625 rhack()
// Simplified dispatch for basic commands.
export async function rhack(key) {
    const g = game;
    assertNotInModal('rhack');
    let parsedCountPrefix = false;
    // C ref: cmd.c:3634 — each rhack cycle starts with nopick cleared.
    g.context.nopick = 0;
 
    // C ref: cmd.c:5100 — assume next command will take game time.
    // Must be set unconditionally, before any command dispatch.
    g.context.move = 1;
    // C ref: cmd.c:4344 — each rhack cycle starts with travel cleared.
    // In C this happens before dispatching the parsed command; keeping
    // stale travel state across time-consuming commands is incorrect.
    g.context.travel = 0;
    g.context.travel1 = 0;
 
    // C ref: cmd.c:4234 — check command queue before parse()/input,
    // regardless of whether caller supplied a key.
    // cmdq_add_ec (from iactions, lock, dig, etc.) queues commands for
    // the next moveloop iteration. Dispatch them before any parse path.
    const queued = cmdq_pop();
    if (queued) {
        if (queued.typ === CMDQ_EXTCMD && typeof queued.ec_entry === 'function') {
            // C ref: cmd.c:4238-4239 — CMDQ_EXTCMD dispatch
            const result = await queued.ec_entry();
            g.context.move = (result & 0x01) ? 1 : 0; // ECMD_TIME
            // C ref: cmd.c post-command tail for extcmd dispatch.
            // Apply reset semantics even for queued extcmds.
            if (g.context.move) {
                // Match C's kickedloc clearing rule (skip for kick).
                if (queued.ec_entry !== dokick && g.kickedloc) {
                    g.kickedloc.x = 0;
                    g.kickedloc.y = 0;
                }
                pushCtxMoveLog('rhack', g.context.move);
            } else {
                reset_cmd_vars(true);
            }
            return;
        }
        key = (queued.typ === CMDQ_KEY) ? (queued.key | 0) : 0;
    }
 
    if (key === 0) {
        // C ref: cmd.c parse() — first-time command input path only.
        g.multi = 0;
        // C ref: cmd.c:5779 — flush_screen(1) before readchar().
        // Paints all pending gnew entries and positions cursor at hero.
        // This is the primary flush point that ensures the grid is current
        // before every command input. bot() is idempotent (clears its
        // flags), so a redundant call from flush_screen is harmless.
        await flush_screen(1);
        key = await nhgetch();
        // C ref: cmd.c parse()/get_count():
        // gather optional numeric prefix, then assign gm.multi and decrement
        // once if non-zero before command dispatch.
        if (key >= 48 && key <= 57) {
            const counted = await getCount(key, 32767, game?.nhDisplay || null);
            g.multi = counted.count | 0;
            key = counted.key | 0;
            parsedCountPrefix = g.multi > 0;
        }
        // C ref: cmd.c parse() — ESC does an early clear_nhwindow(WIN_MESSAGE)
        // before multi/cmd_key setup, then parse does the normal trailing clear.
        if (key === 27) {
            if (g._pending_message) g._last_toplines = g._pending_message;
            await tty_clear_nhwindow('message');
        }
        pushMultiLog('parse', g.multi);
        if (g.multi) {
            g.multi--;
        }
        // C ref: cmd.c parse() → tty_clear_nhwindow(WIN_MESSAGE)
        if (g._pending_message) g._last_toplines = g._pending_message;
        await tty_clear_nhwindow('message');
    }
 
    if (typeof key === 'number') key = String.fromCharCode(key);
 
    // Apply BIND= remapping using the command table before movement/switch
    // dispatch, so custom bindings follow the same command path as canonical
    // keys (C ref: cmd.c bind_key affects parse/rhack dispatch).
    const bound = cmdByKey(key);
    if (bound?.name) {
        const dispatchKey = COMMAND_DISPATCH_KEY[bound.name];
        if (dispatchKey) {
            key = dispatchKey;
        }
    }
 
    // C ref: tty_nhgetch() clears a non-empty topline before command dispatch.
    // Replay can call rhack() with an explicit key (without nhgetch here),
    // so mirror that transition when the message line is still latched.
    // Save toplines before clearing (for ^P prev message).
    if (g._pending_message) g._last_toplines = g._pending_message;
    await tty_clear_nhwindow('message');
 
    if (g.iflags?.getloc_tip_active) {
        if (key === '\u001b' || key === ' ' || key === '\r' || key === '\n') {
            // C ref: getpos tip help runs through xwaitforspace; dismissing the
            // overlay returns to travel prompt mode (does not cancel travel).
            await restoreGetposPrompt(game?.nhDisplay || null);
        }
        g.context.move = 0;
        return;
    }
 
    if (g.iflags?.getloc_travelmode && key === '\u001b') {
        // C ref: ESC cancels getpos → dotravel returns ECMD_CANCEL.
        // Fully exit travel mode so subsequent keys are normal commands.
        await dismissGetposOverlay(game?.nhDisplay || null);
        g.iflags.getloc_travelmode = false;
        g.iflags.getloc_tip_active = false;
        g.context.move = 0;
        return;
    }
 
    // Movement keys (lowercase = step, uppercase = run, Ctrl = rush)
    // C ref: cmd.c movement dispatch — check both hjkl and numpad tables
    const activeVikeys = getVikeys();
    if (activeVikeys[key]) {
        const vk = activeVikeys[key];
        g.u.dx = vk.dx;
        g.u.dy = vk.dy;
        g.u.dz = 0;
        g.context.move = 1;
        // C ref: cmd.c set_move_cmd(dir, run) — plain movement explicitly
        // sets context.run=0 (run/rush use 1/3). This must overwrite any
        // prior run state from earlier commands.
        g.context.run = vk.rush ? 3 : (vk.run ? 1 : 0);
        // C ref: cmd.c:1988-1990 — set domove_attempting for ALL movement
        // (DOMOVE_WALK for plain, DOMOVE_RUSH for run/rush)
        g.domove_attempting = (vk.run || vk.rush) ? DOMOVE_RUSH : DOMOVE_WALK;
        // C ref: cmd.c:3783-3784 — counted plain movement repeats via context.mv.
        if (!(vk.run || vk.rush) && g.multi)
            g.context.mv = true;
        // C ref: cmd.c — capital movement keys set run mode, Ctrl+dir sets rush.
        // Run mode repeats domove via multi counter in moveloop_core.
        // We set multi/mv/run but the actual repeat happens in moveloop.
        if (vk.run || vk.rush) {
            // C ref: cmd.c DOMOVE_RUSH firsttime path resets turn-history
            // for corridor steering.
            g.u.last_str_turn = 0;
            g.context.mv = true;
            g.multi = COLNO;
            pushMultiLog('rhack', g.multi);
            g.cmd_key = key;
        }
        await domove();
        // C ref: cmd.c rhack() DOMOVE_WALK branch clears forcefight after domove.
        g.context.forcefight = false;
        return;
    }
 
    // C ref: cmd.c command dispatch table
    // When num_pad is ON, several letter keys are rebound to non-movement
    // commands. C ref: cmd.c:3351-3362 (number_pad bindings).
    if (game.iflags?.num_pad) {
        switch (key) {
        case 'h': // help (was: west)
            g.context.move = 0;
            // TODO: dohelp() — for now, show extended command help
            await pline('Help is available through #help or ?.');
            break;
        case 'j': { // jump (was: south)
            const res = await dojump();
            g.context.move = (res & ECMD_TIME) ? 1 : 0;
            break;
        }
        case 'k': { // kick (was: north)
            const res = await dokick();
            g.context.move = (res & 0x01) ? 1 : 0;
            break;
        }
        case 'l': { // loot (was: east)
            const res = await doloot();
            g.context.move = (res & ECMD_TIME) ? 1 : 0;
            break;
        }
        case 'u': { // untrap (was: northeast)
            g.context.move = 0;
            await pline('You search for traps nearby.');
            // TODO: dountrap()
            break;
        }
        case 'N': // name (was: run-southeast)
            g.context.move = 0;
            // falls through to existing 'C' naming handler below
            break;
        default:
            // Not a num_pad rebound key — fall through to normal switch
            break;
        }
        // If handled by num_pad switch, return early
        if ('hjklu'.includes(key)) return;
        if (key === 'N') { /* fall through to main switch for naming */ }
    }
 
    switch (key) {
    case 'Z': { // cast spell
        const res = await docast();
        g.context.move = (res & ECMD_TIME) ? 1 : 0;
        break;
    }
    case '\u0004': { // Ctrl-D: kick
        // C ref: cmd.c C('d') → dokick
        const kickResult = await dokick();
        // C ref: ECMD_TIME → context.move=1, otherwise 0
        g.context.move = (kickResult & 0x01) ? 1 : 0; // ECMD_TIME = 0x01
        break;
    }
    case '\u0017': { // Ctrl-W: wizard wish
        // C ref: cmd.c can_do_extcmd — WIZMODECMD requires wizard mode
        if (!g.flags?.debug) {
            await pline("Unavailable command 'wizwish'.");
            // C: failed command → reset_cmd_vars(TRUE) + post-dispatch reset
            reset_cmd_vars(true);
            g.context.move = 0;
            break;
        }
        await wiz_wish();
        g.context.move = 0;
        break;
    }
    case '\u0006': { // Ctrl-F: wizard map
        // C ref: cmd.c C('f') -> wiz_map
        if (!g.flags?.debug) {
            await pline("Unavailable command 'wizmap'.");
            reset_cmd_vars(true);
            g.context.move = 0;
            break;
        }
        await wiz_map();
        g.context.move = 0;
        break;
    }
    case '\u000f': { // Ctrl-O: dungeon overview
        // C ref: dungeon.c dooverview() → dooverview_or_wiz_vicinity()
        // Shows a text window with visited dungeon levels.
        g.context.move = 0;
        const ovWin = create_nhwindow_menu();
        // C ref: dungeon.c show_overview() populates NHW_MENU rows and ends
        // with end_menu(win, 0): no inverse prompt header line.
        const dnum = g.u?.uz?.dnum ?? 0;
        const dname = g.dungeons?.[dnum]?.dname || 'The Dungeons of Doom';
        add_menu(ovWin, null, 0, 0, ATR_INVERSE, NO_COLOR, `${dname}:`, 0);
        add_menu_str(ovWin, `   Level 1: <- You are here.`);
        end_menu(ovWin, null);
        await select_menu(ovWin, 0); // PICK_NONE
        destroy_nhwindow_menu(ovWin);
        break;
    }
    case '\u0010': { // Ctrl-P: previous message
        // C ref: topl.c:21 tty_doprev_message()
        g.context.move = 0;
        const pmw = g.iflags?.prevmsg_window || 's';
        const pmwChar = pmw.charAt(0); // 's'ingle, 'f'ull, 'c'ombination, 'r'eversed
        if (pmwChar === 's') {
            // Single mode: just redisplay current toplines
            const prevMsg = g._last_toplines || g._pending_message || '';
            if (prevMsg) {
                const display = game?.nhDisplay || null;
                g._pending_message = prevMsg;
                g._last_toplines = prevMsg;
                if (display) {
                    display.toplines = prevMsg;
                    display.topMessage = prevMsg;
                    display.toplin = TOPLINE_NEED_MORE;
                    pushRngLogEntry('^toplin[redotoplin=1]');
                    if (typeof display.clearRow === 'function') {
                        display.clearRow(0);
                        display.putstr(0, 0, prevMsg);
                    }
                }
            }
        } else {
            // Full/reversed/combination: show message history in a menu window
            // C ref: topl.c:80-102 (reversed mode)
            const msgHistory = get_message_history();
            const prevmsgWin = create_nhwindow_menu();
            add_menu(prevmsgWin, null, 0, 0, 0, 8/*NO_COLOR*/, 'Message History', 0);
            add_menu_str(prevmsgWin, '');
            for (const msg of msgHistory) {
                add_menu_str(prevmsgWin, msg);
            }
            // C ref: topl.c uses putstr() not add_menu()/end_menu(),
            // so maxrow tracks putstr count (no +1 for prompt) and
            // maxcol = strlen + 1 (not + 2).
            prevmsgWin.textLikePrompt = true; // maxrow without +1
            end_menu(prevmsgWin, null);
            if (prevmsgWin.cols > 0) prevmsgWin.cols--; // putstr width
            await select_menu(prevmsgWin, 0); // PICK_NONE
            destroy_nhwindow_menu(prevmsgWin);
        }
        break;
    }
    case '\u0012': { // Ctrl-R: redraw screen
        // C ref: cmd.c doredraw() → docrt()
        g.context.move = 0;
        // C ref: display.c docrt_flags() does cls() first, then redraws map.
        await cls();
        await docrt();
        break;
    }
    case '\u0014': { // Ctrl-T: teleport self
        // C ref: teleport.c:dotelecmd() -> dotele(ignore_restrictions).
        // dotele() handles teleport eligibility checks, spell fallback,
        // hunger cost, and turn consumption.
        const tookTurn = await dotele(!!g.flags?.debug);
        g.context.move = tookTurn ? 1 : 0;
        break;
    }
    case '\u0018': { // Ctrl-X: show attributes
        // C ref: cmd.c doattributes() → enlightenment()
        // C ref: insight.c enlightenment() uses NHW_MENU with end_menu(win, 0),
        // placing the title as the first content line (not an inverse prompt).
        g.context.move = 0;
        const attrWin = create_nhwindow_menu();
        const rawName = g.plname || 'you';
        const capName = rawName.charAt(0).toUpperCase() + rawName.slice(1);
        const roleName = (g.flags?.female && g.urole?.name?.f) ? g.urole.name.f : (g.urole?.name?.m || 'Adventurer');
        const ulevel = g.u?.ulevel || 1;
        const rankSlot = Math.max(0, Math.min(8, ulevel - 1));
        const rankName = (g.flags?.female && g.urole?.rank?.[rankSlot]?.f)
            ? g.urole.rank[rankSlot].f
            : (g.urole?.rank?.[rankSlot]?.m || roleName);
        const genderAdj = g.flags?.female ? 'female' : 'male';
        const raceNoun = g.urace?.noun || 'human';
        const rankArticle = /^[aeiou]/i.test(rankName) ? 'an' : 'a';
        const levelNameRaw = g.dungeons?.[g.u?.uz?.dnum || 0]?.dname || 'The Dungeons of Doom';
        const levelName = levelNameRaw.startsWith('The ')
            ? `the ${levelNameRaw.slice(4)}`
            : levelNameRaw;
        const dlevel = g.u?.uz?.dlevel || 1;
        const turns = g.moves || 0;
        const xp = g.u?.uexp || 0;
        const nextXp = g.newuexp || 20;
        const hp = g.u?.uhp || 1;
        const hpmax = g.u?.uhpmax || hp;
        const en = g.u?.uen || 0;
        const enmax = g.u?.uenmax || en;
        const ac = g.u?.uac ?? 10;
        const money = money_cnt(g.invent);
        const pickupTypes = g.flags?.pickup_types || '';
        const wearingAnyArmor = !!(g.u?.uarm || g.u?.uarmc || g.u?.uarmh
            || g.u?.uarms || g.u?.uarmg || g.u?.uarmf || g.u?.uarmu);
        const alignName = (g.flags?.initalign === 2) ? 'lawful'
            : (g.flags?.initalign === 0) ? 'chaotic' : 'neutral';
        const missionGod = (g.flags?.initalign === 2) ? (g.urole?.lgod || 'your deity')
            : (g.flags?.initalign === 0) ? (g.urole?.cgod || 'your deity')
                : (g.urole?.ngod || 'your deity');
        // C ref: insight.c:533-545 — show opposing gods (skip player's alignment)
        const opposedParts = [];
        if (g.u.ualign?.type !== A_LAWFUL)
            opposedParts.push(`${align_gname(A_LAWFUL)} (lawful)`);
        if (g.u.ualign?.type !== A_NEUTRAL)
            opposedParts.push(`${align_gname(A_NEUTRAL)} (neutral)`);
        if (g.u.ualign?.type !== A_CHAOTIC)
            opposedParts.push(`${align_gname(A_CHAOTIC)} (chaotic)`);
        const opposedStr = opposedParts.join(' and ');
        const wieldedName = g.u.uwep
            ? ((g.u.uwep.quan || 1) === 1
                ? an(game.objects[g.u.uwep.otyp]?.oc_name || 'weapon')
                : makeplural(game.objects[g.u.uwep.otyp]?.oc_name || 'weapon'))
            : '';
        let weaponSkillLine = '';
        if (g.u.uwep) {
            const wtype = weapon_type(g.u.uwep);
            if (wtype !== P_NONE && !is_ammo(g.u.uwep)) {
                const sklvl = P_SKILL(wtype);
                const hav = (sklvl !== P_UNSKILLED && sklvl !== P_SKILLED);
                const sklvlbuf = (sklvl === P_ISRESTRICTED)
                    ? 'no'
                    : cmdSkillLevelNameFromValue(sklvl).toLowerCase();
                weaponSkillLine = hav
                    ? ` You have ${sklvlbuf} skill with ${skill_name(wtype)}.`
                    : ` You are ${sklvlbuf} in ${skill_name(wtype)}.`;
            }
        } else {
            weaponSkillLine = ' You are unskilled in bare handed combat.';
        }
        const statusLines = [
            ' You aren\'t hungry.',
            ' You are unencumbered.',
            g.u.uwep ? ` You are wielding ${wieldedName}.` : ' You are bare handed.',
            weaponSkillLine,
        ];
        if (!wearingAnyArmor) {
            statusLines.push(' You aren\'t wearing any armor.');
        }
        const lines = [
            `${capName} the ${roleName}'s attributes:`,
            '',
            'Background:',
            ` You are ${rankArticle} ${rankName}, a level ${ulevel} ${genderAdj} ${raceNoun} ${roleName}.`,
            ` You are ${alignName}, on a mission for ${missionGod}`,
            ` who is opposed by ${opposedStr}.`,
            ' You are right-handed.',
            ` You are in ${levelName}, on level ${dlevel}.`,
            turns === 1 ? ' You have just started your adventure.' : ` You entered the dungeon ${turns} turn${turns !== 1 ? 's' : ''} ago.`,
            (ulevel < 30 && g.flags?.debug) ? ` You have ${xp} experience point${xp !== 1 ? 's' : ''}, ${nextXp} ${xp > 0 ? 'more ' : ''}needed to attain level ${ulevel + 1}.` : ` You have ${xp} experience point${xp !== 1 ? 's' : ''}.`,
            '',
            'Basics:',
            ` You have all ${hpmax} hit points.`,
            ` You have all ${enmax} energy points (spell power).`,
            ` Your armor class is ${ac}.`,
            money > 0 ? ` You have ${money} gold pieces in your wallet.` : ' Your wallet is empty.',
            !g.flags?.pickup
                ? ' Autopickup is off.'
                : pickupTypes
                    ? ` Autopickup is on for ${pickupTypes}.`
                    : ' Autopickup is on for all types.',
            '',
            'Characteristics:',
            ` Your strength is ${ACURR(A_STR)}.`,
            ` Your dexterity is ${ACURR(A_DEX)}.`,
            ` Your constitution is ${ACURR(A_CON)}.`,
            ` Your intelligence is ${ACURR(A_INT)}.`,
            ` Your wisdom is ${ACURR(A_WIS)}.`,
            ` Your charisma is ${ACURR(A_CHA)}.`,
            '',
            'Status:',
            ...statusLines,
            '',
            'Miscellaneous:',
            ' Total elapsed playing time is none.',
        ];
        if (g.flags?.debug || g.flags?.explore) {
            lines.push('You are running in debug mode.');
        }
        while (lines.length < 23) lines.push('');
        for (const line of lines) add_menu_str(attrWin, line);
        end_menu(attrWin, null);
        await select_menu(attrWin, 0); // PICK_NONE
        destroy_nhwindow_menu(attrWin);
        break;
    }
    case '\u0016': { // Ctrl-V: wizard level teleport
        if (!g.flags?.debug) {
            await pline("Unavailable command 'wizlevelport'.");
            g.context.move = 0;
            break;
        }
        await wiz_level_tele();
        g.context.move = 0;
        break;
    }
    case '$': { // #showgold
        // C ref: invent.c:4503 doprgold()
        g.context.move = 0;
        const umoney = money_cnt(g.invent);
        if (g.flags?.verbose) {
            if (!umoney) {
                await pline('Your wallet is empty.');
            } else {
                await pline(`Your wallet contains ${umoney} ${currency(umoney)}.`);
            }
        } else {
            if (umoney) {
                await You(`are carrying a total of ${umoney} ${currency(umoney)}.`);
            } else {
                await You('have no money.');
            }
        }
        break;
    }
    case '+': { // showspells
        const res = await dovspell();
        g.context.move = (res & ECMD_TIME) ? 1 : 0;
        break;
    }
    case '.': // wait — C ref: donull() in do.c
        if (await cmd_safety_prevention('Waiting', 'a no-op (to rest)',
                                        'Are you waiting to get hit?', 'did_nothing_flag')) {
            g.context.move = 0;
        } else {
            g.context.move = 1;
        }
        break;
    case 's': // search
        // C ref: cmd.c dispatch sets occupation for repeatable commands
        // before calling dosearch() when a count prefix is active.
        if (!g.occupation && parsedCountPrefix && g.multi) {
            set_occupation(dosearch, 'searching', g.multi, true);
        }
        g.context.move = (await dosearch()) ? 1 : 0;
        break;
    case 'T': { // takeoff
        const res = await dotakeoff();
        g.context.move = (res & ECMD_TIME) ? 1 : 0;
        break;
    }
    case '#': { // extended command
        const typed = await getlin('#', game?.nhDisplay || null, {
            logHookedLifecycle: true,
            autocomplete: extcmdAutocomplete,
        });
        if (typed == null) {
            g.context.move = 0;
            break;
        }
        let extCmd = extcmdAutocomplete(normalizeExtcmdInput(typed));
        // Most extended commands consume a turn. Some (like #chat) do.
        // For now, set context.move=1 for known time-consuming commands.
        const timeCmds = ['chat', 'dip', 'enhance', 'force', 'invoke', 'jump', 'loot',
            'monster', 'offer', 'pray', 'ride', 'rub', 'sit', 'turn', 'twoweapon', 'wipe'];
        if (extCmd === 'version') {
            // C ref: version.c doextversion() → get_lua_version()
            // First call to doextversion creates a Lua state and loads
            // nhlib.lua, which shuffles align[3] consuming rn2(3)+rn2(2).
            if (!g._lua_version_inited) {
                g._lua_version_inited = true;
                rn2(3);
                rn2(2);
            }
            await doextversion_helpitem();
            g.context.move = 0;
        } else if (extCmd === 'terrain') {
            await doterrain_cmd();
            g.context.move = 0;
        } else if (extCmd === 'overview' || extCmd === 'chronicle'
                || extCmd === 'conduct' || extCmd === 'vanquished'
                || extCmd === 'genocided') {
            // C ref: these display-only commands return ECMD_OK (no turn).
            // Stub: just acknowledge without display (no RNG consumed).
            g.context.move = 0;
            break;
        } else if (extCmd === 'annotate') {
            // C ref: cmd.c donamelevel() — prompts for annotation text via getlin.
            // Must consume the getlin input to avoid leftover keys.
            await getlin('annotate');
            g.context.move = 0;
            break;
        } else if (timeCmds.includes(extCmd)) {
            if (extCmd === 'chat') {
                const res = await dotalk();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            }
            // Dispatch extended commands to their implementation functions.
            // Each returns ECMD_TIME or ECMD_OK; we set context.move accordingly.
            if (extCmd === 'pray') {
                const res = await dopray();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            } else if (extCmd === 'enhance') {
                // C ref: weapon.c enhance_weapon_skill()
                const res = await enhance_weapon_skill();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            } else if (extCmd === 'sit') {
                const res = await dosit();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            } else if (extCmd === 'dip') {
                const res = await dodip();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            } else if (extCmd === 'turn') {
                const res = await doturn();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            } else if (extCmd === 'twoweapon') {
                const res = await dotwoweapon();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            } else if (extCmd === 'ride') {
                const res = await doride();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            } else if (extCmd === 'rub') {
                const res = await dorub();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            } else if (extCmd === 'force') {
                const res = await doforce();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            } else if (extCmd === 'wipe') {
                const res = await dowipe();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            } else if (extCmd === 'loot') {
                const res = await doloot();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            } else if (extCmd === 'jump') {
                const res = await dojump();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            } else if (extCmd === 'monster') {
                const res = await domonability();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            } else if (extCmd === 'offer') {
                const res = await dosacrifice();
                g.context.move = (res & ECMD_TIME) ? 1 : 0;
                break;
            } else if (extCmd === 'invoke') {
                // C ref: artifact.c:1749 doinvoke() — getobj + arti_invoke
                // arti_invoke not fully ported but must consume getobj key.
                const invobj = await getobj('invoke', () => true, 0x02 /*GETOBJ_PROMPT*/);
                if (!invobj) {
                    g.context.move = 0;
                } else {
                    await pline('Nothing special happens.');
                    g.context.move = 1;
                }
                break;
            }
            g.context.move = 1;
        } else if (extCmd === 'quit') {
            // C ref: cmd.c extcmdlist "quit" dispatches to done2()
            g.context.move = 0;
            const { done2 } = await import('./end.js');
            await done2();
            break;
        } else if (extCmd === 'shell') {
            // C ref: cmd.c dosh() — spawn a subshell
            g.context.move = 0;
            throw new ShellEscape();
            break;
        } else if (extCmd === 'name') {
            // C ref: do_name.c docallcmd() handles #name and command 'C'.
            const res = await docallcmd();
            g.context.move = (res & ECMD_TIME) ? 1 : 0;
        } else if (extCmd === 'adjust') {
            await doorganize();
            g.context.move = 0;
        } else if (extCmd === 'levelchange') {
            await wiz_level_change();
            g.context.move = 0;
        } else if (extCmd === 'wizgenesis') {
            await wiz_genesis();
            g.context.move = 0;
        } else if (extCmd === 'wizmap') {
            // C ref: cmd.c extcmdlist "wizmap" -> wiz_map (WIZMODECMD)
            if (!g.flags?.debug) {
                await pline("Unavailable command 'wizmap'.");
                g.context.move = 0;
                break;
            }
            await wiz_map();
            g.context.move = 0;
        } else if (extCmd === 'wizwish') {
            // C ref: cmd.c doextcmd() + can_do_extcmd(WIZMODECMD)
            if (!g.flags?.debug) {
                await pline("Unavailable command 'wizwish'.");
                g.context.move = 0;
                break;
            }
            await wiz_wish();
            g.context.move = 0;
        } else if (extCmd === 'wizintrinsic') {
            if (!g.flags?.debug) {
                await pline("Unavailable command 'wizintrinsic'.");
                g.context.move = 0;
                break;
            }
            await wiz_intrinsic();
            g.context.move = 0;
        } else if (extCmd === 'polyself') {
            await dopolyself();
            g.context.move = 0;
        } else {
            if (extCmd) {
                // C ref: win/tty/getline.c:320-324 tty_get_ext_cmd()
                // unknown extended command path:
                // pline("%s%.60s: unknown extended command.", extcmd_char, buf)
                await pline(`${key}${extCmd}: unknown extended command.`);
            }
            g.context.move = 0;
        }
        break;
    }
    case 'a': { // apply
        const res = await doapply();
        g.context.move = (res & ECMD_TIME) ? 1 : 0;
        break;
    }
    case 'e': { // eat
        // C ref: eat.c doeat()
        const res = await doeat();
        g.context.move = (res & ECMD_TIME) ? 1 : 0;
        break;
    }
    case 't': { // throw
        // C ref: dothrow.c dothrow — prompts for item + direction
        const throwRes = await dothrow();
        if (throwRes === 0 /* ECMD_OK */ || throwRes === 2 /* ECMD_CANCEL */)
            g.context.move = 0;
        break;
    }
    case 'f': { // fire (quivered ammo)
        // C ref: dothrow.c dofire — fire quivered/wielded item
        const fireRes = await dofire();
        if (fireRes === 0 /* ECMD_OK */ || fireRes === 2 /* ECMD_CANCEL */)
            g.context.move = 0;
        break;
    }
    case 'Q': { // quiver
        // C ref: cmd.c dowieldquiver — prompt for item, then maybe confirm
        pushMultiLog('doquiver_core', g.multi);
        const letters = inventory_letters((obj) => quiver_ok_suggest(obj));
        // C ref: getobj prompt for quiver command:
        // - Nothing quivered → suggest first eligible letter as default
        // - Something quivered → suggest '-' (unquiver) as default,
        //   with eligible letters shown after
        let promptLetters;
        if (g.u.uquiver) {
            // Hero has something quivered: default is '-' to unquiver
            promptLetters = letters ? `- ${letters}` : '-';
        } else {
            // Nothing quivered: default is first eligible letter
            promptLetters = letters || '-';
        }
        const prompt = `What do you want to ready? [${promptLetters} or ?*]`;
        const item = await prompt_inventory_char(prompt, 'item-prompt');
        if (item === 27) { g.context.move = 0; break; }
        const obj = find_inventory_obj_by_letter(item);
        if (!obj) { g.context.move = 0; break; }
        if (obj === g.u.uswapwep) {
            const display = game?.nhDisplay || null;
            const answer = await ynFunction(
                'That is your alternate weapon.  Ready it instead?',
                'ynq',
                'q'.charCodeAt(0),
                display,
            );
            if (answer !== 'y'.charCodeAt(0)) {
                g.context.move = 0;
                break;
            }
            setuswapwep(null);
        }
        setuqwep(obj);
        await prinv_like(obj);
        g.context.move = 0;
        break;
    }
    case 'r': { // read
        const rresult = await doread();
        g.context.move = (rresult & ECMD_TIME) ? 1 : 0;
        break;
    }
    case 'q': { // quaff
        const qresult = await dodrink();
        g.context.move = (qresult & ECMD_TIME) ? 1 : 0;
        break;
    }
    case 'z': { // zap
        const zresult = await dozap();
        g.context.move = (zresult & ECMD_TIME) ? 1 : 0;
        break;
    }
    case 'P': { // puton (ring/amulet)
        const res = await doputon();
        g.context.move = (res & ECMD_TIME) ? 1 : 0;
        break;
    }
    case 'R': { // remove (ring/amulet)
        const res = await doremring();
        g.context.move = (res & ECMD_TIME) ? 1 : 0;
        break;
    }
    case 'W': { // wear armor
        const res = await dowear();
        g.context.move = (res & ECMD_TIME) ? 1 : 0;
        break;
    }
    case ':': // look
        // Look is a free action — context.move stays 0
        await look_here(g);
        g.context.move = 0;
        break;
    case 'E': { // engrave
        const res = await doengrave();
        g.context.move = (res & ECMD_TIME) ? 1 : 0;
        break;
    }
    case 'd': { // drop
        const res = await dodrop();
        g.context.move = (res & ECMD_TIME) ? 1 : 0;
        break;
    }
    case 'o': { // open
        const res = await doopen();
        g.context.move = (res & ECMD_TIME) ? 1 : 0;
        break;
    }
    case 'c': { // close
        const res = await doclose();
        g.context.move = (res & ECMD_TIME) ? 1 : 0;
        break;
    }
    case ',': // pickup
        // C ref: hack.c:3792 dopickup
        {
            const dpResult = await dopickup();
            g.context.move = (dpResult & ECMD_TIME) ? 1 : 0;
        }
        break;
    case 'w': { // wield
        // C ref: wield.c dowield()
        const res = await dowield();
        g.context.move = (res & ECMD_TIME) ? 1 : 0;
        break;
    }
    case 'i': // inventory
        // C ref: invent.c ddoinv() → display_pickinv()
        g.context.move = 0;
        await ddoinv();
        break;
    case ')': { // current weapon
        // C ref: invent.c doprwep()
        g.context.move = 0;
        if (g.u?.uwep) {
            await pline(`You are wielding ${doname(g.u.uwep)}.`);
        } else {
            await pline('You are bare handed.');
        }
        break;
    }
    case '[': { // worn armor
        // C ref: invent.c doprarm()
        g.context.move = 0;
        const wearingAnyArmor = !!(g.u?.uarm || g.u?.uarmc || g.u?.uarmh
            || g.u?.uarms || g.u?.uarmg || g.u?.uarmf || g.u?.uarmu);
        if (!wearingAnyArmor) {
            await pline('You are not wearing any armor.');
        } else {
            await pline('You are wearing armor.');
        }
        break;
    }
    case '=': { // worn rings
        // C ref: invent.c doprring()
        g.context.move = 0;
        const left = g.u?.uleft || null;
        const right = g.u?.uright || null;
        if (!left && !right) {
            await pline('You are not wearing any rings.');
        } else if (left && right) {
            await pline(`You are wearing ${doname(left)} (left) and ${doname(right)} (right).`);
        } else {
            await pline(`You are wearing ${doname(left || right)}.`);
        }
        break;
    }
    case '"': { // worn amulet
        // C ref: invent.c dopramulet()
        g.context.move = 0;
        if (!g.u?.uamul) {
            await pline('You are not wearing an amulet.');
        } else {
            await pline(`You are wearing ${doname(g.u.uamul)}.`);
        }
        break;
    }
    case '(': { // used tools
        // C ref: invent.c doprtool()
        g.context.move = 0;
        let hasInUseTool = false;
        for (let obj = g.invent; obj; obj = obj.nobj) {
            if ((obj.owornmask & (W_TOOL | W_SADDLE)) !== 0) {
                hasInUseTool = true;
                break;
            }
            if (obj.oclass !== TOOL_CLASS) continue;
            if (obj === g.u?.uwep || obj.lamplit || (obj.otyp === LEASH && (obj.leashmon || 0) > 0)) {
                hasInUseTool = true;
                break;
            }
        }
        if (!hasInUseTool) {
            await pline('You are not using any tools.');
        } else {
            await display_inventory(null, true);
        }
        break;
    }
    case '>': { // go downstairs
        // C ref: do.c:1131 dodown() → next_level() → goto_level()
        const level = g.level;
        const u = g.u;
        if (level && u) {
            // C ref: do.c:dodown() calls set_move_cmd(DIR_DOWN, 0) before checks.
            u.dx = 0; u.dy = 0; u.dz = 1;
            const dn = level.dnstair;
            if (dn && u.ux === dn.x && u.uy === dn.y) {
                g.context.move = 1;
                await goto_level({ dnum: u.uz.dnum, dlevel: u.uz.dlevel + 1 });
            } else {
                g.context.move = 0;
                await You_cant('go down here.');
            }
        }
        break;
    }
    case '_': { // travel
        // C ref: cmd.c dotravel() + dotravel_target()
        const tr = await dotravel_cmd();
        g.context.move = (tr & ECMD_TIME) ? 1 : 0;
        break;
    }
    // C ref: cmd.c:4351-4362 — prefix keys (PREFIXCMD flag)
    // After the prefix, rhack loops back to got_prefix_input and reads
    // another key via parse(). Both keys are consumed in ONE rhack call.
    case 'g': case 'G': case 'F': case 'm': {
        const prefixCh = typeof key === 'number' ? String.fromCharCode(key) : key;
        // C: do_rush/do_run/do_fight sets context state, returns ECMD_OK
        if (prefixCh === 'g') { g.context.run = 2; g.domove_attempting = (g.domove_attempting || 0) | 2; }
        else if (prefixCh === 'G') { g.context.run = 3; g.domove_attempting = (g.domove_attempting || 0) | 2; }
        else if (prefixCh === 'F') { g.context.forcefight = true; g.domove_attempting = (g.domove_attempting || 0) | 1; }
        // 'm': reqmenu prefix, simplified
        // C: goto got_prefix_input → parse() reads second key
        // parse() emits ^multi[parse=0] and reads via readchar
        pushMultiLog('parse', 0);
        const followKey = await nhgetch();
        const followDir = direction_from_key(followKey);
        if (followDir) {
            // C: MOVEMENTCMD after DOMOVE_RUSH → set multi, domove
            g.u.dx = followDir[0];
            g.u.dy = followDir[1];
            g.u.dz = 0;
            if (g.domove_attempting & 2) { // DOMOVE_RUSH
                g.multi = Math.max(COLNO, ROWNO);
                pushMultiLog('rhack', g.multi);
                g.context.mv = true;
            }
            // C ref: cmd.c docmd MOVEMENTCMD path calls domove() immediately
            // for F (forcefight) and walk (DOMOVE_WALK). Run/rush use multi loop.
            if (prefixCh === 'F' || !(g.domove_attempting & 2)) {
                await domove();
                // C ref: cmd.c rhack() DOMOVE_WALK branch clears forcefight
                // immediately after domove returns.
                g.context.forcefight = false;
            }
            g.context.move = 1;
            return;
        }
        // Non-direction follow-up → cancel (double prefix or invalid)
        {
            const cancelMsg = prefixCh === 'g' ? 'Double rush prefix, canceled.'
                : prefixCh === 'G' ? 'Double run prefix, canceled.'
                : prefixCh === 'F' ? 'Double fight prefix, canceled.'
                : '';
            if (cancelMsg) {
                const _d = game?.nhDisplay || null;
                if (_d) {
                    game._pending_message = cancelMsg;
                    _d.toplines = cancelMsg;
                    _d.topMessage = cancelMsg;
                    _d.toplin = 1;
                    pushRngLogEntry('^toplin[redotoplin=1]');
                    if (typeof _d.clearRow === 'function') {
                        _d.clearRow(0); _d.putstr(0, 0, cancelMsg);
                    }
                }
            }
        }
        g.context.run = 0;
        g.domove_attempting = 0;
        g.context.forcefight = false;
        reset_cmd_vars(true);
        return;
    }
    case '@': { // toggle autopickup
        // C ref: options.c:9299 dotogglepickup()
        g.context.move = 0;
        g.flags.pickup = !g.flags.pickup;
        if (g.flags.pickup) {
            // C ref: oc_to_str converts pickup_types to symbols.
            // If pickup_types is empty/unset, displays "all objects".
            const pickupTypes = g.flags?.pickup_types || '';
            const oclStr = pickupTypes ? pickupTypes : 'all';
            // C ref: apelist (autopickup exceptions) adds exception note
            const apelist = g.apelist || null;
            let exceptStr = '';
            if (apelist) {
                let count = 0;
                for (let ape = apelist; ape; ape = ape.next) count++;
                exceptStr = count === 1
                    ? ', with one exception'
                    : ', with some exceptions';
            }
            await pline(`Autopickup: ON, for ${oclStr} objects${exceptStr}.`);
        } else {
            await pline('Autopickup: OFF.');
        }
        break;
    }
    case 'v': { // chronicle (do_gamelog)
        // C ref: cmd.c 'v' → do_gamelog() — show journal of major events
        // Displays a text window with game log entries.
        g.context.move = 0;
        const logWin = create_nhwindow_menu(NHW_TEXT);
        // C ref: insight.c:2579 — uses NHW_TEXT with putstr (plain text, no inverse)
        // NHW_TEXT windows have offx=0 in C's H2344_BROKEN path.
        logWin.forceOffx0 = true;
        // Title is a regular text line, not an end_menu prompt.
        add_menu_str(logWin, 'Logged events:');
        const entries = g.gamelog || [];
        if (entries.length === 0) {
            add_menu_str(logWin, ' none');
        } else {
            // C ref: insight.c:2588 — " Turn" header then "%5ld: %s" per entry
            add_menu_str(logWin, ' Turn');
            for (const entry of entries) {
                const turnStr = String(entry.turn || 0).padStart(5);
                add_menu_str(logWin, `${turnStr}: ${entry.text}`);
            }
        }
        end_menu(logWin, '');
        await select_menu(logWin, 0); // PICK_NONE
        destroy_nhwindow_menu(logWin);
        break;
    }
    case '<': { // go upstairs
        // C ref: do.c:1297 doup()
        g.context.move = 0;
        const level = g.level;
        const u = g.u;
        if (level && u) {
            // C ref: do.c:doup() calls set_move_cmd(DIR_UP, 0) before checks.
            u.dx = 0; u.dy = 0; u.dz = -1;
            const stway = level.upstair;
            if (!stway || u.ux !== stway.x || u.uy !== stway.y) {
                await You_cant('go up here.');
            } else if (u.uz.dlevel === 1) {
                // C ref: do.c:1333 — escape from dungeon prompt
                const ans = await ynFunction(
                    'Beware, there will be no return!  Still climb?',
                    'yn', 'n'.charCodeAt(0), null
                );
                if (String.fromCharCode(ans).toLowerCase() === 'y') {
                    // C: prev_level → goto_level
                    g.context.move = 1;
                    await goto_level({ dnum: u.uz.dnum, dlevel: u.uz.dlevel - 1 });
                }
            } else {
                g.context.move = 1;
                await goto_level({ dnum: u.uz.dnum, dlevel: u.uz.dlevel - 1 });
            }
        }
        break;
    }
    case ';': { // farlook (doquickwhatis)
        // C ref: pager.c:2329 doquickwhatis() → do_look(1, NULL)
        g.context.move = 0;
        await doquickwhatis();
        break;
    }
    case 'S': { // save game
        // C ref: save.c dosave() — clear message before and after y_n.
        g.context.move = 0;
        if (g._pending_message) g._last_toplines = g._pending_message;
        await tty_clear_nhwindow('message');
        const saveAns = await ynFunction('Really save?', 'yn', 'n'.charCodeAt(0), null);
        const saveCh = String.fromCharCode(saveAns).toLowerCase();
        if (g._pending_message) g._last_toplines = g._pending_message;
        await tty_clear_nhwindow('message');
        if (saveCh === 'y') {
            await pline('Saving...');
            throw new GameQuit('Saving...');
        }
        if (g.multi > 0) {
            nomul(0);
        }
        break;
    }
    case '!': { // shell escape
        // C ref: cmd.c dosh() — spawn a subshell
        g.context.move = 0;
        throw new ShellEscape();
    }
    case '?': { // help
        // C ref: pager.c:2860 dohelp()
        g.context.move = 0;
        const helpWin = create_nhwindow_menu();
        start_menu(helpWin);
        const items = [
            ['a', 'About NetHack (version information).'],
            ['b', 'Long description of the game and commands.'],
            ['c', 'List of game commands.'],
            ['d', 'Concise history of NetHack.'],
            ['e', 'Info on a character in the game display.'],
            ['f', 'Info on what a given key does.'],
            ['g', 'List of game options.'],
            ['h', 'Longer explanation of game options.'],
            ['i', "Using the '#optionsfull' or 'm O' command to set options."],
            ['j', 'Full list of keyboard commands.'],
            ['k', 'List of extended commands.'],
            ['l', 'List menu control keys.'],
            ['m', "Description of NetHack's command line."],
            ['n', 'The NetHack license.'],
            ['o', 'Support information.'],
        ];
        for (const [id, text] of items) {
            add_menu(helpWin, id, id, 0, 0, NO_COLOR, text, 0);
        }
        end_menu(helpWin, 'Select one item:');
        const picked = await select_menu(helpWin, PICK_ONE);
        destroy_nhwindow_menu(helpWin);
        const sel = picked?.items?.[0]?.identifier || '';
        if (sel === 'a') {
            await doextversion_helpitem();
        } else if (sel === 'b') {
            await display_help_file('help');
        } else if (sel === 'c') {
            await display_help_file('hh');
        } else if (sel === 'd') {
            await display_help_file('history');
        } else if (sel === 'e') {
            await dowhatis();
        } else if (sel === 'f') {
            await dowhatdoes();
        } else if (sel === 'g') {
            await display_text_window_pages(build_option_help_lines(), { dismissRows: 23 });
        } else if (sel === 'h') {
            await display_help_file('opthelp');
        } else if (sel === 'i') {
            const optMenuLines = await load_help_file_lines('optmenu');
            if (optMenuLines.length) {
                await display_text_window_pages(optMenuLines, { dismissRows: 20 });
            }
        } else if (sel === 'j') {
            await display_text_window_pages(build_key_bindings_help_lines(), { dismissRows: 14 });
        } else if (sel === 'k') {
            await display_help_file('cmdhelp');
        } else if (sel === 'l') {
            await display_text_window_pages(build_menu_controls_help_lines(), { dismissRows: 20 });
        } else if (sel === 'm') {
            const usageLines = await load_help_file_lines('usagehlp');
            if (usageLines.length) {
                await display_text_window_pages(usageLines, { dismissRows: 1 });
            }
        } else if (sel === 'n') {
            await display_help_file('license');
        } else if (sel === 'o') {
            await display_text_window_pages(build_contact_help_lines(), { dismissRows: 5 });
        }
        break;
    }
    case '/': { // whatis
        // C ref: pager.c dowhatis() -> do_look()
        g.context.move = 0;
        await dowhatis();
        break;
    }
    case '\x7f': { // terrain (DEL binding in tty sessions)
        await doterrain_cmd();
        g.context.move = 0;
        break;
    }
    case '\\': { // discoveries
        // C ref: o_init.c dodiscovered() → display known items
        g.context.move = 0;
        // C: creates NHW_TEXT and writes a plain heading line, not an
        // inverse prompt title.
        const discWin = create_nhwindow_menu();
        discWin.forceOffx0 = true;
        discWin.preDisplayMessage = true;
        add_menu_str(discWin, 'Discoveries, by order of discovery within each class');
        add_menu_str(discWin, '');
        const invOrder = g.flags?.inv_order || '';
        const discoClassOrder = invOrder
            ? [...invOrder]
            : [
                WEAPON_CLASS, ARMOR_CLASS, SCROLL_CLASS, SPBOOK_CLASS,
                POTION_CLASS, RING_CLASS, WAND_CLASS, AMULET_CLASS,
                TOOL_CLASS, FOOD_CLASS, GEM_CLASS, COIN_CLASS,
            ];
        let discoveredCt = 0;
        for (const oclass of discoClassOrder) {
            const classItems = [];
            for (let i = 0; i < game.objects.length; i++) {
                const od = game.objects[i];
                if (!od || od.oc_class !== oclass) continue;
                // C ref: o_init.c interesting_to_discover()
                // Only objects with descriptions are listed, and only if
                // discovered, encountered, or user-named.
                if (!od.oc_descr) continue;
                if (!od.oc_uname && !od.oc_name_known && !od.oc_encountered) {
                    continue;
                }
                classItems.push(i);
            }
            classItems.sort((a, b) => {
                const ao = game.objects[a]?.oc_disco_order;
                const bo = game.objects[b]?.oc_disco_order;
                const av = Number.isInteger(ao) ? ao : Number.MAX_SAFE_INTEGER;
                const bv = Number.isInteger(bo) ? bo : Number.MAX_SAFE_INTEGER;
                return (av - bv) || (a - b);
            });
            if (!classItems.length) continue;
            add_menu_heading(discWin, let_to_name(oclass));
            for (const i of classItems) {
                const od = game.objects[i];
                // C ref: o_init.c dodiscovered() uses oc_encountered for prefix.
                const prefix = od.oc_encountered ? '  ' : '* ';
                let typename = od.oc_name || 'unknown';
                if (oclass === SCROLL_CLASS) typename = `scroll of ${typename}`;
                else if (oclass === SPBOOK_CLASS) typename = `spellbook of ${typename}`;
                else if (oclass === POTION_CLASS) typename = `potion of ${typename}`;
                else if (oclass === RING_CLASS) typename = `ring of ${typename}`;
                else if (oclass === WAND_CLASS) typename = `wand of ${typename}`;
                if (od.oc_descr) typename += ` (${od.oc_descr})`;
                add_menu_str(discWin, `${prefix}${typename}`);
                discoveredCt++;
            }
        }
        if (!discoveredCt) {
            add_menu_str(discWin, 'No items have been discovered yet.');
        }
        end_menu(discWin, null);
        await select_menu(discWin, 0); // PICK_NONE
        destroy_nhwindow_menu(discWin);
        break;
    }
    case 'I': { // inventory types (dotypeinv)
        // C ref: invent.c dotypeinv() + pickup.c query_category().
        // Match C's category menu shape (all types + class entries +
        // optional BUC section) so tty window geometry/parity lines up.
        g.context.move = 0;
        if (!g.invent) {
            await You("aren't carrying anything.");
            break;
        }
        const invtWin = create_nhwindow_menu();
        start_menu(invtWin);
        const classSet = new Set();
        let blessedKnown = 0;
        let uncursedKnown = 0;
        for (let obj = g.invent; obj; obj = obj.nobj) {
            const cls = game.objects[obj.otyp]?.oc_class;
            if (cls) classSet.add(cls);
            if (obj.bknown) {
                if (obj.blessed) blessedKnown++;
                else if (!obj.cursed) uncursedKnown++;
            }
        }
 
        // C ref: query_category class ordering for inventory-category menus.
        const classOrder = [
            WEAPON_CLASS, ARMOR_CLASS, SCROLL_CLASS, SPBOOK_CLASS,
            POTION_CLASS, RING_CLASS, WAND_CLASS, TOOL_CLASS,
        ];
        let accel = 'a';
        for (const cls of classOrder) {
            if (!classSet.has(cls)) continue;
            add_menu(invtWin, cls, accel, 0, 0, NO_COLOR, let_to_name(cls), 0);
            accel = String.fromCharCode(accel.charCodeAt(0) + 1);
        }
 
        if (blessedKnown || uncursedKnown) {
            add_menu_str(invtWin, '');
            if (blessedKnown) {
                add_menu(invtWin, 'B', 'B', 0, 0, NO_COLOR, 'Items known to be Blessed', 0);
            }
            if (uncursedKnown) {
                add_menu(invtWin, 'U', 'U', 0, 0, NO_COLOR, 'Items known to be Uncursed', 0);
            }
        }
        end_menu(invtWin, 'What type of object do you want an inventory of?');
        await select_menu(invtWin, 1); // PICK_ONE
        destroy_nhwindow_menu(invtWin);
        break;
    }
    case 'D': { // multidrop
        // C ref: do.c:dodrop() via pickup.c:query_category().
        // Match category menu shape for parity (including CHOOSE_ALL help line).
        g.context.move = 0;
        if (!g.invent) {
            await You("have nothing to drop.");
            break;
        }
        const dropWin = create_nhwindow_menu();
        start_menu(dropWin);
 
        const classSet_dd = new Set();
        let blessedKnown = 0;
        let uncursedKnown = 0;
        for (let obj = g.invent; obj; obj = obj.nobj) {
            const od = game.objects[obj.otyp];
            if (od) classSet_dd.add(od.oc_class);
            if (obj.bknown) {
                if (obj.blessed) blessedKnown++;
                else if (!obj.cursed) uncursedKnown++;
            }
        }
 
        // query_category CHOOSE_ALL entry + hint line.
        add_menu(dropWin, 'A', 'A', 0, 0, NO_COLOR, 'Auto-select every relevant item', 0);
        add_menu_str(dropWin, '    (ignored unless some other choices are also picked)');
        add_menu_str(dropWin, '');
 
        // query_category "All types" category selector.
        add_menu(dropWin, 'a', 'a', 0, 0, NO_COLOR, 'All types', 0);
 
        const classOrder = [
            WEAPON_CLASS, ARMOR_CLASS, SCROLL_CLASS, SPBOOK_CLASS,
            POTION_CLASS, RING_CLASS, WAND_CLASS, TOOL_CLASS,
        ];
        let accel = 'b';
        for (const cls of classOrder) {
            if (!classSet_dd.has(cls)) continue;
            add_menu(dropWin, cls, accel, 0, 0, NO_COLOR, let_to_name(cls), 0);
            accel = String.fromCharCode(accel.charCodeAt(0) + 1);
        }
        add_menu_str(dropWin, '');
        if (blessedKnown) add_menu(dropWin, 'B', 'B', 0, 0, NO_COLOR, 'Items known to be Blessed', 0);
        if (uncursedKnown) add_menu(dropWin, 'U', 'U', 0, 0, NO_COLOR, 'Items known to be Uncursed', 0);
 
        end_menu(dropWin, 'Drop what type of items?');
        await select_menu(dropWin, 1); // PICK_ONE
        destroy_nhwindow_menu(dropWin);
        break;
    }
    case 'C': { // call/name
        // C ref: do_name.c docallcmd()
        const res = await docallcmd();
        g.context.move = (res & ECMD_TIME) ? 1 : 0;
        break;
    }
    case 'x': { // swap weapon
        // C ref: wield.c doswapweapon() — swap primary/secondary weapon
        const swapResult = await doswapweapon();
        g.context.move = (swapResult & ECMD_TIME) ? 1 : 0;
        break;
    }
    case 'p': { // pay shopkeeper
        // C ref: shk.c dopay() — pay shopping bill
        const payResult = await dopay();
        g.context.move = payResult ? 1 : 0;
        break;
    }
    case 'O': { // options
        // C ref: options.c doset() -> doset_simple() in tty path
        g.context.move = 0;
        await doset_simple();
        break;
    }
    case '\u001b': { // ESC — no-op, just clears message state
        // C ref: cmd.c parse() → ESC returns without dispatching a command
        g.context.move = 0;
        break;
    }
    default: {
        // C ref: cmd.c:4425-4436 — unknown/bad command
        // C uses custompline(SUPPRESS_HISTORY, ...) which goes through addtopl.
        const keyCode = (typeof key === 'string')
            ? (key.charCodeAt(0) || 0)
            : Number(key || 0);
        const keyStr = (keyCode >= 32 && keyCode < 127)
            ? String.fromCharCode(keyCode)
            : `\\${keyCode}`;
        const display = game?.nhDisplay || null;
        const msg = `Unknown command '${keyStr}'.`;
        // C: custompline → vpline → putmesg → tty_putstr → show_topl → addtopl
        // Concatenates to the VISIBLE topline (only when toplin > 0).
        // When toplin is EMPTY (0), the previous _pending_message is stale
        // (retained by more() for ^P recall) and should not be concatenated.
        if (display) {
            const toplin = display.toplin ?? 0;
            const existing = toplin > 0 ? (game._pending_message ?? '') : '';
            const concat = existing ? existing + '  ' + msg : msg;
            game._pending_message = concat;
            display.toplines = concat;
            display.topMessage = concat;
            display.toplin = 1; // TOPLINE_NEED_MORE
            pushRngLogEntry('^toplin[addtopl=1]');
            if (typeof display.clearRow === 'function') {
                display.clearRow(0);
                display.putstr(0, 0, concat);
            }
        }
        // C: context.move = FALSE, multi = 0, then return (no reset_cmd_vars)
        g.context.move = 0;
        pushCtxMoveLog('rhack', g.context.move);
        g.multi = 0;
        pushMultiLog('rhack', g.multi);
        return;
    }
    }
    // C ref: cmd.c:3807-3817 post-command tail — conditional dispatch:
    // ECMD_CANCEL|ECMD_FAIL → reset_cmd_vars(TRUE)
    // ECMD_OK (no ECMD_TIME) → reset_cmd_vars(multi < 0)
    // ECMD_TIME → context.move = TRUE (skip reset_cmd_vars entirely)
    if (g.context.move) {
        // C ref: cmd.c:3818-3822 — if hero did anything other than kick,
        // clear kickedloc so pets won't avoid it next turn
        if (key !== '\u0004' /* Ctrl-D / kick */ && g.kickedloc) {
            g.kickedloc.x = 0;
            g.kickedloc.y = 0;
        }
        // Time-consuming command (ECMD_TIME): skip reset, just set move
        pushCtxMoveLog('rhack', g.context.move);
    } else {
        // Free action or cancelled: reset all command state
        // C ref: cmd.c:3811-3812
        // ECMD_OK (no time) clears command queues only when multi < 0.
        // Preserve queued canned/repeat commands in the common case.
        reset_cmd_vars(g.multi < 0);
    }
}
 
// C ref: cmd.c reset_cmd_vars() — reset all command-execution state
// Called after every command dispatch in rhack().
function reset_cmd_vars(reset_cmdq = true) {
    const g = game;
    g.context.run = 0;
    g.context.nopick = false;
    g.context.forcefight = false;
    g.context.move = 0;
    g.context.mv = false;
    // g.domove_attempting = 0; // not yet tracked
    g.multi = 0;
    // g.iflags.menu_requested = false; // not yet tracked
    g.context.travel = 0;
    g.context.travel1 = 0;
    if (reset_cmdq) {
        cmdq_clear(CQ_CANNED);
        cmdq_clear(CQ_REPEAT);
    }
    pushCtxMoveLog('reset_cmd_vars', g.context.move);
    pushMultiLog('reset_cmd_vars', g.multi);
}
 
// C ref: hack.c:1853 handle_tip(TIP_SWIM)
async function handle_tip_swim() {
    const g = game;
    if (!g.flags?.tips) return false;
    const tipsSeen = (g.context.tips ||= []);
    if (tipsSeen[TIP_SWIM]) return false;
    tipsSeen[TIP_SWIM] = true;
    await pline("(Tip: use 'm' prefix to step in if you really want to.)");
    return true;
}
 
// C ref: hack.c:1886 swim_move_danger()
async function swim_move_danger(newx, newy) {
    const g = game;
    const level = g.level;
    const cur = level?.at?.(g.u?.ux, g.u?.uy);
    const dst = level?.at?.(newx, newy);
    if (!cur || !dst) return false;
    const uSimpleFloorType = (x, y) => {
        const loc = level?.at?.(x, y);
        if (!loc) return ROOM;
        const uInAir = Levitation() || Flying() || !grounded(g.youmonst?.data);
        if (IS_WATERWALL(loc.typ)) return WATER;
        if (loc.typ === LAVAWALL) return LAVAWALL;
        if (!uInAir) {
            if (is_pool(x, y)) return POOL;
            if (is_lava(x, y)) return LAVAPOOL;
        }
        return ROOM;
    };
    const oldtyp = uSimpleFloorType(g.u.ux, g.u.uy);
    const newtyp = uSimpleFloorType(newx, newy);
 
    const knownWwalking = !!(g.u?.uarmf
        && g.u.uarmf.otyp === WATER_WALKING_BOOTS
        && g.objects?.[WATER_WALKING_BOOTS]?.oc_name_known
        && !g.u?.usteed);
    const knownLwalking = !!(knownWwalking
        && Fire_resistance()
        && g.u?.uarmf?.oerodeproof
        && g.u?.uarmf?.rknown);
    const liquidWall = IS_WATERWALL(newtyp) || newtyp === LAVAWALL;
    const paranoidSwim = !!((g.flags?.paranoia_bits & PARANOID_SWIM) !== 0);
 
    if (Underwater() && (is_pool(newx, newy) || IS_WATERWALL(newtyp))) {
        return false;
    }
 
    if ((newtyp !== oldtyp)
        && !Stunned() && !Confusion()
        && !!dst.seenv
        && (is_pool(newx, newy) || is_lava(newx, newy) || liquidWall)) {
        const enteringDangerousLiquid = (is_pool(newx, newy) && !knownWwalking)
            || (is_lava(newx, newy) && !knownLwalking && !is_lava(g.u.ux, g.u.uy))
            || liquidWall;
        if (!enteringDangerousLiquid) return false;
        if (g.context.nopick) {
            const tipsSeen = (g.context.tips ||= []);
            tipsSeen[TIP_SWIM] = true;
            return false;
        }
        if (paranoidSwim || liquidWall) {
            await You(`avoid ${ing_suffix(u_locomotion('step'))} into the ${waterbody_name(newx, newy)}.`);
            await handle_tip_swim();
            return true;
        }
    }
    return false;
}
 
// C ref: hack.c:1550 trapmove()
// Returns true iff movement should continue toward destination.
async function trapmove_for_domove(newx, newy, desttrap = null) {
    const g = game;
    const u = g.u;
    if (!u.utrap) return true;
 
    let anchored = false;
    const steedname = u.usteed ? y_monnam(u.usteed) : null;
 
    switch (u.utraptype) {
    case TT_BEARTRAP: {
        // C ref: hack.c:1567-1580
        if (g.flags?.verbose) {
            const predicament = 'caught in a bear trap';
            if (u.usteed) {
                await Norep('%s is %s.', upstart(steedname), predicament);
            } else {
                await Norep('You are %s.', predicament);
            }
        }
        // diagonal movement gives quickest escape
        if ((u.dx && u.dy) || !rn2(5))
            u.utrap--;
        if (!u.utrap) {
            // wriggle_free
            if (u.usteed) {
                await pline('%s finally lurches free.', upstart(steedname));
            } else {
                await You('finally wriggle free.');
            }
            if (anchored)
                await buried_ball_to_punishment();
        }
        break;
    }
    case TT_PIT:
        // C ref: hack.c:1581-1587
        if (desttrap && desttrap.tseen && is_pit(desttrap.ttyp)) {
            return true;
        }
        await climb_pit();
        break;
    case TT_WEB:
        // C ref: hack.c:1588-1608
        if (u_wield_art(ART_STING)) {
            u.utrap = 0; // caller will call reset_utrap()
            await pline('Sting cuts through the web!');
            break;
        }
        if (--u.utrap) {
            if (g.flags?.verbose) {
                const predicament = 'stuck to the web';
                if (u.usteed) {
                    await Norep('%s is %s.', upstart(steedname), predicament);
                } else {
                    await Norep('You are %s.', predicament);
                }
            }
        } else {
            if (u.usteed) {
                await pline('%s breaks out of the web.', upstart(steedname));
            } else {
                await You('disentangle yourself.');
            }
        }
        break;
    case TT_LAVA:
        // C ref: hack.c:1610-1631
        if (g.flags?.verbose) {
            const predicament = 'stuck in the lava';
            if (u.usteed) {
                await Norep('%s is %s.', upstart(steedname), predicament);
            } else {
                await Norep('You are %s.', predicament);
            }
        }
        if (!is_lava(newx, newy)) {
            u.utrap--;
            if ((u.utrap & 0xff) === 0) {
                u.utrap = 0;
                if (u.usteed) {
                    await You('lead %s to the edge of the %s.', steedname,
                        hliquid('lava'));
                } else {
                    await You('pull yourself to the edge of the %s.',
                        hliquid('lava'));
                }
            }
        }
        u.umoved = true;
        break;
    case TT_INFLOOR:
    case TT_BURIEDBALL:
        // C ref: hack.c:1632-1681
        anchored = (u.utraptype === TT_BURIEDBALL);
        if (anchored) {
            const cc = { x: u.ux, y: u.uy };
            if (buried_ball(cc) && dist2(newx, newy, cc.x, cc.y) <= 2) {
                if (g.flags?.verbose)
                    await Norep('You move within the chain\'s reach.');
                return true;
            }
        }
        if (--u.utrap) {
            if (g.flags?.verbose) {
                let predicament, culprit;
                if (anchored) {
                    predicament = 'chained to the';
                    culprit = 'buried ball';
                } else {
                    predicament = 'stuck in the';
                    culprit = surface(u.ux, u.uy);
                }
                if (u.usteed) {
                    if (anchored) {
                        await Norep('You and %s are %s %s.', steedname,
                            predicament, culprit);
                    } else {
                        await Norep('%s is %s %s.', upstart(steedname),
                            predicament, culprit);
                    }
                } else {
                    await Norep('You are %s %s.', predicament, culprit);
                }
            }
        } else {
            // wriggle_free
            if (u.usteed) {
                await pline('%s finally %s free.', upstart(steedname),
                    !anchored ? 'lurches' : 'wrenches the ball');
            } else {
                await You('finally %s free.',
                    !anchored ? 'wriggle' : 'wrench the ball');
            }
            if (anchored)
                await buried_ball_to_punishment();
        }
        break;
    default:
        break;
    }
    return false;
}
 
// C ref: hack.c:2625 carrying_too_much()
async function carrying_too_much() {
    const u = game.u;
    const wtcap = near_capacity();
    const lowHpAndEncumbered = wtcap > SLT_ENCUMBER
        && (Upolyd()
            ? (u.mh < 5 && u.mh !== u.mhmax)
            : (u.uhp < 10 && u.uhp !== u.uhpmax));
    if ((wtcap >= OVERLOADED || lowHpAndEncumbered) && !Is_airlevel(u.uz)) {
        if (wtcap < OVERLOADED) {
            await You("don't have enough stamina to move.");
            exercise(A_CON, false);
        } else {
            await You('collapse under your load.');
        }
        nomul(0);
        return true;
    }
    return false;
}
 
// C ref: hack.c:2674 — domove()
// Thin wrapper that records pre-move state, calls domove_core(),
// then runs post-move effects (engraving smudge, runmode delay).
// RNG: indirect via domove_core (combat rolls, boulder exercise).
export async function domove() {
    const g = game;
    assertNotInModal('domove');
    const u = g.u;
    const ux1 = u.ux;
    const uy1 = u.uy;
    const domoveAttempting = g.domove_attempting ?? 0;
    // C ref: hack.c:2679 — gd.domove_succeeded = 0L;
    g.domove_succeeded = 0;
    try {
        await domove_core();
        // C ref: hack.c:2682-2685 — if the attempt was WALK/RUSH and it
        // succeeded, smudge engraved squares at old and new position and
        // adjust the water-bubble hero tracker (water level only).
        if ((g.domove_succeeded & (DOMOVE_RUSH | DOMOVE_WALK)) !== 0) {
            maybe_smudge_engr(ux1, uy1, u.ux, u.uy);
            // maybe_adjust_hero_bubble — only relevant on water level; noop otherwise.
            if (typeof maybe_adjust_hero_bubble === 'function') maybe_adjust_hero_bubble();
        }
    } finally {
        // C ref: hack.c:2686 — clear movement-attempt bits after each domove().
        g.domove_attempting = 0;
        // C ref: hack.c:2688 — domove() always clears kickedloc.
        if (g.kickedloc) {
            g.kickedloc.x = 0;
            g.kickedloc.y = 0;
        }
    }
    // C ref: hack.c domove() end — runmode_delay_output() (hack.c:3002).
    // Not midlog-instrumented here (unlike allmain.c:596), so inline directly.
    if ((g.context?.run || g.multi) && g.flags?.runmode !== RUN_TPORT) {
        if (g.flags.runmode !== RUN_LEAP || !(g.moves % 7)) {
            g.disp.time_botl = !!g.flags.time;
            await curs_on_u();
            await delay_output();
            if (g.flags.runmode === RUN_CRAWL) {
                await delay_output();
                await delay_output();
                await delay_output();
                await delay_output();
            }
        }
    }
}
 
// C ref: hack.c:2692 — domove_core(): the actual movement logic.
// Handles travel path selection, obstacle/monster bump checks, test_move,
// door opening, boulder push, trap activation, and spoteffects (pickup,
// traps, map messages) at the new position.
async function domove_core() {
    const g = game;
    // C ref: hack.c:2713 — reset door_opened at start of each domove_core.
    g.context.door_opened = false;
    const u = g.u;
    const ux1 = u.ux;
    const uy1 = u.uy;
    const domoveAttempting = g.domove_attempting ?? 0;
    let bc_control = 0;
    let ballx = 0;
    let bally = 0;
    let chainx = 0;
    let chainy = 0;
    let cause_delay = false;
    let newx = u.ux + u.dx;
    let newy = u.uy + u.dy;
    {
        if (g.context.travel) {
            const hadPath = await findtravelpath(TRAVP_TRAVEL);
            if (!hadPath) {
                await findtravelpath(TRAVP_GUESS);
            }
            g.context.travel1 = 0;
        }
        newx = u.ux + u.dx;
        newy = u.uy + u.dy;
        if (await carrying_too_much()) {
            return;
        }
        // C ref: hack.c domove_core() sets previous position at start of move logic.
        // This prevents stale ux0/uy0 from earlier turns from triggering
        // move-end effects (for example maybe_smudge_engr) on failed moves.
        u.ux0 = u.ux;
        u.uy0 = u.uy;
        // C ref: hack.c:2428 impaired_movement()
        if (u_maybe_impaired()) {
            let tries = 0;
            do {
                if (tries++ > 50) {
                    nomul(0);
                    return;
                }
                confdir(true);
                newx = u.ux + u.dx;
                newy = u.uy + u.dy;
            } while (!isok(newx, newy) || bad_rock(g.youmonst?.data, newx, newy));
        }
        // C ref: hack.c domove_core() move_out_of_bounds() check.
        if (!isok(newx, newy)) {
            nomul(0);
            g.context.move = 0;
            pushCtxMoveLog('move_out_of_bounds', g.context.move);
            return;
        }
        if (await escape_from_sticky_mon(newx, newy)) {
            return;
        }
        // C ref: hack.c:2872-2876 — move ball and chain before entering destination.
        if (Punished()) {
            const drag = await drag_ball(
                newx, newy,
                bc_control, ballx, bally, chainx, chainy, cause_delay,
                true,
            );
            if (!drag.result) {
                return;
            }
            bc_control = drag.bc_control;
            ballx = drag.ballx;
            bally = drag.bally;
            chainx = drag.chainx;
            chainy = drag.chainy;
            cause_delay = drag.cause_delay;
        }
 
        const mtmp = m_at(newx, newy);
        if (mtmp && !is_safemon(mtmp)) {
            // C ref: hack.c:2773-2786 — while running, stop instead of attacking
            // a visible/sensed non-safemon (including pets when confusion/stun
            // disables safemon protection).
            if (g.context.run
                && ((!Blind()
                    && mon_visible(mtmp)
                    && mtmp.m_ap_type !== M_AP_FURNITURE
                    && mtmp.m_ap_type !== M_AP_OBJECT)
                    || sensemon(mtmp))) {
                nomul(0);
                g.context.move = 0;
                pushCtxMoveLog('domove_core', g.context.move);
                return;
            }
        }
 
        if (mtmp) {
            // C ref: hack.c:2801 — nomul(0) before attack for non-safe or forcefight
            if (!is_safemon(mtmp) || g.context.forcefight)
                nomul(0);
            // C ref: hack.c domove_core — do_attack() handles safe + hostile monsters
            const attacked = await do_attack(mtmp);
            if (attacked) {
                // C ref: hack.c domove_attackmon_at returns TRUE → domove() returns
                // early before runmode_delay_output(). Combat ends the move.
                return;
            }
            // Safemon swap: C falls through to runmode_delay_output() after swap.
            await swap_with_mon(mtmp, newx, newy);
        } else {
        // C ref: hack.c domove_fight_empty — forcefight at empty/solid tile,
        // and also remembered-invisible marker when using a movement command.
        // C ref: domove keys this on the rendered glyph. rendered_ch reads
        // game.gbuf.rows[y][x].ch (the live render buffer).
        const rememberedInvisMarker = !g.context.forcefight
            && !g.context.nopick
            && rendered_ch(newx, newy) === 'I';
        if (g.context.forcefight || rememberedInvisMarker) {
            if (rememberedInvisMarker) {
                // C ref: domove_fight_empty() unmap_object(x,y); newsym(x,y);
                // before issuing "You attack thin air."
                unmap_object(newx, newy);
                newsym(newx, newy);
            }
            const lev = g.level?.at?.(newx, newy);
            const typ = lev?.typ ?? STONE;
            const solid = typ < DOOR; // C: !ACCESSIBLE(typ) = !(typ >= DOOR)
            const buf = (solid && typ !== STONE) ? 'the wall'
                : solid ? 'the stone'
                : 'thin air';
            await You(`${solid ? 'harmlessly attack' : 'attack'} ${buf}.`);
            nomul(0);
            g.context.move = 1;
            return;
        }
 
        // C ref: hack.c avoid_trap_andor_region() known-trap confirmation.
        if ((g.flags?.paranoia_bits & PARANOID_TRAP) !== 0) {
            const trap = t_at(newx, newy);
            if (!Stunned() && !Confusion()
                && (!g.context.nopick || g.context.run)
                && trap && trap.tseen
                && (await test_move(u.ux, u.uy, newx - u.ux, newy - u.uy, TEST_MOVE))) {
                const into = into_vs_onto(trap.ttyp);
                const q = `Really ${u_locomotion('step')} ${into ? 'into' : 'onto'} that ${trapname(trap.ttyp, false)}?`;
                const ans = await ynFunction(q, 'yn', 'n', false);
                if (ans !== 'y'.charCodeAt(0) && ans !== 'Y'.charCodeAt(0)) {
                    nomul(0);
                    g.context.move = 0;
                    pushCtxMoveLog('avoid_trap_andor_region', g.context.move);
                    return;
                }
            }
        }
        // C ref: hack.c domove_core() trapmove() before test_move().
        if (u.utrap) {
            const moved = await trapmove_for_domove(newx, newy, t_at(newx, newy));
            if (!u.utrap) {
                setBotl('domove_core');
                await reset_utrap(true);
            }
            if (!moved) return;
        }
 
        if (await swim_move_danger(newx, newy)) {
            g.context.move = 0;
            pushCtxMoveLog('domove_core', g.context.move);
            nomul(0);
            return;
        }
 
        // C ref: hack.c:2853-2860 — movement legality and side-effects live in test_move().
        if (!await test_move(u.ux, u.uy, newx - u.ux, newy - u.uy, DO_MOVE)) {
            if (!g.context.door_opened) {
                g.context.move = 0;
                pushCtxMoveLog('domove_core', g.context.move);
                nomul(0);
            }
            return;
        }
 
            u.ux = newx;
            u.uy = newy;
            // C ref: hack.c:2975 — check_leash before umoved/vision update
            await check_leash(u.ux0, u.uy0);
            u.umoved = true;
            g.domove_succeeded |= (g.domove_attempting ?? 0) & (DOMOVE_RUSH | DOMOVE_WALK);
            const loc = game.level?.at(newx, newy);
            const typ = loc?.typ ?? 0;
            if (g.context.run && g.context.run < 8
                && (typ === DOOR || IS_OBSTRUCTED(typ) || IS_FURNITURE(typ))) {
                nomul(0);
            }
            if (Punished()) {
                // C ref: hack.c:2988-2989 — place updated ball/chain before spoteffects().
                move_bc(0, bc_control, ballx, bally, chainx, chainy);
            }
 
            await finishHeroMove(newx, newy);
 
            if (cause_delay) {
                // C ref: hack.c:2996-3000 — delay next move when dragging ball.
                nomul(-2);
                g.multi_reason = 'dragging an iron ball';
                g.nomovemsg = '';
            }
            // C ref: hack.c:2941 — gd.domove_succeeded |= (gd.domove_attempting & (WALK|RUSH))
            // happens only when hero successfully moved.  Already set above
            // as u.umoved=true; record the success for the outer wrapper.
            if ((domoveAttempting & (DOMOVE_RUSH | DOMOVE_WALK))
                && (u.ux !== ux1 || u.uy !== uy1)) {
                g.domove_succeeded |= (domoveAttempting & (DOMOVE_RUSH | DOMOVE_WALK));
            }
        } // end else (no monster)
    }
}
 
// C ref: hack.c:2619 escape_from_sticky_mon()
async function escape_from_sticky_mon(x, y) {
    const g = game;
    if (!g.u.ustuck || (x === g.u.ustuck.mx && y === g.u.ustuck.my)) {
        return false;
    }
 
    let mtmp;
    if (!m_next2u(g.u.ustuck)) {
        set_ustuck(null);
    } else if (sticks(g.youmonst?.data)) {
        mtmp = g.u.ustuck;
        set_ustuck(null);
        await You(`release ${y_monnam(mtmp)}.`);
    } else {
        switch (rn2(!g.u.ustuck.mcanmove ? 8 : 40)) {
        case 3:
            if (!g.u.ustuck.mcanmove) {
                g.u.ustuck.mfrozen = 1;
                g.u.ustuck.msleeping = 0;
            }
            // fallthrough
        default:
            if (Conflict() || g.u.ustuck.mconf || !g.u.ustuck.mtame) {
                await You(`cannot escape from ${y_monnam(g.u.ustuck)}!`);
                nomul(0);
                return true;
            }
            // fallthrough
        case 0:
        case 1:
        case 2:
            mtmp = g.u.ustuck;
            set_ustuck(null);
            await You(`pull free from ${y_monnam(mtmp)}.`);
            break;
        }
    }
    return false;
}
 
// C ref: teleport.c:717 safe_teleds()
// Tries up to 40 random positions, then systematic search.
// RNG: rnd(COLNO-1) + rn2(ROWNO) per attempt.
 
// do_attack and heroMeleeAttack moved to uhitm.js
 
async function swap_with_mon(mtmp, x, y) {
    const u = game.u;
    const ux0 = u.ux;
    const uy0 = u.uy;
 
    // C ref: hack.c:2155-2162 — check for undisplaceable peaceful monsters.
    // In C, the hero has already tentatively moved to (x,y) at this point.
    // If the swap fails, C undoes the move but the turn is still consumed
    // (context.move stays 1, so monsters get their turns).
    if (mtmp.mpeaceful && mundisplaceable(mtmp)) {
        await You(`stop.  ${y_monnam(mtmp)} doesn't want to swap places.`);
        // Turn is consumed but hero doesn't move — matches C's didnt_move=TRUE
        return;
    }
 
    // C ref: hack.c:2162-2168 — remove monster, place at hero's old pos, newsym both.
    mtmp.mtrapped = 0;
    remove_monster_steed(x, y);
    place_monster(mtmp, ux0, uy0);
    // Move hero to new position BEFORE newsym (matches C where hero already moved)
    u.ux = x;
    u.uy = y;
    u.umoved = true;
    newsym(x, y);        // redraw hero's new pos (was pet's pos) — shows hero
    newsym(ux0, uy0);    // redraw hero's old pos (now pet's pos) — shows pet
    // C ref: hack.c:2170 — message after newsym
    await You(`swap places with ${y_monnam(mtmp)}.`);
    await finishHeroMove(x, y);
}
 
// Local dofire/dothrow_like stubs removed — now using real dothrow.js exports
 
// C ref: cmd.c — look_here()
// Report what's at the hero's current position.
async function look_here(g) {
    const u = g.u;
    if (!u || !g.level) return;
    const loc = g.level.at(u.ux, u.uy);
    if (!loc) return;
    const verb = Blind() ? 'feel' : 'see';
    const trap = t_at(u.ux, u.uy);
    if (trap && trap.tseen) {
        await There(`is ${an(trapname(trap.ttyp, false))} here.`);
    }
 
    // Check for stairs
    const up = g.level.upstair;
    const dn = g.level.dnstair;
    if (loc.typ === STAIRS) {
        if (up && u.ux === up.x && u.uy === up.y) {
            await pline('There is a staircase up out of the dungeon here.');
        } else if (dn && u.ux === dn.x && u.uy === dn.y) {
            await pline('There is a staircase down here.');
        }
    }
 
    // Check for objects on the floor
    let foundObject = false;
    if (g.level.objects) {
        for (const obj of g.level.objects) {
            if (obj.ox === u.ux && obj.oy === u.uy) {
                foundObject = true;
                await pline(`You see here ${doname_with_price(obj)}.`);
                break;
            }
        }
    }
    if (!foundObject) {
        await read_engr_at(u.ux, u.uy);
    }
 
    // Check for special terrain
    if (IS_DOOR(loc.typ)) {
        const mask = loc.doormask ?? loc.flags ?? 0;
        if (mask & D_BROKEN) await pline('There is a broken door here.');
        else if (mask & D_ISOPEN) await pline('There is an open door here.');
        else if (mask & D_CLOSED) await pline('There is a closed door here.');
        else if (mask & D_LOCKED) await pline('There is a locked door here.');
        else await pline('There is a doorway here.');
    }
    if (loc.typ === FOUNTAIN) await pline('There is a fountain here.');
    if (loc.typ === THRONE) await pline('There is an opulent throne here.');
    if (loc.typ === SINK) await pline('There is a sink here.');
    if (loc.typ === GRAVE) await pline('There is a headstone here.');
    if (loc.typ === ALTAR) await pline('There is an altar here.');
    if (!foundObject && loc.typ !== FOUNTAIN && loc.typ !== THRONE
        && loc.typ !== SINK && loc.typ !== GRAVE && loc.typ !== ALTAR
        && !IS_DOOR(loc.typ) && loc.typ !== STAIRS) {
        await You(`${verb} no objects here.`);
    }
}
 
// C ref: detect.c:2006 — dosearch0()
// Search surrounding squares for hidden doors, corridors, and traps.
// RNG: rnl(7-fund) for SDOOR/SCORR, rnl(8) for unseen traps
// _emitMidlog: C midlog macros only fire when dosearch0 is called from
// OUTSIDE detect.c (e.g., moveloop auto-search in allmain.c). Calls from
// within detect.c (explicit 's' command via dosearch()) do NOT emit midlogs
// because MIDLOG_IN_DETECT_C suppresses the macro inside the same file.
export async function dosearch0(aflag, _emitMidlog = false) {
    const g = game;
    const u = g.u;
    if (!u || !g.level) return 1;
 
    // C ref: detect.c:2027-2033 — fund from artifact search + lenses
    let fund = 0;
    // TODO: check uwep artifact SPFX_SEARCH for spe bonus
    if (u.ublindf && u.ublindf.otyp === LENSES && !Blind())
        fund += 2;
    if (fund > 5) fund = 5;
 
    if (_emitMidlog) pushRngLogEntry('>dosearch0');
 
    for (let x = u.ux - 1; x < u.ux + 2; x++) {
        for (let y = u.uy - 1; y < u.uy + 2; y++) {
            if (!isok(x, y)) continue;
            if (x === u.ux && y === u.uy) continue;
 
            const loc = g.level.at(x, y);
            if (!loc) continue;
 
            if (loc.typ === SDOOR) {
                if (rnl(7 - fund)) continue;
                cvt_sdoor_to_door(loc);
                recalc_block_point(x, y);
                exercise(A_WIS, true);
                nomul(0);
                feel_location(x, y);
                set_msg_xy(x, y);
                await You('find a hidden door.');
            } else if (loc.typ === SCORR) {
                if (rnl(7 - fund)) continue;
                loc.typ = CORR;
                unblock_point(x, y);
                exercise(A_WIS, true);
                nomul(0);
                feel_newsym(x, y);
                set_msg_xy(x, y);
                await You('find a hidden passage.');
            } else {
                // C ref: detect.c:2064-2066 — check for hidden monsters
                if (!aflag) {
                    const mtmp = m_at(x, y);
                    if (mtmp) {
                        const mfres = await mfind0(mtmp, false);
                        if (mfres === -1 || mfres === 1) {
                            // found invisible or detected monster
                        }
                    }
                }
                // C ref: detect.c:2079-2088 — check for unseen traps
                const trap = g.level.traps?.find(t => t.tx === x && t.ty === y);
                if (trap && !trap.tseen && !rnl(8)) {
                    nomul(0);
                    if (trap.ttyp === STATUE_TRAP) {
                        if (await activate_statue_trap(trap, x, y, false))
                            exercise(A_WIS, true);
                        if (_emitMidlog) pushRngLogEntry('<dosearch0=1');
                        return 1;
                    } else {
                        await find_trap(trap);
                    }
                }
            }
        }
    }
 
    if (_emitMidlog) pushRngLogEntry('<dosearch0=1');
    return 1;
}
 
// C ref: detect.c:2097 — dosearch()
async function dosearch() {
    // C ref: detect.c:2100 — cmd_safety_prevention check
    if (await cmd_safety_prevention('Searching', 'another search',
                                    'You already found a monster.', 'already_found_flag')) {
        return 0;
    }
    return (await dosearch0(0, false)) ? 1 : 0;
}
 
// C ref: cmd.c timed_occupation()
// The stored callback (timed_occ_fn) can be async — it may call pline,
// which may trigger more(), which needs nhgetch. If this function doesn't
// await the callback, the Promise floats and allows other game code to
// run during the modal wait. See #297 for the general pattern.
async function timed_occupation() {
    pushRngLogEntry('>timed_occupation');
    if (typeof game.timed_occ_fn === 'function') {
        await game.timed_occ_fn();
    }
    if (game.multi > 0) {
        game.multi--;
    }
    const rv = game.multi > 0 ? 1 : 0;
    pushRngLogEntry(`<timed_occupation=${rv}`);
    return rv;
}
 
// C ref: cmd.c set_occupation()
// C ref: cmd.c set_occupation() — sets game.occupation with midlog events
// Exported as both set_occupation (C name) and set_occupation_cmd (legacy)
export function set_occupation(fn, txt, xtime, logMonsterNearby = false) {
    const g = game;
    pushRngLogEntry('>set_occupation');
    if (xtime) {
        game.timed_occ_fn = fn;
        g.occupation = timed_occupation;
    } else {
        g.occupation = fn;
    }
    g.occtxt = txt;
    g.occtime = 0;
    g._occupation_log_monster_nearby = !!logMonsterNearby;
    pushRngLogEntry('<set_occupation');
}
 
// C ref: hack.c:4022 — monster_nearby()
// Check if any hostile monster is adjacent to the player.
// C wraps this in midlog via hack.h macro (midlog_enter + midlog_wrap_int).
// monster_nearby: imported from hack.js
 
// ── ddoinv: display inventory ──
// C ref: invent.c ddoinv() -> dispinv_with_action() -> display_inventory()
export async function ddoinv() {
    const g = game;
    if (!g.invent) {
        await pline('Not carrying anything.');
        return;
    }
 
    const c = await display_inventory(null, true);
    if (!c || c === '\x1b') {
        return;
    }
    const otmp = find_inventory_obj_by_letter(c);
    if (otmp) {
        await itemactions(otmp);
    }
}
 
// itemactions, itemactions_title, itemactions_pushkeys moved to iactions.js
 
// C ref: hack.c nomul() — cancel multi-turn actions
export function nomul(nval) {
    const g = game;
    if (g.multi < nval) return; // bug fix from C
    if (g.multi >= 0) g.disp.botl = true;
    g.u.uinvulnerable = false;
    g.u.usleep = 0;
    g.multi = nval;
    pushMultiLog('nomul', g.multi);
    if (nval === 0) {
        g.multi_reason = null;
    }
    end_running(true);
    cmdq_clear(CQ_CANNED);
}
 
// C ref: cmd.c getdir() — get direction from user
// Canonical export — was duplicated as local stubs in 8+ files
export async function getdir(prompt) {
    const g = game;
    // C ref: cmd.c:getdir() — retry loop is only used when '?' asks for help.
    while (true) {
        const promptText = (prompt && !prompt.startsWith('^')) ? prompt : 'In what direction?';
        const dirsym = await ynFunction(promptText, null, '\0', false);
        await tty_clear_nhwindow('message');
 
        if (dirsym === 27) return false; // ESC
 
        const key = typeof dirsym === 'number'
            ? String.fromCharCode(dirsym)
            : String(dirsym || '');
        if (key === '.' || key === 's') {
            g.u.dx = 0; g.u.dy = 0; g.u.dz = 0;
            confdir(false);
            return true;
        }
        if (key === '<') {
            g.u.dx = 0; g.u.dy = 0; g.u.dz = -1;
            return true;
        }
        if (key === '>') {
            g.u.dx = 0; g.u.dy = 0; g.u.dz = 1;
            return true;
        }
 
        const dir = direction_from_key(dirsym);
        if (dir) {
            g.u.dx = dir[0];
            g.u.dy = dir[1];
            g.u.dz = 0;
            confdir(false);
            return true;
        }
 
        // C ref: cmd.c:getdir() uses movecmd(); even on invalid input it
        // sets u.dz=0 before reporting failure. Preserve that side effect so
        // stale vertical direction from prior commands does not leak.
        g.u.dz = 0;
 
        // C ref: cmd.c:getdir() invalid-dir branch:
        // quitchars silently fail; '?' can show help and retry.
        if (key !== ' ' && key !== '\n' && key !== '\r' && key !== '\x1b') {
            const helpRequested = (key === '?');
            if (helpRequested || g.iflags?.cmdassist) {
                const didHelp = await help_dir((prompt && prompt.startsWith('^')) ? key : '\0',
                    helpRequested ? null : 'Invalid direction key!');
                if (helpRequested) continue; // retry prompt
                if (!didHelp)
                    await pline('What a strange direction!');
            } else {
                await pline('What a strange direction!');
            }
        }
        return false;
    }
}
 
// C ref: cmd.c:4297 — confdir()
// If hero is impaired (stunned or confused), pick random movement direction.
const dirs_ord = [0, 2, 4, 6, 1, 3, 5, 7];
 
export function confdir(force_impairment) {
    const u = game.u;
    if (force_impairment || u_maybe_impaired()) {
        const kmax = NODIAG(u.umonnum) ? Math.trunc(N_DIRS / 2) : N_DIRS;
        const k = dirs_ord[rn2(kmax)];
        u.dx = xdir[k];
        u.dy = ydir[k];
    }
}
 
export function init_cmd_globals() {
    game.timed_occ_fn = null;
}