aboutsummaryrefslogtreecommitdiff
path: root/engines/mohawk/riven_external.cpp
blob: 5424a07a3ce4ad4c20a103a01f3d0638a2a9175e (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
/* 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$
 *
 */

#include "mohawk/cursors.h"
#include "mohawk/graphics.h"
#include "mohawk/riven.h"
#include "mohawk/riven_external.h"
#include "mohawk/sound.h"
#include "mohawk/video.h"

#include "gui/message.h"
#include "common/events.h"

namespace Mohawk {

static const uint32 kDomeSliderDefaultState = 0x01F00000;
static const uint32 kDomeSliderSlotCount = 25;

RivenExternal::RivenExternal(MohawkEngine_Riven *vm) : _vm(vm) {
	setupCommands();
	_sliderState = kDomeSliderDefaultState;
}

RivenExternal::~RivenExternal() {
	for (uint32 i = 0; i < _externalCommands.size(); i++)
		delete _externalCommands[i];

	_externalCommands.clear();
}

void RivenExternal::setupCommands() {
	// aspit (Main Menu, Books, Setup) external commands
	COMMAND(xastartupbtnhide);
	COMMAND(xasetupcomplete);
	COMMAND(xaatrusopenbook);
	COMMAND(xaatrusbookback);
	COMMAND(xaatrusbookprevpage);
	COMMAND(xaatrusbooknextpage);
	COMMAND(xacathopenbook);
	COMMAND(xacathbookback);
	COMMAND(xacathbookprevpage);
	COMMAND(xacathbooknextpage);
	COMMAND(xtrapbookback);
	COMMAND(xatrapbookclose);
	COMMAND(xatrapbookopen);
	COMMAND(xarestoregame);
	COMMAND(xadisablemenureturn);
	COMMAND(xaenablemenureturn);
	COMMAND(xalaunchbrowser);
	COMMAND(xadisablemenuintro);
	COMMAND(xaenablemenuintro);
	COMMAND(xademoquit);
	COMMAND(xaexittomain);

	// bspit (Bookmaking Island) external commands
	COMMAND(xblabopenbook);
	COMMAND(xblabbookprevpage);
	COMMAND(xblabbooknextpage);
	COMMAND(xsoundplug);
	COMMAND(xbchangeboiler);
	COMMAND(xbupdateboiler);
	COMMAND(xbsettrap);
	COMMAND(xbcheckcatch);
	COMMAND(xbait);
	COMMAND(xbfreeytram);
	COMMAND(xbaitplate);
	COMMAND(xbisland190_opencard);
	COMMAND(xbisland190_resetsliders);
	COMMAND(xbisland190_slidermd);
	COMMAND(xbisland190_slidermw);
	COMMAND(xbscpbtn);
	COMMAND(xbisland_domecheck);
	COMMAND(xvalvecontrol);
	COMMAND(xbchipper);

	// gspit (Garden Island) external commands
	COMMAND(xgresetpins);
	COMMAND(xgrotatepins);
	COMMAND(xgpincontrols);
	COMMAND(xgisland25_opencard);
	COMMAND(xgisland25_resetsliders);
	COMMAND(xgisland25_slidermd);
	COMMAND(xgisland25_slidermw);
	COMMAND(xgscpbtn);
	COMMAND(xgisland1490_domecheck);
	COMMAND(xgplateau3160_dopools);
	COMMAND(xgwt200_scribetime);
	COMMAND(xgwt900_scribe);
	COMMAND(xgplaywhark);
	COMMAND(xgrviewer);
	COMMAND(xgwharksnd);
	COMMAND(xglview_prisonoff);
	COMMAND(xglview_villageoff);
	COMMAND(xglviewer);
	COMMAND(xglview_prisonon);
	COMMAND(xglview_villageon);

	// jspit (Jungle Island) external commands
	COMMAND(xreseticons);
	COMMAND(xicon);
	COMMAND(xcheckicons);
	COMMAND(xtoggleicon);
	COMMAND(xjtunnel103_pictfix);
	COMMAND(xjtunnel104_pictfix);
	COMMAND(xjtunnel105_pictfix);
	COMMAND(xjtunnel106_pictfix);
	COMMAND(xvga1300_carriage);
	COMMAND(xjdome25_resetsliders);
	COMMAND(xjdome25_slidermd);
	COMMAND(xjdome25_slidermw);
	COMMAND(xjscpbtn);
	COMMAND(xjisland3500_domecheck);
	COMMAND(xhandlecontroldown);
	COMMAND(xhandlecontrolmid);
	COMMAND(xhandlecontrolup);
	COMMAND(xjplaybeetle_550);
	COMMAND(xjplaybeetle_600);
	COMMAND(xjplaybeetle_950);
	COMMAND(xjplaybeetle_1050);
	COMMAND(xjplaybeetle_1450);
	COMMAND(xjlagoon700_alert);
	COMMAND(xjlagoon800_alert);
	COMMAND(xjlagoon1500_alert);
	COMMAND(xschool280_playwhark);
	COMMAND(xjschool280_resetleft);
	COMMAND(xjschool280_resetright);
	COMMAND(xjatboundary);

	// ospit (Gehn's Office) external commands
	COMMAND(xorollcredittime);
	COMMAND(xbookclick);
	COMMAND(xooffice30_closebook);
	COMMAND(xobedroom5_closedrawer);
	COMMAND(xogehnopenbook);
	COMMAND(xogehnbookprevpage);
	COMMAND(xogehnbooknextpage);
	COMMAND(xgwatch);

	// pspit (Prison Island) external commands
	COMMAND(xpisland990_elevcombo);
	COMMAND(xpscpbtn);
	COMMAND(xpisland290_domecheck);
	COMMAND(xpisland25_opencard);
	COMMAND(xpisland25_resetsliders);
	COMMAND(xpisland25_slidermd);
	COMMAND(xpisland25_slidermw);

	// rspit (Rebel Age) external commands
	COMMAND(xrshowinventory);
	COMMAND(xrhideinventory);
	COMMAND(xrcredittime);
	COMMAND(xrwindowsetup);

	// tspit (Temple Island) external commands
	COMMAND(xtexterior300_telescopedown);
	COMMAND(xtexterior300_telescopeup);
	COMMAND(xtisland390_covercombo);
	COMMAND(xtatrusgivesbooks);
	COMMAND(xtchotakesbook);
	COMMAND(xthideinventory);
	COMMAND(xt7500_checkmarbles);
	COMMAND(xt7600_setupmarbles);
	COMMAND(xt7800_setup);
	COMMAND(xdrawmarbles);
	COMMAND(xtakeit);
	COMMAND(xtscpbtn);
	COMMAND(xtisland4990_domecheck);
	COMMAND(xtisland5056_opencard);
	COMMAND(xtisland5056_resetsliders);
	COMMAND(xtisland5056_slidermd);
	COMMAND(xtisland5056_slidermw);
	COMMAND(xtatboundary);

	// Common external commands
	COMMAND(xflies);
}

void RivenExternal::runCommand(uint16 argc, uint16 *argv) {
	Common::String externalCommandName = _vm->getName(ExternalCommandNames, argv[0]);

	for (uint16 i = 0; i < _externalCommands.size(); i++)
		if (externalCommandName == _externalCommands[i]->desc) {
			debug(0, "Running Riven External Command \'%s\'", externalCommandName.c_str());
			(this->*(_externalCommands[i]->proc)) (argv[1], argv[1] ? argv + 2 : NULL);
			return;
		}

	error("Unknown external command \'%s\'", externalCommandName.c_str());
}

void RivenExternal::runDemoBoundaryDialog() {
	GUI::MessageDialog dialog("Exploration beyond this point available only within the full version of\n"
							  "the game.");
	dialog.runModal();
}

void RivenExternal::runEndGame(uint16 video, uint32 delay) {
	_vm->_sound->stopAllSLST();
	_vm->_video->playMovieRiven(video);
	runCredits(video, delay);
}

void RivenExternal::runCredits(uint16 video, uint32 delay) {
	// Initialize our credits state
	_vm->_cursor->hideCursor();
	_vm->_gfx->beginCredits();
	uint nextCreditsFrameStart = 0;

	VideoHandle videoHandle = _vm->_video->findVideoHandleRiven(video);

	while (!_vm->shouldQuit() && _vm->_gfx->getCurCreditsImage() <= 320) {
		if (_vm->_video->getCurFrame(videoHandle) >= (int32)_vm->_video->getFrameCount(videoHandle) - 1) {
			if (nextCreditsFrameStart == 0) {
				// Set us up to start after delay ms
				nextCreditsFrameStart = _vm->_system->getMillis() + delay;
			} else if (_vm->_system->getMillis() >= nextCreditsFrameStart) {
				// the first two frames stay on for 5 seconds
				// the rest of the scroll updates happen at 30Hz
				if (_vm->_gfx->getCurCreditsImage() < 304)
					nextCreditsFrameStart = _vm->_system->getMillis() + 5000;
				else
					nextCreditsFrameStart = _vm->_system->getMillis() + 1000 / 30;

				_vm->_gfx->updateCredits();
			}
		} else if (_vm->_video->updateMovies())
			_vm->_system->updateScreen(); 

		Common::Event event;
		while (_vm->_system->getEventManager()->pollEvent(event))
			;

		_vm->_system->delayMillis(10);
	}

	_vm->setGameOver();
}

void RivenExternal::runDomeButtonMovie() {
	// This command just plays the video of the button moving down and up.
	_vm->_video->playMovieBlockingRiven(2);
}

void RivenExternal::runDomeCheck() {
	// Check if we clicked while the golden frame was showing

	VideoHandle video = _vm->_video->findVideoHandleRiven(1);
	assert(video != NULL_VID_HANDLE);

	int32 curFrame = _vm->_video->getCurFrame(video);
	int32 frameCount = _vm->_video->getFrameCount(video);

	// The final frame of the video is the 'golden' frame (double meaning: the
	// frame that is the magic one is the one with the golden symbol) but we
	// give a 3 frame leeway in either direction.
	if (frameCount - curFrame < 3 || curFrame < 3)
		*_vm->getVar("domecheck") = 1;
}

void RivenExternal::resetDomeSliders(uint16 soundId, uint16 startHotspot) {
	// The rightmost slider should move left until it finds the next slider,
	// then those two continue until they find the third slider. This continues
	// until all five sliders have returned their starting slots.
	byte slidersFound = 0;
	for (uint32 i = 0; i < kDomeSliderSlotCount; i++) {
		if (_sliderState & (1 << i)) {
			// A slider occupies this spot. Increase the number of sliders we
			// have found, but we're not doing any moving this iteration.
			slidersFound++;
		} else {
			// Move all the sliders we have found over one slot
			for (byte j = 0; j < slidersFound; j++) {
				_sliderState &= ~(1 << (i - j - 1));
				_sliderState |= 1 << (i - j);
			}

			// If we have at least one found slider, it has now moved
			// so we should redraw and play a tick sound
			if (slidersFound) {
				_vm->_sound->playSound(soundId);
				drawDomeSliders(startHotspot);
				_vm->_system->delayMillis(100);
			}
		}
	}

	// Sanity checks - the slider count should always be 5 and we should end up at
	// the default state after moving them all over.
	assert(slidersFound == 5);
	assert(_sliderState == kDomeSliderDefaultState);
}

void RivenExternal::checkDomeSliders(uint16 resetSlidersHotspot, uint16 openDomeHotspot) {
	// Let's see if we're all matched up...
	if (*_vm->getVar("adomecombo") == _sliderState) {
		// Set the button hotspot to the open dome hotspot
		_vm->_hotspots[resetSlidersHotspot].enabled = false;
		_vm->_hotspots[openDomeHotspot].enabled = true;
	} else {
		// Set the button hotspot to the reset sliders hotspot
		_vm->_hotspots[resetSlidersHotspot].enabled = true;
		_vm->_hotspots[openDomeHotspot].enabled = false;
	}
}

void RivenExternal::checkSliderCursorChange(uint16 startHotspot) {
	// Set the cursor based on _sliderState and what hotspot we're over
	for (uint16 i = 0; i < kDomeSliderSlotCount; i++) {
		if (_vm->_hotspots[i + startHotspot].rect.contains(_vm->_system->getEventManager()->getMousePos())) {
			if (_sliderState & (1 << (24 - i)))
				_vm->_cursor->setCursor(kRivenOpenHandCursor);
			else
				_vm->_cursor->setCursor(kRivenMainCursor);
			_vm->_system->updateScreen();
			break;
		}
	}
}

void RivenExternal::dragDomeSlider(uint16 soundId, uint16 resetSlidersHotspot, uint16 openDomeHotspot, uint16 startHotspot) {
	int16 foundSlider = -1;

	for (uint16 i = 0; i < kDomeSliderSlotCount; i++) {
		if (_vm->_hotspots[i + startHotspot].rect.contains(_vm->_system->getEventManager()->getMousePos())) {
			// If the slider is not at this hotspot, we can't do anything else
			if (!(_sliderState & (1 << (24 - i))))
				return;

			foundSlider = i;
			break;
		}
	}

	// We're not over any slider
	if (foundSlider < 0)
		return;

	// We've clicked down, so show the closed hand cursor
	_vm->_cursor->setCursor(kRivenClosedHandCursor);
	_vm->_system->updateScreen();

	bool done = false;
	while (!done) {
		Common::Event event;
		while (_vm->_system->getEventManager()->pollEvent(event)) {
			switch (event.type) {
			case Common::EVENT_MOUSEMOVE:
				if (foundSlider < 24 && !(_sliderState & (1 << (23 - foundSlider))) && _vm->_hotspots[foundSlider + startHotspot + 1].rect.contains(event.mouse)) {
					// We've moved the slider right one space
					_sliderState &= ~(_sliderState & (1 << (24 - foundSlider)));
					foundSlider++;
					_sliderState |= 1 << (24 - foundSlider);

					// Now play a click sound and redraw
					_vm->_sound->playSound(soundId);
					drawDomeSliders(startHotspot);
				} else if (foundSlider > 0 && !(_sliderState & (1 << (25 - foundSlider))) && _vm->_hotspots[foundSlider + startHotspot - 1].rect.contains(event.mouse)) {
					// We've moved the slider left one space
					_sliderState &= ~(_sliderState & (1 << (24 - foundSlider)));
					foundSlider--;
					_sliderState |= 1 << (24 - foundSlider);

					// Now play a click sound and redraw
					_vm->_sound->playSound(soundId);
					drawDomeSliders(startHotspot);
				} else
					_vm->_system->updateScreen(); // A normal update for the cursor
				break;
			case Common::EVENT_LBUTTONUP:
				done = true;
				break;
			default:
				break;
			}
		}
		_vm->_system->delayMillis(10);
	}

	// Check to see if we have the right combination
	checkDomeSliders(resetSlidersHotspot, openDomeHotspot);
}

void RivenExternal::drawDomeSliders(uint16 startHotspot) {
	Common::Rect dstAreaRect = Common::Rect(200, 250, 420, 319);

	// On pspit, the rect is different by two pixels
	// (alternatively, we could just use hotspot 3 here, but only on pspit is there a hotspot for this)
	if (_vm->getCurStack() == pspit)
		dstAreaRect.translate(-2, 0);

	// Find out bitmap id
	uint16 bitmapId = _vm->findResourceID(ID_TBMP, "*sliders*");

	for (uint16 i = 0; i < kDomeSliderSlotCount; i++) {
		Common::Rect srcRect = _vm->_hotspots[startHotspot + i].rect;
		srcRect.translate(-dstAreaRect.left, -dstAreaRect.top); // Adjust the rect so it's in the destination area

		Common::Rect dstRect = _vm->_hotspots[startHotspot + i].rect;

		if (_sliderState & (1 << (24 - i)))
			_vm->_gfx->drawImageRect(bitmapId, srcRect, dstRect);
		else
			_vm->_gfx->drawImageRect(bitmapId + 1, srcRect, dstRect);
	}

	_vm->_gfx->updateScreen();
}

// ------------------------------------------------------------------------------------
// aspit (Main Menu, Books, Setup) external commands
// ------------------------------------------------------------------------------------

void RivenExternal::xastartupbtnhide(uint16 argc, uint16 *argv) {
	// The original game hides the start/setup buttons depending on an ini entry.
	// It's safe to ignore this command.
}

void RivenExternal::xasetupcomplete(uint16 argc, uint16 *argv) {
	// The original game sets an ini entry to disable the setup button and use the
	// start button only. It's safe to ignore this part of the command.
	_vm->_sound->stopSound();
	_vm->changeToCard(1);
}

void RivenExternal::xaatrusopenbook(uint16 argc, uint16 *argv) {
	// Get the variable
	uint32 page = *_vm->getVar("aatruspage");

	// Set hotspots depending on the page
	if (page == 1) {
		_vm->_hotspots[1].enabled = false;
		_vm->_hotspots[2].enabled = false;
		_vm->_hotspots[3].enabled = true;
	} else {
		_vm->_hotspots[1].enabled = true;
		_vm->_hotspots[2].enabled = true;
		_vm->_hotspots[3].enabled = false;
	}

	// Draw the image of the page
	_vm->_gfx->drawPLST(page);
}

void RivenExternal::xaatrusbookback(uint16 argc, uint16 *argv) {
	// Return to where we were before entering the book
	_vm->changeToStack(*_vm->getVar("returnstackid"));
	_vm->changeToCard(*_vm->getVar("returncardid"));
}

void RivenExternal::xaatrusbookprevpage(uint16 argc, uint16 *argv) {
	// Get the page variable
	uint32 *page = _vm->getVar("aatruspage");

	// Decrement the page if it's not the first page
	if (*page == 1)
		return;
	(*page)--;

	// Play the page turning sound
	if (_vm->getFeatures() & GF_DEMO)
		_vm->_sound->playSound(4);
	else
		_vm->_sound->playSound(3);

	// Now update the screen :)
	_vm->_gfx->scheduleTransition(1);
	_vm->_gfx->updateScreen();
}

void RivenExternal::xaatrusbooknextpage(uint16 argc, uint16 *argv) {
	// Get the page variable
	uint32 *page = _vm->getVar("aatruspage");

	// Increment the page if it's not the last page
	if (((_vm->getFeatures() & GF_DEMO) && *page == 6) || *page == 10)
		return;
	(*page)++;

	// Play the page turning sound
	if (_vm->getFeatures() & GF_DEMO)
		_vm->_sound->playSound(5);
	else
		_vm->_sound->playSound(4);

	// Now update the screen :)
	_vm->_gfx->scheduleTransition(0);
	_vm->_gfx->updateScreen();
}

void RivenExternal::xacathopenbook(uint16 argc, uint16 *argv) {
	// Get the variable
	uint32 page = *_vm->getVar("acathpage");

	// Set hotspots depending on the page
	if (page == 1) {
		_vm->_hotspots[1].enabled = false;
		_vm->_hotspots[2].enabled = false;
		_vm->_hotspots[3].enabled = true;
	} else {
		_vm->_hotspots[1].enabled = true;
		_vm->_hotspots[2].enabled = true;
		_vm->_hotspots[3].enabled = false;
	}

	// Draw the image of the page
	_vm->_gfx->drawPLST(page);

	// Draw the white page edges
	if (page > 1 && page < 5)
		_vm->_gfx->drawPLST(50);
	else if (page > 5)
		_vm->_gfx->drawPLST(51);

	if (page == 28) {
		// Draw the telescope combination
		// The images for the numbers are tBMP's 13 through 17.
		// The start point is at (156, 247)
		uint32 teleCombo = *_vm->getVar("tcorrectorder");
		static const uint16 kNumberWidth = 32;
		static const uint16 kNumberHeight = 25;
		static const uint16 kDstX = 156;
		static const uint16 kDstY = 247;

		for (byte i = 0; i < 5; i++) {
			uint16 offset = (getComboDigit(teleCombo, i) - 1) * kNumberWidth;
			Common::Rect srcRect = Common::Rect(offset, 0, offset + kNumberWidth, kNumberHeight);
			Common::Rect dstRect = Common::Rect(i * kNumberWidth + kDstX, kDstY, (i + 1) * kNumberWidth + kDstX, kDstY + kNumberHeight);
			_vm->_gfx->drawImageRect(i + 13, srcRect, dstRect);
		}
	}
}

void RivenExternal::xacathbookback(uint16 argc, uint16 *argv) {
	// Return to where we were before entering the book
	_vm->changeToStack(*_vm->getVar("returnstackid"));
	_vm->changeToCard(*_vm->getVar("returncardid"));
}

void RivenExternal::xacathbookprevpage(uint16 argc, uint16 *argv) {
	// Get the variable
	uint32 *page = _vm->getVar("acathpage");

	// Increment the page if it's not the first page
	if (*page == 1)
		return;
	(*page)--;

	// Play the page turning sound
	_vm->_sound->playSound(5);

	// Now update the screen :)
	_vm->_gfx->scheduleTransition(3);
	_vm->_gfx->updateScreen();
}

void RivenExternal::xacathbooknextpage(uint16 argc, uint16 *argv) {
	// Get the variable
	uint32 *page = _vm->getVar("acathpage");

	// Increment the page if it's not the last page
	if (*page == 49)
		return;
	(*page)++;

	// Play the page turning sound
	_vm->_sound->playSound(6);

	// Now update the screen :)
	_vm->_gfx->scheduleTransition(2);
	_vm->_gfx->updateScreen();
}

void RivenExternal::xtrapbookback(uint16 argc, uint16 *argv) {
	// Return to where we were before entering the book
	*_vm->getVar("atrap") = 0;
	_vm->changeToStack(*_vm->getVar("returnstackid"));
	_vm->changeToCard(*_vm->getVar("returncardid"));
}

void RivenExternal::xatrapbookclose(uint16 argc, uint16 *argv) {
	// Close the trap book
	*_vm->getVar("atrap") = 0;

	// Play the page turning sound
	_vm->_sound->playSound(8);

	_vm->refreshCard();
}

void RivenExternal::xatrapbookopen(uint16 argc, uint16 *argv) {
	// Open the trap book
	*_vm->getVar("atrap") = 1;

	// Play the page turning sound
	_vm->_sound->playSound(9);

	_vm->refreshCard();
}

void RivenExternal::xarestoregame(uint16 argc, uint16 *argv) {
	// Launch the load game dialog
	_vm->runLoadDialog();
}

void RivenExternal::xadisablemenureturn(uint16 argc, uint16 *argv) {
	// This function would normally enable the Windows menu item for
	// returning to the main menu. Ctrl+r will do this instead.
	// The original also had this shortcut.
}

void RivenExternal::xaenablemenureturn(uint16 argc, uint16 *argv) {
	// This function would normally enable the Windows menu item for
	// returning to the main menu. Ctrl+r will do this instead.
	// The original also had this shortcut.
}

void RivenExternal::xalaunchbrowser(uint16 argc, uint16 *argv) {
	// Well, we can't launch a browser for obvious reasons ;)
	// The original text is as follows (for reference):

	// If you have an auto-dial configured connection to the Internet,
	// please select YES below.
	//
	// America Online and CompuServe users may experience difficulty. If
	// you find that you are unable to connect, please quit the Riven
	// Demo, launch your browser and type in the following URL:
	//
	//     www.redorb.com/buyriven
	//
	// Would you like to attempt to make the connection?
	//
	// [YES] [NO]

	GUI::MessageDialog dialog("At this point, the Riven Demo would\n"
							  "ask if you would like to open a web browser\n"
							  "to bring you to the Red Orb store to buy\n"
							  "the game. ScummVM cannot do that and\n"
							  "the site no longer exists.");
	dialog.runModal();
}

void RivenExternal::xadisablemenuintro(uint16 argc, uint16 *argv) {
	// This function would normally enable the Windows menu item for
	// playing the intro. Ctrl+p will play the intro movies instead.
	// The original also had this shortcut.

	// Hide the "exit" button here
	_vm->_gfx->hideInventory();
}

void RivenExternal::xaenablemenuintro(uint16 argc, uint16 *argv) {
	// This function would normally enable the Windows menu item for
	// playing the intro. Ctrl+p will play the intro movies instead.
	// The original also had this shortcut.

	// Show the "exit" button here
	_vm->_gfx->showInventory();
}

void RivenExternal::xademoquit(uint16 argc, uint16 *argv) {
	// Exactly as it says on the tin. In the demo, this function quits.
	_vm->setGameOver();
}

void RivenExternal::xaexittomain(uint16 argc, uint16 *argv) {
	// One could potentially implement this function, but there would be no
	// point. This function is only used in the demo's aspit card 9 update
	// screen script. However, card 9 is not accessible from the game without
	// jumping to the card and there's nothing going on in the card so it
	// never gets called. There's also no card 9 in the full game, so the
	// functionality of this card was likely removed before release. The
	// demo executable references some other external commands relating to
	// setting and getting the volume, as well as drawing the volume. I'd
	// venture to guess that this would have been some sort of options card
	// replaced with the Windows/Mac API in the final product.
	//
	// Yeah, this function is just dummied and holds a big comment ;)
}

// ------------------------------------------------------------------------------------
// bspit (Bookmaking Island) external commands
// ------------------------------------------------------------------------------------

void RivenExternal::xblabopenbook(uint16 argc, uint16 *argv) {
	// Get the variable
	uint32 page = *_vm->getVar("blabpage");

	// Draw the image of the page based on the blabbook variable
	_vm->_gfx->drawPLST(page);

	if (page == 14) {
		// Draw the dome combination
		// The images for the numbers are tBMP's 364 through 368
		// The start point is at (240, 82)
		uint32 domeCombo = *_vm->getVar("adomecombo");
		static const uint16 kNumberWidth = 32;
		static const uint16 kNumberHeight = 24;
		static const uint16 kDstX = 240;
		static const uint16 kDstY = 82;
		byte numCount = 0;

		for (int bitPos = 24; bitPos >= 0; bitPos--) {
			if (domeCombo & (1 << bitPos)) {
				uint16 offset = (24 - bitPos) * kNumberWidth;
				Common::Rect srcRect = Common::Rect(offset, 0, offset + kNumberWidth, kNumberHeight);
				Common::Rect dstRect = Common::Rect(numCount * kNumberWidth + kDstX, kDstY, (numCount + 1) * kNumberWidth + kDstX, kDstY + kNumberHeight);
				_vm->_gfx->drawImageRect(numCount + 364, srcRect, dstRect);
				numCount++;
			}
		}

		assert(numCount == 5); // Sanity check
	}
}

void RivenExternal::xblabbookprevpage(uint16 argc, uint16 *argv) {
	// Get the page variable
	uint32 *page = _vm->getVar("blabpage");

	// Decrement the page if it's not the first page
	if (*page == 1)
		return;
	(*page)--;

	// Play the page turning sound
	_vm->_sound->playSound(22);

	// Now update the screen :)
	_vm->_gfx->scheduleTransition(1);
	_vm->_gfx->updateScreen();
}

void RivenExternal::xblabbooknextpage(uint16 argc, uint16 *argv) {
	// Get the page variable
	uint32 *page = _vm->getVar("blabpage");

	// Increment the page if it's not the last page
	if (*page == 22)
		return;
	(*page)++;

	// Play the page turning sound
	_vm->_sound->playSound(23);

	// Now update the screen :)
	_vm->_gfx->scheduleTransition(0);
	_vm->_gfx->updateScreen();
}

void RivenExternal::xsoundplug(uint16 argc, uint16 *argv) {
	uint32 heat = *_vm->getVar("bheat");
	uint32 boilerInactive = *_vm->getVar("bcratergg");

	if (heat != 0)
		_vm->_sound->playSLST(1, _vm->getCurCard());
	else if (boilerInactive != 0)
		_vm->_sound->playSLST(2, _vm->getCurCard());
	else
		_vm->_sound->playSLST(3, _vm->getCurCard());
}

void RivenExternal::xbchangeboiler(uint16 argc, uint16 *argv) {
	uint32 heat = *_vm->getVar("bheat");
	uint32 water = *_vm->getVar("bblrwtr");
	uint32 platform = *_vm->getVar("bblrgrt");

	// Stop any background videos
	_vm->_video->stopVideos();

	if (argv[0] == 1) {
		// Water is filling/draining from the boiler
		if (water == 0) {
			if (platform == 1)
				_vm->_video->activateMLST(12, _vm->getCurCard());
			else
				_vm->_video->activateMLST(10, _vm->getCurCard());
		} else if (heat == 1) {
			if (platform == 1)
				_vm->_video->activateMLST(22, _vm->getCurCard());
			else
				_vm->_video->activateMLST(19, _vm->getCurCard());
		} else {
			if (platform == 1)
				_vm->_video->activateMLST(16, _vm->getCurCard());
			else
				_vm->_video->activateMLST(13, _vm->getCurCard());
		}
	} else if (argv[0] == 2 && water != 0) {
		if (heat == 1) {
			// Turning on the heat
			if (platform == 1)
				_vm->_video->activateMLST(23, _vm->getCurCard());
			else
				_vm->_video->activateMLST(20, _vm->getCurCard());
		} else {
			// Turning off the heat
			if (platform == 1)
				_vm->_video->activateMLST(18, _vm->getCurCard());
			else
				_vm->_video->activateMLST(15, _vm->getCurCard());
		}
	} else if (argv[0] == 3) {
		if (platform == 1) {
			// Lowering the platform
			if (water == 1) {
				if (heat == 1)
					_vm->_video->activateMLST(24, _vm->getCurCard());
				else
					_vm->_video->activateMLST(17, _vm->getCurCard());
			} else
				_vm->_video->activateMLST(11, _vm->getCurCard());
		} else {
			// Raising the platform
			if (water == 1) {
				if (heat == 1)
					_vm->_video->activateMLST(21, _vm->getCurCard());
				else
					_vm->_video->activateMLST(14, _vm->getCurCard());
			} else
				_vm->_video->activateMLST(9, _vm->getCurCard());
		}
	}

	if (argc > 1)
		_vm->_sound->playSLST(argv[1], _vm->getCurCard());
	else if (argv[0] == 2)
		_vm->_sound->playSLST(1, _vm->getCurCard());

	_vm->_cursor->setCursor(kRivenHideCursor);
	_vm->_video->playMovieBlockingRiven(11);
}

void RivenExternal::xbupdateboiler(uint16 argc, uint16 *argv) {
	uint32 heat = *_vm->getVar("bheat");
	uint32 platform = *_vm->getVar("bblrgrt");

	if (heat) {
		if (platform == 0) {
			_vm->_video->activateMLST(8, _vm->getCurCard());
			_vm->_video->playMovieRiven(8);
		} else {
			_vm->_video->activateMLST(7, _vm->getCurCard());
			_vm->_video->playMovieRiven(7);
		}
	} else {
		_vm->_video->disableMovieRiven(7);
		_vm->_video->disableMovieRiven(8);
	}
}

void RivenExternal::xbsettrap(uint16 argc, uint16 *argv) {
	// TODO: Set the Ytram trap
}

void RivenExternal::xbcheckcatch(uint16 argc, uint16 *argv) {
	// TODO: Check if we've caught a Ytram
}

void RivenExternal::xbait(uint16 argc, uint16 *argv) {
	// Set the cursor to the pellet
	_vm->_cursor->setCursor(kRivenPelletCursor);
	_vm->_system->updateScreen();

	// Loop until the player lets go (or quits)
	Common::Event event;
	bool mouseDown = true;
	while (mouseDown) {
		while (_vm->_system->getEventManager()->pollEvent(event)) {
			if (event.type == Common::EVENT_LBUTTONUP)
				mouseDown = false;
			else if (event.type == Common::EVENT_MOUSEMOVE)
				_vm->_system->updateScreen();
			else if (event.type == Common::EVENT_QUIT || event.type == Common::EVENT_RTL)
				return;
		}

		_vm->_system->delayMillis(10); // Take it easy on the CPU
	}

	// Set back the cursor
	_vm->_cursor->setCursor(kRivenMainCursor);
	_vm->_system->updateScreen();

	// Set the bait if we put it on the plate
	if (_vm->_hotspots[9].rect.contains(_vm->_system->getEventManager()->getMousePos())) {
		*_vm->getVar("bbait") = 1;
		_vm->_gfx->drawPLST(4);
		_vm->_gfx->updateScreen();
		_vm->_hotspots[3].enabled = false; // Disable bait hotspot
		_vm->_hotspots[9].enabled = true; // Enable baitplate hotspot
	}
}

void RivenExternal::xbfreeytram(uint16 argc, uint16 *argv) {
	// TODO: Play a random Ytram movie
}

void RivenExternal::xbaitplate(uint16 argc, uint16 *argv) {
	// Remove the pellet from the plate and put it in your hand
	_vm->_gfx->drawPLST(3);
	_vm->_cursor->setCursor(kRivenPelletCursor);
	_vm->_gfx->updateScreen();

	// Loop until the player lets go (or quits)
	Common::Event event;
	bool mouseDown = true;
	while (mouseDown) {
		while (_vm->_system->getEventManager()->pollEvent(event)) {
			if (event.type == Common::EVENT_LBUTTONUP)
				mouseDown = false;
			else if (event.type == Common::EVENT_MOUSEMOVE)
				_vm->_system->updateScreen();
			else if (event.type == Common::EVENT_QUIT || event.type == Common::EVENT_RTL)
				return;
		}

		_vm->_system->delayMillis(10); // Take it easy on the CPU
	}

	// Set back the cursor
	_vm->_cursor->setCursor(kRivenMainCursor);
	_vm->_system->updateScreen();

	// Set the bait if we put it on the plate, remove otherwise
	if (_vm->_hotspots[9].rect.contains(_vm->_system->getEventManager()->getMousePos())) {
		*_vm->getVar("bbait") = 1;
		_vm->_gfx->drawPLST(4);
		_vm->_gfx->updateScreen();
		_vm->_hotspots[3].enabled = false; // Disable bait hotspot
		_vm->_hotspots[9].enabled = true; // Enable baitplate hotspot
	} else {
		*_vm->getVar("bbait") = 0;
		_vm->_hotspots[3].enabled = true; // Enable bait hotspot
		_vm->_hotspots[9].enabled = false; // Disable baitplate hotspot
	}
}

void RivenExternal::xbisland190_opencard(uint16 argc, uint16 *argv) {
	checkDomeSliders(27, 28);
}

void RivenExternal::xbisland190_resetsliders(uint16 argc, uint16 *argv) {
	resetDomeSliders(41, 2);
}

void RivenExternal::xbisland190_slidermd(uint16 argc, uint16 *argv) {
	dragDomeSlider(41, 27, 28, 2);
}

void RivenExternal::xbisland190_slidermw(uint16 argc, uint16 *argv) {
	checkSliderCursorChange(2);
}

void RivenExternal::xbscpbtn(uint16 argc, uint16 *argv) {
	runDomeButtonMovie();
}

void RivenExternal::xbisland_domecheck(uint16 argc, uint16 *argv) {
	runDomeCheck();
}

void RivenExternal::xvalvecontrol(uint16 argc, uint16 *argv) {
	Common::Point startPos = _vm->_system->getEventManager()->getMousePos();

	// Get the variable for the valve
	uint32 *valve = _vm->getVar("bvalve");

	int changeX = 0;
	int changeY = 0;
	bool done = false;

	// Set the cursor to the closed position
	_vm->_cursor->setCursor(kRivenClosedHandCursor);
	_vm->_system->updateScreen();

	while (!done) {
		Common::Event event;

		while (_vm->_system->getEventManager()->pollEvent(event)) {
			switch (event.type) {
			case Common::EVENT_MOUSEMOVE:
				changeX = event.mouse.x - startPos.x;
				changeY = startPos.y - event.mouse.y;
				_vm->_system->updateScreen();
				break;
			case Common::EVENT_LBUTTONUP:
				// FIXME: These values for changes in x/y could be tweaked.
				if (*valve == 0 && changeY <= -10) {
					*valve = 1;
					_vm->_cursor->setCursor(kRivenHideCursor);
					_vm->_system->updateScreen();
					_vm->_video->playMovieBlockingRiven(2);
					_vm->refreshCard();
				} else if (*valve == 1) {
					if (changeX >= 0 && changeY >= 10) {
						*valve = 0;
						_vm->_cursor->setCursor(kRivenHideCursor);
						_vm->_system->updateScreen();
						_vm->_video->playMovieBlockingRiven(3);
						_vm->refreshCard();
					} else if (changeX <= -10 && changeY <= 10) {
						*valve = 2;
						_vm->_cursor->setCursor(kRivenHideCursor);
						_vm->_system->updateScreen();
						_vm->_video->playMovieBlockingRiven(1);
						_vm->refreshCard();
					}
				} else if (*valve == 2 && changeX >= 10) {
					*valve = 1;
					_vm->_cursor->setCursor(kRivenHideCursor);
					_vm->_system->updateScreen();
					_vm->_video->playMovieBlockingRiven(4);
					_vm->refreshCard();
				}
				done = true;
			default:
				break;
			}
		}
		_vm->_system->delayMillis(10);
	}

	// If we changed state and the new state is that the valve is flowing to
	// the boiler, we need to update the boiler state.
	if (*valve == 1) {
		if (*_vm->getVar("bidvlv") == 1) { // Check which way the water is going at the boiler
			if (*_vm->getVar("bblrarm") == 1) {
				// If the pipe is open, make sure the water is drained out
				*_vm->getVar("bheat") = 0;
				*_vm->getVar("bblrwtr") = 0;
			} else {
				// If the pipe is closed, fill the boiler again
				*_vm->getVar("bheat") = *_vm->getVar("bblrvalve");
				*_vm->getVar("bblrwtr") = 1;
			}
		} else {
			// Have the grating inside the boiler match the switch outside
			*_vm->getVar("bblrgrt") = (*_vm->getVar("bblrsw") == 1) ? 0 : 1;
		}
	}
}

void RivenExternal::xbchipper(uint16 argc, uint16 *argv) {
	// Why is this an external command....?
	if (*_vm->getVar("bvalve") == 2)
		_vm->_video->playMovieBlockingRiven(2);
}

// ------------------------------------------------------------------------------------
// gspit (Garden Island) external commands
// ------------------------------------------------------------------------------------

void RivenExternal::lowerPins() {
	// Lower the pins

	uint32 *pinUp = _vm->getVar("gpinup");

	if (*pinUp == 0)
		return;

	uint32 *pinPos = _vm->getVar("gpinpos");
	uint32 startTime = (*pinPos - 1) * 600 + 4830;
	*pinUp = 0;

	// Play the down sound
	_vm->_sound->playSound(13);

	uint32 *upMovie = _vm->getVar("gupmoov");

	// Play the video of the pins going down
	VideoHandle handle = _vm->_video->playMovieRiven(*upMovie);
	assert(handle != NULL_VID_HANDLE);
	_vm->_video->setVideoBounds(handle, Audio::Timestamp(0, startTime, 600), Audio::Timestamp(0, startTime + 550, 600));
	_vm->_video->waitUntilMovieEnds(handle);

	*upMovie = 0;
}

void RivenExternal::xgresetpins(uint16 argc, uint16 *argv) {
	// As the function name suggests, this resets the pins
	lowerPins();
	*_vm->getVar("gupmoov") = 0;
}

void RivenExternal::xgrotatepins(uint16 argc, uint16 *argv) {
	// Rotate the pins, if necessary

	if (*_vm->getVar("gpinup") == 0)
		return;

	uint32 *pinPos = _vm->getVar("gpinpos");
	uint32 startTime = (*pinPos - 1) * 1200;

	if (*pinPos == 4)
		*pinPos = 1;
	else
		*pinPos += 1;

	// Play the rotating sound
	_vm->_sound->playSound(12);

	// Play the video of the pins rotating
	VideoHandle handle = _vm->_video->playMovieRiven(*_vm->getVar("gupmoov"));
	assert(handle != NULL_VID_HANDLE);
	_vm->_video->setVideoBounds(handle, Audio::Timestamp(0, startTime, 600), Audio::Timestamp(0, startTime + 1215, 600));
	_vm->_video->waitUntilMovieEnds(handle);
}

void RivenExternal::xgpincontrols(uint16 argc, uint16 *argv) {
	// Handle a click on a section of an island

	// Get our mouse position and adjust it to the beginning of the hotspot
	Common::Point mousePos = _vm->_system->getEventManager()->getMousePos();
	mousePos.x -= _vm->_hotspots[3].rect.left;
	mousePos.y -= _vm->_hotspots[3].rect.top;

	// And now adjust it to which box we hit
	mousePos.x /= 10;
	mousePos.y /= 11;

	// Lastly, adjust it based on the rotational position
	uint32 pinPos = *_vm->getVar("gpinpos");
	switch (pinPos) {
	case 1:
		mousePos.x = 5 - mousePos.x;
		mousePos.y = (4 - mousePos.y) * 5;
		break;
	case 2:
		mousePos.x = (4 - mousePos.x) * 5;
		mousePos.y = 1 + mousePos.y;
		break;
	case 3:
		mousePos.x = 1 + mousePos.x;
		mousePos.y = mousePos.y * 5;
		break;
	case 4:
		mousePos.x = mousePos.x * 5;
		mousePos.y = 5 - mousePos.y;
		break;
	default:
		// (Should never happen)
		error("Bad pin pos");
	}

	// Now check to see if this section of the island exists
	uint32 islandIndex = *_vm->getVar("glkbtns") - 1;
	uint16 imagePos = mousePos.x + mousePos.y;

	static const uint16 islandImages[5][11] = {
		{ 1, 2, 6, 7 },
		{ 11, 16, 21, 22 },
		{ 12, 13, 14, 15, 17, 18, 19, 20, 23, 24, 25 },
		{ 5 },
		{ 3, 4, 8, 9, 10 }
	};

	// The scripts set gimagemax to hold the max pin array length in islandPins above
	uint32 imageCount = *_vm->getVar("gimagemax");
	uint32 image = 0;
	for (; image < imageCount; image++)
		if (islandImages[islandIndex][image] == imagePos)
			break;

	// If we past it, we don't have a valid map coordinate
	if (image == imageCount)
		return;

	uint32 *pinUp = _vm->getVar("gpinup");
	uint32 *curImage = _vm->getVar("gimagecurr");

	// Lower the pins if they are currently raised
	if (*pinUp == 1) {
		lowerPins();

		// If we just lowered the selected section, don't raise it up again
		if (*curImage == image)
			return;
	}

	// Raise the pins by translating the position to the movie code
	static const uint16 pinMovieCodes[] = { 1, 2, 1, 2, 1, 3, 4, 3, 4, 5, 1, 1, 2, 3, 4, 2, 5, 6, 7, 8, 3, 4, 9, 10, 11 };

	// Play the up sound
	_vm->_sound->playSound(14);

	// Actually play the movie
	VideoHandle handle = _vm->_video->playMovieRiven(pinMovieCodes[imagePos - 1]);
	assert(handle != NULL_VID_HANDLE);
	uint32 startTime = 9630 - pinPos * 600;
	_vm->_video->setVideoBounds(handle, Audio::Timestamp(0, startTime, 600), Audio::Timestamp(0, startTime + 550, 600));
	_vm->_video->waitUntilMovieEnds(handle);

	// Update the relevant variables
	*_vm->getVar("gupmoov") = pinMovieCodes[imagePos - 1];
	*pinUp = 1;
	*curImage = image;
}

void RivenExternal::xgisland25_opencard(uint16 argc, uint16 *argv) {
	checkDomeSliders(28, 29);
}

void RivenExternal::xgisland25_resetsliders(uint16 argc, uint16 *argv) {
	resetDomeSliders(16, 2);
}

void RivenExternal::xgisland25_slidermd(uint16 argc, uint16 *argv) {
	dragDomeSlider(16, 28, 29, 2);
}

void RivenExternal::xgisland25_slidermw(uint16 argc, uint16 *argv) {
	checkSliderCursorChange(2);
}

void RivenExternal::xgscpbtn(uint16 argc, uint16 *argv) {
	runDomeButtonMovie();
}

void RivenExternal::xgisland1490_domecheck(uint16 argc, uint16 *argv) {
	runDomeCheck();
}

void RivenExternal::xgplateau3160_dopools(uint16 argc, uint16 *argv) {
	// Play the deactivation of a pool if one is active and a different one is activated
	_vm->_cursor->setCursor(kRivenHideCursor);
	_vm->_system->updateScreen();
	_vm->_video->playMovieBlockingRiven(*_vm->getVar("glkbtns") * 2);
}

void RivenExternal::xgwt200_scribetime(uint16 argc, uint16 *argv) {
	// Get the current time
	*_vm->getVar("gscribetime") = _vm->_system->getMillis();
}

void RivenExternal::xgwt900_scribe(uint16 argc, uint16 *argv) {
	uint32 *scribeVar = _vm->getVar("gscribe");

	if (*scribeVar == 1 && _vm->_system->getMillis() > *_vm->getVar("gscribetime") + 40000)
		*scribeVar = 2;
}

static const uint16 s_viewerTimeIntervals[] = { 0, 816, 1617, 2416, 3216, 4016, 4816, 5616, 6416, 7216, 8016, 8816 };

void RivenExternal::xgrviewer(uint16 argc, uint16 *argv) {
	// This controls the viewer on the right side of the 'throne' on Garden Island
	// (It shows the colors of the marbles)

	// If the light is on, turn it off
	uint32 *viewerLight = _vm->getVar("grview");
	if (*viewerLight == 1) {
		*viewerLight = 0;
		_vm->_sound->playSound(27);
		_vm->refreshCard();

		// Delay a bit before turning
		_vm->_system->delayMillis(200);
	}

	// Calculate how much we're moving
	static const uint16 hotspotPositions[] = { 2, 1, 5, 4, 3 };
	uint32 *curPos = _vm->getVar("grviewpos");
	uint32 newPos = *curPos + hotspotPositions[_vm->_curHotspot - 1];

	// Now play the movie
	VideoHandle handle = _vm->_video->playMovieRiven(1);
	assert(handle != NULL_VID_HANDLE);
	_vm->_video->setVideoBounds(handle, Audio::Timestamp(0, s_viewerTimeIntervals[*curPos], 600), Audio::Timestamp(0, s_viewerTimeIntervals[newPos], 600));
	_vm->_video->waitUntilMovieEnds(handle);

	// Set the new position and let the card's scripts take over again
	*curPos = newPos % 6; // Clip it to 0-5
	_vm->refreshCard();
}

void RivenExternal::xgplaywhark(uint16 argc, uint16 *argv) {
	// The whark response to using the lights

	// If we've gotten a visit already since we turned out the light, bail out
	uint32 *wharkState = _vm->getVar("gwharktime");

	if (*wharkState != 1)
		return;

	*wharkState = 0;

	// Increase the amount of times the whark has visited
	uint32 *wharkVisits = _vm->getVar("gwhark");
	*wharkVisits += 1;

	// If we're at 5 or more, the whark will no longer visit us :(
	if (*wharkVisits >= 5) {
		*wharkVisits = 5;
		return;
	}

	// Activate the correct video based on the amount of times we've been visited
	switch (*wharkVisits) {
	case 1:
		_vm->_video->activateMLST(3, _vm->getCurCard());
		break;
	case 2:
		// One of two random videos
		_vm->_video->activateMLST(4 + _vm->_rnd->getRandomBit(), _vm->getCurCard());
		break;
	case 3:
		// One of two random videos
		_vm->_video->activateMLST(6 + _vm->_rnd->getRandomBit(), _vm->getCurCard());
		break;
	case 4:
		// Red alert! Shields online! Brace yourself for impact!
		_vm->_video->activateMLST(8, _vm->getCurCard());
		break;
	}

	// For whatever reason the devs felt fit, code 31 is used for all of the videos
	_vm->_video->playMovieBlockingRiven(31);
	_vm->refreshCard();
}

void RivenExternal::xgwharksnd(uint16 argc, uint16 *argv) {
	// TODO: Random background whark videos
}

void RivenExternal::xglviewer(uint16 argc, uint16 *argv) {
	// This controls the viewer on the left side of the 'throne' on Garden Island
	// (It shows the village from the middle of the lake)

	// Calculate how much we're moving
	static const uint16 hotspotPositions[] = { 1, 5, 4, 2, 0, 0, 3 };
	uint32 *curPos = _vm->getVar("glviewpos");
	uint32 newPos = *curPos + hotspotPositions[_vm->_curHotspot - 1];

	// Now play the movie
	VideoHandle handle = _vm->_video->playMovieRiven(1);
	assert(handle != NULL_VID_HANDLE);
	_vm->_video->setVideoBounds(handle, Audio::Timestamp(0, s_viewerTimeIntervals[*curPos], 600), Audio::Timestamp(0, s_viewerTimeIntervals[newPos], 600));
	_vm->_video->waitUntilMovieEnds(handle);

	// Set the new position to the variable
	*curPos = newPos % 6; // Clip it to 0-5

	// And update the screen with the new image
	_vm->_gfx->drawPLST(*curPos + 2);
	_vm->_gfx->updateScreen();
}

void RivenExternal::xglview_villageon(uint16 argc, uint16 *argv) {
	// Turn on the left viewer to 'village mode'
	*_vm->getVar("glview") = 2;
	_vm->_gfx->drawPLST(*_vm->getVar("glviewpos") + 2);
	_vm->_gfx->updateScreen();
}

void RivenExternal::xglview_villageoff(uint16 argc, uint16 *argv) {
	// Turn off the left viewer when in 'village mode' (why is this external?)
	*_vm->getVar("glview") = 0;
	_vm->_gfx->drawPLST(1);
	_vm->_gfx->updateScreen();
}

void RivenExternal::xglview_prisonon(uint16 argc, uint16 *argv) {
	// TODO: Activate random background Catherine videos
}

void RivenExternal::xglview_prisonoff(uint16 argc, uint16 *argv) {
	// TODO: Deactivate random background Catherine videos
}

// ------------------------------------------------------------------------------------
// jspit (Jungle Island) external commands
// ------------------------------------------------------------------------------------

void RivenExternal::xreseticons(uint16 argc, uint16 *argv) {
	// Reset the icons when going to Tay (rspit)
	*_vm->getVar("jicons") = 0;
	*_vm->getVar("jiconorder") = 0;
	*_vm->getVar("jrbook") = 0;
}

// Count up how many icons are pressed
static byte countDepressedIcons(uint32 iconOrderVar) {
	if (iconOrderVar >= (1 << 20))
		return 5;
	else if (iconOrderVar >= (1 << 15))
		return 4;
	else if (iconOrderVar >= (1 << 10))
		return 3;
	else if (iconOrderVar >= (1 << 5))
		return 2;
	else if (iconOrderVar >= (1 << 1))
		return 1;
	else
		return 0;
}

void RivenExternal::xicon(uint16 argc, uint16 *argv) {
	// Set atemp as the status of whether or not the icon can be depressed.
	if (*_vm->getVar("jicons") & (1 << (argv[0] - 1))) {
		// This icon is depressed. Allow depression only if the last depressed icon was this one.
		if ((*_vm->getVar("jiconorder") & 0x1f) == argv[0])
			*_vm->getVar("atemp") = 1;
		else
			*_vm->getVar("atemp") = 2;
	} else
		*_vm->getVar("atemp") = 0;
}

void RivenExternal::xcheckicons(uint16 argc, uint16 *argv) {
	// Reset the icons if this is the sixth icon
	uint32 *iconOrderVar = _vm->getVar("jiconorder");
	if (countDepressedIcons(*iconOrderVar) == 5) {
		*iconOrderVar = 0;
		*_vm->getVar("jicons") = 0;
		_vm->_sound->playSound(46);
	}
}

void RivenExternal::xtoggleicon(uint16 argc, uint16 *argv) {
	// Get the variables
	uint32 *iconsDepressed = _vm->getVar("jicons");
	uint32 *iconOrderVar = _vm->getVar("jiconorder");

	if (*iconsDepressed & (1 << (argv[0] - 1))) {
		// The icon is depressed, now unpress it
		*iconsDepressed &= ~(1 << (argv[0] - 1));
		*iconOrderVar >>= 5;
	} else {
		// The icon is not depressed, now depress it
		*iconsDepressed |= 1 << (argv[0] - 1);
		*iconOrderVar = (*iconOrderVar << 5) + argv[0];
	}

	// Check if the puzzle is complete now and assign 1 to jrbook if the puzzle is complete.
	if (*iconOrderVar == *_vm->getVar("jiconcorrectorder"))
		*_vm->getVar("jrbook") = 1;
}

void RivenExternal::xjtunnel103_pictfix(uint16 argc, uint16 *argv) {
	// Get the jicons variable which contains which of the stones are depressed in the rebel tunnel puzzle
	uint32 iconsDepressed = *_vm->getVar("jicons");

	// Now, draw which icons are depressed based on the bits of the variable
	if (iconsDepressed & (1 << 0))
		_vm->_gfx->drawPLST(2);
	if (iconsDepressed & (1 << 1))
		_vm->_gfx->drawPLST(3);
	if (iconsDepressed & (1 << 2))
		_vm->_gfx->drawPLST(4);
	if (iconsDepressed & (1 << 3))
		_vm->_gfx->drawPLST(5);
	if (iconsDepressed & (1 << 22))
		_vm->_gfx->drawPLST(6);
	if (iconsDepressed & (1 << 23))
		_vm->_gfx->drawPLST(7);
	if (iconsDepressed & (1 << 24))
		_vm->_gfx->drawPLST(8);
}

void RivenExternal::xjtunnel104_pictfix(uint16 argc, uint16 *argv) {
	// Get the jicons variable which contains which of the stones are depressed in the rebel tunnel puzzle
	uint32 iconsDepressed = *_vm->getVar("jicons");

	// Now, draw which icons are depressed based on the bits of the variable
	if (iconsDepressed & (1 << 9))
		_vm->_gfx->drawPLST(2);
	if (iconsDepressed & (1 << 10))
		_vm->_gfx->drawPLST(3);
	if (iconsDepressed & (1 << 11))
		_vm->_gfx->drawPLST(4);
	if (iconsDepressed & (1 << 12))
		_vm->_gfx->drawPLST(5);
	if (iconsDepressed & (1 << 13))
		_vm->_gfx->drawPLST(6);
	if (iconsDepressed & (1 << 14))
		_vm->_gfx->drawPLST(7);
	if (iconsDepressed & (1 << 15))
		_vm->_gfx->drawPLST(8);
	if (iconsDepressed & (1 << 16))
		_vm->_gfx->drawPLST(9);
}

void RivenExternal::xjtunnel105_pictfix(uint16 argc, uint16 *argv) {
	// Get the jicons variable which contains which of the stones are depressed in the rebel tunnel puzzle
	uint32 iconsDepressed = *_vm->getVar("jicons");

	// Now, draw which icons are depressed based on the bits of the variable
	if (iconsDepressed & (1 << 3))
		_vm->_gfx->drawPLST(2);
	if (iconsDepressed & (1 << 4))
		_vm->_gfx->drawPLST(3);
	if (iconsDepressed & (1 << 5))
		_vm->_gfx->drawPLST(4);
	if (iconsDepressed & (1 << 6))
		_vm->_gfx->drawPLST(5);
	if (iconsDepressed & (1 << 7))
		_vm->_gfx->drawPLST(6);
	if (iconsDepressed & (1 << 8))
		_vm->_gfx->drawPLST(7);
	if (iconsDepressed & (1 << 9))
		_vm->_gfx->drawPLST(8);
}

void RivenExternal::xjtunnel106_pictfix(uint16 argc, uint16 *argv) {
	// Get the jicons variable which contains which of the stones are depressed in the rebel tunnel puzzle
	uint32 iconsDepressed = *_vm->getVar("jicons");

	// Now, draw which icons are depressed based on the bits of the variable
	if (iconsDepressed & (1 << 16))
		_vm->_gfx->drawPLST(2);
	if (iconsDepressed & (1 << 17))
		_vm->_gfx->drawPLST(3);
	if (iconsDepressed & (1 << 18))
		_vm->_gfx->drawPLST(4);
	if (iconsDepressed & (1 << 19))
		_vm->_gfx->drawPLST(5);
	if (iconsDepressed & (1 << 20))
		_vm->_gfx->drawPLST(6);
	if (iconsDepressed & (1 << 21))
		_vm->_gfx->drawPLST(7);
	if (iconsDepressed & (1 << 22))
		_vm->_gfx->drawPLST(8);
	if (iconsDepressed & (1 << 23))
		_vm->_gfx->drawPLST(9);
}

void RivenExternal::xvga1300_carriage(uint16 argc, uint16 *argv) {
	// Run the gallows's carriage

	_vm->_cursor->setCursor(kRivenHideCursor);         // Hide the cursor
	_vm->_system->updateScreen();                      // Update
	_vm->_video->playMovieBlockingRiven(1);            // Play handle movie
	_vm->_gfx->scheduleTransition(15);                 // Set pan down transition
	_vm->changeToCard(_vm->matchRMAPToCard(0x18e77));  // Change to card facing up
	_vm->_cursor->setCursor(kRivenHideCursor);         // Hide the cursor (again)
	_vm->_system->updateScreen();                      // Update
	_vm->_video->playMovieBlockingRiven(4);            // Play carriage beginning to drop
	_vm->_gfx->scheduleTransition(14);                 // Set pan up transition
	_vm->changeToCard(_vm->matchRMAPToCard(0x183a9));  // Change to card looking straight again
	_vm->_video->playMovieBlockingRiven(2);

	uint32 *gallows = _vm->getVar("jgallows");
	if (*gallows == 1) {
		// If the gallows is open, play the up movie and return
		_vm->_video->playMovieBlockingRiven(3);
		return;
	}

	// Give the player 5 seconds to click (anywhere)
	uint32 startTime = _vm->_system->getMillis();
	bool gotClick = false;
	while (_vm->_system->getMillis() - startTime <= 5000 && !gotClick) {
		Common::Event event;
		while (_vm->_system->getEventManager()->pollEvent(event)) {
			switch (event.type) {
			case Common::EVENT_MOUSEMOVE:
				_vm->_system->updateScreen();
				break;
			case Common::EVENT_LBUTTONUP:
				gotClick = true;
				break;
			default:
				break;
			}
		}

		_vm->_system->delayMillis(10);
	}

	_vm->_cursor->setCursor(kRivenHideCursor);             // Hide the cursor
	_vm->_system->updateScreen();                          // Update

	if (gotClick) {
		_vm->_gfx->scheduleTransition(16);                 // Schedule dissolve transition
		_vm->changeToCard(_vm->matchRMAPToCard(0x18d4d));  // Move forward
		_vm->_cursor->setCursor(kRivenHideCursor);         // Hide the cursor
		_vm->_system->updateScreen();                      // Update
		_vm->_system->delayMillis(500);                    // Delay a half second before changing again
		_vm->_gfx->scheduleTransition(12);                 // Schedule pan left transition
		_vm->changeToCard(_vm->matchRMAPToCard(0x18ab5));  // Turn right
		_vm->_cursor->setCursor(kRivenHideCursor);         // Hide the cursor
		_vm->_system->updateScreen();                      // Update
		_vm->_video->playMovieBlockingRiven(1);            // Play carriage ride movie
		_vm->changeToCard(_vm->matchRMAPToCard(0x17167));  // We have arrived at the top
	} else
		_vm->_video->playMovieBlockingRiven(3);            // Too slow!
}

void RivenExternal::xjdome25_resetsliders(uint16 argc, uint16 *argv) {
	resetDomeSliders(81, 2);
}

void RivenExternal::xjdome25_slidermd(uint16 argc, uint16 *argv) {
	dragDomeSlider(81, 29, 28, 2);
}

void RivenExternal::xjdome25_slidermw(uint16 argc, uint16 *argv) {
	checkSliderCursorChange(2);
}

void RivenExternal::xjscpbtn(uint16 argc, uint16 *argv) {
	runDomeButtonMovie();
}

void RivenExternal::xjisland3500_domecheck(uint16 argc, uint16 *argv) {
	runDomeCheck();
}

int RivenExternal::jspitElevatorLoop() {
	Common::Point startPos = _vm->_system->getEventManager()->getMousePos();

	Common::Event event;
	int changeLevel = 0;

	_vm->_cursor->setCursor(kRivenClosedHandCursor);
	_vm->_system->updateScreen();

	for (;;) {
		while (_vm->_system->getEventManager()->pollEvent(event)) {
			switch (event.type) {
			case Common::EVENT_MOUSEMOVE:
				if (event.mouse.y > (startPos.y + 10)) {
					changeLevel = -1;
				} else if (event.mouse.y < (startPos.y - 10)) {
					changeLevel = 1;
				} else {
					changeLevel = 0;
				}
				_vm->_system->updateScreen();
				break;
			case Common::EVENT_LBUTTONUP:
				_vm->_cursor->setCursor(kRivenMainCursor);
				_vm->_system->updateScreen();
				return changeLevel;
			default:
				break;
			}
		}
		_vm->_system->delayMillis(10);
	}
}

void RivenExternal::xhandlecontrolup(uint16 argc, uint16 *argv) {
	int changeLevel = jspitElevatorLoop();

	// If we've moved the handle down, go down a floor
	if (changeLevel == -1) {
		_vm->_video->playMovieBlockingRiven(1);
		_vm->_video->playMovieBlockingRiven(2);
		_vm->changeToCard(_vm->matchRMAPToCard(0x1e374));
	}
}

void RivenExternal::xhandlecontroldown(uint16 argc, uint16 *argv) {
	int changeLevel = jspitElevatorLoop();

	// If we've moved the handle up, go up a floor
	if (changeLevel == 1) {
		_vm->_video->playMovieBlockingRiven(1);
		_vm->_video->playMovieBlockingRiven(2);
		_vm->changeToCard(_vm->matchRMAPToCard(0x1e374));
	}
}

void RivenExternal::xhandlecontrolmid(uint16 argc, uint16 *argv) {
	int changeLevel = jspitElevatorLoop();

	if (changeLevel == 0)
		return;

	// Play the handle moving video
	if (changeLevel == 1)
		_vm->_video->playMovieBlockingRiven(7);
	else
		_vm->_video->playMovieBlockingRiven(6);

	// If the whark's mouth is open, close it
	uint32 *mouthVar = _vm->getVar("jwmouth");
	if (*mouthVar == 1) {
		_vm->_video->playMovieBlockingRiven(3);
		_vm->_video->playMovieBlockingRiven(8);
		*mouthVar = 0;
	}

	// Play the elevator video and then change the card
	if (changeLevel == 1) {
		_vm->_video->playMovieBlockingRiven(5);
		_vm->changeToCard(_vm->matchRMAPToCard(0x1e597));
	} else {
		_vm->_video->playMovieBlockingRiven(4);
		_vm->changeToCard(_vm->matchRMAPToCard(0x1e29c));
	}
}

void RivenExternal::xjplaybeetle_550(uint16 argc, uint16 *argv) {
	// Play a beetle animation 25% of the time
	*_vm->getVar("jplaybeetle") = (_vm->_rnd->getRandomNumberRng(0, 3) == 0) ? 1 : 0;
}

void RivenExternal::xjplaybeetle_600(uint16 argc, uint16 *argv) {
	// Play a beetle animation 25% of the time
	*_vm->getVar("jplaybeetle") = (_vm->_rnd->getRandomNumberRng(0, 3) == 0) ? 1 : 0;
}

void RivenExternal::xjplaybeetle_950(uint16 argc, uint16 *argv) {
	// Play a beetle animation 25% of the time
	*_vm->getVar("jplaybeetle") = (_vm->_rnd->getRandomNumberRng(0, 3) == 0) ? 1 : 0;
}

void RivenExternal::xjplaybeetle_1050(uint16 argc, uint16 *argv) {
	// Play a beetle animation 25% of the time
	*_vm->getVar("jplaybeetle") = (_vm->_rnd->getRandomNumberRng(0, 3) == 0) ? 1 : 0;
}

void RivenExternal::xjplaybeetle_1450(uint16 argc, uint16 *argv) {
	// Play a beetle animation 25% of the time as long as the girl is not present
	*_vm->getVar("jplaybeetle") = (_vm->_rnd->getRandomNumberRng(0, 3) == 0 && *_vm->getVar("jgirl") != 1) ? 1 : 0;
}

void RivenExternal::xjlagoon700_alert(uint16 argc, uint16 *argv) {
	// TODO: Sunner related
}

void RivenExternal::xjlagoon800_alert(uint16 argc, uint16 *argv) {
	// TODO: Sunner related
}

void RivenExternal::xjlagoon1500_alert(uint16 argc, uint16 *argv) {
	// Have the sunners move a bit as you get closer ;)
	uint32 *sunners = _vm->getVar("jsunners");
	if (*sunners == 0) {
		_vm->_video->playMovieBlockingRiven(3);
	} else if (*sunners == 1) {
		_vm->_video->playMovieBlockingRiven(2);
		*sunners = 2;
	}
}

void RivenExternal::xjschool280_resetleft(uint16 argc, uint16 *argv) {
	// Dummy function. This resets the unneeded video timing variable (dropLeftStart) in
	// the DVD version.
}

void RivenExternal::xjschool280_resetright(uint16 argc, uint16 *argv) {
	// Dummy function. This resets the unneeded video timing variable (dropRightStart) in
	// the DVD version.
}

void RivenExternal::redrawWharkNumberPuzzle(uint16 overlay, uint16 number) {
	// Update the screen for the whark number puzzle
	// We don't update the whole screen here because we don't want to overwrite the video data
	_vm->_gfx->drawPLST(overlay);
	_vm->_gfx->drawPLST(number + 1);
	_vm->_gfx->updateScreen(Common::Rect(80, 212, 477, 392));
	_vm->_system->updateScreen();
}

void RivenExternal::xschool280_playwhark(uint16 argc, uint16 *argv) {
	// The "monstrous" whark puzzle that teaches the number system

	uint32 *posVar;
	uint16 spinMLST, overlayPLST, doomMLST, snackMLST;

	// Choose left or right based on jwharkpos (which is set by the scripts)
	if (*_vm->getVar("jwharkpos") == 1) {
		posVar = _vm->getVar("jleftpos");
		spinMLST = 1;
		overlayPLST = 12;
		doomMLST = 3;
		snackMLST = 4;
	} else {
		posVar = _vm->getVar("jrightpos");
		spinMLST = 2;
		overlayPLST = 13;
		doomMLST = 5;
		snackMLST = 6;
	}

	// Hide the cursor
	_vm->_cursor->setCursor(kRivenHideCursor);
	_vm->_system->updateScreen();

	// Play the spin movie
	_vm->_video->playMovieBlockingRiven(spinMLST);

	// Get our random number and redraw the area
	uint16 number = _vm->_rnd->getRandomNumberRng(1, 10);
	redrawWharkNumberPuzzle(overlayPLST, number);

	// Handle movement
	// (11560/600)s is the length of each of the two movies. We divide it into 19 parts
	// (one for each of the possible positions the villager can have).
	VideoHandle handle = _vm->_video->playMovieRiven(doomMLST);
	Audio::Timestamp startTime = Audio::Timestamp(0, (11560 / 19) * (*posVar), 600);
	*posVar += number; // Adjust to the end
	Audio::Timestamp endTime = Audio::Timestamp(0, (11560 / 19) * (*posVar), 600);
	_vm->_video->setVideoBounds(handle, startTime, endTime);
	_vm->_video->waitUntilMovieEnds(handle);

	if (*posVar > 19) {
		// The villager has died :(
		_vm->_video->playMovieBlockingRiven(snackMLST);
		redrawWharkNumberPuzzle(overlayPLST, number);
		*posVar = 0;
	}

	// Enable the correct hotspots for the movement now
	_vm->_hotspots[2].enabled = !_vm->_hotspots[2].enabled;
	_vm->_hotspots[3].enabled = !_vm->_hotspots[3].enabled;

	// Update the cursor
	_vm->updateCurrentHotspot();
}

void RivenExternal::xjatboundary(uint16 argc, uint16 *argv) {
	runDemoBoundaryDialog();
}

// ------------------------------------------------------------------------------------
// ospit (Gehn's Office) external commands
// ------------------------------------------------------------------------------------

void RivenExternal::xorollcredittime(uint16 argc, uint16 *argv) {
	// WORKAROUND: The special change stuff only handles one destination and it would
	// be messy to modify the way that currently works. If we use the trap book on Tay,
	// we should be using the Tay end game sequences.
	if (*_vm->getVar("returnstackid") == rspit) {
		_vm->changeToStack(rspit);
		_vm->changeToCard(2);
		return;
	}

	// You used the trap book... why? What were you thinking?
	uint32 *gehnState = _vm->getVar("agehn");

	if (*gehnState == 0)		// Gehn who?
		runEndGame(1, 9500);
	else if (*gehnState == 4)	// You freed him? Are you kidding me?
		runEndGame(2, 12000);
	else						// You already spoke with Gehn. What were you thinking?
		runEndGame(3, 8000);
}

void RivenExternal::xbookclick(uint16 argc, uint16 *argv) {
	// Hide the cursor
	_vm->_cursor->setCursor(kRivenHideCursor);
	_vm->_system->updateScreen();

	// Let's hook onto our video
	VideoHandle video = _vm->_video->findVideoHandleRiven(argv[0]);

	// Convert from the standard QuickTime base time to milliseconds
	// The values are in terms of 1/600 of a second.
	// Have I said how much I just *love* QuickTime? </sarcasm>
	uint32 startTime = argv[1] * 1000 / 600;
	uint32 endTime = argv[2] * 1000 / 600;

	// Track down our hotspot
	// Of course, they're not in any sane order...
	static const uint16 hotspotMap[] = { 1, 3, 2, 0 };
	Common::Rect hotspotRect = _vm->_hotspots[hotspotMap[argv[3] - 1]].rect;

	debug(0, "xbookclick:");
	debug(0, "\tVideo Code = %d", argv[0]);
	debug(0, "\tStart Time = %dms", startTime);
	debug(0, "\tEnd Time   = %dms", endTime);
	debug(0, "\tHotspot    = %d -> %d", argv[3], hotspotMap[argv[3] - 1]);

	// Just let the video play while we wait until Gehn opens the trap book for us
	while (_vm->_video->getElapsedTime(video) < startTime && !_vm->shouldQuit()) {
		if (_vm->_video->updateMovies())
			_vm->_system->updateScreen();

		Common::Event event;
		while (_vm->_system->getEventManager()->pollEvent(event))
			;

		_vm->_system->delayMillis(10);
	}

	// Break out if we're quitting
	if (_vm->shouldQuit())
		return;

	// Update our hotspot stuff
	if (hotspotRect.contains(_vm->_system->getEventManager()->getMousePos()))
		_vm->_cursor->setCursor(kRivenOpenHandCursor);
	else
		_vm->_cursor->setCursor(kRivenMainCursor);

	_vm->_system->updateScreen();
	
	// OK, Gehn has opened the trap book and has asked us to go in. Let's watch
	// and see what the player will do...
	while (_vm->_video->getElapsedTime(video) < endTime && !_vm->shouldQuit()) {
		bool updateScreen = _vm->_video->updateMovies();

		Common::Event event;
		while (_vm->_system->getEventManager()->pollEvent(event)) {
			switch (event.type) {
			case Common::EVENT_MOUSEMOVE:
				if (hotspotRect.contains(_vm->_system->getEventManager()->getMousePos()))
					_vm->_cursor->setCursor(kRivenOpenHandCursor);
				else
					_vm->_cursor->setCursor(kRivenMainCursor);
				updateScreen = true;
				break;
			case Common::EVENT_LBUTTONUP:
				if (hotspotRect.contains(_vm->_system->getEventManager()->getMousePos())) {
					// OK, we've used the trap book! We go for ride lady!
					_vm->_scriptMan->stopAllScripts();                  // Stop all running scripts (so we don't remain in the cage)
					_vm->_video->stopVideos();                          // Stop all videos
					_vm->_cursor->setCursor(kRivenHideCursor);          // Hide the cursor
					_vm->_gfx->drawPLST(3);                             // Black out the screen
					_vm->_gfx->updateScreen();                          // Update the screen
					_vm->_sound->playSound(0);                          // Play the link sound
					_vm->_video->activateMLST(7, _vm->getCurCard());    // Activate Gehn Link Video
					_vm->_video->playMovieBlockingRiven(1);             // Play Gehn Link Video
					*_vm->getVar("agehn") = 4;                          // Set Gehn to the trapped state
					*_vm->getVar("atrapbook") = 1;                      // We've got the trap book again
					_vm->_sound->playSound(0);                          // Play the link sound again
					_vm->changeToCard(_vm->matchRMAPToCard(0x2885));    // Link out!
					return;
				}
				break;
			default:
				break;
			}
		}

		if (updateScreen && !_vm->shouldQuit())
			_vm->_system->updateScreen();

		_vm->_system->delayMillis(10);
	}

	// Break out if we're quitting
	if (_vm->shouldQuit())
		return;

	// Hide the cursor again
	_vm->_cursor->setCursor(kRivenHideCursor);
	_vm->_system->updateScreen();

	// If there was no click and this is the third time Gehn asks us to
	// use the trap book, he will shoot the player. Dead on arrival.
	// Run the credits from here.
	if (*_vm->getVar("agehn") == 3) {
		_vm->_scriptMan->stopAllScripts();
		runCredits(argv[0], 5000);
		return;
	}

	// There was no click, so just play the rest of the video.
	_vm->_video->waitUntilMovieEnds(video);
}

void RivenExternal::xooffice30_closebook(uint16 argc, uint16 *argv) {
	// Close the blank linking book if it's open
	uint32 *book = _vm->getVar("odeskbook");
	if (*book != 1)
		return;

	// Set the variable to be "closed"
	*book = 0;

	// Play the movie
	_vm->_video->playMovieBlockingRiven(1);

	// Set the hotspots into their correct states
	_vm->_hotspots[2].enabled = false;
	_vm->_hotspots[5].enabled = false;
	_vm->_hotspots[6].enabled = true;

	// We now need to draw PLST 1 and refresh, but PLST 1 is
	// drawn when refreshing anyway, so don't worry about that.
	_vm->refreshCard();
}

void RivenExternal::xobedroom5_closedrawer(uint16 argc, uint16 *argv) {
	// Close the drawer if open when clicking on the journal.
	_vm->_video->playMovieBlockingRiven(2);
	*_vm->getVar("ostanddrawer") = 0;
}

void RivenExternal::xogehnopenbook(uint16 argc, uint16 *argv) {
	_vm->_gfx->drawPLST(*_vm->getVar("ogehnpage"));
}

void RivenExternal::xogehnbookprevpage(uint16 argc, uint16 *argv) {
	// Get the page variable
	uint32 *page = _vm->getVar("ogehnpage");

	// Decrement the page if it's not the first page
	if (*page == 1)
		return;
	(*page)--;

	// Play the page turning sound
	_vm->_sound->playSound(12);

	// Now update the screen :)
	_vm->_gfx->scheduleTransition(1);
	_vm->_gfx->updateScreen();
}

void RivenExternal::xogehnbooknextpage(uint16 argc, uint16 *argv) {
	// Get the page variable
	uint32 *page = _vm->getVar("ogehnpage");

	// Increment the page if it's not the last page
	if (*page == 13)
		return;
	(*page)++;

	// Play the page turning sound
	_vm->_sound->playSound(13);

	// Now update the screen :)
	_vm->_gfx->scheduleTransition(0);
	_vm->_gfx->updateScreen();
}

uint16 RivenExternal::getComboDigit(uint32 correctCombo, uint32 digit) {
	static const uint32 powers[] = { 100000, 10000, 1000, 100, 10, 1 };
	return (correctCombo % powers[digit]) / powers[digit + 1];
}

void RivenExternal::xgwatch(uint16 argc, uint16 *argv) {
	// Hide the cursor
	_vm->_cursor->setCursor(kRivenHideCursor);
	_vm->_system->updateScreen();

	uint32 *prisonCombo = _vm->getVar("pcorrectorder");
	uint32 soundTime = _vm->_system->getMillis() - 500; // Start the first sound instantly
	byte curSound = 0;

	while (!_vm->shouldQuit()) {
		// Play the next sound every half second
		if (_vm->_system->getMillis() - soundTime >= 500) {
			if (curSound == 5) // Break out after the last sound is done
				break;

			_vm->_sound->playSound(getComboDigit(*prisonCombo, curSound) + 13);
			curSound++;
			soundTime = _vm->_system->getMillis();
		}
		
		// Poll events just to check for quitting
		Common::Event event;
		while (_vm->_system->getEventManager()->pollEvent(event)) {}

		// Cut down on CPU usage
		_vm->_system->delayMillis(10);
	}

	// Now play the video for the watch
	_vm->_video->activateMLST(1, _vm->getCurCard());
	_vm->_video->playMovieBlockingRiven(1);

	// And, finally, refresh
	_vm->refreshCard();
}

// ------------------------------------------------------------------------------------
// pspit (Prison Island) external commands
// ------------------------------------------------------------------------------------

void RivenExternal::xpisland990_elevcombo(uint16 argc, uint16 *argv) {
	// Play button sound based on argv[0]
	_vm->_sound->playSound(argv[0] + 5);

	// It is impossible to get here if Gehn is not trapped. However,
	// the original also disallows brute forcing the ending if you have
	// not yet trapped Gehn.
	if (*_vm->getVar("agehn") != 4)
		return;

	uint32 *correctDigits = _vm->getVar("pelevcombo");

	// pelevcombo keeps count of how many buttons we have pressed in the correct order.
	// When pelevcombo is 5, clicking the handle will show the video freeing Catherine.
	if (*correctDigits < 5 && argv[0] == getComboDigit(*_vm->getVar("pcorrectorder"), *correctDigits))
		*correctDigits += 1;
	else
		*correctDigits = 0;
}

void RivenExternal::xpscpbtn(uint16 argc, uint16 *argv) {
	runDomeButtonMovie();
}

void RivenExternal::xpisland290_domecheck(uint16 argc, uint16 *argv) {
	runDomeCheck();
}

void RivenExternal::xpisland25_opencard(uint16 argc, uint16 *argv) {
	checkDomeSliders(31, 5);
}

void RivenExternal::xpisland25_resetsliders(uint16 argc, uint16 *argv) {
	resetDomeSliders(10, 6);
}

void RivenExternal::xpisland25_slidermd(uint16 argc, uint16 *argv) {
	dragDomeSlider(10, 31, 5, 6);
}

void RivenExternal::xpisland25_slidermw(uint16 argc, uint16 *argv) {
	checkSliderCursorChange(6);
}

// ------------------------------------------------------------------------------------
// rspit (Rebel Age) external commands
// ------------------------------------------------------------------------------------

void RivenExternal::xrcredittime(uint16 argc, uint16 *argv) {
	// Nice going, you used the trap book on Tay.

	// The game chooses what ending based on agehn for us,
	// so we just have to play the video and credits.
	// For the record, when agehn == 4, Gehn will thank you for
	// showing him the rebel age and then leave you to die.
	// Otherwise, the rebels burn the book. Epic fail either way.
	runEndGame(1, 1500);
}

void RivenExternal::xrshowinventory(uint16 argc, uint16 *argv) {
	// Give the trap book and Catherine's journal to the player
	*_vm->getVar("atrapbook") = 1;
	*_vm->getVar("acathbook") = 1;
	_vm->_gfx->showInventory();
}

void RivenExternal::xrhideinventory(uint16 argc, uint16 *argv) {
	_vm->_gfx->hideInventory();
}

void RivenExternal::xrwindowsetup(uint16 argc, uint16 *argv) {
	// TODO: Randomizing what effect happens when you look out into the middle of Tay (useless! :P)
}

// ------------------------------------------------------------------------------------
// tspit (Temple Island) external commands
// ------------------------------------------------------------------------------------

void RivenExternal::xtexterior300_telescopedown(uint16 argc, uint16 *argv) {
	// First, show the button movie
	_vm->_video->playMovieBlockingRiven(3);

	// Don't do anything else if the telescope power is off
	if (*_vm->getVar("ttelevalve") == 0)
		return;

	uint32 *telescopePos = _vm->getVar("ttelescope");
	uint32 *telescopeCover = _vm->getVar("ttelecover");

	if (*telescopePos == 1) {
		// We're at the bottom, which means one of two things can happen...
		if (*telescopeCover == 1 && *_vm->getVar("ttelepin") == 1) {
			// ...if the cover is open and the pin is up, the game is now over.
			if (*_vm->getVar("pcage") == 2) {
				// The best ending: Catherine is free, Gehn is trapped, Atrus comes to rescue you.
				// And now we fall back to Earth... all the way...
				_vm->_video->activateMLST(8, _vm->getCurCard());
				runEndGame(8, 5000);
			} else if (*_vm->getVar("agehn") == 4) {
				// The ok ending: Catherine is still trapped, Gehn is trapped, Atrus comes to rescue you.
				// Nice going! Catherine and the islanders are all dead now! Just go back to your home...
				_vm->_video->activateMLST(9, _vm->getCurCard());
				runEndGame(9, 5000);
			} else if (*_vm->getVar("atrapbook") == 1) {
				// The bad ending: Catherine is trapped, Gehn is free, Atrus gets shot by Gehn,
				// And then you get shot by Cho. Nice going! Catherine and the islanders are dead
				// and you have just set Gehn free from Riven, not to mention you're dead.
				_vm->_video->activateMLST(10, _vm->getCurCard());
				runEndGame(10, 5000);
			} else {
				// The impossible ending: You don't have Catherine's journal and yet you were somehow
				// able to open the hatch on the telescope. The game provides an ending for those who
				// cheat, load a saved game with the combo, or just guess the telescope combo. Atrus
				// doesn't come and you just fall into the fissure.
				_vm->_video->activateMLST(11, _vm->getCurCard());
				runEndGame(11, 5000);
			}
		} else {
			// ...the telescope can't move down anymore.
			// Play the sound of not being able to move
			_vm->_cursor->setCursor(kRivenHideCursor);
			_vm->_system->updateScreen();
			_vm->_sound->playSoundBlocking(13);
		}
	} else {
		// We're not at the bottom, and we can move down again

		// Play a piece of the moving down movie
		static const uint32 timeIntervals[] = { 4320, 3440, 2560, 1760, 880, 0 };
		uint16 movieCode = (*telescopeCover) ? 1 : 2;
		VideoHandle handle = _vm->_video->playMovieRiven(movieCode);
		_vm->_video->setVideoBounds(handle, Audio::Timestamp(0, timeIntervals[*telescopePos], 600), Audio::Timestamp(0, timeIntervals[*telescopePos - 1], 600));
		_vm->_sound->playSound(14); // Play the moving sound
		_vm->_video->waitUntilMovieEnds(handle);

		// Now move the telescope down a position and refresh
		*telescopePos -= 1;
		_vm->refreshCard();
	}
}

void RivenExternal::xtexterior300_telescopeup(uint16 argc, uint16 *argv) {
	// First, show the button movie
	_vm->_video->playMovieBlockingRiven(3);

	// Don't do anything else if the telescope power is off
	if (*_vm->getVar("ttelevalve") == 0)
		return;

	uint32 *telescopePos = _vm->getVar("ttelescope");

	// Check if we can't move up anymore
	if (*telescopePos == 5) {
		// Play the sound of not being able to move
		_vm->_cursor->setCursor(kRivenHideCursor);
		_vm->_system->updateScreen();
		_vm->_sound->playSoundBlocking(13);
		return;
	}

	// Play a piece of the moving up movie
	static const uint32 timeIntervals[] = { 0, 800, 1680, 2560, 3440, 4320 };
	uint16 movieCode = (*_vm->getVar("ttelecover")) ? 4 : 5;
	VideoHandle handle = _vm->_video->playMovieRiven(movieCode);
	_vm->_video->setVideoBounds(handle, Audio::Timestamp(0, timeIntervals[*telescopePos - 1], 600), Audio::Timestamp(0, timeIntervals[*telescopePos], 600));
	_vm->_sound->playSound(14); // Play the moving sound
	_vm->_video->waitUntilMovieEnds(handle);

	// Now move the telescope up a position and refresh
	*telescopePos += 1;
	_vm->refreshCard();
}

void RivenExternal::xtisland390_covercombo(uint16 argc, uint16 *argv) {
	// Called when clicking the telescope cover buttons. argv[0] is the button number (1...5).
	uint32 *correctDigits = _vm->getVar("tcovercombo");

	if (*correctDigits < 5 && argv[0] == getComboDigit(*_vm->getVar("tcorrectorder"), *correctDigits))
		*correctDigits += 1;
	else
		*correctDigits = 0;

	// If we have hit the correct 5 buttons in a row, activate the hotspot to open up the
	// telescope cover.
	if (*correctDigits == 5)
		_vm->_hotspots[9].enabled = true;
	else
		_vm->_hotspots[9].enabled = false;
}

// Atrus' Journal and Trap Book are added to inventory
void RivenExternal::xtatrusgivesbooks(uint16 argc, uint16 *argv) {
	// Give the player Atrus' Journal and the Trap book
	*_vm->getVar("aatrusbook") = 1;
	*_vm->getVar("atrapbook") = 1;
}

// Trap Book is removed from inventory
void RivenExternal::xtchotakesbook(uint16 argc, uint16 *argv) {
	// And now Cho takes the trap book. Sure, this isn't strictly
	// necessary to add and them remove the trap book... but it
	// seems better to do this ;)
	*_vm->getVar("atrapbook") = 0;
}

void RivenExternal::xthideinventory(uint16 argc, uint16 *argv) {
	_vm->_gfx->hideInventory();
}

// Marble Puzzle related constants
static const uint32 kMarbleCount = 6;
static const int kSmallMarbleWidth = 4;
static const int kSmallMarbleHeight = 2;
static const int kLargeMarbleSize = 8;
static const int kMarbleHotspotSize = 13;
static const char *s_marbleNames[] = { "tred", "torange", "tyellow", "tgreen", "tblue", "tviolet" };

// Marble Puzzle helper functions
// The y portion takes the upper 16 bits, while the x portion takes the lower 16 bits
static void setMarbleX(uint32 *var, byte x) {
	*var = (*var & 0xff00) | (x + 1);
}

static void setMarbleY(uint32 *var, byte y) {
	*var = ((y + 1) << 16) | (*var & 0xff);
}

static byte getMarbleX(uint32 *var) {
	return (*var & 0xff) - 1;
}

static byte getMarbleY(uint32 *var) { // Give that that Y you old hag! </bad Seinfeld reference>
	return ((*var >> 16) & 0xff) - 1;
}

static Common::Rect generateMarbleGridRect(uint16 x, uint16 y) {
	// x/y in terms of 0!
	static const int marbleGridOffsetX[] = { 134, 202, 270, 338, 406 };
	static const int marbleGridOffsetY[] = {  24,  92, 159, 227, 295 };

	uint16 offsetX = marbleGridOffsetX[x / 5] + (x % 5) * kMarbleHotspotSize;
	uint16 offsetY = marbleGridOffsetY[y / 5] + (y % 5) * kMarbleHotspotSize;
	return Common::Rect(offsetX, offsetY, offsetX + kMarbleHotspotSize, offsetY + kMarbleHotspotSize);
}

void RivenExternal::xt7500_checkmarbles(uint16 argc, uint16 *argv) {
	// Set apower if the marbles are in their correct spot. 

	bool valid = true;
	static const uint32 marbleFinalValues[] = { 1114121, 1441798, 0, 65552, 65558, 262146 };

	for (uint16 i = 0; i < kMarbleCount; i++)
		if (*_vm->getVar(s_marbleNames[i]) != marbleFinalValues[i]) {
			valid = false;
			break;
		}

	// If we have the correct combo, activate the power and reset the marble positions
	// Otherwise, make sure the power is off
	if (valid) {
		*_vm->getVar("apower") = 1;
		for (uint16 i = 0; i < kMarbleCount; i++)
			*_vm->getVar(s_marbleNames[i]) = 0;
	} else
		*_vm->getVar("apower") = 0;
}

void RivenExternal::xt7600_setupmarbles(uint16 argc, uint16 *argv) {
	// Draw the small marbles when we're a step away from the waffle
	uint16 baseBitmapId = _vm->findResourceID(ID_TBMP, "*tsmallred");
	bool waffleDown = *_vm->getVar("twaffle") != 0;

	// Note that each of the small marble images is exactly 4x2

	for (uint16 i = 0; i < kMarbleCount; i++) {
		uint32 *var = _vm->getVar(s_marbleNames[i]);

		if (*var == 0) {
			// The marble is still in its initial place
			// (Note that this is still drawn even if the waffle is down)
			int marbleX = 376 + i * 2;
			int marbleY = 253 + i * 4;
			_vm->_gfx->copyImageToScreen(baseBitmapId + i, marbleX, marbleY, marbleX + kSmallMarbleWidth, marbleY + kSmallMarbleHeight);
		} else if (waffleDown) {
			// The marble is on the grid and the waffle is down
			// (Nothing to draw here)
		} else {
			// The marble is on the grid and the waffle is up
			// TODO: Draw them onto the grid
		}
	}
}

void RivenExternal::setMarbleHotspots() {
	// Set the hotspots
	for (uint16 i = 0; i < kMarbleCount; i++) {
		uint32 *marblePos = _vm->getVar(s_marbleNames[i]);

		if (*marblePos == 0) // In the receptacle
			_vm->_hotspots[i + 3].rect = _marbleBaseHotspots[i];
		else                 // On the grid
			_vm->_hotspots[i + 3].rect = generateMarbleGridRect(getMarbleX(marblePos), getMarbleY(marblePos));
	}
}

void RivenExternal::xt7800_setup(uint16 argc, uint16 *argv) {
	// First, let's store the base receptacle hotspots for the marbles
	if (_marbleBaseHotspots.empty())
		for (uint16 i = 0; i < kMarbleCount; i++)
			_marbleBaseHotspots.push_back(_vm->_hotspots[i + 3].rect);

	// Move the marble hotspots based on their position variables
	setMarbleHotspots();
	*_vm->getVar("themarble") = 0;
}

void RivenExternal::drawMarbles() {
	for (uint32 i = 0; i < kMarbleCount; i++) {
		// Don't draw the marble if we're holding it
		if (*_vm->getVar("themarble") - 1 == i)
			continue;

		Common::Rect rect = _vm->_hotspots[i + 3].rect;
		// Trim the rect down a bit
		rect.left += 3;
		rect.top += 3;
		rect.right -= 2;
		rect.bottom -= 2;
		_vm->_gfx->drawExtrasImage(i + 200, rect);
	}
}

void RivenExternal::xdrawmarbles(uint16 argc, uint16 *argv) {
	// Draw marbles in the closeup
	drawMarbles();

	// We have to re-enable the updates here
	// Would be really nice if the scripts did this for us, but alas...
	_vm->_gfx->_updatesEnabled = true;
}

void RivenExternal::xtakeit(uint16 argc, uint16 *argv) {
	// Pick up and move a marble

	// First, let's figure out what marble we're now holding
	uint32 *marble = _vm->getVar("themarble");
	*marble = 0;

	for (uint32 i = 0; i < kMarbleCount; i++)
		if (_vm->_hotspots[i + 3].rect.contains(_vm->_system->getEventManager()->getMousePos())) {
			*marble = i + 1;
			break;
		}

	// xtakeit() shouldn't be called if we're not on a marble hotspot
	assert(*marble);

	// Redraw the background
	_vm->_gfx->drawPLST(1);
	_vm->_gfx->updateScreen();

	// Loop until the player lets go (or quits)
	Common::Event event;
	bool mouseDown = true;
	while (mouseDown) {
		while (_vm->_system->getEventManager()->pollEvent(event)) {
			if (event.type == Common::EVENT_LBUTTONUP)
				mouseDown = false;
			else if (event.type == Common::EVENT_MOUSEMOVE)
				_vm->_system->updateScreen();
			else if (event.type == Common::EVENT_QUIT || event.type == Common::EVENT_RTL)
				return;
		}

		_vm->_system->delayMillis(10); // Take it easy on the CPU
	}

	// Check if we landed in a valid location and no other marble has that location
	uint32 *marblePos = _vm->getVar(s_marbleNames[*marble - 1]);

	bool foundMatch = false;
	for (int y = 0; y < 25 && !foundMatch; y++) {
		for (int x = 0; x < 25 && !foundMatch; x++) {
			Common::Rect testHotspot = generateMarbleGridRect(x, y);

			// Let's try to place the marble!
			if (testHotspot.contains(_vm->_system->getEventManager()->getMousePos())) {
				// Set this as the position
				setMarbleX(marblePos, x);
				setMarbleY(marblePos, y);

				// Let's make sure no other marble is in this spot...
				for (uint16 i = 0; i < kMarbleCount; i++)
					if (i != *marble - 1 && *_vm->getVar(s_marbleNames[i]) == *marblePos)
						*marblePos = 0;

				// We have a match
				foundMatch = true;
			}
		}
	}

	// If we still don't have a match, reset it to the original location
	if (!foundMatch)
		*marblePos = 0;

	// Check the new hotspots and refresh everything
	*marble = 0;
	setMarbleHotspots();
	_vm->updateCurrentHotspot();
	_vm->_gfx->updateScreen();
}

void RivenExternal::xtscpbtn(uint16 argc, uint16 *argv) {
	runDomeButtonMovie();
}

void RivenExternal::xtisland4990_domecheck(uint16 argc, uint16 *argv) {
	runDomeCheck();
}

void RivenExternal::xtisland5056_opencard(uint16 argc, uint16 *argv) {
	checkDomeSliders(29, 30);
}

void RivenExternal::xtisland5056_resetsliders(uint16 argc, uint16 *argv) {
	resetDomeSliders(37, 3);
}

void RivenExternal::xtisland5056_slidermd(uint16 argc, uint16 *argv) {
	dragDomeSlider(37, 29, 30, 3);
}

void RivenExternal::xtisland5056_slidermw(uint16 argc, uint16 *argv) {
	checkSliderCursorChange(3);
}

void RivenExternal::xtatboundary(uint16 argc, uint16 *argv) {
	runDemoBoundaryDialog();
}

// ------------------------------------------------------------------------------------
// Common external commands
// ------------------------------------------------------------------------------------

void RivenExternal::xflies(uint16 argc, uint16 *argv) {
	// TODO: Activate the "flies" effect
}

} // End of namespace Mohawk