aboutsummaryrefslogtreecommitdiff
path: root/queen/logic.cpp
blob: 9476cbf20cefca5a216d87f1de3672d95dc9a980 (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
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
/* ScummVM - Scumm Interpreter
 * Copyright (C) 2003 The ScummVM project
 *
 * 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Header$
 *
 */

#include "stdafx.h"
#include "queen/logic.h"
#include "queen/command.h"
#include "queen/cutaway.h"
#include "queen/defs.h"
#include "queen/debug.h"
#include "queen/display.h"
#include "queen/graphics.h"
#include "queen/input.h"
#include "queen/journal.h"
#include "queen/resource.h"
#include "queen/sound.h"
#include "queen/talk.h"
#include "queen/walk.h"


namespace Queen {

const VerbEnum Logic::PANEL_VERBS[] = {
	VERB_NONE,
	VERB_OPEN,
	VERB_CLOSE,
	VERB_MOVE,
	VERB_GIVE,
	VERB_LOOK_AT,
	VERB_PICK_UP,
	VERB_TALK_TO,
	VERB_USE,
	VERB_SCROLL_UP,
	VERB_SCROLL_DOWN,
	VERB_DIGIT_1, // inventory item 1
	VERB_DIGIT_2, // inventory item 2
	VERB_DIGIT_3, // inventory item 3
	VERB_DIGIT_4, // inventory item 4
};


char* Verb::_verbName[13];

Direction State::findDirection(uint16 state) {
	// queen.c l.4014-4021
	static const Direction sd[] = {
		DIR_BACK,
		DIR_RIGHT,
		DIR_LEFT,
		DIR_FRONT
	};
	return sd[(state >> 2) & 3];
}

StateTalk State::findTalk(uint16 state) {
	return (state & (1 << 9)) ? STATE_TALK_TALK : STATE_TALK_MUTE;
}

StateGrab State::findGrab(uint16 state) {
	// queen.c l.4022-4029
	static const StateGrab gd[] = {
		STATE_GRAB_NONE,
		STATE_GRAB_DOWN,
		STATE_GRAB_UP,
		STATE_GRAB_MID
	};
	return gd[state & 3];
}

StateOn State::findOn(uint16 state) {
	return (state & (1 << 8)) ? STATE_ON_ON : STATE_ON_OFF;
}


Verb State::findDefaultVerb(uint16 state) {
	Verb v;
	switch((state >> 4) & 0xF) {
	case 1:
		v = Verb(VERB_OPEN);
		break;
	case 3:
		v = Verb(VERB_CLOSE);
		break;
	case 7:
		v = Verb(VERB_MOVE);
		break;
	case 8:
		v = Verb(VERB_GIVE);
		break;
	case 12:
		v = Verb(VERB_USE);
		break;
	case 14:
		v = Verb(VERB_PICK_UP);
		break;
	case 9:
		v = Verb(VERB_TALK_TO);
		break;
	case 6:
		v = Verb(VERB_LOOK_AT);
		break;
	default:
		v = Verb(VERB_NONE);
		break;
	}
	return v;
}


StateUse State::findUse(uint16 state) {
	return (state & (1 << 10)) ? STATE_USE : STATE_USE_ON;
}


void State::alterOn(uint16 *objState, StateOn state) {
	switch (state) {
	case STATE_ON_ON:
		*objState |= (1 << 8);
		break;
	case STATE_ON_OFF:
		*objState &= ~(1 << 8);
		break;
	}
}

void State::alterDefaultVerb(uint16 *objState, Verb v) {
	uint16 val;
	switch (v.value()) {
	case VERB_OPEN:
		val = 1;
		break;
	case VERB_CLOSE:
		val = 3;
		break;
	case VERB_MOVE:
		val = 7;
		break;
	case VERB_GIVE:
		val = 8;
		break;
	case VERB_USE:
		val = 12;
		break;
	case VERB_PICK_UP:
		val = 14;
		break;
	case VERB_TALK_TO:
		val = 9;
		break;
	case VERB_LOOK_AT:
		val = 6;
		break;
	default:
		val = 0;
		break;
	}
	*objState = (*objState & ~0xF0) | (val << 4);
}


Common::RandomSource Logic::randomizer;


Logic::Logic(Resource *theResource, Graphics *graphics, Display *theDisplay, Input *input, Sound *sound)
	: _resource(theResource), _graphics(graphics), _display(theDisplay), 
	_input(input), _sound(sound) {
	_settings.talkSpeed = DEFAULT_TALK_SPEED;
	_jas = _resource->loadFile("QUEEN.JAS", 20);
	_joe.x = _joe.y = 0;
	_joe.scale = 100;
	_walk = new Walk(this, _graphics);
	_cmd = new Command(this, _graphics, _input, _walk, _sound);
	_dbg = new Debug(_input, this, _graphics);
	memset(_gameState, 0, sizeof(_gameState));
	memset(_talkSelected, 0, sizeof(_talkSelected));
	initialise();
}

Logic::~Logic() {
	delete[] _jas;
	delete _walk;
	delete _cmd;
	delete _dbg;
}

void Logic::initialise() {
	int16 i, j;
	uint8 *ptr = _jas;

	_numRooms = READ_BE_UINT16(ptr); ptr += 2;
	_numNames = READ_BE_UINT16(ptr); ptr += 2;
	_numObjects = READ_BE_UINT16(ptr); ptr += 2;
	_numDescriptions = READ_BE_UINT16(ptr); ptr += 2;

	// Object data
	_objectData = new ObjectData[_numObjects + 1];
	memset(&_objectData[0], 0, sizeof(ObjectData));
	for (i = 1; i <= _numObjects; i++) {
		_objectData[i].readFrom(ptr);
	}

	// Room data
	_roomData = new uint16[_numRooms + 2];
	_roomData[0] = 0;
	for (i = 1; i <= (_numRooms + 1); i++) {
		_roomData[i] = READ_BE_UINT16(ptr);	ptr += 2;
	}
	_roomData[_numRooms + 1] = _numObjects;

	// SFX Name
	// the following table isn't available in demo version
	if (_resource->isDemo()) {
		_sfxName = NULL;
	}
	else {
		_sfxName = new uint16[_numRooms + 1];
		_sfxName[0] = 0;
		for (i = 1; i <= _numRooms; i++) {
			_sfxName[i] = READ_BE_UINT16(ptr); ptr += 2;
		}	
	}

	// Item information
	_numItems = READ_BE_UINT16(ptr); ptr += 2;

	_itemData = new ItemData[_numItems + 1];
	memset(&_itemData[0], 0, sizeof(ItemData));
	for (i = 1; i <= _numItems; i++) {
		_itemData[i].readFrom(ptr);
	}

	// Graphic Image Data
	_numGraphics = READ_BE_UINT16(ptr); ptr += 2;

	_graphicData = new GraphicData[_numGraphics + 1];
	memset(&_graphicData[0], 0, sizeof(GraphicData));
	for (i = 1; i <= _numGraphics; i++) {
		_graphicData[i].readFrom(ptr);
	}

	_objMax   = new int16[_numRooms + 1];
	_areaMax  = new int16[_numRooms + 1];
	_area     = new Area[_numRooms + 1][MAX_AREAS_NUMBER];

	_objMax[0] = 0;
	_areaMax[0] = 0;
	memset(&_area[0], 0, sizeof(Area) * MAX_AREAS_NUMBER);
	for (i = 1; i <= _numRooms; i++) {
		_objMax[i] = (int16)READ_BE_UINT16(ptr); ptr += 2;
		_areaMax[i] = (int16)READ_BE_UINT16(ptr); ptr += 2;
		memset(&_area[i][0], 0, sizeof(Area));
		for (j = 1; j <= _areaMax[i]; j++) {
			assert(j < MAX_AREAS_NUMBER);
			_area[i][j].readFrom(ptr);
		}
	}

	_objectBox = new Box[_numObjects + 1];
	memset(&_objectBox[0], 0, sizeof(Box));
	for (i = 1; i <= _numObjects; i++) {
		_objectBox[i].readFrom(ptr);
	}

	// Walk OFF Data
	_numWalkOffs = READ_BE_UINT16(ptr);	ptr += 2;

	_walkOffData = new WalkOffData[_numWalkOffs + 1];
	memset(&_walkOffData[0], 0, sizeof(WalkOffData));
	for (i = 1; i <= _numWalkOffs; i++) {
		_walkOffData[i].readFrom(ptr);
	}

	// Special Object Descriptions
	_numObjDesc = READ_BE_UINT16(ptr); ptr += 2;

	_objectDescription = new ObjectDescription[_numObjDesc + 1];
	memset(&_objectDescription[0], 0, sizeof(ObjectDescription));
	for (i = 1; i <= _numObjDesc; i++) {
		_objectDescription[i].readFrom(ptr);
	}

	_cmd->readCommandsFrom(ptr);

	_entryObj = READ_BE_UINT16(ptr); ptr += 2;

	// Furniture DATA
	_numFurniture = READ_BE_UINT16(ptr); ptr += 2;

	_furnitureData = new FurnitureData[_numFurniture + 1];
	memset(&_furnitureData[0], 0, sizeof(_furnitureData));
	for (i = 1; i <= _numFurniture; i++) {
		_furnitureData[i].readFrom(ptr);
	}

	// Actors
	_numActors = READ_BE_UINT16(ptr); ptr += 2;
	_numAAnim = READ_BE_UINT16(ptr); ptr += 2;
	_numAName = READ_BE_UINT16(ptr); ptr += 2;
	_numAFile = READ_BE_UINT16(ptr); ptr += 2;

	_actorData = new ActorData[_numActors + 1];
	memset(&_actorData[0], 0, sizeof(ActorData));
	for (i = 1; i <= _numActors; i++) {
		_actorData[i].readFrom(ptr);
	}

	_numGraphicAnim = READ_BE_UINT16(ptr); ptr += 2;
	
	_graphicAnim = new GraphicAnim[_numGraphicAnim + 1];
	memset(&_graphicAnim[0], 0, sizeof(GraphicAnim));
	for (i = 1; i <= _numGraphicAnim; i++) {
		_graphicAnim[i].readFrom(ptr);
	}

	_currentRoom = _objectData[_entryObj].room;
	_entryObj = 0;

	if(memcmp(ptr, _resource->JASVersion(), 5) != 0) {
		warning("Unexpected queen.jas file format");
	}
	
	_objDescription = new char*[_numDescriptions + 1];
	_objDescription[0] = 0;
	for (i = 1; i <= _numDescriptions; i++)
		_objDescription[i] = _resource->getJAS2Line();

	//Patch for German text bug
	if (_resource->getLanguage() == GERMAN) {
		char *txt = new char[48];
		strcpy(txt, "Es bringt nicht viel, das festzubinden.");
		_objDescription[296] = txt;
	}
	
	_objName = new char*[_numNames + 1];
	_objName[0] = 0;
	for (i = 1; i <= _numNames; i++)
		_objName[i] = _resource->getJAS2Line();

	_roomName = new char*[_numRooms + 1];
	_roomName[0] = 0;
	for (i = 1; i <= _numRooms; i++)
		_roomName[i] = _resource->getJAS2Line();

	Verb::initName(0, NULL);
	for (i = 1; i <= 12; i++)
		Verb::initName(i, _resource->getJAS2Line());

	_joeResponse[0] = 0;
	for (i = 1; i <= JOE_RESPONSE_MAX; i++)
		_joeResponse[i] = _resource->getJAS2Line();

	_aAnim = new char*[_numAAnim + 1];
	_aAnim[0] = 0;
	for (i = 1; i <= _numAAnim; i++)
		_aAnim[i] = _resource->getJAS2Line();

	_aName = new char*[_numAName + 1];
	_aName[0] = 0;
	for (i = 1; i <= _numAName; i++)
		_aName[i] = _resource->getJAS2Line();
	
	_aFile = new char*[_numAFile + 1];
	_aFile[0] = 0;
	for (i = 1; i <= _numAFile; i++)
		_aFile[i] = _resource->getJAS2Line();

	_settings.textToggle = true;	
	if (_resource->isFloppy())
		_sound->speechToggle(false);
	else
		_sound->speechToggle(true);

	_cmd->clear(false);
	_scene = 0;
	memset(_gameState, 0, sizeof(_gameState));
	_graphics->loadPanel();
	_graphics->bobSetupControl();
	joeSetup();
	zoneSetupPanel();

	_oldRoom = 0;
}


ObjectData* Logic::objectData(int index) const {
	index = ABS(index); // cyx: is that really necessary ?
	if (index <= _numObjects)
		return &_objectData[index];
	else
		error("[Logic::objectData] Invalid object data index: %i", index);
}

uint16 Logic::roomData(int room) const {
	return _roomData[room];
}

uint16 Logic::objMax(int room) const {
	return _objMax[room];
}

GraphicData *Logic::graphicData(int index) const {
	return &_graphicData[index];
}

Area *Logic::area(int room, int num) const {
	return &_area[room][num];
}

Area *Logic::currentRoomArea(int num) const {
	if (num == 0 || num > _areaMax[_currentRoom]) {
		error("Logic::currentRoomArea() - Bad area number = %d (max = %d), currentRoom = %d", num, _areaMax[_currentRoom], _currentRoom);
	}

	return &_area[_currentRoom][num];
}

uint16 Logic::areaMax(int room) const {
	return _areaMax[room];
}

uint16 Logic::currentRoomAreaMax() const {
	return _areaMax[_currentRoom];
}

uint16 Logic::walkOffCount() const {
	return _numWalkOffs;
}

WalkOffData *Logic::walkOffData(int index) const {
	return &_walkOffData[index];
}

uint16 Logic::findBob(uint16 obj) {

	uint16 i;
	uint16 bobnum = 0;
	uint16 bobtype = 0; // 1 for animated, 0 for static

	if (obj > _numObjects)
		error("Object index (%i) > _numObjects (%i)", obj, _numObjects);

	uint16 room = _objectData[obj].room;

	if (room >= _numRooms) {
		warning("room (%i) > _numRooms (%i)", room, _numRooms);
	}

	int16 img = _objectData[obj].image;
	if(img != 0) {
		if(img == -3 || img == -4) {
			// a person object
			for(i = _roomData[room] + 1; i <= obj; ++i) {
				img = _objectData[i].image;
				if(img == -3 || img == -4) {
					++bobnum;
				}
			}
		}
		else {
			if(img <= -10) {
				// object has been turned off, but the image order hasn't been updated
				if(_graphicData[-(img + 10)].lastFrame != 0) {
					bobtype = 1;
				}
			}
			else if(img == -2) {
				// -1 static, -2 animated
				bobtype = 1;
			}
			else if(img > 0) {
				if(_graphicData[img].lastFrame != 0) {
					bobtype = 1;
				}
			}

			uint16 idxAnimated = 0;
			uint16 idxStatic = 0;
			for(i = _roomData[room] + 1; i <= obj; ++i) {
				img = _objectData[i].image;
				if(img <= -10) {
					if(_graphicData[-(img + 10)].lastFrame != 0) {
						++idxAnimated;
					}
					else {
						++idxStatic;
					}
				}
				else if(img > 0) {
					if(img > 5000) {
						img -= 5000;
					}

					if (img >= _numGraphics)
						warning("img (%i) >= _numGraphics (%i)", img, _numGraphics);
					
					if(_graphicData[img].lastFrame != 0) {
						++idxAnimated;
					}
					else {
						++idxStatic;
					}
				}
				else if(img == -1) {
					++idxStatic;
				}
				else if(img == -2) {
					++idxAnimated;
				}
			}
			if(bobtype == 0) {
				// static bob
				if(idxStatic > 0) {
					bobnum = 19 + _numFurnitureStatic + idxStatic;
				}
			}
			else {
				// animated bob
				if(idxAnimated > 0) {
					bobnum = 4 + _numFurnitureAnimated + idxAnimated;
				}
			}
		}
	}
	return bobnum;
}


uint16 Logic::findFrame(uint16 obj) {

	uint16 i;
	uint16 framenum = 0;

	uint16 room = _objectData[obj].room;
	int16 img = _objectData[obj].image;
	if(img == -3 || img == -4) {
		uint16 bobnum = 0;
		for(i = _roomData[room] + 1; i <= obj; ++i) {
			img = _objectData[i].image;
			if(img == -3 || img == -4) {
				++bobnum;
			}
		}
		if(bobnum <= 3) {
			framenum = 29 + FRAMES_JOE_XTRA + bobnum;
		}
	}
	else {
		uint16 idx = 0;
		for(i = _roomData[room] + 1; i < obj; ++i) {
			img = _objectData[i].image;
			if(img <= -10) {
				GraphicData* pgd = &_graphicData[-(img + 10)];
				if(pgd->lastFrame != 0) {
					// skip all the frames of the animation
					idx += ABS(pgd->lastFrame) - pgd->firstFrame + 1;
				}
				else {
					// static bob, skip one frame
					++idx;
				}
			}
			else if(img == -1) {
				++idx;
			}
			else if(img > 0) {
				if(img > 5000) {
					img -= 5000;
				}
				GraphicData* pgd = &_graphicData[img];
				uint16 lastFrame = ABS(pgd->lastFrame);
				if(pgd->firstFrame < 0) {
					idx += lastFrame;
				}
				else if(lastFrame != 0) {
					idx += (lastFrame - pgd->firstFrame) + 1;
				}
				else {
					++idx;
				}
			}
		}

		img = _objectData[obj].image;
		if(img <= -10) {
			GraphicData* pgd = &_graphicData[-(img + 10)];
			if(pgd->lastFrame != 0) {
				idx += ABS(pgd->lastFrame) - pgd->firstFrame + 1;
			}
			else {
				++idx;
			}
		}
		else if(img == -1 || img > 0) {
			++idx;
		}

		// calculate only if there are person frames
		if(idx > 0) {
			framenum = 36 + FRAMES_JOE_XTRA + _numFurnitureStatic + _numFurnitureAnimatedLen + idx;
		}
	}
	return framenum;
}


uint16 Logic::objectForPerson(uint16 bobNum) const {

	uint16 bobcur = 0;
	// first object number in the room
	uint16 cur = _roomData[_currentRoom] + 1;
	// last object number in the room
	uint16 last = _roomData[_currentRoom + 1];
	while (cur <= last) {
		int16 image = _objectData[cur].image;
		if (image == -3 || image == -4) {
			// the object is a bob
			++bobcur;
		}
		if (bobcur == bobNum) {
			return cur;
		}
		++cur;
	}
	return 0;
}


WalkOffData *Logic::walkOffPointForObject(uint16 obj) const {
	
	uint16 i;
	for (i = 1; i <= _numWalkOffs; ++i) {
		if (_walkOffData[i].entryObj == obj) {
			return &_walkOffData[i];
		}
	}
	return NULL;
}


void Logic::joeFacing(uint16 dir) {
	_joe.facing = dir;
}

void Logic::joeX(uint16 x) {
	_joe.x = x;
}

void Logic::joeY(uint16 y) {
	_joe.y = y;
}

void Logic::joeWalk(JoeWalkMode walking) {
	_joe.walk = walking;

	// Do this so that Input doesn't need to know the walk value
	_input->dialogueRunning(JWM_SPEAK == walking);
}

void Logic::joeScale(uint16 scale) {
	_joe.scale = scale;
}

void Logic::joeCutFacing(uint16 dir) {

	_joe.cutFacing = dir;
}

void Logic::joePrevFacing(uint16 dir) {
	_joe.prevFacing = dir;
}

int16 Logic::gameState(int index) {
	if (index >= 0 && index < GAME_STATE_COUNT)
		return _gameState[index];
	else
		error("[QueenLogic::gameState] invalid index: %i", index);
}

void Logic::gameState(int index, int16 newValue) {
	if (index >= 0 && index < GAME_STATE_COUNT) {
//		debug(0, "Logic::gameState() - GAMESTATE[%d] = %d", index, newValue);
		_gameState[index] = newValue;
	}
	else
		error("[QueenLogic::gameState] invalid index: %i", index);
}


void Logic::zoneSet(uint16 screen, uint16 zone, uint16 x1, uint16 y1, uint16 x2, uint16 y2) {

	debug(9, "Logic::zoneSet(%d, %d, (%d,%d), (%d,%d))", screen, zone, x1, y1, x2, y2);
	ZoneSlot *pzs = &_zones[screen][zone];
	pzs->valid = true;
	pzs->box.x1 = x1;
	pzs->box.y1 = y1;
	pzs->box.x2 = x2;
	pzs->box.y2 = y2;
}


void Logic::zoneSet(uint16 screen, uint16 zone, const Box& box) {
	
	debug(9, "Logic::zoneSet(%d, %d, (%d,%d), (%d,%d))", screen, zone, box.x1, box.y1, box.x2, box.y2);
	ZoneSlot *pzs = &_zones[screen][zone];
	pzs->valid = true;
	pzs->box = box;
}


uint16 Logic::zoneIn(uint16 screen, uint16 x, uint16 y) const {

	debug(9, "Logic::zoneIn(%d, (%d,%d))", screen, x, y);
	int i;
	if (screen == ZONE_PANEL) {
		y -= ROOM_ZONE_HEIGHT;
	}
	for(i = 1; i < MAX_ZONES_NUMBER; ++i) {
		const ZoneSlot *pzs = &_zones[screen][i];
		if (pzs->valid && pzs->box.contains(x, y)) {
			return i;
		}
	}
	return 0;
}


uint16 Logic::zoneInArea(uint16 screen, uint16 x, uint16 y) const {

	uint16 zone = zoneIn(screen, x, y);
	if (zone <= _objMax[_currentRoom]) {
		zone = 0;
	}
	else {
		zone -= _objMax[_currentRoom];
	}
	return zone;
}


void Logic::zoneClearAll(uint16 screen) {

	debug(9, "Logic::zoneClearAll(%d)", screen);
	int i;
	for(i = 1; i < MAX_ZONES_NUMBER; ++i) {
		_zones[screen][i].valid = false;
	}
}


void Logic::zoneSetup() {

	debug(9, "Logic::zoneSetup()");
	zoneClearAll(ZONE_ROOM);

	int i;
	int zoneNum;

	// setup objects zones
	uint16 maxObjRoom = _objMax[_currentRoom];
	uint16 objRoomNum = _roomData[_currentRoom];
	zoneNum = 1;
	for (i = objRoomNum + 1; i <= objRoomNum + maxObjRoom; ++i) {
		if (_objectData[i].name != 0) {
			zoneSet(ZONE_ROOM, zoneNum, _objectBox[i]);
		}
		++zoneNum;
	}

	// setup room zones (areas)
	uint16 maxAreaRoom = _areaMax[_currentRoom];
	for (zoneNum = 1; zoneNum <= maxAreaRoom; ++zoneNum) {
		zoneSet(ZONE_ROOM, maxObjRoom + zoneNum, _area[_currentRoom][zoneNum].box);
	}
}


void Logic::zoneSetupPanel() {

	// verbs 
	int i;
	for (i = 0; i <= 7; ++i) {
		int x = i * 20;
		zoneSet(ZONE_PANEL, i + 1, x, 10, x + 19, 49);
	}

	// inventory scrolls
	zoneSet(ZONE_PANEL,  9, 160, 10, 179, 29);
	zoneSet(ZONE_PANEL, 10, 160, 30, 179, 49);

	// inventory items
	zoneSet(ZONE_PANEL, 11, 180, 10, 213, 49);
	zoneSet(ZONE_PANEL, 12, 214, 10, 249, 49);
	zoneSet(ZONE_PANEL, 13, 250, 10, 284, 49);
	zoneSet(ZONE_PANEL, 14, 285, 10, 320, 49);
}


void Logic::roomErase() {

	_graphics->frameEraseAll(false);
	_graphics->bankErase(15);
	_graphics->bankErase(11);
	_graphics->bankErase(10);
	_graphics->bankErase(12);

	// TODO: TALKHEAD=0;

	if (_currentRoom >= 114) {
		_display->palFadeOut(0, 255, _currentRoom);
	}
	else {
		_display->palFadeOut(0, 223, _currentRoom);
	}
	
	// TODO: credits system

	// invalidates all persons animations
	uint16 i;
	for (i = 0; i <= 3; ++i) {
		_personFrames[i] = 0;
	}
	for (i = 1; i <= 16; ++i) {
		_newAnim[i][0].frame = 0;
	}

	uint16 cur = _roomData[_oldRoom] + 1;
	uint16 last = _roomData[_oldRoom + 1];
	while (cur <= last) {
		ObjectData *pod = &_objectData[cur];
		if (pod->name == 0) {
			// object has been deleted, invalidate image
			pod->image = 0;
		}
		else if (pod->image > -4000 && pod->image <= -10) {
			if (_graphicData[ABS(pod->image + 10)].lastFrame == 0) {
				// static Bob
				pod->image = -1;
			}
			else {
				// animated Bob
				pod->image = -2;
			}
		}
		++cur;
	}
}


void Logic::roomSetupFurniture() {

	int16 gstate[9];
	_numFurnitureStatic = 0;
	_numFurnitureAnimated = 0;
	_numFurnitureAnimatedLen = 0;
	uint16 curImage = 36 + FRAMES_JOE_XTRA;

	// count the furniture and update gameState
	uint16 furnitureTotal = 0;
	uint16 i;
	for (i = 1; i <= _numFurniture; ++i) {
		if (_furnitureData[i].room == _currentRoom) {
			++furnitureTotal;
			gstate[furnitureTotal] = _furnitureData[i].gameStateValue;
		}
	}
	if (furnitureTotal == 0) {
		return;
	}

	// unpack the furniture from the bank 15
	// there are 3 kinds :
	// - static (bobs), gamestate range = ]0;5000]
	// - animated (bobs), gamestate range = ]0;5000]
	// - static (paste downs), gamestate range = [5000; [

	// unpack the static bobs
	for	(i = 1; i <= furnitureTotal; ++i) {
		int16 obj = gstate[i];
		if (obj > 0 && obj <= 5000) {
			GraphicData *pgd = &_graphicData[obj];
			if (pgd->lastFrame == 0) {
				++_numFurnitureStatic;
				++curImage;
				_graphics->bankUnpack(pgd->firstFrame, curImage, 15);
				++_numFrames;
				BobSlot *pbs = _graphics->bob(19 + _numFurnitureStatic);
				pbs->active = true;
				pbs->x = pgd->x;
				pbs->y = pgd->y;
				pbs->frameNum = curImage;
			}
		}
	}

	// unpack the animated bobs
	uint16 curBob = 0;
	for  (i = 1; i <= furnitureTotal; ++i) {
		int16 obj = gstate[i];
		if (obj > 0 && obj <= 5000) {
			GraphicData *pgd = &_graphicData[obj];

			bool rebound = false;
			int16 lastFrame = pgd->lastFrame;
			if (lastFrame < 0) {
				rebound = true;
				lastFrame = -lastFrame;
			}

			if (lastFrame > 0) {
				_numFurnitureAnimatedLen += lastFrame - pgd->firstFrame + 1;
				++_numFurnitureAnimated;
				uint16 image = curImage + 1;
				int k;
				for (k = pgd->firstFrame; k <= lastFrame; ++k) {
					++curImage;
					_graphics->bankUnpack(k, curImage, 15);
					++_numFrames;
				}
				BobSlot *pbs = _graphics->bob(5 + curBob);
				pbs->animNormal(image, curImage, pgd->speed / 4, rebound, false);
				pbs->x = pgd->x;
				pbs->y = pgd->y;
				++curBob;
			}
		}
	}

	// unpack the paste downs
	++curImage;
	for  (i = 1; i <= furnitureTotal; ++i) {
		int16 obj = gstate[i];
		if (obj > 5000) {
			obj -= 5000;
			GraphicData *pgd = &_graphicData[obj];
			_graphics->bankUnpack(pgd->firstFrame, curImage, 15);
			_graphics->bobPaste(curImage, pgd->x, pgd->y);
			// no need to increment curImage here, as bobPaste() destroys the 
			// unpacked frame after blitting it
		}
	}
}


void Logic::roomSetupObjects() {

	uint16 i;
	// furniture frames are reserved in ::roomSetupFurniture(), we append objects 
	// frames after the furniture ones.
	uint16 curImage = 36 + FRAMES_JOE_XTRA + _numFurnitureStatic + _numFurnitureAnimatedLen;
	uint16 firstRoomObj = _roomData[_currentRoom] + 1;
	uint16 lastRoomObj = _roomData[_currentRoom + 1];
	uint16 numObjectStatic = 0;
	uint16 numObjectAnimated = 0;
	uint16 curBob;

	// invalidates all Bobs for persons (except Joe's one)
	for (i = 1; i <= 3; ++i) {
		_graphics->bob(i)->active = false;
	}

	// static/animated Bobs
	for (i = firstRoomObj; i <= lastRoomObj; ++i) {
		ObjectData *pod = &_objectData[i];
		// setup blanks bobs for turned off objects (in case 
		// you turn them on again)
		if (pod->image == -1) {
			// static OFF Bob
			curBob = 20 + _numFurnitureStatic + numObjectStatic;
			++numObjectStatic;
			// create a blank frame for the for the OFF object
			++_numFrames;
			++curImage;
		}
		else if(pod->image == -2) {
			// animated OFF Bob
			curBob = 5 + _numFurnitureAnimated + numObjectAnimated;
			++numObjectAnimated;
		}
		else if(pod->image > 0 && pod->image < 5000) {
			GraphicData *pgd = &_graphicData[pod->image];
			int16 lastFrame = pgd->lastFrame;
			bool rebound = false;
			if (lastFrame < 0) {
				lastFrame = -lastFrame;
				rebound = true;
			}
			if (pgd->firstFrame < 0) {
				// FIXME: if(TEMPA[1]<0) bobs[CURRBOB].xflip=1;
				curBob = 5 + _numFurnitureAnimated;
				animSetup(pgd, curImage + 1, curBob + numObjectAnimated, pod->name > 0);
				curImage += pgd->lastFrame;
				++numObjectAnimated;
			}
			else if (lastFrame != 0) {
				// animated objects
				uint16 j;
				uint16 firstFrame = curImage + 1;
				for (j = pgd->firstFrame; j <= lastFrame; ++j) {
					++curImage;
					_graphics->bankUnpack(j, curImage, 15);
					++_numFrames;
				}
				curBob = 5 + _numFurnitureAnimated + numObjectAnimated;
				if (pod->name > 0) {
					BobSlot *pbs = _graphics->bob(curBob);
					pbs->active = true;
					pbs->x = pgd->x;
					pbs->y = pgd->y;
					pbs->frameNum = firstFrame;
					if (pgd->speed > 0) {
						pbs->animNormal(firstFrame, curImage, pgd->speed / 4, rebound, false);
					}
				}
				++numObjectAnimated;
			}
			else {
				// static objects
				curBob = 20 + _numFurnitureStatic + numObjectStatic;
				++curImage;
				_graphics->bobClear(curBob);

				// FIXME: if((COMPANEL==2) && (FULLSCREEN==1)) bobs[CURRBOB].y2=199;

				_graphics->bankUnpack(pgd->firstFrame, curImage, 15);
				++_numFrames;
				if (pod->name > 0) {
					BobSlot *pbs = _graphics->bob(curBob);
					pbs->active = true;
					pbs->x = pgd->x;
					pbs->y = pgd->y;
					pbs->frameNum = curImage;
				}
				++numObjectStatic;
			}
		}
	}

	// persons Bobs
	for (i = firstRoomObj; i <= lastRoomObj; ++i) {
		ObjectData *pod = &_objectData[i];
		if (pod->image == -3 || pod->image == -4) {
			debug(0, "Logic::roomSetupObjects() - Setting up person %X, name=%X", i, pod->name);
			uint16 noun = i - _roomData[_currentRoom];
			if (pod->name > 0) {
				curImage = personSetup(noun, curImage);
			}
			else {
				curImage = personAllocate(noun, curImage);
			}
		}
	}

	// paste downs list
	++curImage;
	_numFrames = curImage;
	for (i = firstRoomObj; i <= lastRoomObj; ++i) {
		ObjectData *pod = &_objectData[i];
		if (pod->name > 0) {
			int16 obj = pod->image;
			if (obj > 5000) {
				obj -= 5000;
				GraphicData *pgd = &_graphicData[obj];
				_graphics->bankUnpack(pgd->firstFrame, curImage, 15);
				_graphics->bobPaste(curImage, pgd->x, pgd->y);
			}
		}
	}
}


uint16 Logic::roomRefreshObject(uint16 obj) {

	uint16 curImage = _numFrames;

	if (obj == 0 || obj > _numObjects) {
		warning("Invalid object number %d", obj);
		return curImage;
	}

	ObjectData *pod = &_objectData[obj];
	if (pod->image == 0) {
		return curImage;
	}

	debug(0, "Logic::roomRefreshObject(%X, %s)", obj, _objName[ABS(pod->name)]);

	// check the object is in the current room
	if (pod->room != _currentRoom) {
		warning("Logic::roomRefreshObject() - Trying to display an object (%i=%s) that is not in room (object room=%i, current room=%i)",
			obj, _objName[ABS(pod->name)], pod->room, _currentRoom);
		return curImage;
	}

	// find bob for the object
	uint16 curBob = findBob(obj);
	BobSlot *pbs = _graphics->bob(curBob);

	if (pod->image == -3 || pod->image == -4) {
		// a person object
		if (pod->name <= 0) {
			_graphics->bobClear(curBob);
		}
		else {
			// find person number
			uint16 pNum = 1;
			uint16 i = _roomData[_currentRoom] + 1;
			while (i < obj) {
				if (_objectData[i].image == -3 || _objectData[i].image == -4) {
					++pNum;
				}
				++i;
			}
			curImage = _personFrames[pNum] - 1;
			if (_personFrames[pNum] == 0) {
				curImage = _numFrames;
				_personFrames[pNum] = curImage;
			}
			curImage = personSetup(obj - _roomData[_currentRoom], curImage);
		}
		return curImage;
	}

	// find frame used for object
	curImage = findFrame(obj);

	if (pod->name < 0 || pod->image < 0) {
		// object is hidden or disabled
		_graphics->bobClear(curBob);
		return curImage;
	}

	int image = pod->image;
	if (image > 5000) {
		image -= 5000;
	}
	
	GraphicData *pgd = &_graphicData[image];
	bool rebound = false;
	int16 lastFrame = pgd->lastFrame;
	if (lastFrame < 0) {
		lastFrame = -lastFrame;
		rebound = true;
	}
	if (pgd->firstFrame < 0) {
		animSetup(pgd, curImage, curBob, pod->name != 0);
		curImage += pgd->lastFrame - 1;
	}
	else if (lastFrame != 0) {
		// turn on an animated bob
		_graphics->bankUnpack(pgd->firstFrame, 2, 15);
		pbs->animating = false;
		uint16 firstImage = curImage;
		--curImage;
		uint16 j;
		for (j = pgd->firstFrame; j <= lastFrame; ++j) {
			++curImage;
			_graphics->bankUnpack(j, curImage, 15);
		}
		pbs->active = true;
		pbs->x = pgd->x;
		pbs->y = pgd->y;
		pbs->frameNum = firstImage;
		if (pgd->speed > 0) {
			pbs->animNormal(firstImage, curImage, pgd->speed / 4, rebound, false);
		}
	}
	else {
		// frame 2 is used as a buffer frame to prevent BOB flickering
		_graphics->bankUnpack(pgd->firstFrame, 2, 15);
		_graphics->bankUnpack(pgd->firstFrame, curImage, 15);
		pbs->active = true;
		pbs->x = pgd->x;
		pbs->y = pgd->y;
		pbs->frameNum = curImage;
	}

	return curImage;
}


void Logic::roomSetup(const char *room, int comPanel, bool inCutaway) {

	char filename[20];

	// loads background image
	sprintf(filename, "%s.PCX", room);
	_graphics->loadBackdrop(filename, _currentRoom);

	// custom colors
	_display->palCustomColors(_currentRoom);

	// setup graphics to enter fullscreen/panel mode
	_display->screenMode(comPanel, inCutaway);

	// reset sprites table (bounding box...)
	_graphics->bobClearAll();

	// load/setup objects associated to this room
	sprintf(filename, "%s.BBK", room);
	_graphics->bankLoad(filename, 15);

	zoneSetup();
	_numFrames = 37 + FRAMES_JOE_XTRA;
	roomSetupFurniture();
	roomSetupObjects();
}


void Logic::roomDisplay(uint16 room, RoomDisplayMode mode, uint16 scale, int comPanel, bool inCutaway) {

	debug(0, "Logic::roomDisplay(%d, %d, %d, %d, %d)", room, mode, scale, comPanel, inCutaway);

	roomErase();

	// XXX _sound->loadSFX(SFXNAME[_currentRoom]);

	roomSetup(roomName(room), comPanel, inCutaway);
	ObjectData *pod = NULL;
	if (mode != RDM_FADE_NOJOE) {
		pod = joeSetupInRoom(mode != RDM_FADE_JOE_XY, scale);
	}
	if (mode != RDM_NOFADE_JOE) {
		update();
		BobSlot *joe = _graphics->bob(0);
		if (IS_CD_INTRO_ROOM(_currentRoom)) {
			_display->palFadeIn(0, 255, _currentRoom, joe->active, joe->x, joe->y);
		}
		else {
			_display->palFadeIn(0, 223, _currentRoom, joe->active, joe->x, joe->y);
		}
	}
	if (pod != NULL) {
		_walk->moveJoe(0, pod->x, pod->y, inCutaway);
	}
}


uint16 Logic::findScale(uint16 x, uint16 y) {
	uint16 scale = 100;
	uint16 areaNum = zoneInArea(ZONE_ROOM, x, y);
	if(areaNum != 0) {
		scale = _area[_currentRoom][areaNum].calcScale(y);
	}
	return scale;
}


void Logic::personSetData(int16 noun, const char *actorName, bool loadBank, Person *pp) {

	if (noun <= 0) {
		warning("Logic::personSetData() - Invalid object number: %i", noun);
	}

	uint16 i;
	uint16 obj = _roomData[_currentRoom] + noun;
	int16 img = _objectData[obj].image;
	if (img != -3 && img != -4) {
		warning("Logic::personSetData() - Object %d is not a person", obj);
		return;
	}

	// search Bob number for the person
	uint16 bobNum = 0;
	for (i = _roomData[_currentRoom] + 1; i <= obj; ++i) {
		img = _objectData[i].image;
		if (img == -3 || img == -4) {
			++bobNum;
		}
	}

	// search for a matching actor
	uint16 actor = 0;
	for (i = 1; i <= _numActors; ++i) {
		ActorData *pad = &_actorData[i];
		if (pad->room == _currentRoom) {
			if (_gameState[pad->gameStateSlot] == pad->gameStateValue) {
				if ((bobNum > 0 && bobNum == pad->bobNum) || strcmp(_aName[pad->name], actorName) == 0) {
					actor = i;
					break;
				}
			}
		}
	}

	if (actor != 0) {

		pp->actor = &_actorData[actor];
		pp->name = _aName[pp->actor->name];
		if (pp->actor->anim != 0) {
			pp->anim = _aAnim[pp->actor->anim];
		}
		else {
			pp->anim = NULL;
		}

		debug(0, "Logic::personSetData() - name=%s n=%d", pp->name, actor);

		if (loadBank) {
			const char *actorFile = _aFile[pp->actor->actorFile];
			if (actorFile) {
				_graphics->bankLoad(actorFile, pp->actor->bankNum);
			}
			// if actorFile is null, the person data is already loaded as
			// it is contained in objects room bank (.bbk)
		}

		pp->bobFrame = 29 + FRAMES_JOE_XTRA + pp->actor->bobNum;
	}
}


uint16 Logic::personSetup(uint16 noun, uint16 curImage) {

	Person p;
	personSetData(noun, "", true, &p);

	const ActorData *pad = p.actor;
	uint16 scale = 100;
	uint16 a = zoneInArea(ZONE_ROOM, pad->x, pad->y);
	if (a > 0) {
		// person is not standing in the area box, scale it accordingly
		scale = currentRoomArea(a)->calcScale(pad->y);
	}

	if (noun == 0) {
		warning("Trying to setup person 0");
		return curImage;
	}

	_graphics->bankUnpack(pad->bobFrameStanding, p.bobFrame, p.actor->bankNum);
	bool xflip = false;
	uint16 person = _roomData[_currentRoom] + noun;
	if (_objectData[person].image == -3) {
		// person is facing left
		xflip = true;
	}
	BobSlot *pbs = _graphics->bob(pad->bobNum);
	pbs->active = true;
	pbs->scale = scale;
	pbs->x = pad->x;
	pbs->y = pad->y;
	pbs->frameNum = p.bobFrame;
	pbs->xflip = xflip;

	debug(0, "Logic::personSetup(%d, %d) - bob = %d name = %s", noun, curImage, pad->bobNum, p.name);

	if (p.anim != NULL) {
		_personFrames[pad->bobNum] = curImage + 1;
		curImage = animCreate(curImage, &p);
	}
	else {
		animErase(pad->bobNum);
	}
	return curImage;
}


uint16 Logic::personAllocate(uint16 noun, uint16 curImage) {

	uint16 i;
	uint16 person = _roomData[_currentRoom] + noun;

	// search Bob number for the person
	uint16 bobNum = 0;
	for (i = _roomData[_currentRoom] + 1; i <= person; ++i) {
		int16 img = _objectData[i].image;
		if (img == -3 || img == -4) {
			++bobNum;
		}
	}

	// search for a matching actor
	uint16 actor = 0;
	for (i = 1; i <= _numActors; ++i) {
		ActorData *pad = &_actorData[i];
		if (pad->room == _currentRoom) {
			if (_gameState[pad->gameStateSlot] == pad->gameStateValue) {
				if (bobNum > 0 && bobNum == pad->bobNum) {
					actor = i;
					break;
				}
			}
		}
	}

	if (actor > 0) {
		const char *animStr = _aAnim[_actorData[actor].anim];
		if (animStr) {
			bool allocatedFrames[256];
			memset(allocatedFrames, 0, sizeof(allocatedFrames));
			uint16 f1, f2;
			do {
				sscanf(animStr, "%3hu,%3hu", &f1, &f2);
				animStr += 8;
				allocatedFrames[f1] = true;
			} while(f1 != 0);
			for (i = 1; i <= 255; ++i) {
				if (allocatedFrames[i]) {
					++curImage;
				}
			}
			// FIXME: shouldn't this line be executed BEFORE curImage is incremented ?
			_personFrames[bobNum] = curImage + 1;
		}
	}
	return curImage;
}


uint16 Logic::animCreate(uint16 curImage, const Person *person) {

	AnimFrame *animFrames = _newAnim[person->actor->bobNum];

	uint16 allocatedFrames[256];
	memset(allocatedFrames, 0, sizeof(allocatedFrames));
	const char *p = person->anim;
	int frame = 0;
	uint16 f1, f2;
	do {
		sscanf(p, "%3hu,%3hu", &f1, &f2);
		animFrames[frame].frame = f1;
		animFrames[frame].speed = f2;

		if (f1 > 500) {
			// SFX
			allocatedFrames[f1 - 500] = 1;
		}
		else {
			allocatedFrames[f1] = 1;
		}
		
		p += 8;
		++frame;
	} while(f1 != 0);
	
	// ajust frame numbers
	uint16 n = 1;
	uint16 i;
	for (i = 1; i <= 255; ++i) {
		if (allocatedFrames[i] != 0) {
			allocatedFrames[i] = n;
			++n;
		}
	}
	for (i = 0; animFrames[i].frame != 0; ++i) {
		uint16 frameNum = animFrames[i].frame;
		if (frameNum > 500) {
			animFrames[i].frame = curImage + allocatedFrames[frameNum - 500] + 500;
		}
		else {
			animFrames[i].frame = curImage + allocatedFrames[frameNum];
		}
	}

	// unpack necessary frames
	for (i = 1; i <= 255; ++i) {
		if (allocatedFrames[i] != 0) {
			++curImage;
			_graphics->bankUnpack(i, curImage, person->actor->bankNum);
		}
	}

	// start animation
	_graphics->bob(person->actor->bobNum)->animString(animFrames);

	return curImage;
}


void Logic::animErase(uint16 bobNum) {

	_newAnim[bobNum][0].frame = 0;
	BobSlot *pbs = _graphics->bob(bobNum);
	pbs->animating = false;
	pbs->anim.string.buffer = NULL;
}


void Logic::animReset(uint16 bobNum) {

	if (_newAnim[bobNum][0].frame != 0) {
		_graphics->bob(bobNum)->animString(_newAnim[bobNum]);
	}
}


void Logic::animSetup(const GraphicData *gd, uint16 firstImage, uint16 bobNum, bool visible) {
	
	int16 tempFrames[20];
	memset(tempFrames, 0, sizeof(tempFrames));
	uint16 numTempFrames = 0;
	uint16 i, j;
	for (i = 1; i <= _numGraphicAnim; ++i) {
		const GraphicAnim *pga = &_graphicAnim[i];
		if (pga->keyFrame == gd->firstFrame) {
			int16 frame = pga->frame;
			if (frame > 500) { // SFX
				frame -= 500;
			}
			bool foundMatchingFrame = false;
			for (j = 0; j < numTempFrames; ++j) {
				if (tempFrames[j] == frame) {
					foundMatchingFrame = true;
					break;
				}
			}
			if (!foundMatchingFrame) {
				assert(numTempFrames < 20);
				tempFrames[numTempFrames] = frame;
				++numTempFrames;
			}
		}
	}

	// sort found frames ascending
	bool swap = true;
	while (swap) {
		swap = false;
		for (i = 0; i < numTempFrames - 1; ++i) {
			if (tempFrames[i] > tempFrames[i + 1]) {
				SWAP(tempFrames[i], tempFrames[i + 1]);
				swap = true;
			}
		}
	}

	// queen.c l.962-980 / l.1269-1294
	for (i = 0; i < gd->lastFrame; ++i) {
		_graphics->bankUnpack(ABS(tempFrames[i]), firstImage + i, 15);
	}
	BobSlot *pbs = _graphics->bob(bobNum);
	pbs->animating = false;
	if (visible) {
		pbs->x = gd->x;
		pbs->y = gd->y;
		if (tempFrames[0] < 0) {
			pbs->xflip = true;
		}
		AnimFrame *paf = _newAnim[bobNum];
		for (i = 1; i <= _numGraphicAnim; ++i) {
			const GraphicAnim *pga = &_graphicAnim[i];
			if (pga->keyFrame == gd->firstFrame) {
				uint16 frameNr = 0;
				for (j = 1; j <= gd->lastFrame; ++j) {
					if (pga->frame > 500) {
						if (pga->frame - 500 == tempFrames[j - 1]) {
							frameNr = j + firstImage - 1 + 500;
						}
					}
					else if (pga->frame == tempFrames[j - 1]) {
						frameNr = j + firstImage - 1;
					}
				}
				paf->frame = frameNr;
				paf->speed = pga->speed;
				++paf;
			}
		}
		paf->frame = 0;
		paf->speed = 0;
		pbs->animString(_newAnim[bobNum]);
	}
}


void Logic::joeSetupFromBanks(const char *animBank, const char *standBank) {

	int i;
	_graphics->bankLoad(animBank, 13);
	for (i = 11; i <= 28 + FRAMES_JOE_XTRA; ++i) {
		_graphics->bankUnpack(i - 10, i, 13);
	}
	_graphics->bankErase(13);

	_graphics->bankLoad(standBank, 7);
	_graphics->bankUnpack(1, 33 + FRAMES_JOE_XTRA, 7);
	_graphics->bankUnpack(3, 34 + FRAMES_JOE_XTRA, 7);
	_graphics->bankUnpack(5, 35 + FRAMES_JOE_XTRA, 7);
}


void Logic::joeSetup() {

	joeSetupFromBanks("joe_a.BBK", "joe_b.BBK");
	joeFacing(DIR_FRONT);
}


ObjectData *Logic::joeSetupInRoom(bool autoPosition, uint16 scale) {

	debug(0, "Logic::joeSetupInRoom(%d, %d) joe.x=%d joe.y=%d", autoPosition, scale, _joe.x, _joe.y);

	uint16 oldx;
	uint16 oldy;
	WalkOffData *pwo = NULL;
	ObjectData *pod = objectData(_entryObj);
	if (pod == NULL) {
		error("Logic::joeSetupInRoom() - No object data for obj %d", _entryObj);
	}

	if (!autoPosition || joeX() != 0 || joeY() != 0) {
		oldx = joeX();
		oldy = joeY();
	}
	else {
		// find the walk off point for the entry object and make 
		// Joe walking to that point
		pwo = walkOffPointForObject(_entryObj);
		if (pwo != NULL) {
			oldx = pwo->x;
			oldy = pwo->y;
		}
		else {
			// no walk off point, use object position
			oldx = pod->x;
			oldy = pod->y;
		}
	}

	debug(0, "Logic::joeSetupInRoom() - oldx=%d, oldy=%d scale=%d", oldx, oldy, scale);

	if (scale > 0 && scale < 100) {
		joeScale(scale);
	}
	else {
		uint16 a = zoneInArea(ZONE_ROOM, oldx, oldy);
		if (a > 0) {
			joeScale(currentRoomArea(a)->calcScale(oldy));
		}
		else {
			joeScale(100);
		}
	}

	if (joeCutFacing() > 0) {
		joeFacing(joeCutFacing());
		joeCutFacing(0);
	}
	else {
		// check to see which way Joe entered room
		switch (State::findDirection(pod->state)) {
		case DIR_BACK:
			joeFacing(DIR_FRONT);
			break;
		case DIR_FRONT:
			joeFacing(DIR_BACK);
			break;
		case DIR_LEFT:
			joeFacing(DIR_RIGHT);
			break;
		case DIR_RIGHT:
			joeFacing(DIR_LEFT);
			break;
		}
	}
	joePrevFacing(joeFacing());

	BobSlot *pbs = _graphics->bob(0);
	pbs->scale = joeScale();

	if (_currentRoom == 108) {
		_graphics->cameraBob(-1);
		_graphics->bankLoad("joe_e.act", 7);
		_graphics->bankUnpack(2, 29 + FRAMES_JOE_XTRA, 7);

		_display->horizontalScroll(320);

		joeFacing(DIR_RIGHT);
		joeCutFacing(DIR_RIGHT);
		joePrevFacing(DIR_RIGHT);
	}

	joeFace();
	pbs->active = true;
	pbs->x = oldx;
	pbs->y = oldy;
	pbs->frameNum = 29 + FRAMES_JOE_XTRA;
	joeX(0);
	joeY(0);

	if (pwo != NULL) {
		// entryObj has a walk off point, then walk from there to object x,y
		return pod;
	}
	return NULL;
}


uint16 Logic::joeFace() {

	debug(9, "Logic::joeFace() - curFace = %d, prevFace = %d", _joe.facing, _joe.prevFacing);
	BobSlot *pbs = _graphics->bob(0);
	uint16 frame;
	if (_currentRoom == 108) {
		frame = 1;
	}
	else {
		frame = 33;
		if (joeFacing() == DIR_FRONT) {
			if (joePrevFacing() == DIR_BACK) {
				pbs->frameNum = 33 + FRAMES_JOE_XTRA;
				update();
			}
			frame = 34;
		}
		else if (joeFacing() == DIR_BACK) {
			if (joePrevFacing() == DIR_FRONT) {
				pbs->frameNum = 33 + FRAMES_JOE_XTRA;
				update();
			}
			frame = 35;
		}
		else if ((joeFacing() == DIR_LEFT && joePrevFacing() == DIR_RIGHT) 
			|| 	(joeFacing() == DIR_RIGHT && joePrevFacing() == DIR_LEFT)) {
			pbs->frameNum = 34 + FRAMES_JOE_XTRA;
			update();
		}
		pbs->frameNum = frame + FRAMES_JOE_XTRA;
		pbs->scale = joeScale();
		pbs->xflip = (joeFacing() == DIR_LEFT);
		update();
		joePrevFacing(joeFacing());
		switch (frame) {
		case 33:
			frame = 1;
			break;
		case 34:
			frame = 3;
			break;
		case 35:
			frame = 5;
			break;
		}
	}
	pbs->frameNum = 29 + FRAMES_JOE_XTRA;
	_graphics->bankUnpack(frame, pbs->frameNum, 7);
	return frame;
}


void Logic::joeGrab(uint16 state, uint16 speed) {

	StateGrab sg = State::findGrab(state);
	if (sg != STATE_GRAB_NONE) {
		joeGrabDirection(sg, speed);
	}
}


void Logic::joeGrabDirection(StateGrab grab, uint16 speed) {

	// if speed == 0, then keep Joe in position

	uint16 frame = 0;
	BobSlot *bobJoe = _graphics->bob(0);

	switch (grab) {
	case STATE_GRAB_NONE:
		break;

	case STATE_GRAB_MID:
		if (joeFacing() == DIR_BACK) {
			frame = 6;
		}
		else if (joeFacing() == DIR_FRONT) {
			frame = 4;
		}
		else {
			frame = 2;
		}
		break;

	case STATE_GRAB_DOWN:
		if (joeFacing() == DIR_BACK) {
			frame = 9;
		}
		else {
			frame = 8;
		}
		break;

	case STATE_GRAB_UP:
		// turn back
		_graphics->bankUnpack(5, 29 + FRAMES_JOE_XTRA, 7);
		bobJoe->xflip = (joeFacing() == DIR_LEFT);
		bobJoe->scale = joeScale();
		update();
		// grab up
		_graphics->bankUnpack(7, 29 + FRAMES_JOE_XTRA, 7);
		bobJoe->xflip = (joeFacing() == DIR_LEFT);
		bobJoe->scale = joeScale();
		update();
		// turn back
		if (speed == 0) {
			frame = 7;
		}
		else {
			frame = 5;
		}
		break;
	}

	if (frame != 0) {
		_graphics->bankUnpack(frame, 29 + FRAMES_JOE_XTRA, 7);
		bobJoe->xflip = (joeFacing() == DIR_LEFT);
		bobJoe->scale = joeScale();
		update();

		// extra delay for grab down
		if (grab == STATE_GRAB_DOWN) {
			update();
			update();
		}

		if (speed > 0) {
			joeFace();
		}
	}
}


void Logic::joeUseDress(bool showCut) {

	if (showCut) {
		joeFacing(DIR_FRONT);
		joeFace();
		if (gameState(VAR_DRESSING_MODE) == 0) {
			playCutaway("cdres.CUT");
			inventoryInsertItem(ITEM_CLOTHES);
		}
		else {
			playCutaway("cudrs.CUT");
		}
	}
	_display->palSetJoe(JP_DRESS);
	joeSetupFromBanks("JoeD_A.BBK", "JoeD_B.BBK");
	inventoryDeleteItem(ITEM_DRESS);
	gameState(VAR_DRESSING_MODE, 2);
}


void Logic::joeUseClothes(bool showCut) {

	if (showCut) {
		joeFacing(DIR_FRONT);
		joeFace();
		playCutaway("cdclo.CUT");
		inventoryInsertItem(ITEM_DRESS);
	}
	_display->palSetJoe(JP_CLOTHES);
	joeSetupFromBanks("Joe_A.BBK", "Joe_B.BBK");
	inventoryDeleteItem(ITEM_CLOTHES);
	gameState(VAR_DRESSING_MODE, 0);
}


void Logic::joeUseUnderwear() {

	_display->palSetJoe(JP_CLOTHES);
	joeSetupFromBanks("JoeU_A.BBK", "JoeU_B.BBK");
	gameState(VAR_DRESSING_MODE, 1);
}


void Logic::makePersonSpeak(const char *sentence, Person *person, const char *voiceFilePrefix) {

	_cmd->clear(false);
	Talk::speak(sentence, person, voiceFilePrefix, _graphics, _input, this, _resource, _sound);
}


void Logic::dialogue(const char *dlgFile, int personInRoom, char *cutaway) {

	char cutawayFile[20];
	if (cutaway == NULL) {
		cutaway = cutawayFile;
	}
	_display->fullscreen(true);
	Talk::talk(dlgFile, personInRoom, cutaway, _graphics, _input, this, _resource, _sound);
	if (!cutaway[0]) {
		_display->fullscreen(false);
	}
}


void Logic::playCutaway(const char *cutFile, char *next) {

	char nextFile[20];
	if (next == NULL) {
		next = nextFile;
	}
	_graphics->textClear(CmdText::COMMAND_Y_POS, CmdText::COMMAND_Y_POS);
	Cutaway::run(cutFile, next, _graphics, _input, this, _resource, _sound);
}


void Logic::joeSpeak(uint16 descNum, bool objectType) {

	// joeSpeak(k, false) == SPEAK(JOE_RESPstr[k],"JOE",find_cd_desc(k)) 
	// joeSpeak(k, true)  == SPEAK(OBJECT_DESCRstr[k],"JOE",find_cd_desc(JOERESPMAX+k))
	const char *text = objectType ? _objDescription[descNum] : _joeResponse[descNum];
	if (objectType) {
		descNum += JOE_RESPONSE_MAX;
	}
	char descFilePrefix[10];
	sprintf(descFilePrefix, "JOE%04i", descNum);
	makePersonSpeak(text, NULL, descFilePrefix);
}


Verb Logic::findVerbUnderCursor(int16 cursorx, int16 cursory) const {

	return Verb(PANEL_VERBS[zoneIn(ZONE_PANEL, cursorx, cursory)]);
}


uint16 Logic::findObjectUnderCursor(int16 cursorx, int16 cursory) const {

	uint16 roomObj = 0;
	if (cursory < ROOM_ZONE_HEIGHT) {
		int16 x = cursorx + _display->horizontalScroll();
		roomObj = zoneIn(ZONE_ROOM, x, cursory);
	}
	return roomObj;
}


uint16 Logic::findObjectRoomNumber(uint16 zoneNum) const {

	// l.316-327 select.c
	uint16 noun = zoneNum;
	uint16 objectMax = _objMax[_currentRoom];
	debug(0, "Logic::findObjectRoomNumber(%X, %X)", zoneNum, objectMax);
	if (zoneNum > objectMax) {
		// this is an area box, check for associated object
		uint16 obj = currentRoomArea(zoneNum - objectMax)->object;
		if (obj != 0 && objectData(obj)->name != 0) {
			// there is an object, get its number
			noun = obj - _roomData[_currentRoom];
		}
	}
	return noun;
}


uint16 Logic::findObjectGlobalNumber(uint16 zoneNum) const {

	return _roomData[_currentRoom] + findObjectRoomNumber(zoneNum);
}


uint16 Logic::findInventoryItem(int invSlot) const {
	// queen.c l.3894-3898
	if (invSlot >= 0 && invSlot < 4) {
		return _inventoryItem[invSlot];
	}
	return 0;
}


void Logic::inventorySetup() {

	_graphics->bankLoad("objects.BBK", 14);
	_inventoryItem[0] = ITEM_BAT;
	_inventoryItem[1] = ITEM_JOURNAL;
	_inventoryItem[2] = ITEM_NONE;
	_inventoryItem[3] = ITEM_NONE;
}

void Logic::inventoryRefresh() {

	int16 i;
	uint16 x = 182;
	for (i = 0; i < 4; ++i) {
		uint16 itemNum = _inventoryItem[i];
		if (itemNum != 0) {
			// 1st object in inventory uses frame 8, 
			// whereas 2nd, 3rd and 4th uses frame 9
			uint16 dstFrame = (itemNum != 0) ? 8 : 9;
			// unpack frame for object and draw it
			_graphics->bankUnpack(_itemData[itemNum].frame, dstFrame, 14);
			_graphics->bobDrawInventoryItem(dstFrame, x, 14);
		}
		else {
			// no object, clear the panel 
			_graphics->bobDrawInventoryItem(0, x, 14);
		}
		x += 35;
	}
	// XXX OLDVERB=VERB;
	update();
}

int16 Logic::previousInventoryItem(int16 start) const {
	int i;
	for (i = start - 1; i >= 1; i--)
		if (_itemData[i].name > 0)
			return i;
	for (i = _numItems; i > start; i--)
		if (_itemData[i].name > 0)
			return i;

	return 0;	//nothing found
}

int16 Logic::nextInventoryItem(int16 start) const {
	int i;
	for (i = start + 1; i < _numItems; i++)
		if (_itemData[i].name > 0)
			return i;
	for (i = 1; i < start; i++)
		if (_itemData[i].name > 0)
			return i;

	return 0;	//nothing found
}

void Logic::removeDuplicateItems() {
	for (int i = 0; i < 4; i++)
		for (int j = i + 1; j < 4; j++)
			if (_inventoryItem[i] == _inventoryItem[j])
				_inventoryItem[j] = ITEM_NONE;
}

uint16 Logic::numItemsInventory() const {
	uint16 count = 0;
	for (int i = 1; i < _numItems; i++)
		if (_itemData[i].name > 0)
			count++;

	return count;
}

void Logic::inventoryInsertItem(uint16 itemNum, bool refresh) {
	int16 item = _inventoryItem[0] = (int16)itemNum; 
	_itemData[itemNum].name = ABS(_itemData[itemNum].name);	//set visible
	for (int i = 1; i < 4; i++) {
		item = nextInventoryItem(item);
		_inventoryItem[i] = item;
		removeDuplicateItems();
	}

	if (refresh)
		inventoryRefresh();
}


void Logic::inventoryDeleteItem(uint16 itemNum, bool refresh) {
	int16 item = (int16)itemNum;
	_itemData[itemNum].name = -ABS(_itemData[itemNum].name);	//set invisible
	for (int i = 0; i < 4; i++) {
		item = nextInventoryItem(item);
		_inventoryItem[i] = item;
		removeDuplicateItems();
	}

	if (refresh)
		inventoryRefresh();
}


void Logic::inventoryScroll(uint16 count, bool up) {
	if (!(numItemsInventory() > 4))
		return;

	if (up) {
		for (int i = 3; i > 0; i--)
			_inventoryItem[i] = _inventoryItem[i - 1];
		_inventoryItem[0] = previousInventoryItem(_inventoryItem[0]);
	} else {
		for (int i = 0; i < 3; i++)
			_inventoryItem[i] = _inventoryItem[i + 1];
		_inventoryItem[3] = nextInventoryItem(_inventoryItem[3]);		
	}

	inventoryRefresh();
}


void Logic::objectCopy(int dummyObjectIndex, int realObjectIndex) {
	// P3_COPY_FROM function in cutaway.c
	/* Copy data from Dummy (D) object to object (K)
		 If COPY_FROM Object images are greater than COPY_TO Object
		 images then swap the objects around. */

	ObjectData *dummyObject = objectData(dummyObjectIndex);
	ObjectData *realObject  = objectData(realObjectIndex);
	
	int fromState = (dummyObject->name < 0) ? -1 : 0;

	int frameCountReal  = 1;
	int frameCountDummy = 1;

	int graphic = realObject->image;
	if (graphic > 0) {
		if (graphic > 5000)
			graphic -= 5000;

		GraphicData *data = graphicData(graphic);

		if (data->lastFrame > 0) 
			frameCountReal = data->lastFrame - data->firstFrame + 1;

		graphic = dummyObject->image;
		if (graphic > 0) {
			if (graphic > 5000)
				graphic -= 5000;

			data = graphicData(graphic);

			if (data->lastFrame > 0) 
				frameCountDummy = data->lastFrame - data->firstFrame + 1;
		}
	}

	ObjectData temp = *realObject;
	*realObject = *dummyObject;

	if (frameCountDummy > frameCountReal)
		*dummyObject = temp;

	realObject->name = ABS(realObject->name);

	if  (fromState == -1)
		dummyObject->name = -ABS(dummyObject->name);

	//  Make sure that WALK_OFF_DATA is copied too!

	for (int i = 1; i <= _numWalkOffs; i++) {
		WalkOffData *walkOff = &_walkOffData[i];
		if (walkOff->entryObj == (int16)dummyObjectIndex) {
			walkOff->entryObj = (int16)realObjectIndex;
			break;
		}
	}

}


void Logic::checkPlayer() {
	update();
	_cmd->updatePlayer();
}


void Logic::customMoveJoe(int facing, uint16 areaNum, uint16 walkDataNum) {

	// queen.c l.2838-2911
	debug(9, "customMoveJoe(%d, %d, %d)\n", facing, areaNum, walkDataNum);

	// Stop animating Joe
	_graphics->bob(0)->animating = false;

	// Make Joe face the right direction
	joeFacing(facing);
	joeFace();

	_newRoom = 0;
	_entryObj = 0;

	char nextCut[20];
	memset(nextCut, 0, sizeof(nextCut));

	switch (_currentRoom) {
	case ROOM_JUNGLE_BRIDGE:
		joeSpeak(16);
		break;
	case ROOM_JUNGLE_GORILLA_1:
		playCutaway("c6c.CUT", nextCut);
		break;
	case ROOM_JUNGLE_GORILLA_2:
		playCutaway("c14b.CUT", nextCut);
		break;
	case ROOM_AMAZON_ENTRANCE:
		if (areaNum == 3) {
			playCutaway("c16a.CUT", nextCut);
		}
		break;
	case ROOM_AMAZON_HIDEOUT:
		if (walkDataNum == 4) {
			playCutaway("c17a.CUT", nextCut);
		}
		else if (walkDataNum == 2) {
			playCutaway("c17b.CUT", nextCut);
		}
		break;
	case ROOM_FLODA_OUTSIDE:
		playCutaway("c22a.CUT", nextCut);
		break;
	case ROOM_FLODA_KITCHEN:
		playCutaway("c26b.CUT", nextCut);
		break;
	case ROOM_FLODA_KLUNK:
		playCutaway("c30a.CUT", nextCut);
		break;
	case ROOM_FLODA_HENRY:
		playCutaway("c32c.CUT", nextCut);
		break;
	case ROOM_TEMPLE_ZOMBIES:
		if (areaNum == 6) {
			if (_gameState[21] == 0) {
				playCutaway("c50d.CUT", nextCut);
				while (nextCut[0] != '\0') {
					playCutaway(nextCut, nextCut);
				}
				_gameState[21] = 1;
			} else {
				playCutaway("c50h.CUT", nextCut);
			}
		}
		break;
	case ROOM_TEMPLE_SNAKE:
		playCutaway("c53b.CUT", nextCut);
		break;
	case ROOM_TEMPLE_LIZARD_LASER:
		joeSpeak(19);
		break;
	case ROOM_HOTEL_DOWNSTAIRS:
		joeSpeak(21);
		break;
	case ROOM_HOTEL_LOBBY:
		if (_gameState[VAR_ESCAPE_FROM_HOTEL_COUNT] == 0) {
			playCutaway("c73a.CUT"); 
			_gameState[VAR_ESCAPE_FROM_HOTEL_COUNT] = 1;
			joeUseUnderwear();
			joeFace();
		}
		else if (_gameState[VAR_ESCAPE_FROM_HOTEL_COUNT] == 1) {
			playCutaway("c73b.CUT");
			_gameState[VAR_ESCAPE_FROM_HOTEL_COUNT] = 2;
		}
		else if (_gameState[VAR_ESCAPE_FROM_HOTEL_COUNT] == 2) {
			playCutaway("c73c.CUT");
		}
		break;
	case ROOM_TEMPLE_MAZE_5:
		if (areaNum == 7) {
			joeSpeak(17);
		}
		break;
	case ROOM_TEMPLE_MAZE_6:
		if (areaNum == 5 && _gameState[187] == 0) {
			playCutaway("c101b.CUT", nextCut);
		}
		break;
	case ROOM_FLODA_FRONTDESK:
		if (areaNum == 3) {
			if (_gameState[VAR_BYPASS_FLODA_RECEPTIONIST] == 1) {
				playCutaway("c103e.CUT", nextCut);
			}
			else if (_gameState[VAR_BYPASS_FLODA_RECEPTIONIST] == 0) {
				playCutaway("c103b.CUT", nextCut);
				_gameState[VAR_BYPASS_FLODA_RECEPTIONIST] = 1;
			}
		}
		break;
	}

	while (strlen(nextCut) > 4 && 
		scumm_stricmp(nextCut + strlen(nextCut) - 4, ".cut") == 0) {
		playCutaway(nextCut, nextCut);
	}
}


void Logic::handlePinnacleRoom() {

	// camera does not follow Joe anymore
	_graphics->cameraBob(-1);
	roomDisplay(ROOM_JUNGLE_PINNACLE, RDM_NOFADE_JOE, 100, 2, true);

	BobSlot *joe   = _graphics->bob(6);
	BobSlot *piton = _graphics->bob(7);

	// set scrolling value to mouse position to avoid glitch
	_display->horizontalScroll(_input->mousePosX());

	joe->x = piton->x = 3 * _input->mousePosX() / 4 + 200;

	joe->frameNum = _input->mousePosX() / 36 + 43 + FRAMES_JOE_XTRA;

	// adjust bounding box for fullscreen
	joe->box.y2 = piton->box.y2 = GAME_SCREEN_HEIGHT - 1;

	// bobs have been unpacked from animating objects, we don't need them
	// to animate anymore ; so turn animating off
	joe->animating = piton->animating = false;

	update();
	_display->palFadeIn(0, 223, ROOM_JUNGLE_PINNACLE, joe->active, joe->x, joe->y);

	_entryObj = 0;
	uint16 prevObj = 0;
	while (_input->mouseButton() == 0 || _entryObj == 0) {

		update();
		int mx = _input->mousePosX();
		int my = _input->mousePosY();

		// update screen scrolling
		_display->horizontalScroll(_input->mousePosX());

		// update bobs position / frame
		joe->x = piton->x = 3 * mx / 4 + 200;
		joe->frameNum = mx / 36 + 43 + FRAMES_JOE_XTRA;

		uint16 curObj = findObjectUnderCursor(mx, my);
		if (curObj != 0 && curObj != prevObj) {
			_entryObj = 0;
			curObj += _roomData[_currentRoom]; // global object number
			ObjectData *objData = &_objectData[curObj];
			if (objData->name > 0) {
				_entryObj = objData->entryObj;
				char textCmd[CmdText::MAX_COMMAND_LEN];
				sprintf(textCmd, "%s %s", Verb(VERB_WALK_TO).name(), _objName[objData->name]);
				_graphics->textCurrentColor(INK_MAP7);
				_graphics->textSetCentered(5, textCmd);
			}
			prevObj = curObj;
		}
	}
	_input->clearMouseButton();

	_newRoom = _objectData[_entryObj].room;

	// Only a few commands can be triggered from this room :
	// piton -> crash  : 0x216 (obj=0x2a, song=3)
	// piton -> floda  : 0x217 (obj=0x29, song=16)
	// piton -> bob    : 0x219 (obj=0x2f, song=6)
	// piton -> embark : 0x218 (obj=0x2c, song=7)
	// piton -> jungle : 0x20B (obj=0x2b, song=3)
	// piton -> amazon : 0x21A (obj=0x30, song=3)
	// 
	// Because none of these update objects/areas/gamestate, the EXECUTE_ACTION()
	// call, as the original does, is useless. All we have to do is the playsong 
	// call (all songs have the PLAY_BEFORE type). This way we could get rid of 
	// the hack described in execute.c l.334-339.
	//
	// XXX if (com->song > 0) { playsong(com->song); }

	joe->active = piton->active = false;
	_graphics->textClear(5, 5);

	// camera follows Joe again
	_graphics->cameraBob(0);

	_display->palFadeOut(0, 223, ROOM_JUNGLE_PINNACLE);
}


void Logic::update() {
	_graphics->update(_currentRoom);
	_input->delay();
	_display->palCustomScroll(_currentRoom);
	BobSlot *joe = _graphics->bob(0);
	_display->update(joe->active, joe->x, joe->y);
	_dbg->update(_input->checkKeys());

	if (_input->quickSave())
		if (!_input->cutawayRunning()) {
			_input->quickSaveReset();
			gameSave(0, "Quicksave");
		}
	if (_input->quickLoad())
		if (!_input->cutawayRunning()) {
			_input->quickLoadReset();
			gameLoad(0);
		}
}

bool Logic::gameSave(uint16 slot, const char *desc) {
	if (!desc)	//no description entered
		return false;

	debug(3, "Saving game to slot %d", slot);
	
	int i, j;
	char *buf = new char[32];
	memcpy(buf, desc, strlen(desc) < 32 ? strlen(desc) : 32);
	for (i = strlen(desc); i < 32; i++)
		buf[i] = '\0';
	byte *saveData = new byte[SAVEGAME_SIZE];
	byte *ptr = saveData;
	memcpy(ptr, buf, 32); ptr += 32;
	delete[] buf;
	
	WRITE_BE_UINT16(ptr, _settings.talkSpeed); ptr += 2;
	WRITE_BE_UINT16(ptr, _settings.musicVolume); ptr += 2;
	WRITE_BE_UINT16(ptr, _sound->sfxOn() ? 1 : 0); ptr += 2;
	WRITE_BE_UINT16(ptr, _sound->speechOn() ? 1 : 0); ptr += 2;
	WRITE_BE_UINT16(ptr, _sound->musicOn() ? 1 : 0); ptr += 2;
	WRITE_BE_UINT16(ptr, _settings.textToggle ? 1 : 0); ptr += 2;
	
	for (i = 0; i < 4; i++) {
		WRITE_BE_UINT16(ptr, _inventoryItem[i]); ptr += 2;
	}
	
	WRITE_BE_UINT16(ptr, _graphics->bob(0)->x); ptr += 2;
	WRITE_BE_UINT16(ptr, _graphics->bob(0)->y); ptr += 2;
	WRITE_BE_UINT16(ptr, _currentRoom); ptr += 2;

	for (i = 1; i <= _numObjects; i++)
		_objectData[i].writeTo(ptr);
		
	for (i = 1; i <= _numItems; i++)
		_itemData[i].writeTo(ptr);
		
	for (i = 0; i < GAME_STATE_COUNT; i++) {
		WRITE_BE_UINT16(ptr, gameState(i)); ptr += 2;
	}
	
	for (i = 1; i <= _numRooms; i++)
		for (j = 1; j <= _areaMax[i]; j++)
			_area[i][j].writeTo(ptr);
			
	for (i = 0; i < TALK_SELECTED_COUNT; i++)
			_talkSelected[i].writeTo(ptr);
	
	for (i = 1; i <= _numWalkOffs; i++)
		_walkOffData[i].writeTo(ptr);

	WRITE_BE_UINT16(ptr, _joe.facing); ptr += 2;
	WRITE_BE_UINT16(ptr, 0); ptr += 2; //TODO: tmpbamflag
	WRITE_BE_UINT16(ptr, 0); ptr += 2; //TODO: lastoverride
	
	//TODO: lastmerge, lastalter, altmrgpri
	for (i = 0; i < 3; i++) {
		WRITE_BE_UINT16(ptr, 0); ptr += 2;
	}
	
	if ((ptr - saveData) != SAVEGAME_SIZE) {
		delete[] saveData;
		return false;
	}
	
	bool result = _resource->writeSave(slot, saveData, SAVEGAME_SIZE);
	delete[] saveData;
	
	return result;	
}

bool Logic::gameLoad(uint16 slot) {
	int i, j;
	byte *saveData = new byte[SAVEGAME_SIZE];
	byte *ptr = saveData;
	if (!_resource->readSave(slot, saveData)) {
		warning("Couldn't load savegame from slot %d", slot);
		delete[] saveData;
		return false;
	}
	
	debug(3, "Loading game from slot %d", slot);
	ptr += 32;	//skip description
	_settings.talkSpeed = (int16)READ_BE_UINT16(ptr); ptr += 2;
	_settings.musicVolume = (int16)READ_BE_UINT16(ptr); ptr += 2;
	_sound->sfxToggle(READ_BE_UINT16(ptr) != 0); ptr += 2;
	_sound->speechToggle(READ_BE_UINT16(ptr) != 0); ptr += 2;
	_sound->musicToggle(READ_BE_UINT16(ptr) != 0); ptr += 2;
	_settings.textToggle = READ_BE_UINT16(ptr) != 0; ptr += 2;

	for (i = 0; i < 4; i++) {
		_inventoryItem[i] = (int16)READ_BE_UINT16(ptr); ptr += 2;
	}

	_joe.x = (int16)READ_BE_UINT16(ptr); ptr += 2;
	_joe.y = (int16)READ_BE_UINT16(ptr); ptr += 2;

	currentRoom(READ_BE_UINT16(ptr)); ptr += 2;
	
	for (i = 1; i <= _numObjects; i++)
		_objectData[i].readFrom(ptr);

	for (i = 1; i <= _numItems; i++)
		_itemData[i].readFrom(ptr);

	for (i = 0; i < GAME_STATE_COUNT; i++) {
		gameState(i, (int16)READ_BE_UINT16(ptr)); ptr += 2;
	}

	for (i = 1; i <= _numRooms; i++)
		for (j = 1; j <= _areaMax[i]; j++)
			_area[i][j].readFrom(ptr);
	
	for (i = 0; i < TALK_SELECTED_COUNT; i++)
		_talkSelected[i].readFrom(ptr);
		
	for (i = 1; i <= _numWalkOffs; i++)
		_walkOffData[i].readFrom(ptr);

	joeFacing(READ_BE_UINT16(ptr));  ptr += 2;
	READ_BE_UINT16(ptr); ptr += 2;	//TODO: tmpbamflag
	READ_BE_UINT16(ptr); ptr += 2; //TODO: lastoverride
	//_sound->playSound(_sound->lastOverride())
	
	//TODO: lastmerge, lastalter, altmrgpri
	for (i = 0; i < 3; i++) {
		READ_BE_UINT16(ptr); ptr += 2;
	}

	if ((ptr - saveData) != SAVEGAME_SIZE) {
		delete[] saveData;
		return false;
	}
	
	joeCutFacing(joeFacing());
	joeFace();
	
	//OLDX = _joe.x;
	//OLDY = _joe.y;
	_oldRoom = 0;
	newRoom(_currentRoom);
	_entryObj = 0;

	switch (gameState(VAR_DRESSING_MODE)) {
		case  0: 
			joeUseClothes(false);
			break;
		case  1:
			joeUseUnderwear();
			break;
		case  2:
			joeUseDress(false);
			break;
	}
	inventoryRefresh();
	//bamflag = ..
	
	delete[] saveData;
	return true;
}

void Logic::sceneStart() {
	debug(0, "[Logic::sceneStart] _scene = %i", _scene);
	_scene++;

	_display->showMouseCursor(false);

	if (1 == _scene) { // && _input->cutawayRunning()) { // sceneStart is always called when cutaway is running
		_display->palFadePanel();
	}

	update();
}

void Logic::sceneStop() {
	debug(0, "[Logic::sceneStop] _scene = %i", _scene);
	_scene--;

	if (_scene > 0)
		return;

	_display->palSetAllDirty();
	_display->showMouseCursor(true);
	zoneSetupPanel();
}


void Logic::useJournal() {

	if (_resource->isDemo()) {
		makePersonSpeak("This is a demo, so I can't load or save games*14", NULL, "");
	}
	else {

		// XXX save some vars
		// 
		// XXX tmpbamflag=bamflag;
		// XXX bamflag=0;
		// XXX in_journal=1;

		_cmd->clear(false);

		Journal j(this, _graphics, _display, _sound, &_settings);
		j.use();

		_walk->stopJoe();

		// XXX restore vars
		// 
		// XXX in_journal=0;
		// XXX bamflag=tmpbamflag;
		// XXX TALKQUIT=CUTQUIT=0; Make sure that we turn off cut stuff in case we use Journal during cutaways

	}
}


} // End of namespace Queen