All files / src 6502.js

65.16% Statements 636/976
38.62% Branches 241/624
70.07% Functions 96/137
67.35% Lines 584/867

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                                    698383x       38x               264x       198981x       237493x       147866x       59441x       17x       131385x       151182x       21x       652x       210604x       98662x       59439x       2x                               626532x 626532x 626532x       135751x       4463x           264x 264x 264x 264x 264x 264x 264x 264x 264x 264x 264x   264x 236x 13x 13x           236x 131250x 131250x           28x 19900x 19900x           28x 2x     2x             2253245x       556318x 556318x 556318x       246918x 246918x 246918x 246918x 246918x       1203115x 1203115x                                           407472x 407472x       13696x 13696x       73x       14x       1777992x 1777992x 1717690x 1777992x                           131266x 131266x 131266x   131266x 131266x 131266x 131266x 131266x         131266x 131266x 131266x 16x 16x 16x   131266x 131266x 131266x 131266x 131266x                             314862x 314862x 107278x 107278x 107278x 107278x   207584x 207584x 207584x 207584x 148360x 148360x 148360x 59224x 59221x 59221x 59221x         3x 3x 3x 3x 3x 3x 3x         151165x 151165x 151165x 151165x                                                                                                                                       2x 2x 2x 2x 2x     2x   2x 2x                                                                     14x   14x   14x 14x 14x 14x 14x 14x   14x                                 2615x           2615x     2615x       1x                             1x       2614x                               6x 6x 6x 2614x 2614x 2614x 2614x         2x                                                                                                                                 750x 750x 750x       3x 3x 3x 3x 1x 1x 1x         1x     3x 2x   3x       2x 2x 2x 2x 2x                     860517x 860517x                                     250x 250x 250x 250x 250x 250x   250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x 250x     250x 250x   250x 250x   250x 250x   250x 250x 250x 250x   250x 250x               250x 250x 250x 250x 250x 250x 250x 250x 250x                         42x 42x 42x 2688x 42x 2688x 42x                                                                                                           305333x 305333x 305333x 305333x       433334x 433334x 433334x 433334x                                                                           2x 2x 2x       1x 1x       3x 3x       33x       18x       18x   18x                                                                         2x   1x                                                                                                                                                 15x           15x 15x               3149370x 3149370x 3149370x 3041912x 3041912x 3041912x 3041912x   107458x 107458x 107458x         346268x 346268x 346268x 346268x             267696x 267696x 267696x 267696x 267696x 267680x 267680x 267680x   16x 16x       35x 35x   35x         35x                                                                                                               16x                                                                                                     19x 19x                                               16x 16x 16x 16x 16x     16x       4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 14x 14x 14x   4x 4x   17x 17x 8x   17x   16x   3x               44x                                                                                       26x     26x 26x 26x 26x 26x 26x   26x 26x 26x 26x     26x   26x         26x         26x 26x     26x 26x     26x 26x 26x 26x 26x     26x 26x 26x 26x 26x 26x 26x       26x       26x 25x   1x   26x   26x       26x             96x 95x 95x   1x   96x             94x 94x 256x 256x 256x 128x 128x   6x     92x 23552x 23552x           94x 12320768x   24064x     12296704x     94x           95x     95x 95x 95x 95x 95x 95x 95x   95x 95x         96x 96x 95x 95x 95x   96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 6x 6x                 860517x 860517x 52x   860517x                 250x 12x 133739x 133739x     238x         250x 250x 250x 3103983x 250x   29x 29x 29x 29x       250x 3103983x 3103983x 3103983x 3103983x 3103983x     250x   246x 3103980x 3103980x 3103980x 3103980x       4x 4x 4x 4x 4x 4x 4x 3x 3x   4x 4x 3x 3x           1797273x 1797273x         1797273x 1797273x 1797273x 2x 2x 2x       1797273x 1x   1797272x                 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x   1x       1797272x 1200476x 1200476x 1200476x 1200476x 1200476x 1200476x   1797272x                 1x 1x                                                     92x 3x   92x     92x 92x                                         38x 38x 38x 38x                 6x     6x 6x 6x 6x     6x   6x     6x 6x 6x 6x 6x                 1x 1x 1x 16x     1x 1x 16x         1x     1x 160x 160x       1x 1x     1x 16x       1x 48x 48x       1x 16x 16x       1x 1x       5x 4096x   1x       1x 1x 1x       107443x 107443x           107408x               20x         15x           92787x 92787x 92787x               92782x         5x                               93458x 93458x 93458x 93458x 93458x 93458x   671x     671x 671x 671x   92787x   92787x               1x 1x 1x 1x 1x 1x   1x         1x 1x         1x 1x 1x 3x 3x   3x 3x         1x 1x 2x 2x 2x       1x         9x 9x 9x 1x   9x 9x 1x   8x                                                                                
import * as via from "./via.js";
import { Acia } from "./acia.js";
import { Serial } from "./serial.js";
import { Tube } from "./tube.js";
import { Adc } from "./adc.js";
import { Scheduler } from "./scheduler.js";
import { TouchScreen } from "./touchscreen.js";
import { TeletextAdaptor } from "./teletext_adaptor.js";
import { Filestore } from "./filestore.js";
import { FakeRelayNoise } from "./relaynoise.js";
import { AtomPPIA } from "./ppia.js";
import { AtomMMC2 } from "./mmc.js";
import { unzipRomImage } from "./archive.js";
import { signExtend } from "./binary.js";
import { hexbyte, hexword } from "./hex.js";
import { loadData } from "./loader.js";
 
function _set(byte, mask, set) {
    return (byte & ~mask) | (set ? mask : 0);
}
 
/** One bit per device that can drive the NMI line; the CPU takes the OR of them all. */
export const NmiSource = Object.freeze({
    fdc: 0x01,
    econet: 0x02,
    tube: 0x04,
});
 
class Flags {
    constructor() {
        this._byte = 0x30;
    }
 
    get c() {
        return !!(this._byte & 0x01);
    }
 
    set c(val) {
        this._byte = _set(this._byte, 0x01, val);
    }
 
    get z() {
        return !!(this._byte & 0x02);
    }
 
    set z(val) {
        this._byte = _set(this._byte, 0x02, val);
    }
 
    get i() {
        return !!(this._byte & 0x04);
    }
 
    set i(val) {
        this._byte = _set(this._byte, 0x04, val);
    }
 
    get d() {
        return !!(this._byte & 0x08);
    }
 
    set d(val) {
        this._byte = _set(this._byte, 0x08, val);
    }
 
    get v() {
        return !!(this._byte & 0x40);
    }
 
    set v(val) {
        this._byte = _set(this._byte, 0x40, val);
    }
 
    get n() {
        return !!(this._byte & 0x80);
    }
 
    set n(val) {
        this._byte = _set(this._byte, 0x80, val);
    }
 
    reset() {
        this._byte = 0x30;
    }
 
    debugString() {
        return (
            (this.n ? "N" : "n") +
            (this.v ? "V" : "v") +
            "xx" +
            (this.d ? "D" : "d") +
            (this.i ? "I" : "i") +
            (this.z ? "Z" : "z") +
            (this.c ? "C" : "c")
        );
    }
 
    setzn(v) {
        v &= 0xff;
        this._byte = (this._byte & ~(0x02 | 0x80)) | (v & 0x80) | (v === 0 ? 0x02 : 0x00);
        return v | 0;
    }
 
    asByte() {
        return this._byte | 0x30;
    }
 
    setFromByte(byte) {
        this._byte = byte | 0x30;
    }
}
 
class Base6502 {
    constructor(model, { cycleAccurate = true } = {}) {
        this.model = model;
        this.a = this.x = this.y = this.s = 0;
        this.p = new Flags();
        this.pc = 0;
        this.opcodes = model.opcodesFactory(this, { cycleAccurate });
        this.disassembler = this.opcodes.disassembler;
        this.forceTracing = false;
        this.runner = this.opcodes.runInstruction;
        this.interrupt = 0;
        this._nmiSources = 0;
        this._nmiEdge = false;
 
        if (model.nmos) {
            this.adc = function (addend) {
                if (!this.p.d) {
                    this.adcNonBCD(addend);
                } else E{
                    this.adcBCD(addend);
                }
            };
 
            this.sbc = function (subend) {
                if (!this.p.d) {
                    this.adcNonBCD(subend ^ 0xff);
                } else E{
                    this.sbcBCD(subend);
                }
            };
        } else {
            this.adc = function (addend) {
                if (!this.p.d) {
                    this.adcNonBCD(addend);
                } else E{
                    this.adcBCDcmos(addend);
                }
            };
 
            this.sbc = function (subend) {
                Iif (!this.p.d) {
                    this.adcNonBCD(subend ^ 0xff);
                } else {
                    this.sbcBCDcmos(subend);
                }
            };
        }
    }
 
    incpc() {
        this.pc = (this.pc + 1) & 0xffff;
    }
 
    getb() {
        const result = this.readmem(this.pc);
        this.incpc();
        return result | 0;
    }
 
    getw() {
        let result = this.readmem(this.pc) | 0;
        this.incpc();
        result |= (this.readmem(this.pc) | 0) << 8;
        this.incpc();
        return result | 0;
    }
 
    checkInt() {
        this.takeInt = !!(this.interrupt && !this.p.i);
        this.takeInt |= this._nmiEdge;
    }
 
    // eslint-disable-next-line no-unused-vars
    writemem(address, value) {
        throw new Error("Must be overridden");
    }
 
    writememZpStack(address, value) {
        this.writemem(address, value);
    }
 
    // eslint-disable-next-line no-unused-vars
    readmem(address) {
        throw new Error("Must be overridden");
    }
 
    readmemZpStack(address) {
        return this.readmem(address);
    }
 
    push(v) {
        this.writememZpStack(0x100 + this.s, v);
        this.s = (this.s - 1) & 0xff;
    }
 
    pull() {
        this.s = (this.s + 1) & 0xff;
        return this.readmemZpStack(0x100 + this.s);
    }
 
    get nmi() {
        return this._nmiSources !== 0;
    }
 
    nmiAsserted(source) {
        return (this._nmiSources & source) !== 0;
    }
 
    setNmi(source, level) {
        const wasAsserted = this._nmiSources !== 0;
        if (level) this._nmiSources |= source;
        else this._nmiSources &= ~source;
        if (!wasAsserted && this._nmiSources) this._nmiEdge = true;
    }
 
    /** Called as the NMI vector is taken, for devices that withdraw their request at that point. */
    nmiAcknowledged() {}
 
    polltime() {
        throw new Error("Must be overridden");
    }
 
    brk(isIrq) {
        // Behavior here generally discovered via Visual 6502 analysis.
        // 6502 has a quirky BRK; it was sanitized in 65c12.
        // See also https://wiki.nesdev.com/w/index.php/CPU_interrupts
        let pushAddr = this.pc;
        if (!isIrq) pushAddr = (pushAddr + 1) & 0xffff;
        this.readmem(pushAddr);
 
        this.push(pushAddr >>> 8);
        this.push(pushAddr & 0xff);
        let pushFlags = this.p.asByte();
        if (isIrq) pushFlags &= ~0x10;
        this.push(pushFlags);
 
        // NMI status is determined part way through the BRK / IRQ
        // sequence, and yes, on 6502, an NMI can redirect the vector
        // for a half-way done BRK instruction.
        this.polltime(4);
        let vector = 0xfffe;
        if ((this.model.nmos || isIrq) && this._nmiEdge) {
            vector = 0xfffa;
            this._nmiEdge = false;
            this.nmiAcknowledged();
        }
        this.takeInt = false;
        this.pc = this.readmem(vector) | (this.readmem(vector + 1) << 8);
        this.p.i = true;
        if (this.model.nmos) {
            this.polltime(3);
        } else E{
            this.p.d = false;
            if (isIrq) {
                this.polltime(3);
            } else {
                this.polltime(2);
                // TODO(#1063) check 65c12 BRK interrupt poll timing.
                this.checkInt();
                this.polltime(1);
            }
        }
    }
 
    branch(taken) {
        const offset = signExtend(this.getb());
        if (!taken) {
            this.polltime(1);
            this.checkInt();
            this.polltime(1);
            return;
        }
        const newPc = (this.pc + offset) & 0xffff;
        const pageCrossed = !!((this.pc & 0xff00) ^ (newPc & 0xff00));
        this.pc = newPc;
        if (!this.model.nmos) {
            this.polltime(2 + pageCrossed);
            this.checkInt();
            this.polltime(1);
        } else if (!pageCrossed) {
            this.polltime(1);
            this.checkInt();
            this.polltime(2);
        } else {
            // 6502 polls twice during a taken branch with page
            // crossing and either is sufficient to trigger IRQ.
            // See https://wiki.nesdev.com/w/index.php/CPU_interrupts
            this.polltime(1);
            this.checkInt();
            const sawInt = this.takeInt;
            this.polltime(2);
            this.checkInt();
            this.takeInt |= sawInt;
            this.polltime(1);
        }
    }
 
    adcNonBCD(addend) {
        const result = this.a + addend + (this.p.c ? 1 : 0);
        this.p.v = !!((this.a ^ result) & (addend ^ result) & 0x80);
        this.p.c = !!(result & 0x100);
        this.a = this.p.setzn(result);
    }
 
    // For flags and stuff see URLs like:
    // http://www.visual6502.org/JSSim/expert.html?graphics=false&a=0&d=a900f86911eaeaea&steps=16
    adcBCD(addend) {
        let ah = 0;
        const tempb = (this.a + addend + (this.p.c ? 1 : 0)) & 0xff;
        this.p.z = !tempb;
        let al = (this.a & 0xf) + (addend & 0xf) + (this.p.c ? 1 : 0);
        if (al > 9) {
            al -= 10;
            al &= 0xf;
            ah = 1;
        }
        ah += (this.a >>> 4) + (addend >>> 4);
        this.p.n = !!(ah & 8);
        this.p.v = !((this.a ^ addend) & 0x80) && !!((this.a ^ (ah << 4)) & 0x80);
        this.p.c = false;
        if (ah > 9) {
            this.p.c = true;
            ah -= 10;
            ah &= 0xf;
        }
        this.a = ((al & 0xf) | (ah << 4)) & 0xff;
    }
 
    // With reference to c64doc: http://vice-emu.sourceforge.net/plain/64doc.txt
    // and http://www.visual6502.org/JSSim/expert.html?graphics=false&a=0&d=a900f8e988eaeaea&steps=18
    sbcBCD(subend) {
        const carry = this.p.c ? 0 : 1;
        let al = (this.a & 0xf) - (subend & 0xf) - carry;
        let ah = (this.a >>> 4) - (subend >>> 4);
        if (al & 0x10) {
            al = (al - 6) & 0xf;
            ah--;
        }
        if (ah & 0x10) {
            ah = (ah - 6) & 0xf;
        }
 
        const result = this.a - subend - carry;
        this.p.n = !!(result & 0x80);
        this.p.z = !(result & 0xff);
        this.p.v = !!((this.a ^ result) & (subend ^ this.a) & 0x80);
        this.p.c = !(result & 0x100);
        this.a = al | (ah << 4);
    }
 
    adcBCDcmos(addend) {
        this.polltime(1); // One more cycle, apparently
        const carry = this.p.c ? 1 : 0;
        let al = (this.a & 0xf) + (addend & 0xf) + carry;
        let ah = (this.a >>> 4) + (addend >>> 4);
        if (al > 9) {
            al = (al - 10) & 0xf;
            ah++;
        }
        this.p.v = !((this.a ^ addend) & 0x80) && !!((this.a ^ (ah << 4)) & 0x80);
        this.p.c = false;
        if (ah > 9) {
            ah = (ah - 10) & 0xf;
            this.p.c = true;
        }
        this.a = this.p.setzn(al | (ah << 4));
    }
 
    sbcBCDcmos(subend) {
        this.polltime(1); // One more cycle, apparently
        const carry = this.p.c ? 0 : 1;
        const al = (this.a & 0xf) - (subend & 0xf) - carry;
        let result = this.a - subend - carry;
        Iif (result < 0) {
            result -= 0x60;
        }
        Eif (al < 0) result -= 0x06;
 
        this.adcNonBCD(subend ^ 0xff); // For flags
        this.a = this.p.setzn(result);
    }
 
    arr(arg) {
        // Insane instruction. I started with b-em source, but ended up using:
        // http://www.6502.org/users/andre/petindex/local/64doc.txt as reference,
        // tidying up as needed and fixing a couple of typos.
        if (this.p.d) {
            const temp = this.a & arg;
 
            const ah = temp >>> 4;
            const al = temp & 0x0f;
 
            this.p.n = this.p.c;
            this.a = (temp >>> 1) | (this.p.c ? 0x80 : 0x00);
            this.p.z = !this.a;
            this.p.v = (temp ^ this.a) & 0x40;
 
            if (al + (al & 1) > 5) this.a = (this.a & 0xf0) | ((this.a + 6) & 0xf);
 
            this.p.c = ah + (ah & 1) > 5;
            if (this.p.c) this.a = (this.a + 0x60) & 0xff;
        } else {
            this.a = this.a & arg;
            this.p.v = !!(((this.a >>> 7) ^ (this.a >>> 6)) & 0x01);
            this.a >>>= 1;
            if (this.p.c) this.a |= 0x80;
            this.p.setzn(this.a);
            this.p.c = !!(this.a & 0x40);
        }
    }
}
 
class Tube6502 extends Base6502 {
    constructor(model, cpu, { cpuMultiplier = 1 } = {}) {
        super(model, { cycleAccurate: false });
 
        Iif (!(cpuMultiplier > 0)) throw new Error(`Tube CPU multiplier must be positive, got ${cpuMultiplier}`);
 
        this.cycles = 0;
        this.cyclesPerHostCycle = model.clockMhz / cpu.model.clockMhz;
        this.cpuMultiplier = cpuMultiplier;
        this.romPaged = true;
        this.memory = new Uint8Array(65536);
        this.rom = new Uint8Array(4096);
 
        this.tube = new Tube(cpu, this);
    }
 
    reset(hard) {
        this.romPaged = true;
        this.pc = this.readmem(0xfffc) | (this.readmem(0xfffd) << 8);
        this.p.i = true;
        this.s = (this.s - 3) & 0xff; // Simulate 3 dummy pushes during reset
        // A latched NMI would otherwise survive the reset and be taken on the first instruction
        // after it, defeating the empty R3 FIFO the ULA seeds for exactly that reason.
        this._nmiSources = 0;
        this._nmiEdge = false;
        this.takeInt = false;
        this.tube.reset(hard);
    }
 
    readmem(offset) {
        Iif ((offset & 0xfff8) === 0xfef8) {
            if ((offset & 7) === 0) {
                this.romPaged = false;
            }
            return this.tube.parasiteRead(offset);
        }
        Iif (this.romPaged && (offset & 0xf000) === 0xf000) {
            return this.rom[offset & 0xfff];
        }
        return this.memory[offset & 0xffff];
    }
 
    readmemZpStack(offset) {
        return this.memory[offset & 0xffff];
    }
 
    nmiAcknowledged() {
        this.tube.acknowledgeNmi();
    }
 
    writemem(addr, b) {
        if ((addr & 0xfff8) === 0xfef8) {
            return this.tube.parasiteWrite(addr, b);
        }
        this.memory[addr & 0xffff] = b;
    }
 
    writememZpStack(addr, b) {
        this.memory[addr & 0xffff] = b;
    }
 
    polltime(cycles) {
        this.cycles -= cycles;
    }
 
    polltimeAddr(cycles) {
        this.polltime(cycles);
    }
 
    read(addr) {
        return this.tube.hostRead(addr);
    }
 
    write(addr, b) {
        this.tube.hostWrite(addr, b);
    }
 
    execute(cycles) {
        this.cycles += cycles * this.cyclesPerHostCycle * this.cpuMultiplier;
        Iif (this.cycles < 3) return;
        while (this.cycles > 0) {
            const opcode = this.readmem(this.pc);
            this.incpc();
            this.runner.run(opcode);
            Iif (this.takeInt) this.brk(true);
        }
    }
 
    snapshotState({ includeRoms = false } = {}) {
        return {
            a: this.a,
            x: this.x,
            y: this.y,
            s: this.s,
            pc: this.pc,
            p: this.p.asByte(),
            nmiLevel: this.nmi,
            nmiEdge: this._nmiEdge,
            takeInt: this.takeInt,
            // The parasite has no scheduler of its own, so this is not relative to any epoch.
            cycles: this.cycles,
            romPaged: this.romPaged,
            memory: this.memory.slice(),
            rom: includeRoms ? this.rom.slice() : undefined,
            ula: this.tube.snapshotState(),
        };
    }
 
    restoreState(state) {
        this.a = state.a;
        this.x = state.x;
        this.y = state.y;
        this.s = state.s;
        this.pc = state.pc;
        this.p.setFromByte(state.p);
        this._nmiSources = state.nmiLevel ? NmiSource.tube : 0;
        this._nmiEdge = state.nmiEdge;
        this.takeInt = state.takeInt;
        this.cycles = state.cycles;
        this.romPaged = state.romPaged;
        this.memory.set(state.memory);
        if (state.rom) this.rom.set(state.rom);
 
        // After the registers, so the edge-triggered NMI moves from its saved level to the one
        // the ULA implies: no edge if they agree, and the edge it is owed if they do not.
        this.tube.restoreState(state.ula);
    }
 
    async loadOs() {
        console.log("Loading tube rom from roms/" + this.model.os);
        const tubeRom = this.rom;
        const data = await loadData("roms/" + this.model.os);
        const len = data.length;
        if (len !== 2048) throw new Error("Broken ROM file (length=" + len + ")");
        for (let i = 0; i < len; ++i) {
            tubeRom[i + 2048] = data[i];
        }
    }
}
 
class FakeTube {
    read() {
        return 0xfe;
    }
 
    write() {}
 
    execute() {}
 
    reset() {}
}
 
class DebugHook {
    constructor(cpu, functionName) {
        this.cpu = cpu;
        this.functionName = functionName;
        this.handlers = [];
    }
 
    add(handler) {
        const self = this;
        this.handlers.push(handler);
        Eif (!this.cpu[this.functionName]) {
            this.cpu[this.functionName] = function () {
                for (let i = 0; i < self.handlers.length; ++i) {
                    const handler = self.handlers[i];
                    Iif (handler.apply(handler, arguments)) {
                        self.cpu.stop();
                        return true;
                    }
                }
                return false;
            };
        }
        handler.remove = function () {
            self.remove(handler);
        };
        return handler;
    }
 
    remove(handler) {
        const i = this.handlers.indexOf(handler);
        Iif (i < 0) throw "Unable to find debug hook handler";
        this.handlers = this.handlers.slice(0, i).concat(this.handlers.slice(i + 1));
        Eif (this.handlers.length === 0) {
            this.cpu[this.functionName] = null;
        }
    }
 
    clear() {
        this.handlers = [];
        this.cpu[this.functionName] = null;
    }
}
 
function is1MHzAccess(addr) {
    const FEslowdown = [true, false, true, true, false, false, true, false];
    return addr >= 0xfc00 && addr < 0xff00 && (addr < 0xfe00 || FEslowdown[(addr >>> 5) & 7]);
}
 
export class Cpu6502 extends Base6502 {
    constructor(
        model,
        {
            dbgr,
            video,
            soundChip,
            ddNoise,
            relayNoise = new FakeRelayNoise(),
            music5000,
            cmos,
            config,
            econet,
            cycleAccurate = true,
        } = {},
    ) {
        super(model, { cycleAccurate });
        this.config = config;
        this.keyLayout = config.keyLayout;
        this.debugFlags = this.config.debugFlags;
        this.cmos = cmos;
        this.debugger = dbgr;
 
        this.video = video;
        this.crtc = this.video.crtc;
        this.ula = this.video.ula;
        this.soundChip = soundChip;
        this.music5000 = music5000;
        this.ddNoise = ddNoise;
        this.relayNoise = relayNoise;
        this.memStatOffsetByIFetchBank = 0;
        this.memStatOffset = 0;
        this.memStat = new Uint8Array(512);
        this.memLook = new Int32Array(512); // Cannot be unsigned as we use negative offsets
        this.ramRomOs = new Uint8Array(128 * 1024 + 17 * 16 * 16384);
        this.romOffset = 128 * 1024;
        this.osOffset = this.romOffset + 16 * 16 * 1024;
        this.romsel = 0;
        this.acccon = 0;
        this.oldPcArray = new Uint16Array(256);
        this.oldAArray = new Uint8Array(256);
        this.oldXArray = new Uint8Array(256);
        this.oldYArray = new Uint8Array(256);
        this.oldPcIndex = 0;
        this.resetLine = true;
        this.cpuMultiplier = this.config.cpuMultiplier;
        this.videoCyclesBatch = this.config.videoCyclesBatch | 0;
        this.peripheralCyclesPerSecond = model.cyclesPerSecond;
        this.hasTube = !!this.config.tube;
        this.hasMusic5000 = !!this.config.hasMusic5000;
        this.hasTeletextAdaptor = !!this.config.hasTeletextAdaptor;
        this.teletextAdaptor = this.hasTeletextAdaptor ? new TeletextAdaptor(this) : null;
        this.tube = this.hasTube
            ? new Tube6502(this.config.tube, this, { cpuMultiplier: this.config.tubeCpuMultiplier })
            : new FakeTube();
        this.music5000PageSel = 0;
        this.econet = econet;
 
        this.peripheralCycles = 0;
        this.videoCycles = 0;
 
        this.polltime = this.buildPolltime();
        this.is1MHzAccess = this.buildIs1MHzAccess();
 
        this._debugRead = this._debugWrite = this._debugInstruction = null;
        this.debugInstruction = new DebugHook(this, "_debugInstruction");
        this.debugRead = new DebugHook(this, "_debugRead");
        this.debugWrite = new DebugHook(this, "_debugWrite");
 
        this.scheduler = new Scheduler();
        this.sysvia = new via.SysVia(this, this.scheduler, {
            video: this.video,
            soundChip: this.soundChip,
            cmos: this.cmos,
            isMaster: this.model.isMaster,
            initialLayout: this.keyLayout,
            getGamepads: this.config.getGamepads,
        });
        this.uservia = new via.UserVia(this, this.scheduler, this.model.isMaster, this.config.userPort);
        this.acia = new Acia(this, this.soundChip.toneGenerator, this.scheduler, this.relayNoise);
        this.serial = new Serial(this.acia);
        this.keyboardInterface = this.sysvia;
        this.tapeInterface = this.acia;
        this.adconverter = new Adc(this.sysvia, this.scheduler);
        this.touchScreen = new TouchScreen(this.scheduler, this.model.cyclesPerSecond);
        this.soundChip.setScheduler(this.scheduler);
        this.fdc = new this.model.Fdc(this, this.ddNoise, this.scheduler, this.debugFlags);
    }
 
    getPrevPc(index) {
        return this.oldPcArray[(this.oldPcIndex - index) & 0xff];
    }
 
    // BBC Master memory map (within ramRomOs array):
    // 00000 - 08000 -> base 32KB RAM
    // 08000 - 09000 -> ANDY - 4KB
    // 09000 - 0b000 -> HAZEL - 8KB
    // 0b000 - 10000 -> LYNNE - 20KB
    romSelect(b) {
        this.romsel = b;
        const bankOffset = ((b & 15) << 14) + this.romOffset;
        const offset = bankOffset - 0x8000;
        for (let c = 128; c < 192; ++c) this.memLook[c] = this.memLook[256 + c] = offset;
        const swram = this.model.swram[b & 15] ? 1 : 2;
        for (let c = 128; c < 192; ++c) this.memStat[c] = this.memStat[256 + c] = swram;
        Iif (this.model.isMaster && b & 0x80) {
            // 4Kb RAM (private RAM - ANDY)
            // Zero offset as 0x8000 mapped to 0x8000
            for (let c = 128; c < 144; ++c) {
                this.memLook[c] = this.memLook[256 + c] = 0;
                this.memStat[c] = this.memStat[256 + c] = 1;
            }
        }
    }
 
    writeAcccon(b) {
        this.acccon = b;
        // ACCCON is
        // IRR TST IJF ITU  Y  X  E  D
        //  7   6   5   4   3  2  1  0
        // Video offset (to LYNNE) is controlled by the "D" bit of ACCCON.
        // LYNNE lives at 0xb000 in our map, but the offset we use here is 0x8000
        // as the video circuitry will already be looking at 0x3000 or so above
        // the offset.
        this.videoDisplayPage = b & 1 ? 0x8000 : 0x0000;
 
        const bitE = !!(b & 2);
        const bitX = !!(b & 4);
        const bitY = !!(b & 8);
        // The "X" bit controls the "illegal" paging 20KB region overlay of LYNNE.
        // This loop rewires which paged RAM 0x3000 - 0x7fff hits.
        for (let i = 48; i < 128; ++i) {
            // For "normal" access, it's simple: shadow or not.
            this.memLook[i] = bitX ? 0x8000 : 0;
            // For special Master opcode access at 0xc000 - 0xdfff,
            // it's more involved.
            if (bitY) {
                // If 0xc000 is mapped as RAM, the Master opcode access
                // is disabled; follow what normal access does.
                this.memLook[i + 256] = this.memLook[i];
            } else {
                // Master opcode access enabled; bit E determines whether
                // it hits shadow RAM or normal RAM. This is independent
                // of bit X.
                this.memLook[i + 256] = bitE ? 0x8000 : 0;
            }
        }
        // The "Y" bit pages in HAZEL at c000->dfff. HAZEL is mapped in our RAM
        // at 0x9000, so (0x9000 - 0xc000) = -0x3000 is needed as an offset.
        const hazelRAM = bitY ? 1 : 2;
        const hazelOff = bitY ? -0x3000 : this.osOffset - 0xc000;
        for (let i = 192; i < 224; ++i) {
            this.memLook[i] = this.memLook[i + 256] = hazelOff;
            this.memStat[i] = this.memStat[i + 256] = hazelRAM;
        }
    }
 
    // Works for unpaged RAM only (ie stack and zp)
    readmemZpStack(addr) {
        addr &= 0xffff;
        const res = this.ramRomOs[addr];
        Iif (this._debugRead) this._debugRead(addr, 0, res);
        return res | 0;
    }
 
    writememZpStack(addr, b) {
        addr &= 0xffff;
        b |= 0;
        Iif (this._debugWrite) this._debugWrite(addr, b);
        this.ramRomOs[addr] = b;
    }
 
    // Handy debug function to read a string zero or \n terminated.
    readString(addr) {
        let s = "";
        for (;;) {
            const b = this.readmem(addr);
            addr++;
            if (b === 0 || b === 13) break;
            s += String.fromCharCode(b);
        }
        return s;
    }
 
    findString(string, addr) {
        addr = addr | 0;
        for (; addr < 0xffff; ++addr) {
            let i;
            for (i = 0; i < string.length; ++i) {
                if (this.readmem(addr + i) !== string.charCodeAt(i)) break;
            }
            if (i === string.length) {
                return addr;
            }
        }
        return null;
    }
 
    readArea(addr, len) {
        let str = "";
        for (let i = 0; i < len; ++i) {
            str += hexbyte(this.readmem(addr + i));
        }
        return str;
    }
 
    handleEconetStationId() {
        Iif (!this.econet) return 0xff;
        this.setEconetNmiEnabled(false);
        return this.econet.stationId;
    }
 
    handleEconetNmiEnable() {
        Eif (this.econet) this.setEconetNmiEnabled(true);
        return 0xff;
    }
 
    setEconetNmiEnabled(enabled) {
        this.econet.econetNMIEnabled = enabled;
        this.updateEconetNmi();
    }
 
    updateEconetNmi() {
        this.setNmi(NmiSource.econet, this.econet.nmi);
    }
 
    readDevice(addr) {
        Iif (this.model.isMaster && this.acccon & 0x40) {
            // TST bit of ACCCON
            return this.ramRomOs[this.osOffset + (addr & 0x3fff)];
        }
        addr &= 0xffff;
 
        switch (addr & ~0x0003) {
            case 0xfc10:
                if (this.hasTeletextAdaptor) return this.teletextAdaptor.read(addr - 0xfc10);
                break;
            case 0xfc20:
            case 0xfc24:
            case 0xfc28:
            case 0xfc2c:
            case 0xfc30:
            case 0xfc34:
            case 0xfc38:
            case 0xfc3c:
                // SID Chip.
                break;
            case 0xfc40:
            case 0xfc44:
            case 0xfc48:
            case 0xfc4c:
            case 0xfc50:
            case 0xfc54:
            case 0xfc58:
            case 0xfc5c:
                // IDE
                break;
            case 0xfcfc:
                if (addr === 0xfcff && this.hasMusic5000) return this.music5000PageSel;
                break;
            case 0xfe00:
            case 0xfe04:
                return this.crtc.read(addr);
            case 0xfe08:
            case 0xfe0c:
                return this.acia.read(addr);
            case 0xfe10:
            case 0xfe14:
                return this.serial.read(addr);
            case 0xfe18:
                return this.model.isMaster ? this.adconverter.read(addr) : this.handleEconetStationId();
            case 0xfe20:
                Eif (!this.model.isMaster) return this.handleEconetNmiEnable();
                break;
            case 0xfe24:
            case 0xfe28:
                if (this.model.isMaster) return this.fdc.read(addr);
                break;
            case 0xfe30:
                if (this.model.isMaster) return this.romsel & 0x8f;
                break;
            case 0xfe34:
                if (this.model.isMaster) return this.acccon;
                break;
            case 0xfe38:
                if (this.model.isMaster) return this.handleEconetStationId();
                break;
            case 0xfe3c:
                if (this.model.isMaster) return this.handleEconetNmiEnable();
                break;
            case 0xfe40:
            case 0xfe44:
            case 0xfe48:
            case 0xfe4c:
            case 0xfe50:
            case 0xfe54:
            case 0xfe58:
            case 0xfe5c:
                return this.sysvia.read(addr);
            case 0xfe60:
            case 0xfe64:
            case 0xfe68:
            case 0xfe6c:
            case 0xfe70:
            case 0xfe74:
            case 0xfe78:
            case 0xfe7c:
                return this.uservia.read(addr);
            case 0xfe80:
            case 0xfe84:
            case 0xfe88:
            case 0xfe8c:
            case 0xfe90:
            case 0xfe94:
            case 0xfe98:
            case 0xfe9c:
                if (!this.model.isMaster) return this.fdc.read(addr);
                break;
            case 0xfea0:
                // Econet status register
                if (this.econet) {
                    return this.econet.readRegister(addr & 3);
                }
                break;
            case 0xfec0:
            case 0xfec4:
            case 0xfec8:
            case 0xfecc:
            case 0xfed0:
            case 0xfed4:
            case 0xfed8:
            case 0xfedc:
                if (!this.model.isMaster) return this.adconverter.read(addr);
                break;
            case 0xfee0:
            case 0xfee4:
            case 0xfee8:
            case 0xfeec:
            case 0xfef0:
            case 0xfef4:
            case 0xfef8:
            case 0xfefc:
                return this.tube.read(addr);
        }
 
        Iif (this.hasMusic5000) {
            if ((this.music5000PageSel & 0xf0) === 0x30 && (addr & 0xff00) === 0xfd00) {
                return this.music5000.read(this.music5000PageSel, addr);
            }
        }
 
        Iif (addr >= 0xfc00 && addr < 0xfe00) return 0xff;
        return addr >>> 8;
    }
 
    videoRead(addr) {
        return this.ramRomOs[addr | this.videoDisplayPage] | 0;
    }
 
    readmem(addr) {
        addr &= 0xffff;
        const statOffset = this.memStatOffset + (addr >>> 8);
        if (this.memStat[statOffset]) {
            const offset = this.memLook[statOffset];
            const res = this.ramRomOs[offset + addr];
            Iif (this._debugRead) this._debugRead(addr, res, offset);
            return res | 0;
        } else {
            const res = this.readDevice(addr);
            Iif (this._debugRead) this._debugRead(addr, res, 0);
            return res | 0;
        }
    }
 
    peekmem(addr) {
        const statOffset = this.memStatOffset + (addr >>> 8);
        if (this.memStat[statOffset]) {
            const offset = this.memLook[statOffset];
            return this.ramRomOs[offset + addr];
        } else E{
            return 0xff; // TODO(#1062) peekDevice: this.peekDevice(addr);
        }
    }
 
    writemem(addr, b) {
        addr &= 0xffff;
        b |= 0;
        Iif (this._debugWrite) this._debugWrite(addr, b);
        const statOffset = this.memStatOffset + (addr >>> 8);
        if (this.memStat[statOffset] === 1) {
            const offset = this.memLook[statOffset];
            this.ramRomOs[offset + addr] = b;
            return;
        }
        Iif (addr < 0xfc00 || addr >= 0xff00) return;
        this.writeDevice(addr, b);
    }
 
    writeDevice(addr, b) {
        addr &= 0xffff;
        b |= 0;
 
        Iif (this.hasMusic5000 && (addr & 0xff00) === 0xfd00 && (this.music5000PageSel & 0xf0) === 0x30) {
            this.music5000.write(this.music5000PageSel, addr, b);
            return;
        }
 
        switch (addr & ~0x0003) {
            case 0xfc10:
                if (this.hasTeletextAdaptor) return this.teletextAdaptor.write(addr - 0xfc10, b);
                break;
            case 0xfc20:
            case 0xfc24:
            case 0xfc28:
            case 0xfc2c:
            case 0xfc30:
            case 0xfc34:
            case 0xfc38:
            case 0xfc3c:
                // SID chip
                break;
            case 0xfc40:
            case 0xfc44:
            case 0xfc48:
            case 0xfc4c:
            case 0xfc50:
            case 0xfc54:
            case 0xfc58:
            case 0xfc5c:
                // IDE
                break;
            case 0xfcfc:
                if (addr === 0xfcff && this.hasMusic5000) {
                    this.music5000PageSel = b;
                }
                break;
            case 0xfe00:
            case 0xfe04:
                return this.crtc.write(addr, b);
            case 0xfe08:
            case 0xfe0c:
                return this.acia.write(addr, b);
            case 0xfe10:
            case 0xfe14:
                return this.serial.write(addr, b);
            case 0xfe18:
                if (this.model.isMaster) return this.adconverter.write(addr, b);
                if (!this.model.isMaster && this.econet) this.setEconetNmiEnabled(false);
                break;
            case 0xfe20:
                return this.ula.write(addr, b);
            case 0xfe24:
            case 0xfe28:
                if (this.model.isMaster) {
                    return this.fdc.write(addr, b);
                }
                return this.ula.write(addr, b);
            case 0xfe2c:
                if (!this.model.isMaster) {
                    return this.ula.write(addr, b);
                }
                break;
            case 0xfe30:
                return this.romSelect(b);
            case 0xfe34:
                if (this.model.isMaster) {
                    return this.writeAcccon(b);
                }
                return this.romSelect(b);
            case 0xfe38:
                if (this.model.isMaster && this.econet) this.setEconetNmiEnabled(false);
                break;
            case 0xfe3c:
                if (!this.model.isMaster) {
                    return this.romSelect(b);
                }
                break;
            case 0xfe40:
            case 0xfe44:
            case 0xfe48:
            case 0xfe4c:
            case 0xfe50:
            case 0xfe54:
            case 0xfe58:
            case 0xfe5c:
                return this.sysvia.write(addr, b);
            case 0xfe60:
            case 0xfe64:
            case 0xfe68:
            case 0xfe6c:
            case 0xfe70:
            case 0xfe74:
            case 0xfe78:
            case 0xfe7c:
                return this.uservia.write(addr, b);
            case 0xfe80:
            case 0xfe84:
            case 0xfe88:
            case 0xfe8c:
            case 0xfe90:
            case 0xfe94:
            case 0xfe98:
            case 0xfe9c:
                if (!this.model.isMaster) return this.fdc.write(addr, b);
                break;
 
            case 0xfea0:
            case 0xfea4:
            case 0xfea8:
            case 0xfeac:
            case 0xfeb0:
            case 0xfeb4:
            case 0xfeb8:
            case 0xfebc:
                Eif (this.econet) this.econet.writeRegister(addr & 3, b);
                break;
            case 0xfec0:
            case 0xfec4:
            case 0xfec8:
            case 0xfecc:
            case 0xfed0:
            case 0xfed4:
            case 0xfed8:
            case 0xfedc:
                if (!this.model.isMaster) return this.adconverter.write(addr, b);
                break;
            case 0xfee0:
            case 0xfee4:
            case 0xfee8:
            case 0xfeec:
            case 0xfef0:
            case 0xfef4:
            case 0xfef8:
            case 0xfefc:
                return this.tube.write(addr, b);
        }
    }
 
    async loadRom(name, offset) {
        Eif (name.indexOf("http") !== 0) name = "roms/" + name;
        console.log("Loading ROM from " + name);
        const ramRomOs = this.ramRomOs;
        let data = await loadData(name);
        Iif (/\.zip/i.test(name)) {
            data = (await unzipRomImage(data)).data;
        }
        ramRomOs.set(data, offset);
    }
 
    async loadOs(os) {
        const extraRoms = Array.prototype.slice.call(arguments, 1).concat(this.config.extraRoms);
        os = "roms/" + os;
        console.log(`Loading OS from ${os}`);
        const ramRomOs = this.ramRomOs;
        const data = await loadData(os);
        const len = data.length;
        Iif (len < 16384 || len & 16383) throw new Error(`Broken OS ROM file (length=${len})`);
        ramRomOs.set(data, this.osOffset);
        const numExtraBanks = (len - 16384) / 16384;
        let romIndex = 16 - numExtraBanks;
        for (let i_1 = 0; i_1 < numExtraBanks; ++i_1) {
            const srcBase = 16384 + 16384 * i_1;
            const destBase = this.romOffset + (romIndex + i_1) * 16384;
            ramRomOs.set(data.subarray(srcBase, srcBase + 16384), destBase);
        }
        const awaiting = [];
        for (let i_2 = 0; i_2 < extraRoms.length; ++i_2) {
            // Skip over banks 4-7 (sideways RAM on a Master)
            romIndex--;
            while (this.model.swram[romIndex]) {
                romIndex--;
            }
            if (romIndex < 0) throw new Error("Too many extra ROMs (no free sideways ROM banks)");
 
            awaiting.push(this.loadRom(extraRoms[i_2], this.romOffset + romIndex * 16384));
        }
        return await Promise.all(awaiting);
    }
 
    setReset(resetOn) {
        this.resetLine = !resetOn;
    }
 
    snapshotState({ includeRoms = false } = {}) {
        return {
            // CPU registers
            a: this.a,
            x: this.x,
            y: this.y,
            s: this.s,
            pc: this.pc,
            p: this.p.asByte(),
            nmiLevel: this.nmi,
            nmiEdge: this._nmiEdge,
            halted: this.halted,
            takeInt: this.takeInt,
            // Memory control
            romsel: this.romsel,
            acccon: this.acccon,
            videoDisplayPage: this.videoDisplayPage,
            // Cycle tracking
            currentCycles: this.currentCycles,
            targetCycles: this.targetCycles,
            cycleSeconds: this.cycleSeconds,
            peripheralCycles: this.peripheralCycles,
            videoCycles: this.videoCycles,
            music5000PageSel: this.music5000PageSel,
            // RAM only by default; pass includeRoms:true to also capture
            // sideways ROM/RAM slots (adds ~256KB to the snapshot).
            ram: this.ramRomOs.slice(0, this.romOffset),
            roms: includeRoms ? this.ramRomOs.slice(this.romOffset, this.romOffset + 16 * 16384) : undefined,
            // Sub-component state
            scheduler: this.scheduler.snapshotState(),
            sysvia: this.sysvia.snapshotState(),
            uservia: this.uservia.snapshotState(),
            video: this.video.snapshotState(),
            soundChip: this.soundChip.snapshotState(),
            acia: this.acia.snapshotState(),
            adc: this.adconverter.snapshotState(),
            touchScreen: this.touchScreen.snapshotState(),
            fdc: this.fdc.snapshotState(),
            teletextAdaptor: this.teletextAdaptor ? this.teletextAdaptor.snapshotState() : undefined,
            tube: this.hasTube ? this.tube.snapshotState({ includeRoms }) : undefined,
        };
    }
 
    restoreState(state) {
        // 1. Scheduler epoch first (so task offsets resolve correctly)
        this.scheduler.restoreState(state.scheduler);
 
        // 2. CPU registers
        this.a = state.a;
        this.x = state.x;
        this.y = state.y;
        this.s = state.s;
        this.pc = state.pc;
        this.p.setFromByte(state.p);
        // interrupt is rebuilt by sub-component restores (VIA updateIFR, ACIA updateIrq)
        this.interrupt = 0;
        this._nmiSources = 0;
        this.halted = state.halted;
        this.takeInt = state.takeInt;
 
        // 3. Memory
        this.ramRomOs.set(state.ram);
        // Load ROMs if present (e.g. from BEM snapshot import)
        Iif (state.roms) {
            this.ramRomOs.set(state.roms.slice(0, 16 * 16384), this.romOffset);
        }
        // Selectively overwrite individual sideways RAM banks (e.g. from BeebEm UEF import)
        // without touching ROM banks that jsbeeb has already loaded.
        Iif (state.swRamBanks) {
            for (const [bank, data] of Object.entries(state.swRamBanks)) {
                this.ramRomOs.set(data.slice(0, 16384), this.romOffset + Number(bank) * 16384);
            }
        }
        this.videoDisplayPage = state.videoDisplayPage;
        this.music5000PageSel = state.music5000PageSel;
 
        // 4. Rebuild memStat/memLook from romsel/acccon
        this.romSelect(state.romsel);
        Iif (this.model.isMaster) this.writeAcccon(state.acccon);
 
        // 5. Cycle tracking
        this.currentCycles = state.currentCycles;
        this.targetCycles = state.targetCycles;
        this.cycleSeconds = state.cycleSeconds;
        this.peripheralCycles = state.peripheralCycles;
        this.videoCycles = state.videoCycles;
 
        // 6. Sub-components (these re-register scheduler tasks)
        this.sysvia.restoreState(state.sysvia);
        this.uservia.restoreState(state.uservia);
        this.video.restoreState(state.video);
        this.soundChip.restoreState(state.soundChip);
        this.acia.restoreState(state.acia);
        this.adconverter.restoreState(state.adc);
        if (this.teletextAdaptor && state.teletextAdaptor) this.teletextAdaptor.restoreState(state.teletextAdaptor);
 
        // Touchscreen state, added without a version bump. Absent from an older snapshot, whose
        // touchscreen keeps its current state, unpolled.
        if (state.touchScreen) this.touchScreen.restoreState(state.touchScreen);
 
        // FDC state (v2+). If absent (v1 snapshot), FDC keeps its current state, and the saved
        // level is the only record of its line.
        if (state.fdc) {
            this.fdc.restoreState(state.fdc);
        } else {
            this.setNmi(NmiSource.fdc, state.nmiLevel);
        }
        if (this.econet) this.updateEconetNmi();
        // After the devices have re-driven their lines, so a line coming back up is not an edge.
        this._nmiEdge = state.nmiEdge;
 
        // Tube state (v3+). Rather than leave the parasite running on state the host knows
        // nothing about, reset it; restoreSnapshot() rejects such a pairing before reaching here.
        Iif (this.hasTube) {
            if (state.tube) this.tube.restoreState(state.tube);
            else this.tube.reset(true);
        }
    }
 
    reset(hard) {
        if (hard) {
            this.setupMemoryMap();
            this.resetPeripherals(hard);
        } else {
            this.fdc.reset();
        }
        this.resetCpuState(hard);
    }
 
    // Override in subclasses for different memory maps.
    setupMemoryMap() {
        // On the Master, opcodes executing from 0xc000 - 0xdfff can optionally have their memory accesses
        // redirected to shadow RAM.
        this.memStatOffsetByIFetchBank = this.model.isMaster ? (1 << 0xc) | (1 << 0xd) : 0x0000;
        if (!this.model.isTest) {
            for (let i = 0; i < 128; ++i) this.memStat[i] = this.memStat[256 + i] = 1;
            for (let i = 128; i < 256; ++i) this.memStat[i] = this.memStat[256 + i] = 2;
            for (let i = 0; i < 128; ++i) this.memLook[i] = this.memLook[256 + i] = 0;
            for (let i = 128; i < 192; ++i) this.memLook[i] = this.memLook[256 + i] = this.romOffset - 0x8000;
            for (let i = 192; i < 256; ++i) this.memLook[i] = this.memLook[256 + i] = this.osOffset - 0xc000;
 
            for (let i = 0xfc; i < 0xff; ++i) this.memStat[i] = this.memStat[256 + i] = 0;
        } else {
            // Test sets everything as RAM.
            for (let i = 0; i < 256; ++i) {
                this.memStat[i] = this.memStat[256 + i] = 1;
                this.memLook[i] = this.memLook[256 + i] = 0;
            }
        }
        // DRAM content is not guaranteed to contain any particular
        // value on start up, so we choose values that help avoid
        // bugs in various games.
        for (let i = 0; i < this.romOffset; ++i) {
            if (i < 0x100) {
                // For Clogger.
                this.ramRomOs[i] = 0x00;
            } else {
                // For Eagle Empire.
                this.ramRomOs[i] = 0xff;
            }
        }
        this.videoDisplayPage = 0;
    }
 
    // Override in subclasses for different peripheral sets.
    // Only called on hard reset.
    resetPeripherals() {
        Iif (this.config.printerPort)
            this.uservia.ca2changecallback = (level, output) => this.config.printerPort.outputStrobe(level, output);
 
        this.sysvia.reset();
        this.uservia.reset();
        this.acia.reset();
        this.serial.reset();
        this.ddNoise.spinDown();
        this.fdc.powerOnReset();
        this.adconverter.reset();
 
        this.touchScreen.reset();
        if (this.econet) this.filestore = new Filestore(this, this.econet);
    }
 
    // Universal CPU state reset. Shared by all machine types.
    resetCpuState(hard) {
        this.tube.reset(hard);
        if (hard) {
            this.targetCycles = 0;
            this.currentCycles = 0;
            this.cycleSeconds = 0;
        }
        this.pc = this.readmem(0xfffc) | (this.readmem(0xfffd) << 8);
        this.p.i = true;
        this.s = (this.s - 3) & 0xff; // Simulate 3 dummy pushes during reset
        this._nmiEdge = false;
        this._nmiSources = 0;
        this.halted = false;
        this.breakpointResume = false;
        this.music5000PageSel = 0;
        this.video.reset(this, this.sysvia, hard);
        this.soundChip.reset(hard);
        if (this.teletextAdaptor) this.teletextAdaptor.reset(hard);
        Eif (this.music5000) this.music5000.reset(hard);
        if (hard && this.econet) {
            this.econet.reset();
            this.filestore.reset();
        }
    }
 
    updateKeyLayout() {
        this.sysvia.setKeyLayout(this.keyLayout);
    }
 
    polltimeAddr(cycles, addr, isWrite) {
        cycles = cycles | 0;
        if (this.is1MHzAccess(addr, isWrite)) {
            cycles += 1 + ((cycles ^ this.currentCycles) & 1);
        }
        this.polltime(cycles);
    }
 
    // Bake in the 1MHz bus check at construction time. On the Master, ACCCON
    // TST (bit 6) remaps FRED, JIM, and SHEILA reads (&FC00-&FEFF) to the
    // internal 2MHz bus, but writes still go through the external 1MHz bus.
    // Non-Master machines just use the static address check with no ACCCON
    // awareness.
    buildIs1MHzAccess() {
        if (this.model.isMaster) {
            return (addr, isWrite) => {
                Iif (!isWrite && this.acccon & 0x40 && addr >= 0xfc00 && addr < 0xff00) return false;
                return is1MHzAccess(addr);
            };
        }
        return is1MHzAccess;
    }
 
    // Builds common code between polltimeSlow and polltimeFast
    buildPolltime() {
        const nop = (_cycles) => {};
        const tubeStuff = this.hasTube ? (cycles) => this.tube.execute(cycles) : nop;
        const teletextStuff = this.teletextAdaptor ? (cycles) => this.teletextAdaptor.polltime(cycles) : nop;
        const musicStuff = this.music5000 ? (cycles) => this.music5000.polltime(cycles) : nop;
        const econetStuff = this.econet
            ? (cycles) => {
                  const retrigger = this.econet.polltime(cycles);
                  if (retrigger) this.setNmi(NmiSource.econet, false);
                  this.updateEconetNmi();
                  this.filestore.polltime(cycles);
              }
            : nop;
 
        const commonStuff = (cycles) => {
            this.scheduler.polltime(cycles);
            tubeStuff(cycles);
            teletextStuff(cycles);
            musicStuff(cycles);
            econetStuff(cycles);
        };
 
        if (this.cpuMultiplier === 1 && this.videoCyclesBatch === 0) {
            // Simplest, common case where multiplier is 1 and batching is off.
            return (cycles) => {
                cycles |= 0;
                this.currentCycles += cycles;
                this.video.polltime(cycles);
                commonStuff(cycles);
            };
        } else {
            // Handle speedup case.
            return (cycles) => {
                cycles |= 0;
                this.currentCycles += cycles;
                this.peripheralCycles += cycles;
                this.videoCycles += cycles;
                cycles = (this.videoCycles / this.cpuMultiplier) | 0;
                if (cycles > this.videoCyclesBatch) {
                    this.video.polltime(cycles);
                    this.videoCycles -= (cycles * this.cpuMultiplier) | 0;
                }
                cycles = (this.peripheralCycles / this.cpuMultiplier) | 0;
                if (!cycles) return;
                this.peripheralCycles -= (cycles * this.cpuMultiplier) | 0;
                commonStuff(cycles);
            };
        }
    }
 
    execute(numCyclesToRun) {
        this.halted = false;
        this.targetCycles += numCyclesToRun;
        // To prevent issues with wrapping around / overflowing the accuracy that poxy Javascript numbers have,
        // find the smaller of the target and current cycles, and if that's over one second's worth; subtract
        // that from both, to keep the domain low (while accumulating seconds). Take care to preserve the bottom
        // bit though; as that encodes whether we're on an even or odd bus cycle.
        const smaller = Math.min(this.targetCycles, this.currentCycles) & 0xfffffffe;
        const cyclesPerSecond = this.model.cyclesPerSecond;
        if (smaller >= cyclesPerSecond) {
            this.targetCycles -= cyclesPerSecond;
            this.currentCycles -= cyclesPerSecond;
            this.cycleSeconds++;
        }
        // Any tracing or debugging means we need to run the potentially slower version: the debug read or
        // debug write might change tracing or other debugging while we're running.
        if (this.forceTracing || this._debugInstruction || this._debugRead || this._debugWrite) {
            return this.executeInternal();
        } else {
            return this.executeInternalFast();
        }
    }
 
    executeInternal() {
        // Skip the debug-instruction check on the very first instruction only
        // when resuming from a previous breakpoint stop (so we don't immediately
        // re-trigger the same breakpoint).  Previously this skipped the first
        // instruction of every execute() chunk, which could miss breakpoints.
        let skipNext = this.breakpointResume;
        this.breakpointResume = false;
        while (!this.halted && this.currentCycles < this.targetCycles) {
            this.oldPcIndex = (this.oldPcIndex + 1) & 0xff;
            this.oldPcArray[this.oldPcIndex] = this.pc;
            this.memStatOffset = this.memStatOffsetByIFetchBank & (1 << (this.pc >>> 12)) ? 256 : 0;
            const opcode = this.readmem(this.pc);
            Iif (this._debugInstruction && !skipNext && this._debugInstruction(this.pc, opcode)) {
                this.breakpointResume = true;
                return false;
            }
            skipNext = false;
            this.incpc();
            this.runner.run(opcode);
            this.oldAArray[this.oldPcIndex] = this.a;
            this.oldXArray[this.oldPcIndex] = this.x;
            this.oldYArray[this.oldPcIndex] = this.y;
            Iif (this.takeInt) this.brk(true);
            Iif (!this.resetLine) this.reset(false);
        }
        return !this.halted;
    }
 
    executeInternalFast() {
        while (!this.halted && this.currentCycles < this.targetCycles) {
            this.memStatOffset = this.memStatOffsetByIFetchBank & (1 << (this.pc >>> 12)) ? 256 : 0;
            const opcode = this.readmem(this.pc);
            this.incpc();
            this.runner.run(opcode);
            Iif (this.takeInt) this.brk(true);
            Iif (!this.resetLine) this.reset(false);
        }
        return !this.halted;
    }
 
    stop() {
        this.halted = true;
    }
 
    /** Changes the host key layout for the keyboard, and for every reset after it. */
    setKeyLayout(layout) {
        this.keyLayout = layout;
        this.sysvia.setKeyLayout(layout);
    }
 
    dumpTrace(maxToShow, func) {
        if (!maxToShow) maxToShow = 256;
        if (maxToShow > 256) maxToShow = 256;
        const disassembler = this.disassembler;
        func =
            func ||
            function (pc, a, x, y) {
                const dis = disassembler.disassemble(pc, true)[0];
                console.log(
                    hexword(pc),
                    (dis + "                       ").substring(0, 15),
                    hexbyte(a),
                    hexbyte(x),
                    hexbyte(y),
                );
            };
        for (let i = maxToShow - 2; i >= 0; --i) {
            const j = (this.oldPcIndex - i) & 255;
            func(this.oldPcArray[j], this.oldAArray[j], this.oldXArray[j], this.oldYArray[j]);
        }
        func(this.pc, this.a, this.x, this.y);
    }
 
    async initialise() {
        if (this.model.os.length) {
            await this.loadOs.apply(this, this.model.os);
        }
        Iif (this.hasTube) {
            await this.tube.loadOs();
        }
        this.reset(true);
        this.debugger.setCpu(this);
    }
}
 
// Acorn Atom memory map:
//   0x0000-0x7FFF  RAM (32KB, or 40KB with extensions up to 0x9FFF)
//   0x0A00-0x0AFF  FDC (8271) -- hole in RAM region
//   0x8000-0x9FFF  Video RAM (shared with MC6847 VDG)
//   0xA000-0xAFFF  Banked ROM/RAM (Branquart, 16 x 4KB banks via latch at 0xBFFF)
//   0xB000-0xB003  PPIA (8255)
//   0xB400-0xB40F  AtomMMC
//   0xB800-0xB80F  VIA (6522)
//   0xBFFF         Bank select latch (write-only)
//   0xC000-0xEFFF  ROM (BASIC, FP, DOS in 4KB blocks)
//   0xF000-0xFFFF  OS kernel ROM (4KB)
//
// Branquart banking: bits 0-3 of the latch at 0xBFFF select which 4KB
// bank is visible at 0xA000-0xAFFF. Banks can contain ROM or RAM.
// The latch is write-only; bit 6 is a lock bit.
 
// Storage for Branquart banks starts after the BBC ROM area.
const BranquartOffset = 128 * 1024 + 17 * 16 * 16384;
const BranquartBankSize = 0x1000; // 4KB per bank
const NumBranquartBanks = 16;
const AtomRomBlockSize = 0x1000; // 4KB
 
export class AtomCpu6502 extends Cpu6502 {
    setKeyLayout(layout) {
        this.keyLayout = layout;
        this.atomppia.setKeyLayout(layout);
    }
 
    constructor(model, options) {
        super(model, options);
 
        // Atom peripherals
        this.atomppia = new AtomPPIA(this, this.keyLayout, this.scheduler);
        this.atommc = new AtomMMC2(this);
        this.keyboardInterface = this.atomppia;
        this.tapeInterface = this.atomppia;
 
        // Branquart bank selection
        this.branquartLatch = 0;
        // Track which banks are ROM (false) vs RAM (true) for write protection.
        this.branquartRam = new Array(NumBranquartBanks).fill(true);
 
        // Expand ramRomOs to include Branquart bank storage.
        const expandedSize = BranquartOffset + NumBranquartBanks * BranquartBankSize;
        Eif (this.ramRomOs.length < expandedSize) {
            const expanded = new Uint8Array(expandedSize);
            expanded.set(this.ramRomOs);
            this.ramRomOs = expanded;
        }
 
        // reset() and debugger.setCpu() are called by initialise() after loadOs().
    }
 
    // Select which Branquart bank is visible at 0xA000-0xAFFF by
    // updating the memLook table. This keeps reads on the fast path.
    selectBranquartBank(bank) {
        bank &= 0x0f;
        const offset = BranquartOffset + bank * BranquartBankSize - 0xa000;
        for (let i = 0xa0; i < 0xb0; ++i) {
            this.memLook[i] = this.memLook[256 + i] = offset;
        }
        // ROM banks are read-only, RAM banks are writable
        const stat = this.branquartRam[bank] ? 1 : 2;
        for (let i = 0xa0; i < 0xb0; ++i) {
            this.memStat[i] = this.memStat[256 + i] = stat;
        }
    }
 
    setupMemoryMap() {
        this.memStatOffsetByIFetchBank = 0; // no shadow RAM on Atom
 
        // 0x0000-0x9FFF: RAM (including video RAM at 0x8000)
        for (let i = 0; i < 0xa0; ++i) {
            this.memStat[i] = this.memStat[256 + i] = 1;
            this.memLook[i] = this.memLook[256 + i] = 0;
        }
 
        // 0xA000-0xAFFF: Branquart banked region (set up via selectBranquartBank)
        this.branquartLatch = 0;
        this.selectBranquartBank(0);
 
        // 0xB000-0xBFFF: Device I/O (PPIA, MMC, VIA, bank latch)
        for (let i = 0xb0; i < 0xc0; ++i) {
            this.memStat[i] = this.memStat[256 + i] = 0;
        }
 
        // 0xC000-0xEFFF: ROM (4KB blocks loaded into romOffset area)
        for (let i = 0xc0; i < 0xf0; ++i) {
            this.memStat[i] = this.memStat[256 + i] = 2;
            this.memLook[i] = this.memLook[256 + i] = this.romOffset - 0xa000;
        }
 
        // 0xF000-0xFFFF: OS kernel ROM
        for (let i = 0xf0; i < 0x100; ++i) {
            this.memStat[i] = this.memStat[256 + i] = 2;
            this.memLook[i] = this.memLook[256 + i] = this.osOffset - 0xf000;
        }
 
        // FDC at 0x0A00 (device hole in RAM, if model uses FDC)
        Eif (this.model.Fdc) {
            this.memStat[0x0a] = this.memStat[256 + 0x0a] = 0;
        }
 
        // Randomise video RAM and seed bytes
        for (let i = 8; i < 13; ++i) this.ramRomOs[i] = (256 * Math.random()) | 0;
        for (let i = 0x8000; i < 0x9000; ++i) this.ramRomOs[i] = (256 * Math.random()) | 0;
 
        this.videoDisplayPage = 0;
    }
 
    resetPeripherals() {
        super.resetPeripherals();
        this.atomppia.reset();
        this.atommc.reset(true);
    }
 
    readDevice(addr) {
        addr &= 0xffff;
        switch (addr & ~0x0003) {
            case 0x0a00:
            case 0x0a04:
                return this.fdc.read(addr);
            case 0xb000:
            case 0xb004:
                return this.atomppia.read(addr);
            case 0xb008:
            case 0xb00c:
                return 0x00;
            case 0xb400:
            case 0xb404:
            case 0xb408:
            case 0xb40c:
                return this.atommc.read(addr);
            case 0xb800:
            case 0xb804:
            case 0xb808:
            case 0xb80c:
                return this.uservia.read(addr);
        }
        return addr >>> 8; // open bus
    }
 
    writeDevice(addr, b) {
        addr &= 0xffff;
        b |= 0;
        switch (addr & ~0x0003) {
            case 0x0a00:
            case 0x0a04:
                return this.fdc.write(addr, b);
            case 0xb000:
            case 0xb004:
            case 0xb008:
            case 0xb00c:
                return this.atomppia.write(addr, b);
            case 0xb400:
            case 0xb404:
            case 0xb408:
            case 0xb40c:
                return this.atommc.write(addr, b);
            case 0xb800:
            case 0xb804:
            case 0xb808:
            case 0xb80c:
                return this.uservia.write(addr, b);
            case 0xbffc:
                if (addr === 0xbfff) {
                    this.branquartLatch = b & 0xff;
                    this.selectBranquartBank(b & 0x0f);
                }
                return;
        }
    }
 
    writemem(addr, b) {
        addr &= 0xffff;
        b |= 0;
        Iif (this._debugWrite) this._debugWrite(addr, b);
        const statOffset = this.memStatOffset + (addr >>> 8);
        const stat = this.memStat[statOffset];
        if (stat === 1) {
            // Notify VDG of CPU address bus activity for snow effect
            Iif (this.video.video6847) {
                this.video.video6847.cpuAddrAccess(addr);
            }
            const offset = this.memLook[statOffset];
            this.ramRomOs[offset + addr] = b;
            return;
        }
        Iif (stat === 2) return; // ROM: write ignored
        // Device page
        this.writeDevice(addr, b);
    }
 
    // Atom ROMs are 4KB, not 16KB like BBC.
    // OS layout: osOffset holds 4KB kernel at 0xF000.
    // Extra ROMs (BASIC, FP, DOS) are 4KB blocks at romOffset+0..romOffset+0x5000
    // mapped at 0xC000, 0xD000, 0xE000 etc.
    async loadOs(os) {
        const extraRoms = Array.prototype.slice.call(arguments, 1).concat(this.config.extraRoms);
        const bankRoms = this.model.banks || [];
        os = "roms/" + os;
        console.log(`Loading Atom OS from ${os}`);
        const data = await loadData(os);
        const len = data.length;
 
        Iif (len < AtomRomBlockSize || len % AtomRomBlockSize !== 0) {
            throw new Error(`Broken Atom ROM file (length=${len})`);
        }
 
        // Clear the OS area and load the kernel at osOffset (mapped to 0xF000)
        this.ramRomOs.fill(0x00, this.osOffset, this.osOffset + 0x4000);
        this.ramRomOs.set(data.subarray(0, AtomRomBlockSize), this.osOffset);
 
        // Load extra ROMs (BASIC, FP, DOS) into 4KB blocks.
        // romIndex counts down from 5: slot 4 maps to 0xE000 (romOffset+0x4000),
        // slot 3 to 0xD000 (romOffset+0x3000), slot 2 to 0xC000 (romOffset+0x2000).
        let romIndex = 5;
        const awaiting = [];
        for (const rom of extraRoms) {
            romIndex--;
            Iif (romIndex < 2)
                throw new Error("Too many extra ROMs for Atom (max 3 addressable slots at 0xC000-0xEFFF)");
            Eif (rom !== "") {
                awaiting.push(this.loadRom(rom, this.romOffset + romIndex * AtomRomBlockSize));
            }
        }
 
        // Load Branquart bank ROMs (max 16 banks)
        const numBanks = Math.min(bankRoms.length, NumBranquartBanks);
        for (let bankIndex = 0; bankIndex < numBanks; bankIndex++) {
            Eif (bankRoms[bankIndex] !== "") {
                awaiting.push(this.loadRom(bankRoms[bankIndex], BranquartOffset + bankIndex * BranquartBankSize));
                this.branquartRam[bankIndex] = false; // mark as ROM
            }
        }
 
        return await Promise.all(awaiting);
    }
 
    // Override loadRom to accept 4KB ROMs
    async loadRom(name, offset) {
        if (name.indexOf("http") !== 0) name = "roms/" + name;
        let data = await loadData(name);
        if (/\.zip/i.test(name)) {
            data = (await unzipRomImage(data)).data;
        }
        const len = data.length;
        if (len !== 16384 && len !== 8192 && len !== 4096) {
            throw new Error(`Broken ROM file ${name} (length=${len})`);
        }
        this.ramRomOs.set(data, offset);
    }
 
    // Atom key layout goes through PPIA, not SysVia
    updateKeyLayout() {
        this.atomppia.setKeyLayout(this.keyLayout);
    }
 
    snapshotState(options) {
        const state = super.snapshotState(options);
        // Atom-specific state
        state.branquartLatch = this.branquartLatch;
        state.branquartRam = [...this.branquartRam];
        // Save Branquart bank contents
        state.branquartBanks = this.ramRomOs.slice(
            BranquartOffset,
            BranquartOffset + NumBranquartBanks * BranquartBankSize,
        );
        state.atomppia = this.atomppia.snapshotState();
        return state;
    }
 
    // No-op: the Atom doesn't have BBC sideways ROM banking.
    // This prevents super.restoreState() from corrupting the Atom memory map.
    romSelect() {}
 
    restoreState(state) {
        super.restoreState(state);
 
        // Restore Atom-specific state after the parent has handled
        // CPU registers, memory, cycle tracking, and sub-components.
        if (state.branquartRam) this.branquartRam = [...state.branquartRam];
        if (state.branquartBanks) {
            this.ramRomOs.set(state.branquartBanks, BranquartOffset);
        }
        this.branquartLatch = state.branquartLatch || 0;
        this.selectBranquartBank(this.branquartLatch & 0x0f);
        if (state.atomppia) this.atomppia.restoreState(state.atomppia);
    }
}