encrusted 1.0.0

A z-machine (interpreter) for Infocom-era text adventure games
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
use std::fs::File;
use std::path::PathBuf;
use std::io::prelude::*;
use std::fmt;
use std::fmt::Write as FmtWrite;
use std::collections::{HashSet, HashMap};
use std::boxed::Box;
use std::process;

use enum_primitive::FromPrimitive;
use rand;
use rand::{Rng, SeedableRng};
use base64;
use serde_json;

use buffer::Buffer;
use frame::Frame;
use instruction::Instruction;
use instruction::Opcode;
use instruction::OperandType;
use instruction::Operand;
use instruction::Branch;
use quetzal::QuetzalSave;
use options::Options;
use traits::UI;


#[derive(Debug)]
enum ZStringState {
    Alphabet(usize),
    Abbrev(u8),
    Tenbit1,
    Tenbit2(u8),
}


#[derive(Debug, Serialize)]
pub struct Object {
    number: u16,
    name: String,
    children: Vec<Box<Object>>,
}

impl Object {
    fn new(number: u16, zvm: &Zmachine) -> Box<Object> {
        let mut name = if number > 0 {
            zvm.get_object_name(number)
        } else {
            String::from("(Null Object)")
        };

        if name == "" {
            name += "(No Name)";
        }

        Box::new(Object { number, name, children: Vec::new() })
    }

    fn print_tree(&self, indent: &str, mut depth: u8, is_last: bool) -> String {
        let mut next = String::from(indent);
        let mut out = String::new();

        if depth == 0 {
            out += &format!("{} ({})\n", self.name, self.number);
        } else {
            out += &format!("{}{}── {} ({})\n",
                indent,
                if is_last { "└" } else { "├" },
                self.name,
                self.number);

            next += if is_last { "    " } else { "|   " };
        }

        depth += 1;

        for (i, child) in self.children.iter().enumerate() {
            let is_last_child = i == self.children.len()-1;
            out += &(**child).print_tree(&next, depth, is_last_child);
        }

        out
    }

    fn to_string(&self) -> String {
        if !self.children.is_empty() {
            self.print_tree("", 0, false)
        } else {
            format!("{} ({})", self.name, self.number)
        }
    }
}

impl fmt::Display for Object {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.to_string())
    }
}


#[derive(Debug)]
struct ObjectProperty {
    num: u8,
    len: u8,
    addr: usize,
    next: usize,
}

impl ObjectProperty {
    fn zero() -> ObjectProperty {
        ObjectProperty { num: 0, addr: 0, len: 0, next: 0 }
    }
}


pub struct Zmachine {
    pub ui:           Box<UI>,
    pub options:      Options,
    pub instr_log:    String,
    version:          u8,
    memory:           Buffer,
    original_dynamic: Vec<u8>,
    save_dir:         String,
    save_name:        String,
    static_start:     usize,
    routine_offset:   usize,
    string_offset:    usize,
    alphabet:         [Vec<String>; 3],
    abbrev_table:     usize,
    separators:       Vec<char>,
    dictionary:       HashMap<String, usize>,
    frames:           Vec<Frame>,
    initial_pc:       usize,
    pc:               usize,
    globals_addr:     usize,
    prop_defaults:    usize,
    obj_table_addr:   usize,
    obj_size:         usize,
    attr_width:       usize,
    paused_instr:     Option<Instruction>,
    current_state:    Option<(String, Vec<u8>)>,
    undos:            Vec<(String, Vec<u8>)>,
    redos:            Vec<(String, Vec<u8>)>,
    rng:              rand::XorShiftRng,
}

impl Zmachine {
    pub fn new(data: Vec<u8>, ui: Box<UI>, options: Options) -> Zmachine {
        let memory = Buffer::new(data);

        let version       = memory.read_byte(0x00);
        let initial_pc    = memory.read_word(0x06) as usize;
        let prop_defaults = memory.read_word(0x0A) as usize;
        let static_start  = memory.read_word(0x0E) as usize;

        let mut zvm = Zmachine {
            version,
            ui,
            save_dir:         format!("{}", &options.save_dir),
            save_name:        format!("{}.sav", &options.save_name),
            options,
            instr_log:        String::new(),
            original_dynamic: memory.slice(0, static_start).to_vec(),
            globals_addr:     memory.read_word(0x0C) as usize,
            routine_offset:   memory.read_word(0x28) as usize,
            string_offset:    memory.read_word(0x2A) as usize,
            static_start,
            initial_pc,
            pc:               initial_pc,
            frames:           vec![Frame::empty()],
            alphabet:         Zmachine::default_alphabet(),
            abbrev_table:     memory.read_word(0x18) as usize,
            separators:       Vec::new(),
            dictionary:       HashMap::new(),
            prop_defaults,
            obj_table_addr:   prop_defaults + (if version <= 3 { 31 } else { 63 }) * 2,
            obj_size:         if version <= 3 { 9 } else { 14 },
            attr_width:       if version <= 3 { 4 } else { 6 },
            paused_instr:     None,
            current_state:    None,
            undos:            Vec::new(),
            redos:            Vec::new(),
            rng:              rand::SeedableRng::from_seed([90, 111, 114, 107]),
            memory,
        };

        // read into dictionary & word separators
        zvm.populate_dictionary();

        zvm
    }

    #[allow(dead_code)]
    fn calculate_checksum(memory: &Buffer) -> u16 {
        let mut sum: usize = 0;
        let len = memory.read_byte(0x1A) as usize * 2;

        for i in 0x40..len {
            sum += memory.read_byte(i) as usize;
        }

        (sum % 0x10000) as u16
    }

    #[allow(non_snake_case)]
    fn default_alphabet() -> [Vec<String>; 3] {
        let A0 = " .....abcdefghijklmnopqrstuvwxyz";
        let A1 = " .....ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        let A2 = " ......\n0123456789.,!?_#'\"/\\-:()";

        [
            A0.chars().map(|c| c.to_string()).collect(),
            A1.chars().map(|c| c.to_string()).collect(),
            A2.chars().map(|c| c.to_string()).collect(),
        ]
    }

    fn unpack(&self, addr: u16) -> usize {
        let addr = addr as usize;

        match self.version {
            1...3 => addr * 2,
            4...7 => addr * 4,
            _     => addr * 8,
        }
    }

    fn unpack_routine_addr(&self, addr: u16) -> usize {
        match self.unpack(addr) {
            x @ 6...7 => x + self.routine_offset * 8,
            x         => x,
        }
    }

    fn unpack_print_paddr(&self, addr: u16) -> usize {
        match self.unpack(addr) {
            x @ 6...7 => x + self.string_offset * 8,
            x         => x,
        }
    }

    fn read_global(&self, index: u8) -> u16 {
        if index > 240 { panic!("Can't read global{}!", index); }

        let addr = self.globals_addr + index as usize * 2;
        self.memory.read_word(addr)
    }

    fn write_global(&mut self, index: u8, value: u16) {
        if index > 240 { panic!("Can't write global{}!", index); }

        let addr = self.globals_addr + index as usize * 2;
        self.memory.write_word(addr, value);
    }

    fn read_local(&self, index: u8) -> u16 {
        self.frames.last()
            .expect("Can't write local, no frames!")
            .read_local(index)
    }

    fn write_local(&mut self, index: u8, value: u16) {
        self.frames.last_mut()
            .expect("Can't write local, no frames!")
            .write_local(index, value);
    }

    fn stack_push(&mut self, value: u16) {
        self.frames.last_mut()
            .expect("Can't push to stack, no frames!")
            .stack_push(value);
    }

    fn stack_pop(&mut self) -> u16 {
        self.frames.last_mut()
            .expect("Can't pop stack, no frames!")
            .stack_pop()
    }

    fn stack_peek(&mut self) -> u16 {
        self.frames.last_mut()
            .expect("Can't peek stack, no frames!")
            .stack_peek()
    }

    fn read_variable(&mut self, index: u8) -> u16 {
        match index {
            0        => self.stack_pop(),
            1...15   => self.read_local(index-1),
            16...255 => self.read_global(index-16),
            _        => unreachable!(),
        }
    }

    fn read_indirect_variable(&mut self, index: u8) -> u16 {
        match index {
            0        => self.stack_peek(),
            1...15   => self.read_local(index-1),
            16...255 => self.read_global(index-16),
            _        => unreachable!(),
        }
    }

    fn write_variable(&mut self, index: u8, value: u16) {
        match index {
            0        => self.stack_push(value),
            1...15   => self.write_local(index-1, value),
            16...255 => self.write_global(index-16, value),
            _        => unreachable!(),
        }
    }

    fn write_indirect_variable(&mut self, index: u8, value: u16) {
        match index {
            0        => {self.stack_pop(); self.stack_push(value);}
            1...15   => self.write_local(index-1, value),
            16...255 => self.write_global(index-16, value),
            _        => unreachable!(),
        }
    }

    fn get_abbrev(&self, index: u8) -> String {
        if index > 96 {
            panic!("Bad abbrev index: {}", index);
        }

        let offset = 2 * index as usize;
        let packed_addr = self.memory.read_word(self.abbrev_table + offset);
        let addr = self.unpack(packed_addr);

        self.read_zstring(addr)
    }

    fn read_zstring(&self, addr: usize) -> String {
        use self::ZStringState::*;

        let mut state = Alphabet(0);
        let mut index = addr;
        let mut zstring = String::new();

        // this closure borrows the zstring while it steps through each zchar.
        // (wrapped here in its own scope to force the borrow to end)
        {
            let mut step = |zchar: u8| {
                state = match (zchar, &state) {
                    // the next zchar will be an abbrev index
                    (1, &Alphabet(_)) => Abbrev(1),
                    (2, &Alphabet(_)) => Abbrev(2),
                    (3, &Alphabet(_)) => Abbrev(3),
                    // shift character for the next zchar
                    (4, &Alphabet(_)) => Alphabet(1),
                    (5, &Alphabet(_)) => Alphabet(2),
                    // special 10bit case, next 2 zchars = one 10bit zscii char
                    (6, &Alphabet(2)) => Tenbit1,
                    (_, &Tenbit1) => Tenbit2(zchar),
                    (_, &Tenbit2(first)) => {
                        let letter = ((first << 5) + zchar) as char;
                        zstring.push_str(&letter.to_string());
                        Alphabet(0)
                    }
                    // get the abbrev at this addr
                    (_, &Abbrev(num)) => {
                        let abbrev = self.get_abbrev((num-1) * 32 + zchar);
                        zstring.push_str(&abbrev);
                        Alphabet(0)
                    }
                    // normal case, adds letter from correct alphabet and resets to A0
                    (_, &Alphabet(num)) => {
                        let letter = &self.alphabet[num][zchar as usize];
                        zstring.push_str(letter);
                        Alphabet(0)
                    }
                };
            };

            // 3 zchars per each 16 bit word + a "stop" bit on top
            // 0 10101 01010 10101
            loop {
                let word = self.memory.read_word(index);
                index += 2;

                step(((word >> 10) & 0b00011111) as u8);
                step(((word >> 5)  & 0b00011111) as u8);
                step( (word        & 0b00011111) as u8);

                // stop bit
                if word & 0x8000 != 0 { break; }
            }

        } // <- drop process closure, ending zstring borrow

        zstring
    }

    // reads the ENCODED byte length of a zstring, how many consecutive
    // bytes in memory it is (not just the number of characters)
    fn zstring_length(&self, addr: usize) -> usize {
        let mut length = 0;

        loop {
            let word = self.memory.read_word(addr + length);
            length += 2;

            // stop bit
            if word & 0x8000 != 0 { break; }
        }

        length
    }

    fn populate_dictionary(&mut self) {
        let dictionary_start = self.memory.read_word(0x08) as usize;
        let mut read = self.memory.get_reader(dictionary_start);

        let separator_count = read.byte();

        for _ in 0..separator_count {
            self.separators.push(read.byte() as char);
        }

        let entry_length = read.byte() as usize;
        let entry_count  = read.word() as usize;
        let entry_start  = read.position();

        for n in 0..entry_count {
            let addr = entry_start + n * entry_length;
            let entry = self.read_zstring(addr);

            self.dictionary.insert(entry, addr);
        }
    }

    fn check_dict(&self, word: &str) -> usize {
        let length = if self.version <= 3 { 6 } else { 9 };
        let mut short = word.to_string();
        short.truncate(length);

        match self.dictionary.get(&short) {
            Some(addr) => *addr,
            None => 0,
        }
    }

    fn tokenise(&mut self, text: &str, parse_addr: usize) {
        // v1-4 start storing @ byte 1, v5+ start @2;
        let start = if self.version <= 4 { 1 } else { 2 };
        let mut input = String::from(text);
        let mut found = HashMap::new();

        for sep in &self.separators {
            input = input.replace(&sep.to_string(), &format!(" {} ", sep))
        }

        let tokens = input.split(' ')
            .filter(|token| !token.is_empty())
            .map(|token| {
                let offset = found.entry(token).or_insert(0);
                let position = text[*offset..].find(token).unwrap();

                let dict_addr = self.check_dict(token);
                let token_addr = *offset + position + start;

                *offset += position + token.len();

                (dict_addr, token.len(), token_addr)
            })
            .collect::<Vec<_>>();

        let mut write = self.memory.get_writer(parse_addr + 1);
        write.byte(tokens.len() as u8);

        tokens.iter().for_each(|&(dict_addr, len, token_addr)| {
            write.word(dict_addr as u16);
            write.byte(len as u8);
            write.byte(token_addr as u8);
        });
    }

    fn get_object_addr(&self, object: u16) -> usize {
        if object == 0 {
            panic!("Trying to get the address for the INVALID_OBJECT 0");
        }

        self.obj_table_addr + ((object as usize - 1) * self.obj_size)
    }

    fn get_object_prop_table_addr(&self, object: u16) -> usize {
        let addr = self.get_object_addr(object)
            // skip attributes
            + self.attr_width
            // ship parent/child/sibling data
            + if self.version <= 3 { 3 } else { 9 };

        // the property table address is in the next word:
        self.memory.read_word(addr) as usize
    }

    // Object name is found at the start the object's property table:
    //   text-length   text of short name of object
    //   ---byte----   --some even number of bytes--
    fn get_object_name(&self, object: u16) -> String {
        let addr = self.get_object_prop_table_addr(object);
        let text_length = self.memory.read_byte(addr);

        if text_length > 0 {
            self.read_zstring(addr + 1)
        } else {
            String::new()
        }
    }

    fn get_parent(&self, object: u16) -> u16 {
        let addr = self.get_object_addr(object) + self.attr_width;

        if self.version <= 3 {
            self.memory.read_byte(addr) as u16
        } else {
            self.memory.read_word(addr)
        }
    }

    fn set_parent(&mut self, object: u16, parent: u16) {
        let addr = self.get_object_addr(object) + self.attr_width;

        if self.version <= 3 {
            self.memory.write_byte(addr, parent as u8);
        } else {
            self.memory.write_word(addr, parent);
        }
    }

    fn get_sibling(&self, object: u16) -> u16 {
        let addr = self.get_object_addr(object) + self.attr_width;

        if self.version <= 3 {
            self.memory.read_byte(addr + 1) as u16
        } else {
            self.memory.read_word(addr + 2)
        }
    }

    fn set_sibling(&mut self, object: u16, sibling: u16) {
        let addr = self.get_object_addr(object) + self.attr_width;

        if self.version <= 3 {
            self.memory.write_byte(addr + 1, sibling as u8);
        } else {
            self.memory.write_word(addr + 2, sibling);
        }
    }

    fn get_child(&self, object: u16) -> u16 {
        let addr = self.get_object_addr(object) + self.attr_width;

        if self.version <= 3 {
            self.memory.read_byte(addr + 2) as u16
        } else {
            self.memory.read_word(addr + 4)
        }
    }

    fn set_child(&mut self, object: u16, child: u16) {
        let addr = self.get_object_addr(object) + self.attr_width;

        if self.version <= 3 {
            self.memory.write_byte(addr + 2, child as u8);
        } else {
            self.memory.write_word(addr + 4, child);
        }
    }

    fn remove_obj(&mut self, object: u16) {
        let parent = self.get_parent(object);
        if parent == 0 { return; }

        // fix the tree to patch any holes:
        // 1- if the obj is the first child, make the obj's sibling the new child
        // 2- otherwise, connect the two siblings on each side of the obj
        let parents_first_child = self.get_child(parent);
        let younger_sibling = self.get_sibling(object);

        fn get_older(this: &Zmachine, obj: u16, prev: u16) -> u16 {
            let next = this.get_sibling(prev);
            if next == obj { prev } else { get_older(this, obj, next) }
        }

        if object == parents_first_child {
            // fix the parent / first child relationship, upgrade the younger sibling
            //   A              A
            //   |        =>    |
            //   B--C--D        C--D
            self.set_child(parent, younger_sibling);
        } else {
            // fix the hole between two siblings ( A--B--C  ->  A--C )
            let older_sibling = get_older(self, object, parents_first_child);
            self.set_sibling(older_sibling, younger_sibling);
        }

        // remove the object by settings its parent to the null object
        // and clear its sibling reference, since it was moved above
        self.set_parent(object, 0);
        self.set_sibling(object, 0);
    }

    fn insert_obj(&mut self, object: u16, destination: u16) {
        let parents_first_child = self.get_child(destination);

        // skip if object is already in the right place
        if parents_first_child == object { return; }

        // first remove the object from its position and fix that change
        self.remove_obj(object);

        // set parent/child relationship (object becomes the new first child)
        self.set_parent(object, destination);
        self.set_child(destination, object);

        // move the previous first child into this object's sibling spot
        self.set_sibling(object, parents_first_child);
    }

    fn get_total_object_count(&self) -> u16 {
        // by convention, the property table for object #1 is located AFTER
        // the last object in the object table:
        let obj_table_end = self.get_object_prop_table_addr(1);
        let obj_size = self.attr_width + if self.version <= 3 { 3 } else { 9 } + 2;

        // v1-3 have a max of 255 objects, v4+ can have up to 65535
        ((obj_table_end - self.obj_table_addr) / obj_size) as u16
    }

    fn add_object_children(&self, parent: &mut Object) {
        // follow linked list of siblings to get all children:
        // Parent
        //   |
        // Child -- Sibling -- Sibling -- Sibling ...
        let mut next = self.get_child(parent.number);

        while next > 0 {
            parent.children.push(Object::new(next, self));
            next = self.get_sibling(next);
        }

        // get the children of each child
        for child in &mut parent.children {
            self.add_object_children(&mut *child);
        }
    }

    pub fn get_object_tree(&self) -> Object {
        // start using the INVALID_OBJECT 0 as the root
        let mut root = Object::new(0, self);

        // find all top level objects (objects with no parents)
        for i in 1..self.get_total_object_count()+1 {
            if self.get_parent(i) == 0 {
                root.children.push(Object::new(i, self));
            }
        }

        // recursively fetch children for each top level object
        for object in &mut root.children {
            self.add_object_children(&mut *object);
        }

        *root
    }

    fn find_object(&self, name: &str) -> Option<u16> {
        for i in 1..self.get_total_object_count()+1 {
            if self.get_object_name(i).to_lowercase() == name.to_lowercase() {
                return Some(i);
            }
        }

        None
    }

    fn find_yourself(&self) -> Option<u16> {
        self.find_object("cretin")
            .or(self.find_object("you"))
            .or(self.find_object("yourself"))
    }

    fn test_attr(&self, object: u16, attr: u16) -> u16 {
        if attr as usize > self.attr_width * 8 {
            panic!("Can't test out-of-bounds attribute: {}", attr);
        }

        let addr = self.get_object_addr(object) + attr as usize / 8;
        let byte = self.memory.read_byte(addr);
        let bit = attr % 8;

        if byte & (128 >> bit) != 0 { 1 } else { 0 }
    }

    fn set_attr(&mut self, object: u16, attr: u16) {
        if attr as usize > self.attr_width * 8 {
            panic!("Can't set out-of-bounds attribute: {}", attr);
        }

        let addr = self.get_object_addr(object) + attr as usize / 8;
        let byte = self.memory.read_byte(addr);
        let bit = attr % 8;

        self.memory.write_byte(addr, byte | (128 >> bit));
    }

    fn clear_attr(&mut self, object: u16, attr: u16) {
        if attr as usize > self.attr_width * 8 {
            panic!("Can't clear out-of-bounds attribute: {}", attr);
        }

        let addr = self.get_object_addr(object) + attr as usize / 8;
        let byte = self.memory.read_byte(addr);
        let bit = attr % 8;

        self.memory.write_byte(addr, byte & !(128 >> bit));
    }

    fn get_default_prop(&self, property_number: u16) -> u16 {
        let word_index = (property_number - 1) as usize;
        let addr = self.prop_defaults + word_index * 2;

        self.memory.read_word(addr)
    }

    fn read_object_prop(&self, addr: usize) -> ObjectProperty {
        let header = self.memory.read_byte(addr);
        let len;
        let num;
        let value_addr;

        match self.version {
            1...3 => {
                num = header % 32;
                len = header / 32 + 1;
                value_addr = addr + 1; // 1 byte header
            }
            _ => {
                num = header & 0b00111111;

                if header & 0b10000000 != 0 {
                    len = self.memory.read_byte(addr + 1) & 0b00111111;
                    value_addr = addr + 2; // 2 byte header
                } else {
                    len = if header & 0b01000000 != 0 { 2 } else { 1 };
                    value_addr = addr + 1; // 1 byte header
                }
            }
        }

        ObjectProperty {
            num,
            len,
            addr: value_addr,
            next: value_addr + len as usize
        }
    }

    fn find_prop(&self, object: u16, property_number: u16) -> ObjectProperty {
        if property_number == 0 { return ObjectProperty::zero(); }

        let addr = self.get_object_prop_table_addr(object);
        let str_length = self.memory.read_byte(addr) as usize * 2; // words in name
        let first_addr = addr + str_length + 1;

        let property_number = property_number as u8;
        let mut prop = self.read_object_prop(first_addr);

        // linear prop read until property_number is found or until we run out
        // props are listed in decreasing order, check to make
        // sure the requested property even exists
        while prop.num != 0 && prop.num != property_number {
            if property_number > prop.num { return ObjectProperty::zero(); }
            prop = self.read_object_prop(prop.next);
        }

        prop
    }

    fn get_prop_value(&self, object: u16, property_number: u16) -> u16 {
        let prop = self.find_prop(object, property_number);

        if prop.num == 0 {
            self.get_default_prop(property_number)
        } else if prop.len == 1 {
            self.memory.read_byte(prop.addr) as u16
        } else {
            self.memory.read_word(prop.addr)
        }
    }

    fn get_prop_addr(&self, object: u16, property_number: u16) -> usize {
        let prop = self.find_prop(object, property_number);

        if prop.num != 0 { prop.addr } else { 0 }
    }

    fn get_prop_len(&self, prop_data_addr: usize) -> u8 {
        // weird required edge case
        if prop_data_addr == 0 { return 0; }

        // address given is the property DATA, the property HEADER is right before
        let prop_header = self.memory.read_byte(prop_data_addr - 1);

        if self.version <= 3 {
            prop_header / 32 + 1
        } else if prop_header & 0b10000000 != 0 {
            prop_header & 0b00111111
        } else if prop_header & 0b01000000 != 0 {
            2
        } else {
            1
        }
    }

    fn get_next_prop(&self, object: u16, property_number: u16) -> u16 {
        // if property 0 is requested, give the first property present
        if property_number == 0 {
            let addr = self.get_object_prop_table_addr(object);
            let str_length = self.memory.read_byte(addr) as usize * 2;
            let first_prop = addr + str_length + 1;

            self.read_object_prop(first_prop).num as u16
        } else {
            let prop = self.find_prop(object, property_number);

            self.read_object_prop(prop.next).num as u16
        }
    }

    fn put_prop(&mut self, object: u16, property_number: u16, value: u16) {
        let prop = self.find_prop(object, property_number);

        if prop.len == 1 {
            self.memory.write_byte(prop.addr, value as u8);
        } else {
            self.memory.write_word(prop.addr, value);
        }
    }

    // Web UI only
    #[allow(dead_code)]
    pub fn get_current_room(&self) -> (u16, String) {
        let num = self.read_global(0);
        let name = self.get_object_name(num);

        (num, name)
    }

    fn get_status(&self) -> (String, String) {
        let num = self.read_global(0);
        let left = self.get_object_name(num);

        // bit 1 in header flags:
        // 0 => score/turns
        // 1 => AM/PM
        let right = if self.memory.read_byte(0x01) & 0b00000010 == 0 {
            let score = self.read_global(1) as i16;
            let turns = self.read_global(2);

            format!("{}/{}", score, turns)
        } else {
            let mut hours = self.read_global(1);
            let minutes = self.read_global(2);
            let am_pm = if hours >= 12 { "PM" } else { "AM" };
            if hours > 12 { hours -= 12; }

            format!("{:02}:{:02} {}", hours, minutes, am_pm)
        };

        (left, right)
    }

    pub fn update_status_bar(&self) {
        // status bar only used in v1-3
        if self.version > 3 { return; }

        let (left, right) = self.get_status();
        self.ui.set_status_bar(&left, &right);
    }

    fn save_state(&self, pc: usize) -> Vec<u8> {
        // save the whole dynamic memory region (between 0 and the start of static)
        let dynamic  = self.memory.slice(0, self.static_start);
        let original = self.original_dynamic.as_slice();
        let frames   = &self.frames;
        let chksum   = self.memory.read_word(0x1c);
        let release  = self.memory.read_word(0x02);
        let serial   = self.memory.read(0x12, 6);

        QuetzalSave::make(pc, dynamic, original, frames, chksum, release, serial)
    }

    fn restore_state(&mut self, data: &[u8]) {
        let save = QuetzalSave::from_bytes(&data[..], &self.original_dynamic[..]);

        // verify that the save if so the right game and that the memory is ok
        if save.chksum != self.memory.read_word(0x1C) {
            panic!("Invalid save, checksum is different");
        }

        if self.static_start < save.memory.len() {
            panic!("Invalid save, memory is too long");
        }

        self.pc = save.pc;
        self.frames = save.frames;
        self.memory.write(0, save.memory.as_slice());
    }

    pub fn undo(&mut self) -> bool {
        if let Some(ref instr) = self.paused_instr {
            if instr.opcode != Opcode::VAR_228 {
                return false;
            }
        }

        if self.undos.is_empty() {
            self.ui.print("\n[Can't undo that far.]\n");
            return false;
        }

        let new_current = self.undos.pop().unwrap();
        self.redos.push(self.current_state.take().unwrap());

        self.restore_state(new_current.1.as_slice());
        self.current_state = Some(new_current);

        true
    }

    pub fn redo(&mut self) -> bool {
        if let Some(ref instr) = self.paused_instr {
            if instr.opcode != Opcode::VAR_228 {
                return false;
            }
        }

        if self.redos.is_empty() {
            self.ui.print("\n[Nothing to redo.]\n");
            return false;
        }

        let new_current = self.redos.pop().unwrap();
        self.undos.push(self.current_state.take().unwrap());

        self.restore_state(new_current.1.as_slice());
        self.current_state = Some(new_current);

        true
    }

    fn get_arguments(&mut self, operands: &[Operand]) -> Vec<u16> {
        operands.iter()
            .map(|operand| match *operand {
                Operand::Small(val)    => val as u16,
                Operand::Large(val)    => val,
                Operand::Variable(val) => self.read_variable(val),
            })
            .collect()
    }

    fn return_from_routine(&mut self, value: u16) {
        let frame = self.frames.pop().expect("Can't pop off last frame!");
        self.pc = frame.resume;

        if let Some(index) = frame.store {
            self.write_variable(index, value);
        }
    }

    fn process_branch(&mut self, branch: &Branch, next: usize, result: u16) {
        let Branch { address, returns, condition } = *branch;
        let result = if result >= 1 { 1 } else { 0 };

        if let Some(index) = address {
            self.pc = if result == condition { index } else { next };
        }

        if let Some(value) = returns {
            if result == condition {
                self.return_from_routine(value);
            } else {
                self.pc = next
            }
        }
    }

    fn process_result(&mut self, instr: &Instruction, value: u16) {
        // store the result if needed
        if let Some(index) = instr.store {
            self.write_variable(index, value);
        }

        // check if we need to branch
        if let Some(ref branch) = instr.branch {
            self.process_branch(branch, instr.next, value);
        } else {
            self.pc = instr.next;
        }
    }

    fn decode_instruction(&self, addr: usize) -> Instruction {
        let mut read = self.memory.get_reader(addr);
        let first = read.byte();

        let btm_4 = |num| num & 0b00001111;
        let btm_5 = |num| num & 0b00011111;
        let get_types = |bytes: &[u8]| OperandType::from(bytes);

        let get_opcode = |code: u8, offset: u16| {
            let num = code as u16 + offset;

            match Opcode::from_u16(num) {
                Some(val) => val,
                None => panic!("Opcode not found: {:?}", num),
            }
        };

        use self::OperandType::*;

        let (opcode, optypes) = match first {
            0xbe        => (get_opcode(read.byte(), 1000), get_types(&[read.byte()])),
            0x00...0x1f => (get_opcode(btm_5(first), 0),   vec![Small, Small]),
            0x20...0x3f => (get_opcode(btm_5(first), 0),   vec![Small, Variable]),
            0x40...0x5f => (get_opcode(btm_5(first), 0),   vec![Variable, Small]),
            0x60...0x7f => (get_opcode(btm_5(first), 0),   vec![Variable, Variable]),
            0x80...0x8f => (get_opcode(btm_4(first), 128), vec![Large]),
            0x90...0x9f => (get_opcode(btm_4(first), 128), vec![Small]),
            0xa0...0xaf => (get_opcode(btm_4(first), 128), vec![Variable]),
            0xb0...0xbf => (get_opcode(btm_4(first), 176), vec![]), // OP_0
            0xc0...0xdf => (get_opcode(btm_5(first), 0),   get_types(&[read.byte()])),
            0xe0...0xff => {
                let opcode = get_opcode(btm_5(first), 224);

                if opcode == Opcode::VAR_236 || opcode == Opcode::VAR_250 {
                    (opcode, get_types(&[read.byte(), read.byte()]))
                } else {
                    (opcode, get_types(&[read.byte()]))
                }
            }
            _ => unreachable!(),

        };

        let operands = optypes.iter()
            .map(|optype| match *optype {
                OperandType::Small    => Operand::Small(read.byte()),
                OperandType::Large    => Operand::Large(read.word()),
                OperandType::Variable => Operand::Variable(read.byte()),
                OperandType::Omitted  => unreachable!(),
            })
            .collect();

        let store = if Instruction::does_store(opcode, self.version) {
            Some(read.byte())
        } else {
            None
        };

        let branch = if Instruction::does_branch(opcode, self.version) {
            let byte = read.byte() as usize;
            let condition = if byte & 0b10000000 != 0 { 1 } else { 0 };

            let offset = if byte & 0b01000000 != 0 {
                byte & 0b00111111
            } else {
                ((byte & 0b00111111) << 8) + read.byte() as usize
            };

            // the offset (if two bytes) is a 14 bit unsigned int: 2^14 = 16384
            let address = if offset > (16384/2) {
                Some(read.position() + offset - 16384 - 2)
            } else {
                Some(read.position() + offset - 2)
            };

            match offset {
                0 => Some(Branch { condition, address: None, returns: Some(0) }),
                1 => Some(Branch { condition, address: None, returns: Some(1) }),
                _ => Some(Branch { condition, address, returns: None }),
            }
        } else {
            None
        };

        let text = if Instruction::does_text(opcode) {
            Some(self.read_zstring(read.position()))
        } else {
            None
        };

        let text_length = if text.is_some() {
            self.zstring_length(read.position())
        } else {
            0
        };

        let name = Instruction::name(opcode, self.version);
        let next = read.position() + text_length;

        Instruction { addr, opcode, name, operands, store, branch, text, next }
    }

    pub fn handle_instruction(&mut self, instr: &Instruction) {
        use self::Opcode::*;

        // ~mutably~ gets the arguments (might pop stack)
        let args = self.get_arguments(instr.operands.as_slice());

        // Match instructions that return values for storing or branching (or both)
        // `result` is an option. either a matched instruction or none (no match)
        let result = match (instr.opcode, &args[..]) {
            (OP2_1,   &[a, ref bs..])  => Some( self.do_je(a, bs) ),
            (OP2_2,   &[a, b])         => Some( self.do_jl(a, b) ),
            (OP2_3,   &[a, b])         => Some( self.do_jg(a, b) ),
            (OP2_4,   &[var, value])   => Some( self.do_dec_chk(var, value) ),
            (OP2_5,   &[var, value])   => Some( self.do_inc_chk(var, value) ),
            (OP2_6,   &[obj1, obj2])   => Some( self.do_jin(obj1, obj2) ),
            (OP2_7,   &[map, flags])   => Some( self.do_test(map, flags) ),
            (OP2_8,   &[a, b])         => Some( self.do_or(a, b) ),
            (OP2_9,   &[a, b])         => Some( self.do_and(a, b) ),
            (OP2_10,  &[obj, attr])    => Some( self.do_test_attr(obj, attr) ),
            (OP2_15,  &[array, index]) => Some( self.do_loadw(array, index) ),
            (OP2_16,  &[array, index]) => Some( self.do_loadb(array, index) ),
            (OP2_17,  &[obj, prop])    => Some( self.do_get_prop(obj, prop) ),
            (OP2_18,  &[obj, prop])    => Some( self.do_get_prop_addr(obj, prop) ),
            (OP2_19,  &[obj, prop])    => Some( self.do_get_next_prop(obj, prop) ),
            (OP2_20,  &[a, b])         => Some( self.do_add(a, b) ),
            (OP2_21,  &[a, b])         => Some( self.do_sub(a, b) ),
            (OP2_22,  &[a, b])         => Some( self.do_mul(a, b) ),
            (OP2_23,  &[a, b])         => Some( self.do_div(a, b) ),
            (OP2_24,  &[a, b])         => Some( self.do_mod(a, b) ),
            (OP1_128, &[a])            => Some( self.do_jz(a) ),
            (OP1_129, &[obj])          => Some( self.do_get_sibling(obj) ),
            (OP1_130, &[obj])          => Some( self.do_get_child(obj) ),
            (OP1_131, &[obj])          => Some( self.do_get_parent(obj) ),
            (OP1_132, &[addr])         => Some( self.do_get_prop_len(addr) ),
            (OP1_142, &[var])          => Some( self.do_load(var) ),
            (OP1_143, &[value])        => Some( self.do_not(value) ),
            (OP0_189, &[])             => Some( self.do_verify() ),
            (VAR_231, &[range])        => Some( self.do_random(range) ),
            _ => None,
        };

        // If one of the above instructions matched, handle its result by
        // either storing it / branching on it / advancing the program counter.
        // Then return early since this instruction is done.
        if let Some(value) = result {
            self.process_result(instr, value);
            return;
        }

        // All other instructions (don't produce a value, only a side effect)
        match (instr.opcode, &args[..]) {
            (OP2_11,  &[obj, attr])  => self.do_set_attr(obj, attr),
            (OP2_12,  &[obj, attr])  => self.do_clear_attr(obj, attr),
            (OP2_13,  &[var, value]) => self.do_store(var, value),
            (OP2_14,  &[obj, dest])  => self.do_insert_obj(obj, dest),
            (OP2_25,  &[addr, arg])  => self.do_call(instr, addr, &[arg]), // call_2s
            (OP2_26,  &[addr, arg])  => self.do_call(instr, addr, &[arg]), // call_2n
            (OP1_133, &[var])        => self.do_inc(var),
            (OP1_134, &[var])        => self.do_dec(var),
            (OP1_135, &[addr])       => self.do_print_addr(addr),
            (OP1_136, &[addr])       => self.do_call(instr, addr, &[]), // call_1s
            (OP1_137, &[obj])        => self.do_remove_obj(obj),
            (OP1_138, &[obj])        => self.do_print_obj(obj),
            (OP1_139, &[value])      => self.do_ret(value),
            (OP1_140, &[offset])     => self.do_jump(offset, instr),
            (OP1_141, &[addr])       => self.do_print_paddr(addr),
            (OP0_176, _)             => self.do_rtrue(),
            (OP0_177, _)             => self.do_rfalse(),
            (OP0_178, _)             => self.do_print(instr),
            (OP0_179, _)             => self.do_print_ret(instr),
            (OP0_181, _)             => self.do_save(instr),
            (OP0_182, _)             => self.do_restore(instr),
            (OP0_183, _)             => self.do_restart(),
            (OP0_184, _)             => self.do_ret_popped(),
            (OP0_187, _)             => self.do_newline(),
            (OP0_188, _)             => self.do_show_status(),
            (VAR_224, &[addr, ref rest..])    => self.do_call(instr, addr, rest), // call
            (VAR_225, &[array, index, value]) => self.do_storew(array, index, value),
            (VAR_226, &[array, index, value]) => self.do_storeb(array, index, value),
            (VAR_227, &[obj, prop, value])    => self.do_put_prop(obj, prop, value),
            (VAR_228, &[text, parse])         => self.do_sread(instr, text, parse),
            (VAR_229, &[chr])                 => self.do_print_char(chr),
            (VAR_230, &[num])                 => self.do_print_num(num),
            (VAR_232, &[value])               => self.do_push(value),
            (VAR_233, &[var])                 => self.do_pull(var),
            (VAR_236, &[addr, ref rest..])    => self.do_call(instr, addr, rest), // call_vs2
            (VAR_249, &[addr, ref rest..])    => self.do_call(instr, addr, rest), // call_vn
            (VAR_250, &[addr, ref rest..])    => self.do_call(instr, addr, rest), // call_vn2

            // special cases to no-op: (input/output streams & sound effects)
            // these might be present in some v3 games but aren't implemented yet
            (VAR_243, _) | (VAR_244, _) | (VAR_245, _) => (),

            _ => panic!("\n\nOpcode not yet implemented: {} ({:?}) @ {:#04x}\n\n",
                        instr.name, instr.opcode, self.pc)
        }

        // advance pc to the next instruction
        // (but not for jumps, calls, save/restore, or anything with special needs)
        if instr.advances() && instr.should_advance(self.version) {
            self.pc = instr.next;
        }
    }

    fn is_debug_command(&self, input: &str) -> bool {
        if !input.starts_with('$') { return false; }

        let parts = input.split(' ').collect::<Vec<_>>();
        let command = parts.first().unwrap();

        let valid = [
            "$dump", "$dict", "$tree", "$room", "$you", "$find", "$object",
            "$parent", "$simple", "$attrs", "$props", "$header", "$history",
            "$have_attr", "$have_prop", "$undo", "$redo", "$redo", "$teleport",
            "$steal", "$help"
        ];

        valid.contains(command)
    }

    fn print_command_help(&mut self) {
        self.ui.debug("\
            Available debug commands: \n\n\
            $dump               (list stack frames and PC) \n\
            $dict               (show games's dictionary) \n\
            $tree               (list current object tree) \n\
            $room               (show current room's sub-tree) \n\
            $you                (show your sub-tree) \n\
            $find name          (find object number from name) \n\
            $object num/name    (show object's sub-tree) \n\
            $parent num/name    (show object's parent sub-tree) \n\
            $simple num         (object info, simple view) \n\
            $attrs num/name     (list object attributes) \n\
            $props num/name     (list object properties) \n\
            $header             (show header info) \n\
            $history            (list saved states) \n\
            $have_attr num      (list objects that have given attribute enabled) \n\
            $have_prop num      (list objects that have given property) \n\
            $teleport num/name  (teleport to a room) \n\
            $steal num/name     (takes any item) \n\
            $undo \n\
            $redo \n\
            $quit
        ");
    }

    fn handle_debug_command(&mut self, input: &str) -> bool {
        let mut should_ask_again = true;
        let parts = input.split(' ').collect::<Vec<_>>();
        let (command, rest) = parts.split_first().unwrap();
        let arg = &rest.join(" ");

        match *command {
            "$help"   => self.print_command_help(),
            "$dump"   => self.debug_dump(),
            "$dict"   => self.debug_dictionary(),
            "$tree"   => self.debug_object_tree(),
            "$room"   => self.debug_room(),
            "$you"    => self.debug_yourself(),
            "$find"   => self.debug_find_object(arg),
            "$object" => self.debug_object(arg),
            "$parent" => self.debug_parent(arg),
            "$attrs"  => self.debug_object_attributes(arg),
            "$props"  => self.debug_object_properties(arg),
            "$simple" => self.debug_object_simple(arg.parse().unwrap_or(1)),
            "$header" => self.debug_header(),
            "$history"   => self.debug_history(),
            "$have_attr" => self.debug_have_attribute(arg),
            "$have_prop" => self.debug_have_property(arg),
            "$steal"     => self.debug_steal(arg),
            "$teleport"  => self.debug_teleport(arg),
            "$quit" => process::exit(0),
            // if undo/redo fails, should ask for input again
            // if they succeed, do nothing because zmachine state changed
            "$undo" => { should_ask_again = !self.undo() },
            "$redo" => { should_ask_again = !self.redo() },
            // unrecognized commands should ask for user input again
            _ => { should_ask_again = false; }
        }

        should_ask_again
    }

    // Terminal UI only
    #[allow(dead_code)]
    pub fn run(&mut self) {
        self.ui.clear();

        // continue instructions until the quit instruction
        loop {
            let instr = self.decode_instruction(self.pc);
            if instr.opcode == Opcode::OP0_186 { break; }

            self.handle_instruction(&instr);
        }

        self.ui.reset();
    }

    // Web UI only
    #[allow(dead_code)]
    pub fn step(&mut self) -> bool {
        // loop through instructions until user input is needed
        // (saves/restores need a save name, read instructions need user input)
        // Pauses on these instructions and control is passed back to js
        loop {
            let instr = self.decode_instruction(self.pc);

            if self.options.log_instructions {
                write!(self.instr_log, "\n{}", &instr).unwrap();
            }

            if instr.opcode == Opcode::OP0_186 {
                return true; // done == true
            }

            match instr.opcode {
                Opcode::OP0_181 => {
                    let pc = instr.next - 1;
                    let state = self.save_state(pc);
                    let b64 = base64::encode(&state);

                    let (location, info) = self.get_status();
                    let status = [&location, " - ", &info].concat();

                    let msg = serde_json::to_string(&(status, b64)).unwrap();
                    self.ui.message("save", &msg);

                    // Advance the pc, assuming that the save was successful
                    self.process_save_result(&instr);
                }
                Opcode::OP0_182 => {
                    self.ui.message("restore", "");
                    self.paused_instr = Some(instr);
                    return false;
                }
                Opcode::VAR_228 => {
                    // web ui saves current state here BEFORE processing user input
                    let (location, info) = self.get_status();
                    let status = [&location, " - ", &info].concat();

                    let state = self.save_state(self.pc);
                    let b64 = base64::encode(&state);

                    let msg = serde_json::to_string(&(status, b64)).unwrap();
                    self.ui.message("savestate", &msg);

                    self.current_state = Some((location, state));
                    self.paused_instr = Some(instr);
                    return false;
                }
                _ => {
                    self.handle_instruction(&instr);
                }
            }
        }
    }

    // Web UI only - gives user input to the paused read instruction
    // (passes control back JS afterwards)
    #[allow(dead_code)]
    pub fn handle_input(&mut self, input: String) {
        // VAR_228 only here (anything else would be an error)
        let instr = self.paused_instr.take().unwrap();

        // handle special debugging commands
        // these inputs shouldn't be processed normally
        if self.is_debug_command(&input) {
            if self.handle_debug_command(&input) {
                self.ui.print("\n>");
            }

            // return execution to JS, which will read user input again:
            return;
        }

        // new input changes timelines, so remove any obsolete redos
        self.redos.clear();

        // move current state into the undo list now
        if self.current_state.is_some() {
            self.undos.push(self.current_state.take().unwrap());
        }

        // explicitly handle read (need to get args first)
        let args = self.get_arguments(instr.operands.as_slice());
        self.do_sread_second(args[0], args[1], input);
        self.pc = instr.next;
    }

    // Web UI only
    #[allow(dead_code)]
    pub fn restore(&mut self, data: String) {
        let state = base64::decode(&data);

        // cancel restore (sending an empty string or if base64 decode fails)
        if data.is_empty() || state.is_err() {
            let instr = self.paused_instr.take().unwrap();
            self.process_result(&instr, 0);
        } else {
            self.restore_state(state.unwrap().as_slice());
            self.process_restore_result();
        }
    }

    // Web UI only
    // Loads a saved state _without_ processing a restore result (like the above)
    #[allow(dead_code)]
    pub fn load_savestate(&mut self, data: String) {
        let state = base64::decode(&data).unwrap();
        self.restore_state(state.as_slice());
    }
}


// Instruction handlers
impl Zmachine {
    // OP2_1
    fn do_je(&self, a: u16, values: &[u16]) -> u16 {
        if values.iter().any(|x| a == *x) { 1 } else { 0 }
    }

    // OP2_2
    fn do_jl(&self, a: u16, b: u16) -> u16 {
        if (a as i16) < (b as i16) { 1 } else { 0 }
    }

    // OP2_3
    fn do_jg(&self, a: u16, b: u16) -> u16 {
        if (a as i16) > (b as i16) { 1 } else { 0 }
    }

    // OP2_4
    fn do_dec_chk(&mut self, var: u16, value: u16) -> u16 {
        let after = self.read_indirect_variable(var as u8) as i16 - 1;
        self.write_indirect_variable(var as u8, after as u16);

        if after < (value as i16) { 1 } else { 0 }
    }

    // OP2_5
    fn do_inc_chk(&mut self, var: u16, value: u16) -> u16 {
        let after = self.read_indirect_variable(var as u8) as i16 + 1;
        self.write_indirect_variable(var as u8, after as u16);

        if after > (value as i16) { 1 } else { 0 }
    }

    // OP2_6
    fn do_jin(&self, obj1: u16, obj2: u16) -> u16 {
        if self.get_parent(obj1) == obj2 { 1 } else { 0 }
    }

    // OP2_7
    fn do_test(&self, bitmap: u16, flags: u16) -> u16 {
        if bitmap & flags == flags { 1 } else { 0 }
    }

    // OP2_8
    fn do_or(&self, a: u16, b: u16) -> u16 {
        a | b
    }

    // OP2_9
    fn do_and(&self, a: u16, b: u16) -> u16 {
        a & b
    }

    // OP2_10
    fn do_test_attr(&self, obj: u16, attr: u16) -> u16 {
        self.test_attr(obj, attr)
    }

    // OP2_11
    fn do_set_attr(&mut self, obj: u16, attr: u16) {
        self.set_attr(obj, attr)
    }

    // OP2_12
    fn do_clear_attr(&mut self, obj: u16, attr: u16) {
        self.clear_attr(obj, attr)
    }

    // OP2_13
    fn do_store(&mut self, var: u16, value: u16) {
        self.write_indirect_variable(var as u8, value);
    }

    // OP2_14
    fn do_insert_obj(&mut self, object: u16, destination: u16) {
        self.insert_obj(object, destination);
    }

    // OP2_15
    fn do_loadw(&self, array: u16, index: u16) -> u16 {
        self.memory.read_word((array + 2 * index) as usize)
    }

    // OP2_16
    fn do_loadb(&self, array: u16, index: u16) -> u16 {
        self.memory.read_byte((array + index) as usize) as u16
    }

    // OP2_17
    fn do_get_prop(&self, object: u16, property_number: u16) -> u16 {
        self.get_prop_value(object, property_number)
    }

    // OP2_18
    fn do_get_prop_addr(&self, object: u16, property_number: u16) -> u16 {
        self.get_prop_addr(object, property_number) as u16
    }

    // OP2_19
    fn do_get_next_prop(&self, object: u16, property_number: u16) -> u16 {
        self.get_next_prop(object, property_number)
    }

    // OP2_20
    fn do_add(&self, a: u16, b: u16) -> u16 {
        (a as i16 + b as i16) as u16
    }

    // OP2_21
    fn do_sub(&self, a: u16, b: u16) -> u16 {
        (a as i16 - b as i16) as u16
    }

    // OP2_22
    fn do_mul(&self, a: u16, b: u16) -> u16 {
        (a as i16 * b as i16) as u16
    }

    // OP2_23
    fn do_div(&self, a: u16, b: u16) -> u16 {
        (a as i16 / b as i16) as u16
    }

    // OP2_24
    fn do_mod(&self, a: u16, b: u16) -> u16 {
        (a as i16 % b as i16) as u16
    }


    // OP1_128
    fn do_jz(&self, a: u16) -> u16 {
        if a == 0 { 1 } else { 0 }
    }

    // OP1_129
    fn do_get_sibling(&self, object: u16) -> u16 {
        self.get_sibling(object)
    }

    // OP1_130
    fn do_get_child(&self, object: u16) -> u16 {
        self.get_child(object)
    }

    // OP1_131
    fn do_get_parent(&self, object: u16) -> u16 {
        self.get_parent(object)
    }

    // OP1_132
    fn do_get_prop_len(&self, addr: u16) -> u16 {
        self.get_prop_len(addr as usize) as u16
    }

    // OP1_133
    fn do_inc(&mut self, var: u16) {
        let value = self.read_indirect_variable(var as u8);

        self.write_indirect_variable(var as u8, (value as i16 + 1) as u16);
    }

    // OP1_134
    fn do_dec(&mut self, var: u16) {
        let value = self.read_indirect_variable(var as u8);

        self.write_indirect_variable(var as u8, (value as i16 - 1) as u16);
    }

    // OP1_135
    fn do_print_addr(&mut self, addr: u16) {
        let zstring = self.read_zstring(addr as usize);
        self.ui.print(&zstring);
    }

    // OP1_136 : call_1s

    // OP1_137
    fn do_remove_obj(&mut self, obj: u16) {
        self.remove_obj(obj);
    }

    // OP1_138
    fn do_print_obj(&mut self, obj: u16) {
        let name = self.get_object_name(obj);
        self.ui.print_object(&name);
    }

    // OP1_139
    fn do_ret(&mut self, value: u16) {
        self.return_from_routine(value);
    }

    // OP1_140
    fn do_jump(&mut self, offest: u16, instr: &Instruction) {
        self.pc = if (offest as i16) < 0 {
            instr.next - (-(offest as i16)) as usize - 2
        } else {
            instr.next + offest as usize - 2
        };
    }

    // OP1_141
    fn do_print_paddr(&mut self, addr: u16) {
        let paddr = self.unpack_print_paddr(addr);
        let zstring = self.read_zstring(paddr);
        self.ui.print(&zstring);
    }

    // OP1_142
    fn do_load(&mut self, var: u16) -> u16 {
        self.read_indirect_variable(var as u8)
    }

    // OP1_143
    fn do_not(&self, value: u16) -> u16 {
        !value
    }


    // OP0_176
    fn do_rtrue(&mut self) {
        self.return_from_routine(1);
    }

    // OP0_177
    fn do_rfalse(&mut self) {
        self.return_from_routine(0);
    }

    // OP0_178
    fn do_print(&mut self, instr: &Instruction) {
        let text = instr.text.as_ref().expect("Can't print with no text!");
        self.ui.print(text);
    }

    // OP0_179
    fn do_print_ret(&mut self, instr: &Instruction) {
        let text = instr.text.as_ref().expect("Can't print with no text!");
        self.ui.print(text);
        self.ui.print("\n");
        self.return_from_routine(1);
    }

    // OP0_180 : nop, never actually used

    // OP0_181
    fn do_save(&mut self, instr: &Instruction) {
        let prompt = format!("\nFilename [{}]: ", self.save_name);
        self.ui.print(&prompt);

        let input = self.ui.get_user_input();
        let mut path = PathBuf::from(&self.save_dir);
        let mut file;

        match input.to_lowercase().as_ref() {
            ""|"yes"|"y" => path.push(&self.save_name),
            "no"|"n"|"cancel" => {
                self.process_result(instr, 0);
                return;
            }
            _ => path.push(input),
        }

        if let Ok(handle) = File::create(&path) {
            file = handle;
        } else {
            self.ui.print("Can't save to that file, try another?\n");
            self.process_result(instr, 0);
            return;
        }

        // save file name for next use
        self.save_name = path.file_name().unwrap().to_string_lossy().into_owned();

        // The save PC points to either the save instructions branch data or store
        // data. In either case, this is the last byte of the instruction. (so -1)
        let pc = instr.next - 1;
        let data = self.save_state(pc);
        file.write_all(&data[..]).expect("Error saving to file");

        self.process_save_result(instr);
    }

    fn process_save_result(&mut self, instr: &Instruction) {
        // (v1-3): follow branch if needed (value "1" means the save succeeded)
        // (v4+):  or store the value "1" at the give store position
        self.process_result(instr, 1);
    }


    // OP0_182
    fn do_restore(&mut self, instr: &Instruction) {
        let prompt = format!("\nFilename [{}]: ", self.save_name);
        self.ui.print(&prompt);

        let input = self.ui.get_user_input();
        let mut path = PathBuf::from(&self.save_dir);
        let mut data = Vec::new();
        let mut file;

        match input.to_lowercase().as_ref() {
            ""|"yes"|"y" => path.push(&self.save_name),
            "no"|"n"|"cancel" => {
                self.process_result(instr, 0);
                return;
            }
            _ => path.push(input),
        }

        if let Ok(handle) = File::open(&path) {
            file = handle;
        } else {
            self.ui.print("Can't open that file, try another?\n");
            self.process_result(instr, 0);
            return;
        }

        // save file name for next use
        self.save_name = path.file_name().unwrap().to_string_lossy().into_owned();

        // restore program counter position, stack frames, and dynamic memory
        file.read_to_end(&mut data).expect("Error reading save file");
        self.restore_state(data.as_slice());
        self.process_restore_result();
    }

    fn process_restore_result(&mut self) {
        // In versions 1-3 the PC points to the BRANCH data of the save instruction.
        // Saves branch if successful, so follow the branch if the topmost bit
        // (condition bit) of the branch data is set. Otherwise go to the next
        // instruction (the next byte address).
        //
        // In versions 4+ the PC points to the number that the save result should
        // be saved in. (Saves store the value 2 when successful)
        //
        // (note: this logic only applies to the save/restore instructions)
        let byte = self.memory.read_byte(self.pc);

        if self.version <= 3 {
            if byte & 0b10000000 != 0 {
                self.pc += (byte & 0b00111111) as usize - 2; // follow branch
            } else {
                self.pc += 1; // next instruction
            }
        } else {
            self.pc += 1;
            self.write_variable(byte, 2); // store "we just restored" value
        }
    }

    // OP0_183
    fn do_restart(&mut self) {
        self.pc = self.initial_pc;
        self.frames.clear();
        self.frames.push(Frame::empty());
        self.memory.write(0, self.original_dynamic.as_slice());
    }

    // OP0_184
    fn do_ret_popped(&mut self) {
        let value = self.stack_pop();
        self.return_from_routine(value);
    }


    // OP0_187
    fn do_newline(&mut self) {
        self.ui.print("\n");
    }

    // OP0_188
    fn do_show_status(&self) {
        self.update_status_bar();
    }

    // OP0_189
    fn do_verify(&self) -> u16 {
        1
    }


    // All calls:
    // OP2_25, OP2_26, OP1_136, VAR_224, VAR_236, VAR_249, VAR_250
    // and OP1_143 when version > 3
    //
    // The only difference between the different opcodes is number of arguments
    // and whether or not to store or branch based on the result of the call
    //
    fn do_call(&mut self, instr: &Instruction, addr: u16, args: &[u16]) {
        // weird edge case: addr 0 means do nothing, then store/branch on 0
        if addr == 0 {
            self.process_result(instr, 0);
            return;
        }

        // decode routine / prepopulate routine local variables
        let routine_addr = self.unpack_routine_addr(addr);
        let mut read = self.memory.get_reader(routine_addr);

        let mut locals = Vec::new();
        let count = read.byte();

        for _ in 0..count {
            match self.version {
                1...4 => locals.push(read.word()),
                _     => locals.push(0),
            };
        }

        let first_instr = read.position();
        let frame = Frame::new(instr.next, instr.store, locals, args);

        self.pc = first_instr;
        self.frames.push(frame);
    }

    // VAR_225
    fn do_storew(&mut self, array: u16, index: u16, value: u16) {
        self.memory.write_word((array + 2 * index) as usize, value);
    }

    // VAR_226
    fn do_storeb(&mut self, array: u16, index: u16, value: u16) {
        self.memory.write_byte((array + index) as usize, value as u8);
    }

    // VAR_227
    fn do_put_prop(&mut self, obj: u16, prop: u16, value: u16) {
        self.put_prop(obj, prop, value);
    }

    // VAR_228
    fn do_sread(&mut self, instr: &Instruction, text_addr: u16, parse_addr: u16) {
        // need to update the status bar before each read
        self.update_status_bar();
        // add extra space so it doesn't look janky (non-spec)
        self.ui.print(" ");

        let input = self.ui.get_user_input();

        // handle special debugging commands
        // these inputs shouldn't be processed normally
        if self.is_debug_command(&input) {
            if self.handle_debug_command(&input) {
                self.ui.print("\n>");
                self.do_sread(instr, text_addr, parse_addr);
            }

            return;
        }

        self.do_sread_second(text_addr, parse_addr, input);

        // save state JUST after having processed user input
        // new input changes timelines, so remove any obsolete redos
        self.redos.clear();

        // push the current state into the undo list
        if self.current_state.is_some() {
            self.undos.push(self.current_state.take().unwrap());
        }

        // and save the current state
        let location = self.get_object_name(self.read_global(0));
        let state = self.save_state(instr.next);
        self.current_state = Some((location, state));
    }

    fn do_sread_second(&mut self, text_addr: u16, parse_addr: u16, mut raw: String) {
        let text_addr  = text_addr as usize;
        let parse_addr = parse_addr as usize;

        // versions 1-4 have to store an extra 0, so the max length is 1 less
        let mut max_length = self.memory.read_byte(text_addr as usize);
        if self.version <= 4 { max_length -= 1; }

        raw.truncate(max_length as usize);
        let input = &raw.to_lowercase();

        let bytes = input.as_bytes();
        let len = bytes.len();

        // ver 1-4 start storing @ byte 1, ending with a terminating 0
        // ver 5+ save the input length @1, start storing @2, and DON'T end with 0
        if self.version <= 4 {
            self.memory.write(text_addr + 1, bytes);
            self.memory.write_byte(text_addr + 1 + len, 0);
        } else {
            self.memory.write_byte(text_addr + 1, len as u8);
            self.memory.write(text_addr + 2, bytes);
        }

        // skip tokenization step if parse_addr is 0
        if parse_addr != 0 {
            self.tokenise(input, parse_addr);
        }
    }

    // VAR_229
    fn do_print_char(&mut self, chr: u16) {
        self.ui.print(&(chr as u8 as char).to_string());
    }

    // VAR_230
    fn do_print_num(&mut self, signed: u16) {
        self.ui.print(&(signed as i16).to_string());
    }

    // VAR_231
    fn do_random(&mut self, range: u16) -> u16 {
        let range = range as i16;

        if range <= 0 {
            self.rng.reseed([range as u32, 0, 0, 0]);
            0
        } else if range == 1 {
            1
        } else {
            (self.rng.gen::<f32>() * range as f32).ceil() as u16
        }
    }

    // VAR_232
    fn do_push(&mut self, value: u16) {
        self.stack_push(value)
    }

    // VAR_233
    fn do_pull(&mut self, var: u16) {
        let value = self.stack_pop();
        self.write_indirect_variable(var as u8, value);
    }
}


// debug functions
#[allow(dead_code)]
impl Zmachine {
    fn debug_header(&mut self) {
        let version    = self.memory.read_byte(0x00);
        let release    = self.memory.read_word(0x02);
        let initial_pc = self.memory.read_word(0x06);
        let checksum   = self.memory.read_word(0x1C);

        let serial = self.memory.read(0x12, 6).to_vec();
        let ascii = String::from_utf8_lossy(&serial[..]);

        self.ui.debug(&format!("\
            Version: {} \n\
            Release: {} / Serial: {} \n\
            Checksum: {:#x} \n\
            Initial PC: {:#x} \n\
        ", version, release, ascii, checksum, initial_pc));
    }

    fn debug_dictionary(&mut self) {
        let mut out = String::new();
        let mut words = self.dictionary.keys().collect::<Vec<_>>();
        words.sort();

        let width = words.iter().fold(0, |longest, word| {
            if word.len() > longest { word.len() } else { longest }
        });

        for word in &words {
            write!(out, "{:1$}   ", word, width).unwrap()
        }

        out.push_str("\n");
        self.ui.debug(&format!("{}", out));
    }

    fn debug_dump(&mut self) {
        let mut out = String::new();
        write!(out, "PC @ {}\n", self.pc).unwrap();

        for frame in &self.frames {
            write!(out, "{}\n", frame).unwrap();
        }

        self.ui.debug(&out);
    }

    fn debug_object_simple(&mut self, obj_num: u16) {
        self.ui.debug(&format!("\nObject #{}", obj_num));

        let addr = self.get_object_addr(obj_num);
        let mut read = self.memory.get_reader(addr);

        if self.version <= 3 {
            self.ui.debug(&format!(
                "Attributes: {:08b} {:08b} {:08b} {:08b}",
                read.byte(), read.byte(), read.byte(), read.byte()));

            self.ui.debug(&format!(
                "Parent: {}, Sibling: {}, Child: {}",
                read.byte(), read.byte(), read.byte()));
        } else {
            self.ui.debug(&format!(
                "Attributes: {:08b} {:08b} {:08b} {:08b} {:08b} {:08b}",
                read.byte(), read.byte(), read.byte(), read.byte(),
                read.byte(), read.byte()));

            self.ui.debug(&format!(
                "Parent: {}, Sibling: {}, Child: {}",
                read.word(), read.word(), read.word()));
        }

        let prop_addr = read.word() as usize;
        self.ui.debug(&format!("Property table @ {:x}", prop_addr));

        let text_length = self.memory.read_byte(prop_addr);
        let short_name = if text_length > 0 {
            self.read_zstring(prop_addr + 1)
        } else {
            String::new()
        };

        self.ui.debug(&format!("{} (len: {})\n", short_name, text_length));
    }

    fn get_object_number(&self, input: &str) -> u16 {
        if let Ok(num) = input.parse() {
            num
        } else if let Some(num) = self.find_object(input) {
            num
        } else {
            0
        }
    }

    fn debug_object(&mut self, input: &str) {
        let num = self.get_object_number(input);
        if num == 0 { return; }

        let mut obj = Object::new(num, self);
        self.add_object_children(&mut obj);
        self.ui.debug(&obj.to_string());
    }

    fn debug_object_tree(&mut self) {
        let tree = self.get_object_tree();
        self.ui.debug(&tree.to_string());
    }

    fn debug_object_properties(&mut self, input: &str) {
        let num = self.get_object_number(input);
        if num == 0 { return; }

        self.ui.debug(&format!("Object: #{}", num));

        let addr = self.get_object_prop_table_addr(num);
        let str_length = self.memory.read_byte(addr) as usize * 2; // words in name
        let first_addr = addr + str_length + 1;

        let mut prop = self.read_object_prop(first_addr);
        let mut slice = self.memory.read(prop.addr, prop.len as usize);

        self.ui.debug(&format!("{:2} {:?}", prop.num, slice));

        while prop.num != 0 {
            prop = self.read_object_prop(prop.next);
            slice = self.memory.read(prop.addr, prop.len as usize);

            self.ui.debug(&format!("{:2} {:?}", prop.num, slice));
        }
    }

    fn debug_object_attributes(&mut self, input: &str) {
        let num = self.get_object_number(input);
        if num == 0 { return; }

        let name = self.get_object_name(num);
        let mut attributes = Vec::new();

        for i in 0..(self.attr_width * 8) as u16 {
            if self.test_attr(num, i) == 1 {
                attributes.push(i);
            }
        }

        self.ui.debug(&format!("{} ({})\n{:?}", name, num, attributes));
    }

    pub fn debug_object_details(&self, obj_num: u16) -> String {
        if obj_num == 0 { return String::new(); }

        let mut out = String::from("Properties:\n");

        let addr = self.get_object_prop_table_addr(obj_num);
        let str_length = self.memory.read_byte(addr) as usize * 2; // words in name
        let first_addr = addr + str_length + 1;

        let mut prop = self.read_object_prop(first_addr);
        let mut slice = self.memory.read(prop.addr, prop.len as usize);

        write!(out, "{:2} {:?}\n", prop.num, slice).unwrap();

        while prop.num != 0 {
            prop = self.read_object_prop(prop.next);
            slice = self.memory.read(prop.addr, prop.len as usize);

            write!(out, "{:2} {:?}\n", prop.num, slice).unwrap();
        }

        let mut attributes = Vec::new();

        for i in 0..(self.attr_width * 8) as u16 {
            if self.test_attr(obj_num, i) == 1 {
                attributes.push(i);
            }
        }

        write!(out, "\nAttributes:\n{:?}", attributes).unwrap();

        return out;
    }

    fn debug_have_attribute(&mut self, attr_str: &str) {
        let attr = attr_str.parse().unwrap_or(0);
        let mut objects = Vec::new();

        for obj_num in 1..self.get_total_object_count()+1 {
            if self.test_attr(obj_num, attr) == 1 {
                objects.push(Object::new(obj_num, self));
            }
        }

        for obj in &objects {
            self.ui.debug(&obj.to_string());
        }
    }

    fn debug_have_property(&mut self, prop_str: &str) {
        let prop_num = prop_str.parse().unwrap_or(0);
        let mut objects = Vec::new();

        for obj_num in 1..self.get_total_object_count()+1 {
            let prop = self.find_prop(obj_num, prop_num);

            if prop.num != 0 {
                objects.push(Object::new(obj_num, self));
            }
        }

        for obj in &objects {
            self.ui.debug(&obj.to_string());
        }
    }

    fn debug_room(&mut self) {
        let mut room = Object::new(self.read_global(0), self);
        self.add_object_children(&mut room);
        self.ui.debug(&room.to_string());
    }

    fn debug_yourself(&mut self) {
        if let Some(num) = self.find_yourself() {
            let mut you = Object::new(num, self);
            self.add_object_children(&mut you);
            self.ui.debug(&you.to_string());
        }
    }

    fn debug_parent(&mut self, input: &str) {
        let num = self.get_object_number(input);
        if num == 0 { return; }

        let parent_num = self.get_parent(num);

        if parent_num == 0 {
            self.ui.debug(&format!("Parent if the root object 0"));
        } else {
            let mut parent = Object::new(parent_num, self);
            self.add_object_children(&mut parent);
            self.ui.debug(&parent.to_string());
        }
    }

    fn debug_find_object(&mut self, name: &str) {
        if let Some(num) = self.find_object(name) {
            let object = Object::new(num, self);
            self.ui.debug(&format!("{}", object));
        }
    }

    fn debug_teleport(&mut self, input: &str) {
        let you = self.find_yourself().expect("Can't find you in the object tree");
        let num = self.get_object_number(input);

        if num == 0 {
            self.ui.print("I can't find that room...\n");
            return;
        } else {
            self.ui.print("Zzzap! Somehow you are in a different place...\n");
        }

        self.insert_obj(you, num);
    }

    fn debug_steal(&mut self, input: &str) {
        let you = self.find_yourself().expect("Can't find you in the object tree");
        let num = self.get_object_number(input);

        if num == 0 {
            self.ui.print("I can't find that object...\n");
            return;
        } else {
            self.ui.print(&format!("Zzzing! Somehow you are holding the {}...\n", input));
        }

        self.insert_obj(num, you);
    }

    pub fn debug_history(&mut self) {
        let undo_count = self.undos.len();
        let total = self.undos.len() + self.redos.len() + 1;

        self.ui.debug(&format!("History:"));

        for (i, state) in self.undos.iter().enumerate() {
            let index = i + 1;
            self.ui.debug(&format!("    ({}/{}) @ {}", index, total, state.0));
        }

        if let Some(ref current) = self.current_state {
            let index = undo_count + 1;
            self.ui.debug(&format!(" -> ({}/{}) @ {}", index, total, current.0));
        }

        for (i, state) in self.redos.iter().rev().enumerate() {
            let index = undo_count + i + 2;
            self.ui.debug(&format!("    ({}/{}) @ {}", index, total, state.0));
        }
    }

    fn debug_routine(&mut self, routine_addr: usize) {
        let mut read = self.memory.get_reader(routine_addr);
        let mut locals = Vec::new();
        let count = read.byte();

        for _ in 0..count {
            match self.version {
                1...4 => locals.push(read.word()),
                _     => locals.push(0),
            };
        }

        let first_instr = self.decode_instruction(read.position());
        let mut set: HashSet<Instruction> = HashSet::new();

        fn follow(zvm: &Zmachine, set: &mut HashSet<Instruction>, instr: Instruction) {
            if set.contains(&instr) { return }

            let branch = match instr.branch {
                Some(Branch { address: Some(addr), .. }) => Some(addr),
                _ => None,
            };

            let next = if instr.advances() {
                Some(instr.next)
            } else {
                None
            };

            set.insert(instr);

            if let Some(addr) = branch {
                follow(zvm, set, zvm.decode_instruction(addr));
            };

            if let Some(addr) = next {
                follow(zvm, set, zvm.decode_instruction(addr));
            };
        };

        follow(self, &mut set, first_instr);

        let mut instructions = set.iter().collect::<Vec<_>>();
        instructions.sort_by_key(|i| i.addr);

        self.ui.debug(&format!("Locals: {:?}", locals));

        for instr in &instructions {
            self.ui.debug(&format!("{}", instr));
        };
    }
}