aboutsummaryrefslogtreecommitdiff
path: root/engines/sci/engine/scriptdebug.cpp
blob: 6eb882c35ed61410a8765c9ea33e3c8dd4e62831 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * $URL$
 * $Id$
 *
 */

// Script debugger functionality. Absolutely not threadsafe.

#include "sci/sci.h"
#include "sci/engine/state.h"
#include "sci/engine/gc.h"
#include "sci/engine/kernel_types.h"
#include "sci/engine/kernel.h"
#include "sci/engine/savegame.h"
#include "sci/gfx/gfx_widgets.h"
#include "sci/gfx/gfx_gui.h"
#include "sci/gfx/gfx_state_internal.h"	// required for GfxContainer, GfxPort, GfxVisual
#include "sci/resource.h"
#include "sci/vocabulary.h"
#include "sci/sfx/iterator.h"
#include "sci/sfx/sci_midi.h"

#include "common/util.h"
#include "common/savefile.h"

#include "sound/audiostream.h"

namespace Sci {

extern int debug_sleeptime_factor;
int _debugstate_valid = 0; // Set to 1 while script_debug is running
int _debug_step_running = 0; // Set to >0 to allow multiple stepping
int _debug_commands_not_hooked = 1; // Commands not hooked to the console yet?
int _debug_seeking = 0; // Stepping forward until some special condition is met
int _debug_seek_level = 0; // Used for seekers that want to check their exec stack depth
int _debug_seek_special = 0;  // Used for special seeks(1)
int _weak_validations = 1; // Some validation errors are reduced to warnings if non-0
reg_t _debug_seek_reg = NULL_REG;  // Used for special seeks(2)

#define _DEBUG_SEEK_NOTHING 0
#define _DEBUG_SEEK_CALLK 1 // Step forward until callk is found
#define _DEBUG_SEEK_LEVEL_RET 2 // Step forward until returned from this level
#define _DEBUG_SEEK_SPECIAL_CALLK 3 // Step forward until a /special/ callk is found
#define _DEBUG_SEEK_SO 5 // Step forward until specified PC (after the send command) and stack depth
#define _DEBUG_SEEK_GLOBAL 6 // Step forward until one specified global variable is modified

static reg_t *p_pc;
static StackPtr *p_sp;
static StackPtr *p_pp;
static reg_t *p_objp;
static int *p_restadjust;
static SegmentId *p_var_segs;
static reg_t **p_vars;
static reg_t **p_var_base;
static int *p_var_max; // May be NULL even in valid state!

static const int MIDI_cmdlen[16] = {0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 1, 1, 2, 0};

char inputbuf[256] = "";

union cmd_param_t {
	int32 val;
	const char *str;
	reg_t reg;
};

typedef int (*ConCommand)(EngineState *s, const Common::Array<cmd_param_t> &cmdParams);

struct cmd_mm_entry_t {
	const char *name;
	const char *description;
}; // All later structures must "extend" this

struct cmd_command_t : public cmd_mm_entry_t {
	ConCommand command;
	const char *param;
};

#if 0
// Unused
#define LOOKUP_SPECIES(species) (\
	(species >= 1000) ? species : *(s->_classtable[species].scriptposp) \
		+ s->_classtable[species].class_offset)
#endif

// Dummy function, so that it compiles
int con_hook_command(ConCommand command, const char *name, const char *param, const char *description) {

	return 0;
}

static const char *_debug_get_input() {
	char newinpbuf[256];

	printf("> ");
	if (!fgets(newinpbuf, 254, stdin))
		return NULL;

	size_t l = strlen(newinpbuf);
	if (l > 0 && newinpbuf[0] != '\n') {
		if (newinpbuf[l-1] == '\n') newinpbuf[l-1] = 0;
		memcpy(inputbuf, newinpbuf, 256);
	}

	return inputbuf;
}

static int _parse_ticks(byte *data, int *offset_p, int size) {
	int ticks = 0;
	int tempticks;
	int offset = 0;

	do {
		tempticks = data[offset++];
		ticks += (tempticks == SCI_MIDI_TIME_EXPANSION_PREFIX) ? SCI_MIDI_TIME_EXPANSION_LENGTH : tempticks;
	} while (tempticks == SCI_MIDI_TIME_EXPANSION_PREFIX && offset < size);

	if (offset_p)
		*offset_p = offset;

	return ticks;
}

static void midi_hexdump(byte *data, int size, int notational_offset) { // Specialised for SCI01 tracks (this affects the way cumulative cues are treated )
	int offset = 0;
	int prev = 0;

	if (*data == 0xf0) // SCI1 priority spec
		offset = 8;

	while (offset < size) {
		int old_offset = offset;
		int offset_mod;
		int time = _parse_ticks(data + offset, &offset_mod, size);
		int cmd;
		int pleft;
		int firstarg = 0;
		int i;
		int blanks = 0;

		offset += offset_mod;
		fprintf(stderr, "  [%04x] %d\t",
		        old_offset + notational_offset, time);

		cmd = data[offset];
		if (!(cmd & 0x80)) {
			cmd = prev;
			if (prev < 0x80) {
				fprintf(stderr, "Track broken at %x after"
				        " offset mod of %d\n",
				        offset + notational_offset, offset_mod);
				Common::hexdump(data, size, 16, notational_offset);
				return;
			}
			fprintf(stderr, "(rs %02x) ", cmd);
			blanks += 8;
		} else {
			++offset;
			fprintf(stderr, "%02x ", cmd);
			blanks += 3;
		}
		prev = cmd;

		pleft = MIDI_cmdlen[cmd >> 4];
		if (SCI_MIDI_CONTROLLER(cmd) && data[offset] == SCI_MIDI_CUMULATIVE_CUE)
			--pleft; // This is SCI(0)1 specific

		for (i = 0; i < pleft; i++) {
			if (i == 0)
				firstarg = data[offset];
			fprintf(stderr, "%02x ", data[offset++]);
			blanks += 3;
		}

		while (blanks < 16) {
			blanks += 4;
			fprintf(stderr, "    ");
		}

		while (blanks < 20) {
			++blanks;
			fprintf(stderr, " ");
		}

		if (cmd == SCI_MIDI_EOT)
			fprintf(stderr, ";; EOT");
		else if (cmd == SCI_MIDI_SET_SIGNAL) {
			if (firstarg == SCI_MIDI_SET_SIGNAL_LOOP)
				fprintf(stderr, ";; LOOP point");
			else
				fprintf(stderr, ";; CUE (%d)", firstarg);
		} else if (SCI_MIDI_CONTROLLER(cmd)) {
			if (firstarg == SCI_MIDI_CUMULATIVE_CUE)
				fprintf(stderr, ";; CUE (cumulative)");
			else if (firstarg == SCI_MIDI_RESET_ON_SUSPEND)
				fprintf(stderr, ";; RESET-ON-SUSPEND flag");
		}
		fprintf(stderr, "\n");

		if (old_offset >= offset) {
			fprintf(stderr, "-- Not moving forward anymore,"
			        " aborting (%x/%x)\n", offset, old_offset);
			return;
		}
	}
}

int c_sfx_01_header_dump(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	Resource *song = s->resmgr->findResource(kResourceTypeSound, cmdParams[0].val, 0);

	if (!song) {
		sciprintf("Doesn't exist\n");
		return 1;
	}

	uint32 offset = 0;

	sciprintf("SCI01 song track mappings:\n");

	if (*song->data == 0xf0) // SCI1 priority spec
		offset = 8;

	if (song->size <= 0)
		return 1;

	while (song->data[offset] != 0xff) {
		byte device_id = song->data[offset];
		sciprintf("* Device %02x:\n", device_id);
		offset++;

		if (offset + 1 >= song->size)
			return 1;

		while (song->data[offset] != 0xff) {
			int track_offset;
			int end;
			byte header1, header2;

			if (offset + 7 >= song->size)
				return 1;

			offset += 2;

			track_offset = READ_LE_UINT16(song->data + offset);
			header1 = song->data[track_offset];
			header2 = song->data[track_offset+1];
			track_offset += 2;

			end = READ_LE_UINT16(song->data + offset + 2);
			sciprintf("  - %04x -- %04x", track_offset, track_offset + end);

			if (track_offset == 0xfe)
				sciprintf(" (PCM data)\n");
			else
				sciprintf(" (channel %d, special %d, %d playing notes, %d foo)\n",
				          header1 & 0xf, header1 >> 4, header2 & 0xf, header2 >> 4);
			offset += 4;
		}
		offset++;
	}

	return 0;
}

int c_sfx_01_track(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	Resource *song = s->resmgr->findResource(kResourceTypeSound, cmdParams[0].val, 0);

	int offset = cmdParams[1].val;

	if (!song) {
		sciprintf("Doesn't exist\n");
		return 1;
	}

	midi_hexdump(song->data + offset, song->size, offset);

	return 0;
}

static int show_node(EngineState *s, reg_t addr) {
	MemObject *mobj = GET_SEGMENT(*s->seg_manager, addr.segment, MEM_OBJ_LISTS);

	if (mobj) {
		ListTable *lt = (ListTable *)mobj;
		List *list;

		if (!lt->isValidEntry(addr.offset)) {
			sciprintf("Address does not contain a list\n");
			return 1;
		}

		list = &(lt->_table[addr.offset]);

		sciprintf("%04x:%04x : first x last = (%04x:%04x, %04x:%04x)\n", PRINT_REG(addr), PRINT_REG(list->first), PRINT_REG(list->last));
	} else {
		NodeTable *nt;
		Node *node;
		mobj = GET_SEGMENT(*s->seg_manager, addr.segment, MEM_OBJ_NODES);

		if (!mobj) {
			sciprintf("Segment #%04x is not a list or node segment\n", addr.segment);
			return 1;
		}

		nt = (NodeTable *)mobj;

		if (!nt->isValidEntry(addr.offset)) {
			sciprintf("Address does not contain a node\n");
			return 1;
		}
		node = &(nt->_table[addr.offset]);

		sciprintf("%04x:%04x : prev x next = (%04x:%04x, %04x:%04x); maps %04x:%04x -> %04x:%04x\n",
		          PRINT_REG(addr), PRINT_REG(node->pred), PRINT_REG(node->succ), PRINT_REG(node->key), PRINT_REG(node->value));
	}

	return 0;
}

int objinfo(EngineState *s, reg_t pos);

void song_lib_dump(const songlib_t &songlib, int line);

static int c_songlib_print(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	song_lib_dump(s->_sound._songlib, __LINE__);

	return 0;
}

static int c_vr(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	reg_t reg = cmdParams[0].reg;
	reg_t reg_end = cmdParams.size() > 1 ? cmdParams[1].reg : NULL_REG;
	int type_mask = determine_reg_type(s, reg, 1);
	int filter;
	int found = 0;

	sciprintf("%04x:%04x is of type 0x%x%s: ", PRINT_REG(reg), type_mask & ~KSIG_INVALID, type_mask & KSIG_INVALID ? " (invalid)" : "");

	type_mask &= ~KSIG_INVALID;

	if (reg.segment == 0 && reg.offset == 0) {
		sciprintf("Null.\n");
		return 0;
	}

	if (reg_end.segment != reg.segment) {
		sciprintf("Ending segment different from starting segment. Assuming no bound on dump.\n");
		reg_end = NULL_REG;
	}

	for (filter = 1; filter < 0xf000; filter <<= 1) {
		int type = type_mask & filter;

		if (found && type) {
			sciprintf("--- Alternatively, it could be a ");
		}


		switch (type) {
		case 0:
			break;

		case KSIG_LIST: {
			//List *l = lookup_list(s, reg);

			sciprintf("list\n");

			// TODO: printList has been moved to console.cpp
			/*
			if (l)
				printList(l);
			else
				sciprintf("Invalid list.\n");
			*/
		}
		break;

		case KSIG_NODE:
			sciprintf("list node\n");
			show_node(s, reg);
			break;

		case KSIG_OBJECT:
			sciprintf("object\n");
			objinfo(s, reg);
			break;

		case KSIG_REF: {
			int size;
			unsigned char *block = s->seg_manager->dereference(reg, &size);

			sciprintf("raw data\n");

			if (reg_end.segment != 0 && size < reg_end.offset - reg.offset) {
				sciprintf("Block end out of bounds (size %d). Resetting.\n", size);
				reg_end = NULL_REG;
			}

			if (reg_end.segment != 0 && (size >= reg_end.offset - reg.offset))
				size = reg_end.offset - reg.offset;

			if (reg_end.segment != 0)
				sciprintf("Block size less than or equal to %d\n", size);

			Common::hexdump(block, size, 16, 0);
		}
		break;

		case KSIG_ARITHMETIC:
			sciprintf("arithmetic value\n  %d (%04x)\n", (int16) reg.offset, reg.offset);
			break;

		default:
			sciprintf("unknown type %d.\n", type);

		}

		if (type) {
			sciprintf("\n");
			found = 1;
		}
	}

	return 0;
}

static int c_mousepos(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	sci_event_t event;

	sciprintf("Click somewhere in the game window...\n");

	while (event = gfxop_get_event(s->gfx_state, SCI_EVT_MOUSE_RELEASE), event.type != SCI_EVT_MOUSE_RELEASE) {};

	sciprintf("Mouse pointer at (%d, %d)\n", s->gfx_state->pointer_pos.x, s->gfx_state->pointer_pos.y);

	return 0;
}

int c_debuginfo(EngineState *s) {
	if (!_debugstate_valid) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	sciprintf("acc=%04x:%04x prev=%04x:%04x &rest=%x\n", PRINT_REG(s->r_acc), PRINT_REG(s->r_prev), *p_restadjust);

	if (!s->_executionStack.empty()) {
		sciprintf("pc=%04x:%04x obj=%04x:%04x fp=ST:%04x sp=ST:%04x\n", PRINT_REG(*p_pc), PRINT_REG(*p_objp), PRINT_STK(*p_pp), PRINT_STK(*p_sp));
	} else
		sciprintf("<no execution stack: pc,obj,fp omitted>\n");

	return 0;
}

int c_debuginfo(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	return c_debuginfo(s);
}

int c_step(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	_debugstate_valid = 0;
	if (cmdParams.size() && (cmdParams[0].val > 0))
		_debug_step_running = cmdParams[0].val - 1;

	return 0;
}

#if 0
// TODO Re-implement con:so
int c_stepover(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	int opcode, opnumber;

	if (!_debugstate_valid) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	_debugstate_valid = 0;
	opcode = s->_heap[*p_pc];
	opnumber = opcode >> 1;
	if (opnumber == 0x22 /* callb */ || opnumber == 0x23 /* calle */ ||
	        opnumber == 0x25 /* send */ || opnumber == 0x2a /* self */ || opnumber == 0x2b /* super */) {
		_debug_seeking = _DEBUG_SEEK_SO;
		_debug_seek_level = s->_executionStack.size()-1;
		// Store in _debug_seek_special the offset of the next command after send
		switch (opcode) {
		case 0x46: // calle W
			_debug_seek_special = *p_pc + 5;
			break;

		case 0x44: // callb W
		case 0x47: // calle B
		case 0x56: // super W
			_debug_seek_special = *p_pc + 4;
			break;

		case 0x45: // callb B
		case 0x57: // super B
		case 0x4A: // send W
		case 0x54: // self W
			_debug_seek_special = *p_pc + 3;
			break;

		default:
			_debug_seek_special = *p_pc + 2;
		}
	}

	return 0;
}
#endif

int c_sim_parse(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	unsigned int i;
	const char *operators = ",&/()[]#<>";

	if (!_debugstate_valid) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	if (cmdParams.size() == 0) {
		s->parser_valid = 0;
		return 0;
	}

	for (i = 0; i < cmdParams.size(); i++) {
		int flag = 0;
		Common::String token = cmdParams[i].str;

		if (token.size() == 1) {// could be an operator
			int j = 0;
			while (operators[j] && (operators[j] != token[0]))
				j++;
			if (operators[j]) {
				s->parser_nodes[i].type = 1;
				s->parser_nodes[i].content.value = j + 0xf0;
				flag = 1; // found an operator
			}
		}

		if (!flag) {
			const char *openb = strchr(token.c_str(), '['); // look for opening braces
			ResultWord result;

			if (openb)
				token = Common::String(token.begin(), openb);	// remove them and the rest

			result = vocab_lookup_word(token.c_str(), token.size(), s->_parserWords, s->_parserSuffixes);

			if (result._class != -1) {
				s->parser_nodes[i].type = 0;
				s->parser_nodes[i].content.value = result._group;
			} else { // group name was specified directly?
				int val = strtol(token.c_str(), NULL, 0);
				if (val) {
					s->parser_nodes[i].type = 0;
					s->parser_nodes[i].content.value = val;
				} else { // invalid and not matched
					sciprintf("Couldn't interpret '%s'\n", token.c_str());
					s->parser_valid = 0;
					return 1;
				}
			}
		}

	}

	s->parser_nodes[cmdParams.size()].type = -1; // terminate

	s->parser_valid = 2;

	return 0;
}

int c_viewinfo(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	int view = cmdParams[0].val;
	int palette = cmdParams[1].val;
	int loops, i;
	gfxr_view_t *view_pixmaps = NULL;
	gfx_color_t transparent = { PaletteEntry(), 0, -1, -1, 0 };

	if (!s) {
		sciprintf("Not in debug state\n");
		return 1;
	}
	sciprintf("Resource view.%d ", view);

	loops = gfxop_lookup_view_get_loops(s->gfx_state, view);

	if (loops < 0)
		sciprintf("does not exist.\n");
	else {
		sciprintf("has %d loops:\n", loops);

		for (i = 0; i < loops; i++) {
			int j, cels;

			sciprintf("Loop %d: %d cels.\n", i, cels = gfxop_lookup_view_get_cels(s->gfx_state, view, i));
			for (j = 0; j < cels; j++) {
				int width;
				int height;
				Common::Point mod;

				// Show pixmap on screen
				view_pixmaps = s->gfx_state->gfxResMan->getView(view, &i, &j, palette);
				gfxop_draw_cel(s->gfx_state, view, i, j, Common::Point(0,0), transparent, palette);

				gfxop_get_cel_parameters(s->gfx_state, view, i, j, &width, &height, &mod);

				sciprintf("   cel %d: size %dx%d, adj+(%d,%d)\n", j, width, height, mod.x, mod.y);
			}
		}
	}

	return 0;
}

int c_list_sentence_fragments(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	if (!s) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	for (uint i = 0; i < s->_parserBranches.size(); i++) {
		int j = 0;

		sciprintf("R%02d: [%x] ->", i, s->_parserBranches[i].id);
		while ((j < 10) && s->_parserBranches[i].data[j]) {
			int dat = s->_parserBranches[i].data[j++];

			switch (dat) {
			case VOCAB_TREE_NODE_COMPARE_TYPE:
				dat = s->_parserBranches[i].data[j++];
				sciprintf(" C(%x)", dat);
				break;

			case VOCAB_TREE_NODE_COMPARE_GROUP:
				dat = s->_parserBranches[i].data[j++];
				sciprintf(" WG(%x)", dat);
				break;

			case VOCAB_TREE_NODE_FORCE_STORAGE:
				dat = s->_parserBranches[i].data[j++];
				sciprintf(" FORCE(%x)", dat);
				break;

			default:
				if (dat > VOCAB_TREE_NODE_LAST_WORD_STORAGE) {
					int dat2 = s->_parserBranches[i].data[j++];
					sciprintf(" %x[%x]", dat, dat2);
				} else
					sciprintf(" ?%x?", dat);
			}
		}
		sciprintf("\n");
	}

	sciprintf("%d rules.\n", s->_parserBranches.size());

	return 0;
}

enum {
	_parse_eoi,
	_parse_token_pareno,
	_parse_token_parenc,
	_parse_token_nil,
	_parse_token_number
};

int _parse_getinp(int *i, int *nr, const Common::Array<cmd_param_t> &cmdParams) {
	const char *token;

	if ((unsigned)*i == cmdParams.size())
		return _parse_eoi;

	token = cmdParams[(*i)++].str;

	if (!strcmp(token, "("))
		return _parse_token_pareno;

	if (!strcmp(token, ")"))
		return _parse_token_parenc;

	if (!strcmp(token, "nil"))
		return _parse_token_nil;

	*nr = strtol(token, NULL, 0);

	return _parse_token_number;
}

int _parse_nodes(EngineState *s, int *i, int *pos, int type, int nr, const Common::Array<cmd_param_t> &cmdParams) {
	int nexttk, nextval, newpos, oldpos;

	if (type == _parse_token_nil)
		return 0;

	if (type == _parse_token_number) {
		s->parser_nodes[*pos += 1].type = PARSE_TREE_NODE_LEAF;
		s->parser_nodes[*pos].content.value = nr;
		return *pos;
	}
	if (type == _parse_eoi) {
		sciprintf("Unbalanced parentheses\n");
		return -1;
	}
	if (type == _parse_token_parenc) {
		sciprintf("Syntax error at token %d\n", *i);
		return -1;
	}
	s->parser_nodes[oldpos = ++(*pos)].type = PARSE_TREE_NODE_BRANCH;

	nexttk = _parse_getinp(i, &nextval, cmdParams);
	if ((newpos = s->parser_nodes[oldpos].content.branches[0] = _parse_nodes(s, i, pos, nexttk, nextval, cmdParams)) == -1)
		return -1;

	nexttk = _parse_getinp(i, &nextval, cmdParams);
	if ((newpos = s->parser_nodes[oldpos].content.branches[1] = _parse_nodes(s, i, pos, nexttk, nextval, cmdParams)) == -1)
		return -1;

	if (_parse_getinp(i, &nextval, cmdParams) != _parse_token_parenc)
		sciprintf("Expected ')' at token %d\n", *i);

	return oldpos;
}

int c_set_parse_nodes(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	int i = 0;
	int foo, bar;
	int pos = -1;

	if (!s) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	bar = _parse_getinp(&i, &foo, cmdParams);
	if (_parse_nodes(s, &i, &pos, bar, foo, cmdParams) == -1)
		return 1;

	vocab_dump_parse_tree("debug-parse-tree", s->parser_nodes);
	return 0;
}

// parses with a GNF rule set

int c_parse(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	ResultWordList words;
	char *error;
	const char *string;

	if (!s) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	string = cmdParams[0].str;
	sciprintf("Parsing '%s'\n", string);
	bool res = vocab_tokenize_string(words, string, s->_parserWords, s->_parserSuffixes, &error);
	if (res && !words.empty()) {
		int syntax_fail = 0;

		vocab_synonymize_tokens(words, s->_synonyms);

		sciprintf("Parsed to the following blocks:\n");

		for (ResultWordList::const_iterator i = words.begin(); i != words.end(); ++i)
			sciprintf("   Type[%04x] Group[%04x]\n", i->_class, i->_group);

		if (vocab_gnf_parse(s->parser_nodes, words, s->_parserBranches[0], s->parser_rules, 1))
			syntax_fail = 1; // Building a tree failed

		if (syntax_fail)
			sciprintf("Building a tree failed.\n");
		else
			vocab_dump_parse_tree("debug-parse-tree", s->parser_nodes);

	} else {
		sciprintf("Unknown word: '%s'\n", error);
		free(error);
	}

	return 0;
}

int c_stack(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	if (!s) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	if (s->_executionStack.empty()) {
		sciprintf("No exec stack!");
		return 1;
	}

	ExecStack &xs = s->_executionStack.back();

	for (int i = cmdParams[0].val ; i > 0; i--) {
		if ((xs.sp - xs.fp - i) == 0)
			sciprintf("-- temp variables --\n");
		if (xs.sp - i >= s->stack_base)
			sciprintf("ST:%04x = %04x:%04x\n", PRINT_STK(xs.sp - i), PRINT_REG(xs.sp[-i]));
	}

	return 0;
}

const char *selector_name(EngineState *s, int selector) {
	if (selector >= 0 && selector < (int)s->_selectorNames.size())
		return s->_selectorNames[selector].c_str();
	else
		return "--INVALID--";
}

int prop_ofs_to_id(EngineState *s, int prop_ofs, reg_t objp) {
	Object *obj = obj_get(s, objp);
	byte *selectoroffset;
	int selectors;

	if (!obj) {
		sciprintf("Applied prop_ofs_to_id on non-object at %04x:%04x\n", PRINT_REG(objp));
		return -1;
	}

	selectors = obj->_variables.size();

	if (s->version < SCI_VERSION_1_1)
		selectoroffset = ((byte *)(obj->base_obj)) + SCRIPT_SELECTOR_OFFSET + selectors * 2;
	else {
		if (!(obj->_variables[SCRIPT_INFO_SELECTOR].offset & SCRIPT_INFO_CLASS)) {
			obj = obj_get(s, obj->_variables[SCRIPT_SUPERCLASS_SELECTOR]);
			selectoroffset = (byte *)obj->base_vars;
		} else
			selectoroffset = (byte *)obj->base_vars;
	}

	if (prop_ofs < 0 || (prop_ofs >> 1) >= selectors) {
		sciprintf("Applied prop_ofs_to_id to invalid property offset %x (property #%d not in [0..%d]) on object at %04x:%04x\n",
		          prop_ofs, prop_ofs >> 1, selectors - 1, PRINT_REG(objp));
		return -1;
	}

	return READ_LE_UINT16(selectoroffset + prop_ofs);
}

reg_t disassemble(EngineState *s, reg_t pos, int print_bw_tag, int print_bytecode) {
// Disassembles one command from the heap, returns address of next command or 0 if a ret was encountered.
	MemObject *mobj = GET_SEGMENT(*s->seg_manager, pos.segment, MEM_OBJ_SCRIPT);
	Script *script_entity = NULL;
	byte *scr;
	int scr_size;
	reg_t retval = make_reg(pos.segment, pos.offset + 1);
	uint16 param_value;
	int opsize;
	uint opcode;
	int bytecount = 1;
	int i = 0;

	if (!mobj) {
		sciprintf("Disassembly failed: Segment %04x non-existant or not a script\n", pos.segment);
		return retval;
	} else
		script_entity = (Script *)mobj;

	scr = script_entity->buf;
	scr_size = script_entity->buf_size;

	if (pos.offset >= scr_size) {
		sciprintf("Trying to disassemble beyond end of script\n");
		return pos;
	}

	opsize = scr[pos.offset];
	opcode = opsize >> 1;

	if (!_debugstate_valid) {
		sciprintf("Not in debug state\n");
		return retval;
	}

	opsize &= 1; // byte if true, word if false

	sciprintf("%04x:%04x: ", PRINT_REG(pos));

	if (print_bytecode) {
		while (g_opcode_formats[opcode][i]) {
			switch (g_opcode_formats[opcode][i++]) {

			case Script_SByte:
			case Script_Byte:
				bytecount++;
				break;

			case Script_Word:
			case Script_SWord:
				bytecount += 2;
				break;

			case Script_SVariable:
			case Script_Variable:
			case Script_Property:
			case Script_Global:
			case Script_Local:
			case Script_Temp:
			case Script_Param:
			case Script_SRelative:
				if (opsize)
					bytecount ++;
				else
					bytecount += 2;
				break;

			default:
				break;
			}
		}

		if (pos.offset + bytecount > scr_size) {
			sciprintf("Operation arguments extend beyond end of script\n");
			return retval;
		}

		for (i = 0; i < bytecount; i++)
			sciprintf("%02x ", scr[pos.offset + i]);

		for (i = bytecount; i < 5; i++)
			sciprintf("   ");
	}

	if (print_bw_tag)
		sciprintf("[%c] ", opsize ? 'B' : 'W');
	sciprintf("%s", opcode < s->_opcodes.size() ? s->_opcodes[opcode].name.c_str() : "undefined");

	i = 0;
	while (g_opcode_formats[opcode][i]) {
		switch (g_opcode_formats[opcode][i++]) {
		case Script_Invalid:
			sciprintf("-Invalid operation-");
			break;

		case Script_SByte:
		case Script_Byte:
			sciprintf(" %02x", scr[retval.offset++]);
			break;

		case Script_Word:
		case Script_SWord:
			sciprintf(" %04x", 0xffff & (scr[retval.offset] | (scr[retval.offset+1] << 8)));
			retval.offset += 2;
			break;

		case Script_SVariable:
		case Script_Variable:
		case Script_Property:
		case Script_Global:
		case Script_Local:
		case Script_Temp:
		case Script_Param:
			if (opsize)
				param_value = scr[retval.offset++];
			else {
				param_value = 0xffff & (scr[retval.offset] | (scr[retval.offset+1] << 8));
				retval.offset += 2;
			}

			if (opcode == op_callk)
				sciprintf(" %s[%x]", (param_value < s->_kfuncTable.size()) ?
							((param_value < s->_kernelNames.size()) ? s->_kernelNames[param_value].c_str() : "[Unknown(postulated)]")
							: "<invalid>", param_value);
			else
				sciprintf(opsize ? " %02x" : " %04x", param_value);

			break;

		case Script_Offset:
			if (opsize)
				param_value = scr[retval.offset++];
			else {
				param_value = 0xffff & (scr[retval.offset] | (scr[retval.offset+1] << 8));
				retval.offset += 2;
			}
			sciprintf(opsize ? " %02x" : " %04x", param_value);
			break;

		case Script_SRelative:
			if (opsize)
				param_value = scr[retval.offset++];
			else {
				param_value = 0xffff & (scr[retval.offset] | (scr[retval.offset+1] << 8));
				retval.offset += 2;
			}
			sciprintf(opsize ? " %02x  [%04x]" : " %04x  [%04x]", param_value, (0xffff) & (retval.offset + param_value));
			break;

		case Script_End:
			retval = NULL_REG;
			break;

		default:
			sciprintf("Internal assertion failed in 'disassemble', %s, L%d\n", __FILE__, __LINE__);

		}
	}

	if (pos == *p_pc) { // Extra information if debugging the current opcode
		if ((opcode == op_pTos) || (opcode == op_sTop) || (opcode == op_pToa) || (opcode == op_aTop) ||
		        (opcode == op_dpToa) || (opcode == op_ipToa) || (opcode == op_dpTos) || (opcode == op_ipTos)) {
			int prop_ofs = scr[pos.offset + 1];
			int prop_id = prop_ofs_to_id(s, prop_ofs, *p_objp);

			sciprintf("	(%s)", selector_name(s, prop_id));
		}
	}

	sciprintf("\n");

	if (pos == *p_pc) { // Extra information if debugging the current opcode
		if (opcode == op_callk) {
			int stackframe = (scr[pos.offset + 2] >> 1) + (*p_restadjust);
			int argc = ((*p_sp)[- stackframe - 1]).offset;

			if (!(s->flags & GF_SCI0_OLD))
				argc += (*p_restadjust);

			sciprintf(" Kernel params: (");

			for (int j = 0; j < argc; j++) {
				sciprintf("%04x:%04x", PRINT_REG((*p_sp)[j - stackframe]));
				if (j + 1 < argc)
					sciprintf(", ");
			}
			sciprintf(")\n");
		} else if ((opcode == op_send) || (opcode == op_self)) {
			int restmod = *p_restadjust;
			int stackframe = (scr[pos.offset + 1] >> 1) + restmod;
			reg_t *sb = *p_sp;
			uint16 selector;
			reg_t *val_ref;
			reg_t fun_ref;

			while (stackframe > 0) {
				int argc = sb[- stackframe + 1].offset;
				const char *name = NULL;
				reg_t called_obj_addr = *p_objp;

				if (opcode == op_send)
					called_obj_addr = s->r_acc;
				else if (opcode == op_self)
					called_obj_addr = *p_objp;

				selector = sb[- stackframe].offset;

				name = obj_get_name(s, called_obj_addr);

				if (!name)
					name = "<invalid>";

				sciprintf("  %s::%s[", name, (selector > s->_selectorNames.size()) ? "<invalid>" : selector_name(s, selector));

				switch (lookup_selector(s, called_obj_addr, selector, &val_ref, &fun_ref)) {
				case kSelectorMethod:
					sciprintf("FUNCT");
					argc += restmod;
					restmod = 0;
					break;
				case kSelectorVariable:
					sciprintf("VAR");
					break;
				case kSelectorNone:
					sciprintf("INVALID");
					break;
				}

				sciprintf("](");

				while (argc--) {
					sciprintf("%04x:%04x", PRINT_REG(sb[- stackframe + 2]));
					if (argc)
						sciprintf(", ");
					stackframe--;
				}

				sciprintf(")\n");
				stackframe -= 2;
			} // while (stackframe > 0)
		} // Send-like opcodes
	} // (heappos == *p_pc)

	return retval;
}

int c_dumpnodes(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	int end = MIN<int>(cmdParams[0].val, VOCAB_TREE_NODES);
	int i;

	if (!_debugstate_valid) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	for (i = 0; i < end; i++) {
		sciprintf(" Node %03x: ", i);
		if (s->parser_nodes[i].type == PARSE_TREE_NODE_LEAF)
			sciprintf("Leaf: %04x\n", s->parser_nodes[i].content.value);
		else
			sciprintf("Branch: ->%04x, ->%04x\n", s->parser_nodes[i].content.branches[0],
			          s->parser_nodes[i].content.branches[1]);
	}

	return 0;
}

static const char *varnames[] = {"global", "local", "temp", "param"};
static const char *varabbrev = "gltp";

int c_vmvarlist(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	int i;

	for (i = 0;i < 4;i++) {
		sciprintf("%s vars at %04x:%04x ", varnames[i], PRINT_REG(make_reg(p_var_segs[i], p_vars[i] - p_var_base[i])));
		if (p_var_max)
			sciprintf("  total %d", p_var_max[i]);
		sciprintf("\n");
	}

	return 0;
}

int c_vmvars(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	const char *vartype_pre = strchr(varabbrev, *cmdParams[0].str);
	int vartype;
	int idx = cmdParams[1].val;

	if (!vartype_pre) {
		sciprintf("Invalid variable type '%c'\n", *cmdParams[0].str);
		return 1;
	}
	vartype = vartype_pre - varabbrev;

	if (idx < 0) {
		sciprintf("Invalid: negative index\n");
		return 1;
	}
	if ((p_var_max) && (p_var_max[vartype] <= idx)) {
		sciprintf("Max. index is %d (0x%x)\n", p_var_max[vartype], p_var_max[vartype]);
		return 1;
	}

	switch (cmdParams.size()) {
	case 2:
		sciprintf("%s var %d == %04x:%04x\n", varnames[vartype], idx, PRINT_REG(p_vars[vartype][idx]));
		break;

	case 3:
		p_vars[vartype][idx] = cmdParams[2].reg;
		break;

	default:
		sciprintf("Too many arguments\n");
	}

	return 0;
}

static int c_backtrace(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	if (!_debugstate_valid) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	sciprintf("Call stack (current base: 0x%x):\n", s->execution_stack_base);
	Common::List<ExecStack>::iterator iter;
	uint i = 0;
	for (iter = s->_executionStack.begin();
	     iter != s->_executionStack.end(); ++iter, ++i) {
		ExecStack &call = *iter;
		const char *objname = obj_get_name(s, call.sendp);
		int paramc, totalparamc;

		switch (call.type) {

		case EXEC_STACK_TYPE_CALL: {// Normal function
			sciprintf(" %x:[%x]  %s::%s(", i, call.origin, objname, (call.selector == -1) ? "<call[be]?>" :
			          selector_name(s, call.selector));
		}
		break;

		case EXEC_STACK_TYPE_KERNEL: // Kernel function
			sciprintf(" %x:[%x]  k%s(", i, call.origin, s->_kernelNames[-(call.selector)-42].c_str());
			break;

		case EXEC_STACK_TYPE_VARSELECTOR:
			sciprintf(" %x:[%x] vs%s %s::%s (", i, call.origin, (call.argc) ? "write" : "read",
			          objname, s->_selectorNames[call.selector].c_str());
			break;
		}

		totalparamc = call.argc;

		if (totalparamc > 16)
			totalparamc = 16;

		for (paramc = 1; paramc <= totalparamc; paramc++) {
			sciprintf("%04x:%04x", PRINT_REG(call.variables_argp[paramc]));

			if (paramc < call.argc)
				sciprintf(", ");
		}

		if (call.argc > 16)
			sciprintf("...");

		sciprintf(")\n    obj@%04x:%04x", PRINT_REG(call.objp));
		if (call.type == EXEC_STACK_TYPE_CALL) {
			sciprintf(" pc=%04x:%04x", PRINT_REG(call.addr.pc));
			if (call.sp == CALL_SP_CARRY)
				sciprintf(" sp,fp:carry");
			else {
				sciprintf(" sp=ST:%04x", PRINT_STK(call.sp));
				sciprintf(" fp=ST:%04x", PRINT_STK(call.fp));
			}
		} else
			sciprintf(" pc:none");

		sciprintf(" argp:ST:%04x", PRINT_STK(call.variables_argp));
		if (call.type == EXEC_STACK_TYPE_CALL)
			sciprintf(" script: %d", (*(Script *)s->seg_manager->_heap[call.addr.pc.segment]).nr);
		sciprintf("\n");
	}

	return 0;
}

static int c_visible_map(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	if (!s) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	// TODO
#if 0
	if (s->onscreen_console)
		con_restore_screen(s, s->osc_backup);

	if (cmdParams[0].val <= 3)
		s->pic_visible_map = cmdParams[0].val;
	c_redraw_screen(s);

	if (s->onscreen_console)
		s->osc_backup = con_backup_screen(s);
#endif
	return 0;
}

static int c_gfx_priority(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	if (!_debugstate_valid) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	if (cmdParams.size()) {
		int zone = cmdParams[0].val;
		if (zone < 0)
			zone = 0;
		if (zone > 15) zone = 15;

		sciprintf("Zone %x starts at y=%d\n", zone, PRIORITY_BAND_FIRST(zone));
	} else {
		sciprintf("Priority bands start at y=%d\nThey end at y=%d\n", s->priority_first, s->priority_last);
	}

	return 0;
}

static int c_gfx_drawpic(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	int flags = 1, default_palette = 0;

	if (!_debugstate_valid) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	if (cmdParams.size() > 1) {
		default_palette = cmdParams[1].val;

		if (cmdParams.size() > 2)
			flags = cmdParams[2].val;
	}

	gfxop_new_pic(s->gfx_state, cmdParams[0].val, flags, default_palette);
	gfxop_clear_box(s->gfx_state, gfx_rect(0, 0, 320, 200));
	gfxop_update(s->gfx_state);
	gfxop_sleep(s->gfx_state, 0);

	return 0;
}

#ifdef GFXW_DEBUG_WIDGETS
extern GfxWidget *debug_widgets[];
extern int debug_widget_pos;

static int c_gfx_print_widget(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	if (!_debugstate_valid) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	if (cmdParams.size()) {
		unsigned int i;
		for (i = 0; i < cmdParams.size() ; i++) {
			int widget_nr = cmdParams[i].val;

			sciprintf("===== Widget #%d:\n", widget_nr);
			debug_widgets[widget_nr]->print(0);
		}

	} else if (debug_widget_pos > 1)
		sciprintf("Widgets 0-%d are active\n", debug_widget_pos - 1);
	else if (debug_widget_pos == 1)
		sciprintf("Widget 0 is active\n");
	else
		sciprintf("No widgets are active\n");

	return 0;
}
#endif

static int c_gfx_draw_cel(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	int view = cmdParams[0].val;
	int loop = cmdParams[1].val;
	int cel = cmdParams[2].val;
	int palette = cmdParams[3].val;

	if (!s) {
		sciprintf("Not in debug state!\n");
		return 1;
	}

	gfxop_set_clip_zone(s->gfx_state, gfx_rect_fullscreen);
	gfxop_draw_cel(s->gfx_state, view, loop, cel, Common::Point(160, 100), s->ega_colors[0], palette);
	gfxop_update(s->gfx_state);

	return 0;
}

static int c_gfx_fill_screen(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	int col = cmdParams[0].val;

	if (!s) {
		sciprintf("Not in debug state!\n");
		return 1;
	}

	if (col < 0 || col > 15)
		col = 0;

	gfxop_set_clip_zone(s->gfx_state, gfx_rect_fullscreen);
	gfxop_fill_box(s->gfx_state, gfx_rect_fullscreen, s->ega_colors[col]);
	gfxop_update(s->gfx_state);

	return 0;
}

static int c_gfx_draw_rect(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	int col = cmdParams[4].val;

	if (!s) {
		sciprintf("Not in debug state!\n");
		return 1;
	}

	if (col < 0 || col > 15)
		col = 0;

	gfxop_set_clip_zone(s->gfx_state, gfx_rect_fullscreen);
	gfxop_fill_box(s->gfx_state, gfx_rect(cmdParams[0].val, cmdParams[1].val, cmdParams[2].val, cmdParams[3].val), s->ega_colors[col]);
	gfxop_update(s->gfx_state);

	return 0;
}

static int c_gfx_propagate_rect(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	int map = cmdParams[4].val;
	rect_t rect;

	if (!s) {
		sciprintf("Not in debug state!\n");
		return 1;
	}

	if (map < 0 || map > 1)
		map = 0;

	gfxop_set_clip_zone(s->gfx_state, gfx_rect_fullscreen);

	rect = gfx_rect(cmdParams[0].val, cmdParams[1].val, cmdParams[2].val, cmdParams[3].val);

	if (map == 1)
		gfxop_clear_box(s->gfx_state, rect);
	else
		gfxop_update_box(s->gfx_state, rect);
	gfxop_update(s->gfx_state);
	gfxop_sleep(s->gfx_state, 0);

	return 0;
}

#define GETRECT(ll, rr, tt, bb) \
	ll = GET_SELECTOR(pos, ll); \
	rr = GET_SELECTOR(pos, rr); \
	tt = GET_SELECTOR(pos, tt); \
	bb = GET_SELECTOR(pos, bb);

#if 0
// Unreferenced - removed
static int c_gfx_draw_viewobj(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
#ifdef __GNUC__
#warning "Re-implement con:gfx_draw_viewobj"
#endif
#if 0
	HeapPtr pos = (HeapPtr)(cmdParams[0].val);
	int is_view;
	int x, y, priority;
	int nsLeft, nsRight, nsBottom, nsTop;
	int brLeft, brRight, brBottom, brTop;

	if (!s) {
		sciprintf("Not in debug state!\n");
		return 1;
	}

	if ((pos < 4) || (pos > 0xfff0)) {
		sciprintf("Invalid address.\n");
		return 1;
	}

	if (((int16)READ_LE_UINT16(s->heap + pos + SCRIPT_OBJECT_MAGIC_OFFSET)) != SCRIPT_OBJECT_MAGIC_NUMBER) {
		sciprintf("Not an object.\n");
		return 0;
	}


	is_view = (lookup_selector(s, pos, s->selector_map.x, NULL) == kSelectorVariable) &&
	    (lookup_selector(s, pos, s->selector_map.brLeft, NULL) == kSelectorVariable) &&
	    (lookup_selector(s, pos, s->selector_map.signal, NULL) == kSelectorVariable) &&
	    (lookup_selector(s, pos, s->selector_map.nsTop, NULL) == kSelectorVariable);

	if (!is_view) {
		sciprintf("Not a dynamic View object.\n");
		return 0;
	}

	x = GET_SELECTOR(pos, x);
	y = GET_SELECTOR(pos, y);
	priority = GET_SELECTOR(pos, priority);
	GETRECT(brLeft, brRight, brBottom, brTop);
	GETRECT(nsLeft, nsRight, nsBottom, nsTop);
	gfxop_set_clip_zone(s->gfx_state, gfx_rect_fullscreen);

	brTop += 10;
	brBottom += 10;
	nsTop += 10;
	nsBottom += 10;

	gfxop_fill_box(s->gfx_state, gfx_rect(nsLeft, nsTop, nsRight - nsLeft + 1, nsBottom - nsTop + 1), s->ega_colors[2]);

	gfxop_fill_box(s->gfx_state, gfx_rect(brLeft, brTop, brRight - brLeft + 1, brBottom - brTop + 1), s->ega_colors[1]);

	gfxop_fill_box(s->gfx_state, gfx_rect(x - 1, y - 1, 3, 3), s->ega_colors[0]);

	gfxop_fill_box(s->gfx_state, gfx_rect(x - 1, y, 3, 1), s->ega_colors[priority]);

	gfxop_fill_box(s->gfx_state, gfx_rect(x, y - 1, 1, 3), s->ega_colors[priority]);

	gfxop_update(s->gfx_state);

	return 0;
#endif
}
#endif

static int c_gfx_update_zone(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	if (!_debugstate_valid) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	return s->gfx_state->driver->update(s->gfx_state->driver, gfx_rect(cmdParams[0].val, cmdParams[1].val, cmdParams[2].val, cmdParams[3].val),
										Common::Point(cmdParams[0].val, cmdParams[1].val), GFX_BUFFER_FRONT);
}

static int c_disasm_addr(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	reg_t vpc = cmdParams[0].reg;
	int op_count = 1;
	int do_bwc = 0;
	int do_bytes = 0;
	unsigned int i;
	int invalid = 0;
	int size;

	s->seg_manager->dereference(vpc, &size);
	size += vpc.offset; // total segment size

	for (i = 1; i < cmdParams.size(); i++) {
		if (!scumm_stricmp(cmdParams[i].str, "bwt"))
			do_bwc = 1;
		else if (!scumm_stricmp(cmdParams[i].str, "bc"))
			do_bytes = 1;
		else if (toupper(cmdParams[i].str[0]) == 'C')
			op_count = atoi(cmdParams[i].str + 1);
		else {
			invalid = 1;
			sciprintf("Invalid option '%s'\n", cmdParams[i].str);
		}
	}

	if (invalid || op_count < 0)
		return invalid;

	do {
		vpc = disassemble(s, vpc, do_bwc, do_bytes);

	} while ((vpc.offset > 0) && (vpc.offset + 6 < size) && (--op_count));
	return 0;
}

static int c_disasm(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	Object *obj = obj_get(s, cmdParams[0].reg);
	int selector_id = script_find_selector(s, cmdParams[1].str);
	reg_t addr;

	if (!obj) {
		sciprintf("Not an object.");
		return 1;
	}

	if (selector_id < 0) {
		sciprintf("Not a valid selector name.");
		return 1;
	}

	if (lookup_selector(s, cmdParams[0].reg, selector_id, NULL, &addr) != kSelectorMethod) {
		sciprintf("Not a method.");
		return 1;
	}

	do {
		addr = disassemble(s, addr, 0, 0);
	} while (addr.offset > 0);

	return 0;
}

static int c_sg(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	_debug_seeking = _DEBUG_SEEK_GLOBAL;
	_debug_seek_special = cmdParams[0].val;
	_debugstate_valid = 0;

	return 0;
}

static int c_snk(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	int callk_index;
	char *endptr;

	if (!_debugstate_valid) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	if (cmdParams.size() > 0) {
		/* Try to convert the parameter to a number. If the conversion stops
		   before end of string, assume that the parameter is a function name
		   and scan the function table to find out the index. */
		callk_index = strtoul(cmdParams [0].str, &endptr, 0);
		if (*endptr != '\0') {
			callk_index = -1;
			for (uint i = 0; i < s->_kernelNames.size(); i++)
				if (cmdParams [0].str == s->_kernelNames[i]) {
					callk_index = i;
					break;
				}

			if (callk_index == -1) {
				sciprintf("Unknown kernel function '%s'\n", cmdParams[0].str);
				return 1;
			}
		}

		_debug_seeking = _DEBUG_SEEK_SPECIAL_CALLK;
		_debug_seek_special = callk_index;
		_debugstate_valid = 0;
	} else {
		_debug_seeking = _DEBUG_SEEK_CALLK;
		_debugstate_valid = 0;
	}

	return 0;
}

static int c_sret(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	_debug_seeking = _DEBUG_SEEK_LEVEL_RET;
	_debug_seek_level = s->_executionStack.size()-1;
	_debugstate_valid = 0;
	return 0;
}

static int c_go(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	_debug_seeking = 0;
	_debugstate_valid = 0;
	script_debug_flag = 0;
	return 0;
}

static int c_set_acc(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	s->r_acc = cmdParams[0].reg;
	return 0;
}

static int c_send(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	reg_t object = cmdParams[0].reg;
	const char *selector_name = cmdParams[1].str;
	StackPtr stackframe = s->_executionStack.front().sp;
	int selector_id;
	unsigned int i;
	ExecStack *xstack;
	Object *o;
	reg_t *vptr;
	reg_t fptr;

	selector_id = script_find_selector(s, selector_name);

	if (selector_id < 0) {
		sciprintf("Unknown selector: \"%s\"\n", selector_name);
		return 1;
	}

	o = obj_get(s, object);
	if (o == NULL) {
		sciprintf("Address \"%04x:%04x\" is not an object\n", PRINT_REG(object));
		return 1;
	}

	SelectorType selector_type = lookup_selector(s, object, selector_id, &vptr, &fptr);

	if (selector_type == kSelectorNone) {
		sciprintf("Object does not support selector: \"%s\"\n", selector_name);
		return 1;
	}

	stackframe[0] = make_reg(0, selector_id);
	stackframe[1] = make_reg(0, cmdParams.size() - 2);

	for (i = 2; i < cmdParams.size(); i++)
		stackframe[i] = cmdParams[i].reg;

	xstack = add_exec_stack_entry(s, fptr,
	                 s->_executionStack.front().sp + cmdParams.size(),
	                 object, cmdParams.size() - 2,
	                 s->_executionStack.front().sp - 1, 0, object,
	                 s->_executionStack.size()-1, SCI_XS_CALLEE_LOCALS);
	xstack->selector = selector_id;
	xstack->type = selector_type == kSelectorVariable ? EXEC_STACK_TYPE_VARSELECTOR : EXEC_STACK_TYPE_CALL;

	// Now commit the actual function:
	xstack = send_selector(s, object, object, stackframe, cmdParams.size() - 2, stackframe);

	xstack->sp += cmdParams.size();
	xstack->fp += cmdParams.size();

	s->_executionStackPosChanged = true;

	return 0;
}

static int c_resource_id(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	int id = cmdParams[0].val;

	sciprintf("%s.%d (0x%x)\n", getResourceTypeName((ResourceType)(id >> 11)), id & 0x7ff, id & 0x7ff);

	return 0;
}

struct generic_config_flag_t {
	const char *name;
	const char option;
	unsigned int flag;
};

static void handle_config_update(const generic_config_flag_t *flags_list, int flags_nr, const char *subsystem,
								 int *active_options_p, const char *changestring /* or NULL to display*/) {
	if (!changestring) {
		int j;

		sciprintf("Logging in %s:\n", subsystem);
		if (!(*active_options_p))
			sciprintf("  (nothing)\n");

		for (j = 0; j < flags_nr; j++)
			if (*active_options_p & flags_list[j].flag) {
				sciprintf("  - %s (%c)\n", flags_list[j].name, flags_list[j].option);
			}
	} else {
		int mode;
		int j = 0;
		int flags = 0;

		if (changestring[0] == '-')
			mode = 0;
		else if (changestring[0] == '+')
			mode = 1;
		else {
			sciprintf("Mode spec must start with '+' or '-' in '%s'\n", changestring);
			return;
		}

		while (changestring[++j]) {
			int k;
			int flag = 0;

			if (changestring[j] == '*')
				flags = ~0; // Everything
			else
				for (k = 0; !flag && k < flags_nr; k++)
					if (flags_list[k].option == changestring[j])
						flag = flags_list[k].flag;

			if (!flag) {
				sciprintf("Invalid/unknown mode flag '%c'\n", changestring[j]);
				return;
			}
			flags |= flag;
		}

		if (mode) // +
			*active_options_p |= flags;
		else // -
			*active_options_p &= ~flags;
	}
}

static int c_handle_config_update(const generic_config_flag_t *flags, int flags_nr, const char *subsystem,
			int *active_options_p, const Common::Array<cmd_param_t> &cmdParams) {

	if (!_debugstate_valid) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	if (cmdParams.size() == 0)
		handle_config_update(flags, flags_nr, subsystem, active_options_p, 0);

	for (uint i = 0; i < cmdParams.size(); i++)
		handle_config_update(flags, flags_nr, subsystem, active_options_p, cmdParams[i].str);

	return 0;
}

#define SFX_DEBUG_MODES 2
#define FROBNICATE_HANDLE(reg) ((reg).segment << 16 | (reg).offset)

static int c_sfx_debuglog(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	const generic_config_flag_t sfx_debug_modes[SFX_DEBUG_MODES] = {
		{"Song activation/deactivation", 's', SFX_DEBUG_SONGS},
		{"Song cue polling and delivery", 'c', SFX_DEBUG_CUES}
	};

	return c_handle_config_update(sfx_debug_modes, SFX_DEBUG_MODES, "sound subsystem", (int *)&(s->_sound._debug), cmdParams);
}

static int c_sfx_remove(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	reg_t id = cmdParams[0].reg;
	int handle = FROBNICATE_HANDLE(id);

	if (id.segment) {
		s->_sound.sfx_song_set_status(handle, SOUND_STATUS_STOPPED);
		s->_sound.sfx_remove_song(handle);
		PUT_SEL32V(id, signal, -1);
		PUT_SEL32V(id, nodePtr, 0);
		PUT_SEL32V(id, handle, 0);
	}

	return 0;
}

static int c_is_sample(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	Resource *song = s->resmgr->findResource(kResourceTypeSound, cmdParams[0].val, 0);
	SongIterator *songit;
	Audio::AudioStream *data;

	if (!song) {
		sciprintf("Not a sound resource.\n");
		return 1;
	}

	songit = songit_new(song->data, song->size, SCI_SONG_ITERATOR_TYPE_SCI0, 0xcaffe /* What do I care about the ID? */);

	if (!songit) {
		sciprintf("Error-- Could not convert to song iterator\n");
		return 1;
	}

	if ((data = songit->getAudioStream())) {
/*
		sciprintf("\nIs sample (encoding %dHz/%s/%04x).\n", data->conf.rate, (data->conf.stereo) ?
		          ((data->conf.stereo == SFX_PCM_STEREO_LR) ? "stereo-LR" : "stereo-RL") : "mono", data->conf.format);
*/
		delete data;
	} else
		sciprintf("Valid song, but not a sample.\n");

	delete songit;

	return 0;
}

#define GETRECT(ll, rr, tt, bb) \
	ll = GET_SELECTOR(pos, ll); \
	rr = GET_SELECTOR(pos, rr); \
	tt = GET_SELECTOR(pos, tt); \
	bb = GET_SELECTOR(pos, bb);

#if 0
#ifdef __GNUC__
#warning "Re-implement viewobjinfo"
#endif
static void viewobjinfo(EngineState *s, HeapPtr pos) {
	char *signals[16] = {
		"stop_update",
		"updated",
		"no_update",
		"hidden",
		"fixed_priority",
		"always_update",
		"force_update",
		"remove",
		"frozen",
		"is_extra",
		"hit_obstacle",
		"doesnt_turn",
		"no_cycler",
		"ignore_horizon",
		"ignore_actor",
		"dispose!"
	};

	int x, y, z, priority;
	int cel, loop, view, signal;
	int nsLeft, nsRight, nsBottom, nsTop;
	int lsLeft, lsRight, lsBottom, lsTop;
	int brLeft, brRight, brBottom, brTop;
	int i;
	int have_rects = 0;
	Common::Rect nsrect, nsrect_clipped, brrect;

	if (lookup_selector(s, pos, s->selector_map.nsBottom, NULL) == kSelectorVariable) {
		GETRECT(nsLeft, nsRight, nsBottom, nsTop);
		GETRECT(lsLeft, lsRight, lsBottom, lsTop);
		GETRECT(brLeft, brRight, brBottom, brTop);
		have_rects = 1;
	}

	GETRECT(view, loop, signal, cel);

	sciprintf("\n-- View information:\ncel %d/%d/%d at ", view, loop, cel);

	x = GET_SELECTOR(pos, x);
	y = GET_SELECTOR(pos, y);
	priority = GET_SELECTOR(pos, priority);
	if (s->selector_map.z > 0) {
		z = GET_SELECTOR(pos, z);
		sciprintf("(%d,%d,%d)\n", x, y, z);
	} else
		sciprintf("(%d,%d)\n", x, y);

	if (priority == -1)
		sciprintf("No priority.\n\n");
	else
		sciprintf("Priority = %d (band starts at %d)\n\n", priority, PRIORITY_BAND_FIRST(priority));

	if (have_rects) {
		sciprintf("nsRect: [%d..%d]x[%d..%d]\n", nsLeft, nsRight, nsTop, nsBottom);
		sciprintf("lsRect: [%d..%d]x[%d..%d]\n", lsLeft, lsRight, lsTop, lsBottom);
		sciprintf("brRect: [%d..%d]x[%d..%d]\n", brLeft, brRight, brTop, brBottom);
	}

	nsrect = get_nsrect(s, pos, 0);
	nsrect_clipped = get_nsrect(s, pos, 1);
	brrect = set_base(s, pos);
	sciprintf("new nsRect: [%d..%d]x[%d..%d]\n", nsrect.x, nsrect.xend, nsrect.y, nsrect.yend);
	sciprintf("new clipped nsRect: [%d..%d]x[%d..%d]\n", nsrect_clipped.x, nsrect_clipped.xend, nsrect_clipped.y, nsrect_clipped.yend);
	sciprintf("new brRect: [%d..%d]x[%d..%d]\n", brrect.x, brrect.xend, brrect.y, brrect.yend);
	sciprintf("\n signals = %04x:\n", signal);

	for (i = 0; i < 16; i++)
		if (signal & (1 << i))
			sciprintf("  %04x: %s\n", 1 << i, signals[i]);
}
#endif
#undef GETRECT

int objinfo(EngineState *s, reg_t pos) {
	Object *obj = obj_get(s, pos);
	Object *var_container = obj;
	int i;

	if (!obj) {
		sciprintf("[%04x:%04x]: Not an object.", PRINT_REG(pos));
		return 1;
	}

	// Object header
	sciprintf("[%04x:%04x] %s : %3d vars, %3d methods\n", PRINT_REG(pos), obj_get_name(s, pos),
				obj->_variables.size(), obj->methods_nr);

	if (!(obj->_variables[SCRIPT_INFO_SELECTOR].offset & SCRIPT_INFO_CLASS))
		var_container = obj_get(s, obj->_variables[SCRIPT_SUPERCLASS_SELECTOR]);
	sciprintf("  -- member variables:\n");
	for (i = 0; (uint)i < obj->_variables.size(); i++) {
		sciprintf("    ");
		if (i < var_container->variable_names_nr) {
			sciprintf("[%03x] %s = ", VM_OBJECT_GET_VARSELECTOR(var_container, i), selector_name(s, VM_OBJECT_GET_VARSELECTOR(var_container, i)));
		} else
			sciprintf("p#%x = ", i);

		reg_t val = obj->_variables[i];
		sciprintf("%04x:%04x", PRINT_REG(val));

		Object *ref = obj_get(s, val);
		if (ref)
			sciprintf(" (%s)", obj_get_name(s, val));

		sciprintf("\n");
	}
	sciprintf("  -- methods:\n");
	for (i = 0; i < obj->methods_nr; i++) {
		reg_t fptr = VM_OBJECT_READ_FUNCTION(obj, i);
		sciprintf("    [%03x] %s = %04x:%04x\n", VM_OBJECT_GET_FUNCSELECTOR(obj, i), selector_name(s, VM_OBJECT_GET_FUNCSELECTOR(obj, i)), PRINT_REG(fptr));
	}
	if (s->seg_manager->_heap[pos.segment]->getType() == MEM_OBJ_SCRIPT)
		sciprintf("\nOwner script:\t%d\n", s->seg_manager->getScript(pos.segment)->nr);

	return 0;
}

int c_vo(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	return objinfo(s, cmdParams[0].reg);
}

int c_obj(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	return objinfo(s, *p_objp);
}

int c_accobj(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	return objinfo(s, s->r_acc);
}

int c_shownode(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	reg_t addr = cmdParams[0].reg;

	return show_node(s, addr);
}

// Breakpoint commands

static Breakpoint *bp_alloc(EngineState *s) {
	Breakpoint *bp;

	if (s->bp_list) {
		bp = s->bp_list;
		while (bp->next)
			bp = bp->next;
		bp->next = (Breakpoint *)malloc(sizeof(Breakpoint));
		bp = bp->next;
	} else {
		s->bp_list = (Breakpoint *)malloc(sizeof(Breakpoint));
		bp = s->bp_list;
	}

	bp->next = NULL;

	return bp;
}

int c_bpx(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	Breakpoint *bp;

	/* Note: We can set a breakpoint on a method that has not been loaded yet.
	   Thus, we can't check whether the command argument is a valid method name.
	   A breakpoint set on an invalid method name will just never trigger. */

	bp = bp_alloc(s);

	bp->type = BREAK_SELECTOR;
	bp->data.name = (char *)malloc(strlen(cmdParams [0].str) + 1);
	strcpy(bp->data.name, cmdParams [0].str);
	s->have_bp |= BREAK_SELECTOR;

	return 0;
}

int c_bpe(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	Breakpoint *bp;

	bp = bp_alloc(s);

	bp->type = BREAK_EXPORT;
	bp->data.address = (cmdParams [0].val << 16 | cmdParams [1].val);
	s->have_bp |= BREAK_EXPORT;

	return 0;
}

int c_bplist(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	Breakpoint *bp;
	int i = 0;
	int bpdata;

	bp = s->bp_list;
	while (bp) {
		sciprintf("  #%i: ", i);
		switch (bp->type) {
		case BREAK_SELECTOR:
			sciprintf("Execute %s\n", bp->data.name);
			break;
		case BREAK_EXPORT:
			bpdata = bp->data.address;
			sciprintf("Execute script %d, export %d\n", bpdata >> 16, bpdata & 0xFFFF);
			break;
		}

		bp = bp->next;
		i++;
	}

	return 0;
}

int c_bpdel(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	Breakpoint *bp, *bp_next, *bp_prev;
	int i = 0, found = 0;
	int type;

	// Find breakpoint with given index
	bp_prev = NULL;
	bp = s->bp_list;
	while (bp && i < cmdParams [0].val) {
		bp_prev = bp;
		bp = bp->next;
		i++;
	}
	if (!bp) {
		sciprintf("Invalid breakpoint index %i\n", cmdParams [0].val);
		return 1;
	}

	// Delete it
	bp_next = bp->next;
	type = bp->type;
	if (type == BREAK_SELECTOR) free(bp->data.name);
	free(bp);
	if (bp_prev)
		bp_prev->next = bp_next;
	else
		s->bp_list = bp_next;

	// Check if there are more breakpoints of the same type. If not, clear
	// the respective bit in s->have_bp.
	for (bp = s->bp_list; bp; bp = bp->next) {
		if (bp->type == type) {
			found = 1;
			break;
		}
	}

	if (!found)
		s->have_bp &= ~type;

	return 0;
}

int c_se(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	stop_on_event = 1;
	_debugstate_valid = script_debug_flag = script_error_flag = 0;

	return 0;
}

int c_type(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	int t = determine_reg_type(s, cmdParams[0].reg, 1);
	int invalid = t & KSIG_INVALID;

	switch (t & ~KSIG_INVALID) {
	case 0:
		sciprintf("Invalid");
		break;

	case KSIG_LIST:
		sciprintf("List");
		break;

	case KSIG_OBJECT:
		sciprintf("Object");
		break;

	case KSIG_REF:
		sciprintf("Reference");
		break;

	case KSIG_ARITHMETIC:
		sciprintf("Arithmetic");
		break;

	default:
		sciprintf("Erroneous unknown type %02x(%d decimal)\n", t, t);
	}

	sciprintf("%s\n", invalid ? " (invalid)" : "");

	return 0;
}

int c_statusbar(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	if (!s) {
		sciprintf("Not in debug state\n");
		return 1;
	}

	s->titlebar_port->_color = s->ega_colors[cmdParams[0].val];
	s->titlebar_port->_bgcolor = s->ega_colors[cmdParams[1].val];

	s->status_bar_foreground = cmdParams[0].val;
	s->status_bar_background = cmdParams[1].val;

	sciw_set_status_bar(s, s->titlebar_port, s->_statusBarText, s->status_bar_foreground, s->status_bar_background);
	gfxop_update(s->gfx_state);

	return 0;
}

static void _print_address(void * _, reg_t addr) {
	if (addr.segment)
		sciprintf("  %04x:%04x\n", PRINT_REG(addr));
}

static int c_gc_show_reachable(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	reg_t addr = cmdParams[0].reg;

	MemObject *mobj = GET_SEGMENT_ANY(*s->seg_manager, addr.segment);
	if (!mobj) {
		sciprintf("Unknown segment : %x\n", addr.segment);
		return 1;
	}

	sciprintf("Reachable from %04x:%04x:\n", PRINT_REG(addr));
	mobj->listAllOutgoingReferences(s, addr, NULL, _print_address);

	return 0;
}

static int c_gc_show_freeable(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	reg_t addr = cmdParams[0].reg;

	MemObject *mobj = GET_SEGMENT_ANY(*s->seg_manager, addr.segment);
	if (!mobj) {
		sciprintf("Unknown segment : %x\n", addr.segment);
		return 1;
	}

	sciprintf("Freeable in segment %04x:\n", addr.segment);
	mobj->listAllDeallocatable(addr.segment, NULL, _print_address);

	return 0;
}

static int c_gc_normalise(EngineState *s, const Common::Array<cmd_param_t> &cmdParams) {
	reg_t addr = cmdParams[0].reg;

	MemObject *mobj = GET_SEGMENT_ANY(*s->seg_manager, addr.segment);
	if (!mobj) {
		sciprintf("Unknown segment : %x\n", addr.segment);
		return 1;
	}

	addr = mobj->findCanonicAddress(s->seg_manager, addr);
	sciprintf(" %04x:%04x\n", PRINT_REG(addr));

	return 0;
}

void script_debug(EngineState *s, reg_t *pc, StackPtr *sp, StackPtr *pp, reg_t *objp, int *restadjust,
	SegmentId *segids, reg_t **variables, reg_t **variables_base, int *variables_nr, int bp) {
	// Do we support a separate console?

	int old_debugstate = _debugstate_valid;

	p_var_segs = segids;
	p_vars = variables;
	p_var_max = variables_nr;
	p_var_base = variables_base;
	p_pc = pc;
	p_sp = sp;
	p_pp = pp;
	p_objp = objp;
	p_restadjust = restadjust;
	sciprintf("%d: acc=%04x:%04x  ", script_step_counter, PRINT_REG(s->r_acc));
	_debugstate_valid = 1;
	disassemble(s, *pc, 0, 1);
	if (_debug_seeking == _DEBUG_SEEK_GLOBAL)
		sciprintf("Global %d (0x%x) = %04x:%04x\n", _debug_seek_special,
		          _debug_seek_special, PRINT_REG(s->script_000->locals_block->_locals[_debug_seek_special]));

	_debugstate_valid = old_debugstate;

	if (!script_debug_flag)
		return;

	if (_debug_seeking && !bp) { // Are we looking for something special?
		MemObject *mobj = GET_SEGMENT(*s->seg_manager, pc->segment, MEM_OBJ_SCRIPT);

		if (mobj) {
			Script *scr = (Script *)mobj;
			byte *code_buf = scr->buf;
			int code_buf_size = scr->buf_size;
			int opcode = pc->offset >= code_buf_size ? 0 : code_buf[pc->offset];
			int op = opcode >> 1;
			int paramb1 = pc->offset + 1 >= code_buf_size ? 0 : code_buf[pc->offset + 1];
			int paramf1 = (opcode & 1) ? paramb1 : (pc->offset + 2 >= code_buf_size ? 0 : (int16)READ_LE_UINT16(code_buf + pc->offset + 1));

			switch (_debug_seeking) {
			case _DEBUG_SEEK_SPECIAL_CALLK:
				if (paramb1 != _debug_seek_special)
					return;

			case _DEBUG_SEEK_CALLK: {
				if (op != op_callk)
					return;
				break;
			}

			case _DEBUG_SEEK_LEVEL_RET: {
				if ((op != op_ret) || (_debug_seek_level < (int)s->_executionStack.size()-1))
					return;
				break;
			}

			case _DEBUG_SEEK_SO:
				if ((*pc != _debug_seek_reg) || (int)s->_executionStack.size()-1 != _debug_seek_level)
					return;
				break;

			case _DEBUG_SEEK_GLOBAL:

				if (op < op_sag)
					return;
				if ((op & 0x3) > 1)
					return; // param or temp
				if ((op & 0x3) && s->_executionStack.back().local_segment > 0)
					return; // locals and not running in script.000
				if (paramf1 != _debug_seek_special)
					return; // CORRECT global?
				break;

			}

			_debug_seeking = _DEBUG_SEEK_NOTHING;
			// OK, found whatever we were looking for
		}
	}

	_debugstate_valid = (_debug_step_running == 0);

	if (_debugstate_valid) {
		p_pc = pc;
		p_sp = sp;
		p_pp = pp;
		p_objp = objp;
		p_restadjust = restadjust;
		p_var_segs = segids;
		p_vars = variables;
		p_var_max = variables_nr;
		p_var_base = variables_base;

		c_debuginfo(s);
		sciprintf("Step #%d\n", script_step_counter);
		disassemble(s, *pc, 0, 1);

		if (_debug_commands_not_hooked) {
			_debug_commands_not_hooked = 0;

			con_hook_command(c_sfx_remove, "sfx_remove", "!a", "Kills a playing sound.");
			con_hook_command(c_debuginfo, "registers", "", "Displays all current register values");
			con_hook_command(c_vmvars, "vmvars", "!sia*", "Displays or changes variables in the VM\n\nFirst parameter is either g(lobal), l(ocal), t(emp) or p(aram).\nSecond parameter is the var number\nThird parameter (if specified) is the value to set the variable to");
			con_hook_command(c_vmvarlist, "vmvarlist", "!", "Displays the addresses of variables in the VM");
			con_hook_command(c_step, "s", "i*", "Executes one or several operations\n\nEXAMPLES\n\n"
			                 "    s 4\n\n  Execute 4 commands\n\n    s\n\n  Execute next command");
#if 0
			// TODO Re-implement con:so
			con_hook_command(c_stepover, "so", "", "Executes one operation skipping over sends");
#endif
			con_hook_command(c_disasm_addr, "disasm-addr", "!as*", "Disassembles one or more commands\n\n"
			                 "USAGE\n\n  disasm-addr [startaddr] <options>\n\n"
			                 "  Valid options are:\n"
			                 "  bwt  : Print byte/word tag\n"
			                 "  c<x> : Disassemble <x> bytes\n"
			                 "  bc   : Print bytecode\n\n");
			con_hook_command(c_disasm, "disasm", "!as", "Disassembles a method by name\n\nUSAGE\n\n  disasm <obj> <method>\n\n");
			con_hook_command(c_obj, "obj", "!", "Displays information about the\n  currently active object/class.\n"
			                 "\n\nSEE ALSO\n\n  vo.1, accobj.1");
			con_hook_command(c_accobj, "accobj", "!", "Displays information about an\n  object or class at the\n"
			                 "address indexed by acc.\n\nSEE ALSO\n\n  obj.1, vo.1");
			con_hook_command(c_stack, "stack", "i", "Dumps the specified number of stack elements");
			con_hook_command(c_backtrace, "bt", "", "Dumps the send/self/super/call/calle/callb stack");
			con_hook_command(c_snk, "snk", "s*", "Steps forward until it hits the next\n  callk operation.\n"
			                 "  If invoked with a parameter, it will\n  look for that specific callk.\n");
			con_hook_command(c_se, "se", "", "Steps forward until an SCI event is received.\n");
			con_hook_command(c_set_acc, "set_acc", "!a", "Sets the accumulator");
			con_hook_command(c_send, "send", "!asa*", "Sends a message to an object\nExample: send ?fooScript cue");
			con_hook_command(c_sret, "sret", "", "Steps forward until ret is called\n  on the current execution stack\n  level.");
			con_hook_command(c_resource_id, "resource_id", "i", "Identifies a resource number by\n"
			                 "  splitting it up in resource type\n  and resource number.");
			con_hook_command(c_visible_map, "set_vismap", "i", "Sets the visible map.\n  Default is 0 (visual).\n"
			                 "  Other useful values are:\n  1: Priority\n  2: Control\n  3: Auxiliary\n");
			con_hook_command(c_statusbar, "statusbar", "ii", "Sets the colors of the status bar. Also controllable from the script.\n");
			con_hook_command(c_bpx, "bpx", "s", "Sets a breakpoint on the execution of\n  the specified method.\n\n  EXAMPLE:\n"
			                 "  bpx ego::doit\n\n  May also be used to set a breakpoint\n  that applies whenever an object\n"
			                 "  of a specific type is touched:\n  bpx foo::\n");
			con_hook_command(c_bpe, "bpe", "ii", "Sets a breakpoint on the execution of specified exported function.\n");
			con_hook_command(c_bplist, "bplist", "", "Lists all breakpoints.\n");
			con_hook_command(c_bpdel, "bpdel", "i", "Deletes a breakpoint with specified index.");
			con_hook_command(c_go, "go", "", "Executes the script.\n");
			con_hook_command(c_dumpnodes, "dumpnodes", "i", "shows the specified number of nodes\nfrom the parse node tree");
			con_hook_command(c_mousepos, "mousepos", "", "Reveal the location of a mouse click.\n\n");
			con_hook_command(c_viewinfo, "viewinfo", "ii", "Displays the number of loops\n  and cels of each loop"
			                 " for the\n  specified view resource and palette.");
			con_hook_command(c_list_sentence_fragments, "list_sentence_fragments", "", "Lists all sentence fragments (which\n"
			                 "  are used to build Parse trees).");
			con_hook_command(c_parse, "parse", "s", "Parses a sequence of words and prints\n  the resulting parse tree.\n"
			                 "  The word sequence must be provided as a\n  single string.");
			con_hook_command(c_set_parse_nodes, "set_parse_nodes", "s*", "Sets the contents of all parse nodes.\n"
			                 "  Input token must be separated by\n  blanks.");
			con_hook_command(c_sfx_debuglog, "sfx_debuglog", "s*",
			                 "Sets or prints the sound subsystem debug\n"
			                 "settings\n\n"
			                 "USAGE\n\n"
			                 "  sfx_debuglog {[+|-][p|u|x|b]+}*\n\n"
			                 "  sfx_debuglog\n\n"
			                 "    Prints current settings\n\n"
			                 "  sfx_debuglog +X\n\n"
			                 "    Activates all debug features listed in X\n\n"
			                 "  sfx_debuglog -X\n\n"
			                 "    Deactivates the debug features listed in X\n\n"
			                 "  Debug features:\n"
			                 "    s: Active song changes\n"
			                 "    c: Song cues\n");

#ifdef GFXW_DEBUG_WIDGETS
			con_hook_command(c_gfx_print_widget, "gfx_print_widget", "i*", "If called with no parameters, it\n  shows which widgets are active.\n"
			                 "  With parameters, it lists the\n  widget corresponding to the\n  numerical index specified (for\n  each parameter).");
#endif
			con_hook_command(c_gfx_drawpic, "gfx_drawpic", "ii*", "Draws a pic resource\n\nUSAGE\n  gfx_drawpic <nr> [<pal> [<fl>]]\n"
			                 "  where <nr> is the number of the pic resource\n  to draw\n  <pal> is the optional default\n  palette for the pic (0 is"
			                 "\n  assumed if not specified)\n  <fl> are any pic draw flags (default\n  is 1)");
			con_hook_command(c_gfx_fill_screen, "gfx_fill_screen", "i", "Fills the screen with one\n  of the EGA colors\n");
			con_hook_command(c_gfx_draw_rect, "gfx_draw_rect", "iiiii", "Draws a rectangle to the screen\n  with one of the EGA colors\n\nUSAGE\n\n"
			                 "  gfx_draw_rect <x> <y> <xl> <yl> <color>");
			con_hook_command(c_gfx_propagate_rect,
			                 "gfx_propagate_rect",
			                 "iiiii",
			                 "Propagates a lower gfx buffer to a\n"
			                 "  higher gfx buffer.\n\nUSAGE\n\n"
			                 "  gfx_propagate_rect <x> <y> <xl> <yl> <buf>\n");
			con_hook_command(c_gfx_update_zone, "gfx_update_zone", "iiii", "Propagates a rectangular area from\n  the back buffer to the front buffer"
			                 "\n\nUSAGE\n\n"
			                 "  gfx_update_zone <x> <y> <xl> <yl>");
#if 0
			// TODO: Re-enable con:draw_viewobj
			con_hook_command(c_gfx_draw_viewobj, "draw_viewobj", "i", "Draws the nsRect and brRect of a\n  dynview object.\n\n  nsRect is green, brRect\n"
			                 "  is blue.\n");
#endif
			con_hook_command(c_gfx_draw_cel, "gfx_draw_cel", "iiii", "Draws a single view\n  cel to the center of the\n  screen\n\n"
			                 "USAGE\n  gfx_draw_cel <view> <loop> <cel> <palette>\n");
			con_hook_command(c_gfx_priority, "gfx_priority", "i*", "Prints information about priority\n  bands\nUSAGE\n\n  gfx_priority\n\n"
			                 "  will print the min and max values\n  for the priority bands\n\n  gfx_priority <val>\n\n  Print start of the priority\n"
			                 "  band for the specified\n  priority\n");
			con_hook_command(c_vo, "vo", "!a",
			                 "Examines an object\n\n"
			                 "SEE ALSO\n\n"
			                 "  addresses.3, type.1");
			con_hook_command(c_vr, "vr", "!aa*",
			                 "Examines an arbitrary reference\n\n");
			con_hook_command(c_sg, "sg", "!i",
			                 "Steps until the global variable with the\n"
			                 "specified index is modified.\n\nSEE ALSO\n\n"
			                 "  s.1, snk.1, so.1, bpx.1");
			con_hook_command(c_songlib_print, "songlib_print", "",
			                 "");
			con_hook_command(c_type, "type", "!a",
			                 "Determines the type of a value\n\n"
			                 "SEE ALSO\n\n  addresses.3, vo.1");
			con_hook_command(c_shownode, "shownode", "!a",
			                 "Prints information about a list node\n"
			                 "  or list base.\n\n");
			con_hook_command(c_is_sample, "is-sample", "i",
			                 "Tests whether a given sound resource\n"
			                 "  is a PCM sample, and displays infor-\n"
			                 "  mation on it if it is.\n\n");
			con_hook_command(c_sfx_01_header_dump, "sfx-01-header", "i",
			                 "Dumps the header of an SCI01 song\n\n"
			                 "SEE ALSO\n\n"
			                 "  sfx-01-track.1\n\n");
			con_hook_command(c_sfx_01_track, "sfx-01-track", "ii",
			                 "Dumps a track from an SCI01 song\n\n"
			                 "USAGE\n\n"
			                 "  sfx-01-track <song> <offset>\n\n"
			                 "SEE ALSO\n\n"
			                 "  sfx-01-header.1\n\n");
			con_hook_command(c_gc_show_reachable, "gc-list-reachable", "!a",
			                 "Prints all addresses directly reachable from\n"
			                 "  the memory object specified as parameter.\n\n"
			                 "SEE ALSO\n\n"
			                 "  gc-list-freeable.1, gc-normalise.1, gc.1,\n"
			                 "  gc-all-reachable.1");
			con_hook_command(c_gc_show_freeable, "gc-list-freeable", "!a",
			                 "Prints all addresses freeable in the segment\n"
			                 "  associated with the address (offset is ignored).\n\n"
			                 "SEE ALSO\n\n"
			                 "  gc-list-freeable.1, gc-normalise.1, gc.1,\n"
			                 "  gc-all-reachable.1");
			con_hook_command(c_gc_normalise, "gc-normalise", "!a",
			                 "Prints the \"normal\" address of a given address,\n"
			                 "  i.e. the address we would free in order to free\n"
			                 "  the object associated with the original address.\n\n"
			                 "SEE ALSO\n\n"
			                 "  gc-list-freeable.1, gc-list-reachable.1, gc.1,\n"
			                 "  gc-all-reachable.1");

/*
			con_hook_int(&script_debug_flag, "script_debug_flag", "Set != 0 to enable debugger\n");
			con_hook_int(&script_abort_flag, "script_abort_flag", "Set != 0 to abort execution\n");
			con_hook_int(&script_step_counter, "script_step_counter", "# of executed SCI operations\n");
			con_hook_int(&_weak_validations, "weak_validations", "Set != 0 to turn some validation errors\n"
			             "  into warnings\n");

			con_hook_int(&script_gc_interval, "gc-interval", "Number of kernel calls in between gcs");
			con_hook_int(&debug_sleeptime_factor, "sleep-factor", "Factor to multiply with wait times\n  Set to 0 to speed up games");
*/
		} // If commands were not hooked up
	}

	if (_debug_step_running)
		_debug_step_running--;

	while (_debugstate_valid) {
		int skipfirst = 0;
		const char *commandstring;

		// Suspend music playing
		s->_sound.sfx_suspend(true);

		commandstring = _debug_get_input();

		// Check if a specific destination has been given
		if (commandstring && (commandstring[0] == '.' || commandstring[0] == ':'))
			skipfirst = 1;

		//if (commandstring && commandstring[0] != ':')
		//	con_parse(s, commandstring + skipfirst);
		sciprintf("\n");

		// Resume music playing
		s->_sound.sfx_suspend(false);
	}
}

} // End of namespace Sci