aboutsummaryrefslogtreecommitdiff
path: root/engines/mohawk/myst_stacks/myst.cpp
blob: f9ba6a42fa479e8b65f2fadd488e623a3b20df5f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
/* 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.
 *
 */

#include "mohawk/cursors.h"
#include "mohawk/myst.h"
#include "mohawk/myst_areas.h"
#include "mohawk/myst_graphics.h"
#include "mohawk/myst_state.h"
#include "mohawk/sound.h"
#include "mohawk/video.h"
#include "mohawk/myst_stacks/myst.h"

#include "common/events.h"
#include "common/system.h"
#include "common/textconsole.h"

namespace Mohawk {
namespace MystStacks {

Myst::Myst(MohawkEngine_Myst *vm) :
		MystScriptParser(vm), _state(_vm->_gameState->_myst) {
	setupOpcodes();

	// Card ID preinitialized by the engine for use by opcode 18
	// when linking back to Myst in the library
	_savedCardId = 4329;

	_towerRotationBlinkLabel = false;
	_libraryBookcaseChanged = false;
	_dockVaultState = 0;
	_cabinDoorOpened = 0;
	_cabinHandleDown = 0;
	_cabinMatchState = 2;
	_cabinGaugeMovieEnabled = false;
	_matchBurning = false;
	_tree = nullptr;
	_treeAlcove = nullptr;
	_treeStopped = false;
	_treeMinPosition = 0;
	_imagerValidationStep = 0;
	_observatoryCurrentSlider = nullptr;
	_butterfliesMoviePlayed = false;
	_state.treeLastMoveTime = _vm->_system->getMillis();
}

Myst::~Myst() {
}

#define OPCODE(op, x) _opcodes.push_back(new MystOpcode(op, (OpcodeProcMyst) &Myst::x, #x))

void Myst::setupOpcodes() {
	// "Stack-Specific" Opcodes
	OPCODE(100, NOP);
	OPCODE(101, o_libraryBookPageTurnLeft);
	OPCODE(102, o_libraryBookPageTurnRight);
	OPCODE(103, o_fireplaceToggleButton);
	OPCODE(104, o_fireplaceRotation);
	OPCODE(105, o_courtyardBoxesCheckSolution);
	OPCODE(106, o_towerRotationStart);
	OPCODE(107, NOP);
	OPCODE(108, o_towerRotationEnd);
	OPCODE(109, o_imagerChangeSelection);
	OPCODE(113, o_dockVaultOpen);
	OPCODE(114, o_dockVaultClose);
	OPCODE(115, o_bookGivePage);
	OPCODE(116, o_clockWheelsExecute);
	OPCODE(117, o_imagerPlayButton);
	OPCODE(118, o_imagerEraseButton);
	OPCODE(119, o_towerElevatorAnimation);
	OPCODE(120, o_generatorButtonPressed);
	OPCODE(121, o_cabinSafeChangeDigit);
	OPCODE(122, o_cabinSafeHandleStartMove);
	OPCODE(123, o_cabinSafeHandleMove);
	OPCODE(124, o_cabinSafeHandleEndMove);
	OPCODE(126, o_clockLeverStartMove);
	OPCODE(127, o_clockLeverEndMove);
	OPCODE(128, o_treePressureReleaseStart);
	if (!observatoryIsDDMMYYYY2400()) {
		OPCODE(129, o_observatoryMonthChangeStart);
		OPCODE(130, o_observatoryMonthChangeStart);
		OPCODE(131, o_observatoryDayChangeStart);
		OPCODE(132, o_observatoryDayChangeStart);
	} else {
		OPCODE(129, o_observatoryDayChangeStart);
		OPCODE(130, o_observatoryDayChangeStart);
		OPCODE(131, o_observatoryMonthChangeStart);
		OPCODE(132, o_observatoryMonthChangeStart);
	}
	OPCODE(133, o_observatoryGoButton);
	OPCODE(134, o_observatoryMonthSliderMove);
	OPCODE(135, o_observatoryDaySliderMove);
	OPCODE(136, o_observatoryYearSliderMove);
	OPCODE(137, o_observatoryTimeSliderMove);
	OPCODE(138, o_clockResetLeverStartMove);
	OPCODE(139, o_clockResetLeverMove);
	OPCODE(140, o_clockResetLeverEndMove);
	OPCODE(141, o_circuitBreakerStartMove);
	OPCODE(142, o_circuitBreakerMove);
	OPCODE(143, o_circuitBreakerEndMove);
	OPCODE(144, o_clockLeverMove);
	OPCODE(145, o_clockLeverMove);
	OPCODE(146, o_boilerIncreasePressureStart);
	OPCODE(147, o_boilerLightPilot);
	OPCODE(148, NOP);
	OPCODE(149, o_boilerIncreasePressureStop);
	OPCODE(150, o_boilerDecreasePressureStart);
	OPCODE(151, o_boilerDecreasePressureStop);
	OPCODE(152, NOP);
	OPCODE(153, o_basementIncreasePressureStart);
	OPCODE(154, o_basementIncreasePressureStop);
	OPCODE(155, o_basementDecreasePressureStart);
	OPCODE(156, o_basementDecreasePressureStop);
	OPCODE(157, o_rocketPianoMove);
	OPCODE(158, o_rocketSoundSliderStartMove);
	OPCODE(159, o_rocketSoundSliderMove);
	OPCODE(160, o_rocketSoundSliderEndMove);
	OPCODE(161, o_rocketPianoStart);
	OPCODE(162, o_rocketPianoStop);
	OPCODE(163, o_rocketLeverStartMove);
	OPCODE(164, o_rocketOpenBook);
	OPCODE(165, o_rocketLeverMove);
	OPCODE(166, o_rocketLeverEndMove);
	OPCODE(167, NOP);
	OPCODE(168, o_treePressureReleaseStop);
	OPCODE(169, o_cabinLeave);
	OPCODE(170, o_observatoryMonthSliderStartMove);
	OPCODE(171, o_observatoryMonthSliderEndMove);
	OPCODE(172, o_observatoryDaySliderStartMove);
	OPCODE(173, o_observatoryDaySliderEndMove);
	OPCODE(174, o_observatoryYearSliderStartMove);
	OPCODE(175, o_observatoryYearSliderEndMove);
	OPCODE(176, o_observatoryTimeSliderStartMove);
	OPCODE(177, o_observatoryTimeSliderEndMove);
	OPCODE(180, o_libraryCombinationBookStop);
	OPCODE(181, NOP);
	OPCODE(182, o_cabinMatchLight);
	OPCODE(183, o_courtyardBoxEnter);
	OPCODE(184, o_courtyardBoxLeave);
	OPCODE(185, NOP);
	OPCODE(186, o_clockMinuteWheelStartTurn);
	OPCODE(187, NOP);
	OPCODE(188, o_clockWheelEndTurn);
	OPCODE(189, o_clockHourWheelStartTurn);
	OPCODE(190, o_libraryCombinationBookStartRight);
	OPCODE(191, o_libraryCombinationBookStartLeft);
	OPCODE(192, o_observatoryTimeChangeStart);
	OPCODE(193, NOP);
	OPCODE(194, o_observatoryChangeSettingStop);
	OPCODE(195, o_observatoryTimeChangeStart);
	OPCODE(196, o_observatoryYearChangeStart);
	OPCODE(197, o_observatoryYearChangeStart);
	OPCODE(198, o_dockVaultForceClose);
	OPCODE(199, o_imagerEraseStop);

	// "Init" Opcodes
	OPCODE(200, o_libraryBook_init);
	OPCODE(201, o_courtyardBox_init);
	OPCODE(202, o_towerRotationMap_init);
	OPCODE(203, o_forechamberDoor_init);
	OPCODE(204, o_shipAccess_init);
	OPCODE(205, NOP);
	OPCODE(206, o_butterflies_init);
	OPCODE(208, o_imager_init);
	OPCODE(209, o_libraryBookcaseTransform_init);
	OPCODE(210, o_generatorControlRoom_init);
	OPCODE(211, o_fireplace_init);
	OPCODE(212, o_clockGears_init);
	OPCODE(213, o_gulls1_init);
	OPCODE(214, o_observatory_init);
	OPCODE(215, o_gulls2_init);
	OPCODE(216, o_treeCard_init);
	OPCODE(217, o_treeEntry_init);
	OPCODE(218, o_boilerMovies_init);
	OPCODE(219, o_rocketSliders_init);
	OPCODE(220, o_rocketLinkVideo_init);
	OPCODE(221, o_greenBook_init);
	OPCODE(222, o_gulls3_init);

	// "Exit" Opcodes
	OPCODE(300, o_bookAddSpecialPage_exit);
	OPCODE(301, NOP);
	OPCODE(302, NOP);
	OPCODE(303, NOP);
	OPCODE(304, o_treeCard_exit);
	OPCODE(305, o_treeEntry_exit);
	OPCODE(306, o_boiler_exit);
	OPCODE(307, o_generatorControlRoom_exit);
	OPCODE(308, NOP);
	OPCODE(309, NOP);
	OPCODE(312, NOP);
}

#undef OPCODE

void Myst::disablePersistentScripts() {
	_libraryBookcaseMoving = false;
	_generatorControlRoomRunning = false;
	_libraryCombinationBookPagesTurning = false;
	_clockTurningWheel = 0;
	_towerRotationMapRunning = false;
	_boilerPressureIncreasing = false;
	_boilerPressureDecreasing = false;
	_basementPressureIncreasing = false;
	_basementPressureDecreasing = false;
	_imagerValidationRunning = false;
	_imagerRunning = false;
	_observatoryRunning = false;
	_observatoryMonthChanging = false;
	_observatoryDayChanging = false;
	_observatoryYearChanging = false;
	_observatoryTimeChanging = false;
	_greenBookRunning = false;
	_clockLeverPulled = false;
	_gullsFlying1 = false;
	_gullsFlying2 = false;
	_gullsFlying3 = false;
}

void Myst::runPersistentScripts() {
	if (_towerRotationMapRunning)
		towerRotationMap_run();

	if (_generatorControlRoomRunning)
		generatorControlRoom_run();

	if (_libraryCombinationBookPagesTurning)
		libraryCombinationBook_run();

	if (_libraryBookcaseMoving)
		libraryBookcaseTransform_run();

	if (_clockTurningWheel)
		clockWheel_run();

	if (_matchBurning)
		matchBurn_run();

	if (_boilerPressureIncreasing)
		boilerPressureIncrease_run();

	if (_boilerPressureDecreasing)
		boilerPressureDecrease_run();

	if (_basementPressureIncreasing)
		basementPressureIncrease_run();

	if (_basementPressureDecreasing)
		basementPressureDecrease_run();

	if (!_treeStopped)
		tree_run();

	if (_imagerValidationRunning)
		imagerValidation_run();

	if (_imagerRunning)
		imager_run();

	if (_observatoryRunning)
		observatory_run();

	if (_observatoryMonthChanging)
		observatoryMonthChange_run();

	if (_observatoryDayChanging)
		observatoryDayChange_run();

	if (_observatoryYearChanging)
		observatoryYearChange_run();

	if (_observatoryTimeChanging)
		observatoryTimeChange_run();

	if (_greenBookRunning)
		greenBook_run();

	if (_clockLeverPulled)
		clockGears_run();

	if (_gullsFlying1)
		gullsFly1_run();

	if (_gullsFlying2)
		gullsFly2_run();

	if (_gullsFlying3)
		gullsFly3_run();
}

uint16 Myst::getVar(uint16 var) {
	switch(var) {
	case 0: // Myst Library Bookcase Closed
		return _state.libraryBookcaseDoor;
	case 1:
		if (_globals.ending != 4)
			return _state.libraryBookcaseDoor != 1;
		else if (_state.libraryBookcaseDoor == 1)
			return 2;
		else
			return 3;
	case 2: // Marker Switch Near Cabin
		return _state.cabinMarkerSwitch;
	case 3: // Marker Switch Near Clock Tower
		return _state.clockTowerMarkerSwitch;
	case 4: // Marker Switch on Dock
		return _state.dockMarkerSwitch;
	case 5: // Marker Switch Near Ship Pool
		return _state.poolMarkerSwitch;
	case 6: // Marker Switch Near Cogs
		return _state.gearsMarkerSwitch;
	case 7: // Marker Switch Near Generator Room
		return _state.generatorMarkerSwitch;
	case 8: // Marker Switch Near Stellar Observatory
		return _state.observatoryMarkerSwitch;
	case 9: // Marker Switch Near Rocket Ship
		return _state.rocketshipMarkerSwitch;
	case 10: // Ship Floating State
		return _state.shipFloating;
	case 11: // Cabin Door Open State
		return _cabinDoorOpened;
	case 12: // Clock tower gears bridge
		return _state.clockTowerBridgeOpen;
	case 13: // Tower in right position
		return _state.towerRotationAngle == 271
				|| _state.towerRotationAngle == 83
				|| _state.towerRotationAngle == 129
				|| _state.towerRotationAngle == 152;
	case 14: // Tower Solution (Key) Plaque
		switch (_state.towerRotationAngle) {
		case 271:
			return 1;
		case 83:
			return 2;
		case 129:
			return 3;
		case 152:
			return 4;
		default:
			return 0;
		}
	case 15: // Tower Window (Book) View
		switch (_state.towerRotationAngle) {
		case 271:
			return 1;
		case 83:
			if (_state.gearsOpen)
				return 6;
			else
				return 2;
		case 129:
			if (_state.shipFloating)
				return 5;
			else
				return 3;
		case 152:
			return 4;
		default:
			return 0;
		}
	case 16: // Tower Window (Book) View From Ladder Top
		if (_state.towerRotationAngle != 271 && _state.towerRotationAngle != 83	&& _state.towerRotationAngle != 129) {
			if (_state.towerRotationAngle == 152)
				return 2;
			else
				return 0;
		} else
			return 1;
	case 23: // Fireplace Pattern Correct
		return _fireplaceLines[0] == 195
				&& _fireplaceLines[1] == 107
				&& _fireplaceLines[2] == 163
				&& _fireplaceLines[3] == 147
				&& _fireplaceLines[4] == 204
				&& _fireplaceLines[5] == 250;
	case 24: // Fireplace Blue Page Present
		if (_globals.ending != 4)
			return !(_globals.bluePagesInBook & 32) && (_globals.heldPage != 6);
		else
			return 0;
	case 25: // Fireplace Red Page Present
		if (_globals.ending != 4)
			return !(_globals.redPagesInBook & 32) && (_globals.heldPage != 12);
		else
			return 0;
	case 26: // Courtyard Image Box - Cross
	case 27: // Courtyard Image Box - Leaf
	case 28: // Courtyard Image Box - Arrow
	case 29: // Courtyard Image Box - Eye
	case 30: // Courtyard Image Box - Snake
	case 31: // Courtyard Image Box - Spider
	case 32: // Courtyard Image Box - Anchor
	case 33: // Courtyard Image Box - Ostrich
		if (!_tempVar)
			return 0;
		else if (_state.courtyardImageBoxes & (0x01 << (var - 26)))
			return 2;
		else
			return 1;
	case 34: // Sound Control In Dock forechamber
		if (_state.imagerActive) {
			if (_state.imagerSelection == 40 && !_state.imagerMountainErased)
				return 1;
			else if (_state.imagerSelection == 67 && !_state.imagerWaterErased)
				return 2;
			else
				return 0;
		}

		return 0;
	case 35: // Dock Forechamber Imager Control Left Digit
		if (_state.imagerSelection > 9)
			return _state.imagerSelection / 10 - 1;
		else
			return 9;
	case 36: // Dock Forechamber Imager Control Right Digit
		return (10 + _state.imagerSelection - 1) % 10;
	case 37: // Clock Tower Control Wheels Position
		return 3 * ((_state.clockTowerMinutePosition / 5) % 3) + _state.clockTowerHourPosition % 3;
	case 40: // Gears Open State
		return _state.gearsOpen;
	case 41: // Dock Marker Switch Vault State
		return _dockVaultState;
	case 43: // Clock Tower Time
		return _state.clockTowerHourPosition * 12 + _state.clockTowerMinutePosition / 5;
	case 44: // Rocket ship power state
		if (_state.generatorBreakers || _state.generatorVoltage == 0)
			return 0;
		else if (_state.generatorVoltage != 59)
			return 1;
		else
			return 2;
	case 45: // Dock Vault Imager Active On Water
		return _state.imagerActive && _state.imagerSelection == 67 && !_state.imagerWaterErased;
	case 46:
		return bookCountPages(100);
	case 47:
		return bookCountPages(101);
	case 48:
		if (_state.dockMarkerSwitch && !_state.shipFloating)
			return 1;
		else if (!_state.dockMarkerSwitch && _state.shipFloating)
			return 2;
		else
			return 0;
	case 49: // Generator running
		return _state.generatorVoltage > 0;
	case 51: // Forechamber Imager Movie Control
		if (_state.imagerSelection == 40 && !_state.imagerMountainErased)
			return 1;
		else if (_state.imagerSelection == 67 && !_state.imagerWaterErased)
			return 2;
		else if (_state.imagerSelection == 8 && !_state.imagerAtrusErased)
			return 3;
		else if (_state.imagerSelection == 47 && !_state.imagerMarkerErased)
			return 4;
		else
			return 0;
	case 52: // Generator Switch #1
	case 53: // Generator Switch #2
	case 54: // Generator Switch #3
	case 55: // Generator Switch #4
	case 56: // Generator Switch #5
	case 57: // Generator Switch #6
	case 58: // Generator Switch #7
	case 59: // Generator Switch #8
	case 60: // Generator Switch #9
	case 61: // Generator Switch #10
		return (_state.generatorButtons & (1 << (var - 52))) != 0;
	case 62: // Generator Power Dial Left LED Digit
		return _generatorVoltage / 10;
	case 63: // Generator Power Dial Right LED Digit
		return _generatorVoltage % 10;
	case 64: // Generator Power To Spaceship Dial Left LED Digit
		if (_state.generatorVoltage > 59 || _state.generatorBreakers)
			return 0;
		else
			return _state.generatorVoltage / 10;
	case 65: // Generator Power To Spaceship Dial Right LED Digit
		if (_state.generatorVoltage > 59 || _state.generatorBreakers)
			return 0;
		else
			return _state.generatorVoltage % 10;
	case 66: // Generators lights on
		return 0;
	case 67: // Cabin Safe Lock Number #1 - Left
		return _state.cabinSafeCombination / 100;
	case 68: // Cabin Safe Lock Number #2
		return (_state.cabinSafeCombination / 10) % 10;
	case 69: // Cabin Safe Lock Number #3 - Right
		return _state.cabinSafeCombination % 10;
	case 70: // Cabin Safe Matchbox State
		return _cabinMatchState;
	case 71: // Stellar Observatory Lights
		return _state.observatoryLights;
	case 72: // Channelwood tree position
		return _state.treePosition;
	case 73: // Stellar Observatory Date - Month
		return _state.observatoryMonthSetting;
	case 74: // Stellar Observatory Date - Day #1 (Left)
		if (_state.observatoryDaySetting / 10 == 0)
			return 10;
		else
			return _state.observatoryDaySetting / 10;
	case 75: // Stellar Observatory Date - Day #2 (Right)
		return _state.observatoryDaySetting % 10;
	case 76: // Stellar Observatory Date - Year #1 (Left)
		if (_state.observatoryYearSetting >= 1000)
			return (_state.observatoryYearSetting / 1000) % 10;
		else
			return 10;
	case 77: // Stellar Observatory Date - Year #2
		if (_state.observatoryYearSetting >= 100)
			return (_state.observatoryYearSetting / 100) % 10;
		else
			return 10;
	case 78: // Stellar Observatory Date - Year #3
		if (_state.observatoryYearSetting >= 10)
			return (_state.observatoryYearSetting / 10) % 10;
		else
			return 10;
	case 79: // Stellar Observatory Date - Year #4 (Right)
		return (_state.observatoryYearSetting / 1) % 10;
	case 80: // Stellar Observatory Hour #1 - Left ( Number 1 (0) or Blank (10))
		if (!observatoryIsDDMMYYYY2400()) {
			if (_state.observatoryTimeSetting % (12 * 60) < (10 * 60))
				return 10;
			else
				return 1;
		} else {
			if (_state.observatoryTimeSetting < (10 * 60))
				return 10;
			else if (_state.observatoryTimeSetting < (20 * 60))
				return 1;
			else
				return 2;
		}
	case 81: // Stellar Observatory Hour #2 - Right
		if (!observatoryIsDDMMYYYY2400())
			return ((_state.observatoryTimeSetting % (12 * 60)) / 60) % 10;
		else
			return (_state.observatoryTimeSetting / 60) % 10;
	case 82: // Stellar Observatory Minutes #1 - Left
		return (_state.observatoryTimeSetting % 60) / 10;
	case 83: // Stellar Observatory Minutes #2 - Right
		return (_state.observatoryTimeSetting % 60) % 10;
	case 88: // Stellar Observatory AM/PM
		if (_state.observatoryTimeSetting < (12 * 60))
			return 0; // AM
		else
			return 1; // PM
	case 89:
	case 90:
	case 91:
	case 92: // Stellar observatory sliders state
		return 1;
	case 93: // Breaker nearest Generator Room Blown
		return _state.generatorBreakers == 1;
	case 94: // Breaker nearest Rocket Ship Blown
		return _state.generatorBreakers == 2;
	case 95: // Going out of tree destination selection
		if (_state.treePosition == 0)
			return 0;
		else if (_state.treePosition == 4 || _state.treePosition == 5)
			return 1;
		else
			return 2;
	case 96: // Generator Power Dial Needle Position
		return _state.generatorVoltage / 4;
	case 97: // Generator Power To Spaceship Dial Needle Position
		if (_state.generatorVoltage > 59 || _state.generatorBreakers)
			return 0;
		else
			return _state.generatorVoltage / 4;
	case 98: // Cabin Boiler Pilot Light Lit
		return _state.cabinPilotLightLit;
	case 99: // Cabin Boiler Gas Valve Position
		return _state.cabinValvePosition % 6;
	case 102: // Red page
		if (_globals.ending != 4)
			return !(_globals.redPagesInBook & 1) && (_globals.heldPage != 7);
		else
			return 0;
	case 103: // Blue page
		if (_globals.ending != 4)
			return !(_globals.bluePagesInBook & 1) && (_globals.heldPage != 1);
		else
			return 0;
	case 300: // Rocket Ship Music Puzzle Slider State
		return 1;
	case 302: // Green Book Opened Before Flag
		return _state.greenBookOpenedBefore;
	case 303: // Library Bookcase status changed
		return _libraryBookcaseChanged;
	case 304: // Tower Rotation Map Initialized
		return _towerRotationMapInitialized;
	case 305: // Cabin Boiler Lit
		return _state.cabinPilotLightLit == 1 && _state.cabinValvePosition > 0;
	case 306: // Cabin Boiler Steam Sound Control
		if (_state.cabinPilotLightLit == 1) {
			if (_state.cabinValvePosition <= 0)
				return 26;
			else
				return 27;
		}

		return _state.cabinValvePosition;
	case 307: // Cabin Boiler Fully Pressurized
		return _state.cabinPilotLightLit == 1 && _state.cabinValvePosition > 12;
	case 308: // Cabin handle position
		return _cabinHandleDown;
	default:
		return MystScriptParser::getVar(var);
	}
}

void Myst::toggleVar(uint16 var) {
	switch(var) {
	case 2: // Marker Switch Near Cabin
		_state.cabinMarkerSwitch = (_state.cabinMarkerSwitch + 1) % 2;
		break;
	case 3: // Marker Switch Near Clock Tower
		_state.clockTowerMarkerSwitch = (_state.clockTowerMarkerSwitch + 1) % 2;
		break;
	case 4: // Marker Switch on Dock
		_state.dockMarkerSwitch = (_state.dockMarkerSwitch + 1) % 2;
		break;
	case 5: // Marker Switch Near Ship Pool
		_state.poolMarkerSwitch = (_state.poolMarkerSwitch + 1) % 2;
		break;
	case 6: // Marker Switch Near Cogs
		_state.gearsMarkerSwitch = (_state.gearsMarkerSwitch + 1) % 2;
		break;
	case 7: // Marker Switch Near Generator Room
		_state.generatorMarkerSwitch = (_state.generatorMarkerSwitch + 1) % 2;
		break;
	case 8: // Marker Switch Near Stellar Observatory
		_state.observatoryMarkerSwitch = (_state.observatoryMarkerSwitch + 1) % 2;
		break;
	case 9: // Marker Switch Near Rocket Ship
		_state.rocketshipMarkerSwitch = (_state.rocketshipMarkerSwitch + 1) % 2;
		break;
	case 24: // Fireplace Blue Page
		if (_globals.ending != 4 && !(_globals.bluePagesInBook & 32)) {
			if (_globals.heldPage == 6)
				_globals.heldPage = 0;
			else
				_globals.heldPage = 6;
		}
		break;
	case 25: // Fireplace Red page
		if (_globals.ending != 4 && !(_globals.redPagesInBook & 32)) {
			if (_globals.heldPage == 12)
				_globals.heldPage = 0;
			else
				_globals.heldPage = 12;
		}
		break;
	case 26: // Courtyard Image Box - Cross
	case 27: // Courtyard Image Box - Leaf
	case 28: // Courtyard Image Box - Arrow
	case 29: // Courtyard Image Box - Eye
	case 30: // Courtyard Image Box - Snake
	case 31: // Courtyard Image Box - Spider
	case 32: // Courtyard Image Box - Anchor
	case 33: // Courtyard Image Box - Ostrich
		{
			uint16 mask = 0x01 << (var - 26);
			if (_state.courtyardImageBoxes & mask)
				_state.courtyardImageBoxes &= ~mask;
			else
				_state.courtyardImageBoxes |= mask;
		}
		break;
	case 41: // Vault white page
		if (_globals.ending != 4) {
			if (_dockVaultState == 1) {
				_dockVaultState = 2;
				_globals.heldPage = 0;
			} else if (_dockVaultState == 2) {
				_dockVaultState = 1;
				_globals.heldPage = 13;
			}
		}
		break;
	case 102: // Red page
		if (_globals.ending != 4 && !(_globals.redPagesInBook & 1)) {
			if (_globals.heldPage == 7)
				_globals.heldPage = 0;
			else
				_globals.heldPage = 7;
		}
		break;
	case 103: // Blue page
		if (_globals.ending != 4 && !(_globals.bluePagesInBook & 1)) {
			if (_globals.heldPage == 1)
				_globals.heldPage = 0;
			else
				_globals.heldPage = 1;
		}
		break;
	default:
		MystScriptParser::toggleVar(var);
		break;
	}
}

bool Myst::setVarValue(uint16 var, uint16 value) {
	bool refresh = false;

	switch (var) {
	case 0: // Myst Library Bookcase Closed
		if (_state.libraryBookcaseDoor != value) {
			_state.libraryBookcaseDoor = value;
			_tempVar = 0;
			refresh = true;
		}
		break;
	case 11: // Cabin Door Open State
		if (_cabinDoorOpened != value) {
			_cabinDoorOpened = value;
			refresh = true;
		}
		break;
	case 70: // Cabin Safe Matchbox State
		if (_cabinMatchState != value) {
			_cabinMatchState = value;
			refresh = true;
		}
		break;
	case 71: // Stellar Observatory Lights
		_state.observatoryLights = value;
		break;
	case 89:
	case 90:
	case 91:
	case 92:
	case 300: // Set slider value
		break; // Do nothing
	case 302: // Green Book Opened Before Flag
		_state.greenBookOpenedBefore = value;
		break;
	case 303: // Library Bookcase status changed
		_libraryBookcaseChanged = value;
		break;
	case 304: // Myst Library Image Present on Tower Rotation Map
		_towerRotationMapInitialized = value;
		break;
	case 308: // Cabin handle position
		_cabinHandleDown = value;
		break;
	case 309: // Tree stopped
		_treeStopped = value;
		break;
	case 310: // Imager validation step
		_imagerValidationStep = value;
		break;
	default:
		refresh = MystScriptParser::setVarValue(var, value);
		break;
	}

	return refresh;
}

uint16 Myst::bookCountPages(uint16 var) {
	uint16 pages = 0;
	uint16 cnt = 0;

	// Select book according to var
	if (var == 100)
		pages = _globals.redPagesInBook;
	else if (var == 101)
		pages = _globals.bluePagesInBook;

	// Special page present
	if (pages & 64)
		return 6;

	// Count pages
	if (pages & 1)
		cnt++;

	if (pages & 2)
		cnt++;

	if (pages & 4)
		cnt++;

	if (pages & 8)
		cnt++;

	if (pages & 16)
		cnt++;

	return cnt;
}

void Myst::o_libraryBookPageTurnLeft(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Turn book page left", op);

	if (_libraryBookPage - 1 >= 0) {
		_libraryBookPage--;

		Common::Rect rect = Common::Rect(0, 0, 544, 333);
		_vm->_gfx->copyImageToScreen(_libraryBookBaseImage + _libraryBookPage, rect);

		if (_vm->_rnd->getRandomBit())
			_vm->_sound->replaceSoundMyst(_libraryBookSound1);
		else
			_vm->_sound->replaceSoundMyst(_libraryBookSound2);

		_vm->_system->updateScreen();
	}
}

void Myst::o_libraryBookPageTurnRight(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Turn book page right", op);

	if (_libraryBookPage + 1 < _libraryBookNumPages) {
		_libraryBookPage++;

		Common::Rect rect = Common::Rect(0, 0, 544, 333);
		_vm->_gfx->copyImageToScreen(_libraryBookBaseImage + _libraryBookPage, rect);

		if (_vm->_rnd->getRandomBit())
			_vm->_sound->replaceSoundMyst(_libraryBookSound1);
		else
			_vm->_sound->replaceSoundMyst(_libraryBookSound2);

		_vm->_system->updateScreen();
	}
}

void Myst::o_fireplaceToggleButton(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	// Used on Myst Card 4162 (Fireplace Grid)
	debugC(kDebugScript, "Opcode %d: Fireplace grid toggle button", op);

	uint16 bitmask = argv[0];
	uint16 line = _fireplaceLines[var - 17];

	debugC(kDebugScript, "\tvar: %d", var);
	debugC(kDebugScript, "\tbitmask: 0x%02X", bitmask);

	if (line & bitmask) {
		// Unset button
		for (uint i = 4795; i >= 4779; i--) {
			_vm->_gfx->copyImageToScreen(i, getInvokingResource<MystArea>()->getRect());
			_vm->_system->updateScreen();
		}
		_fireplaceLines[var - 17] &= ~bitmask;
	} else {
		// Set button
		for (uint i = 4779; i <= 4795; i++) {
			_vm->_gfx->copyImageToScreen(i, getInvokingResource<MystArea>()->getRect());
			_vm->_system->updateScreen();
		}
		_fireplaceLines[var - 17] |= bitmask;
	}
}

void Myst::o_fireplaceRotation(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	// Used on Myst Card 4162 and 4166 (Fireplace Puzzle Rotation Movies)
	uint16 movieNum = argv[0];
	debugC(kDebugScript, "Opcode %d: Play Fireplace Puzzle Rotation Movies", op);
	debugC(kDebugScript, "\tmovieNum: %d", movieNum);

	if (movieNum)
		_vm->_video->playMovieBlocking(_vm->wrapMovieFilename("fpout", kMystStack), 167, 4);
	else
		_vm->_video->playMovieBlocking(_vm->wrapMovieFilename("fpin", kMystStack), 167, 4);
}

void Myst::o_courtyardBoxesCheckSolution(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	uint16 soundId = argv[0];

	debugC(kDebugScript, "Opcode %d: Ship Puzzle Logic", op);
	debugC(kDebugScript, "\tsoundId: %d", soundId);

	// Change ship state if the boxes are correctly enabled
	if (_state.courtyardImageBoxes == 50 && !_state.shipFloating) {
		_vm->_cursor->hideCursor();
		_state.shipFloating = 1;
		_vm->_sound->playSoundBlocking(soundId);
		_vm->_cursor->showCursor();
	} else if (_state.courtyardImageBoxes != 50 && _state.shipFloating) {
		_vm->_cursor->hideCursor();
		_state.shipFloating = 0;
		_vm->_sound->playSoundBlocking(soundId);
		_vm->_cursor->showCursor();
	}
}

void Myst::o_towerRotationStart(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	_towerRotationBlinkLabel = false;
	_towerRotationMapClicked = true;
	_towerRotationSpeed = 0;

	_vm->_cursor->setCursor(700);

	const Common::Point center = Common::Point(383, 124);
	Common::Point end = towerRotationMapComputeCoords(center, _state.towerRotationAngle);
	towerRotationMapComputeAngle();
	towerRotationMapDrawLine(center, end);

	_vm->_sound->replaceSoundMyst(5378, Audio::Mixer::kMaxChannelVolume, true);
}

void Myst::o_towerRotationEnd(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	_towerRotationMapClicked = false;

	// Set angle value to expected value
	if (_state.towerRotationAngle >= 265
			&& _state.towerRotationAngle <= 277
			&& _state.rocketshipMarkerSwitch) {
		_state.towerRotationAngle = 271;
	} else if (_state.towerRotationAngle >= 77
			&& _state.towerRotationAngle <= 89
			&& _state.gearsMarkerSwitch) {
		_state.towerRotationAngle = 83;
	} else if (_state.towerRotationAngle >= 123
			&& _state.towerRotationAngle <= 135
			&& _state.dockMarkerSwitch) {
		_state.towerRotationAngle = 129;
	} else if (_state.towerRotationAngle >= 146
			&& _state.towerRotationAngle <= 158
			&& _state.cabinMarkerSwitch) {
		_state.towerRotationAngle = 152;
	}

	_vm->_sound->replaceSoundMyst(6378);

	_towerRotationBlinkLabel = true;
	_towerRotationBlinkLabelCount = 0;
}

void Myst::o_imagerChangeSelection(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Dock imager change selection", op);

	if (_imagerValidationStep != 10) {
		_imagerValidationStep = 0;

		int16 signedValue = argv[0];
		uint16 d1 = (_state.imagerSelection / 10) % 10;
		uint16 d2 = _state.imagerSelection % 10;

		if (var == 35 && signedValue > 0 && d1 < 9)
			d1++;
		else if (var == 35 && signedValue < 0 && d1 > 0)
			d1--;
		else if (var == 36 && signedValue > 0 && d2 < 9)
			d2++;
		else if (var == 36 && signedValue < 0 && d2 > 0)
			d2--;

		_state.imagerSelection = 10 * d1 + d2;
		_state.imagerActive = 0;

		_vm->redrawArea(var);
	}
}

void Myst::o_dockVaultOpen(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	// Used on Myst 4143 (Dock near Marker Switch)
	uint16 soundId = argv[0];
	uint16 delay = argv[1];
	uint16 directionalUpdateDataSize = argv[2];

	debugC(kDebugScript, "Opcode %d: Vault Open Logic", op);
	debugC(kDebugScript, "\tsoundId: %d", soundId);
	debugC(kDebugScript, "\tdirectionalUpdateDataSize: %d", directionalUpdateDataSize);

	if ((_state.cabinMarkerSwitch == 1) &&
		(_state.clockTowerMarkerSwitch == 1) &&
		(_state.dockMarkerSwitch == 0) &&
		(_state.gearsMarkerSwitch == 1) &&
		(_state.generatorMarkerSwitch == 1) &&
		(_state.observatoryMarkerSwitch == 1) &&
		(_state.poolMarkerSwitch == 1) &&
		(_state.rocketshipMarkerSwitch == 1)) {
		if (_globals.heldPage != 13 && _globals.ending != 4)
			_dockVaultState = 2;
		else
			_dockVaultState = 1;

		_vm->_sound->replaceSoundMyst(soundId);
		_vm->redrawArea(41, false);
		animatedUpdate(directionalUpdateDataSize, &argv[3], delay);
	}
}

void Myst::o_dockVaultClose(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	// Used on Myst 4143 (Dock near Marker Switch)
	uint16 soundId = argv[0];
	uint16 delay = argv[1];
	uint16 directionalUpdateDataSize = argv[2];

	debugC(kDebugScript, "Opcode %d: Vault Close Logic", op);
	debugC(kDebugScript, "\tsoundId: %d", soundId);
	debugC(kDebugScript, "\tdirectionalUpdateDataSize: %d", directionalUpdateDataSize);

	if ((_state.cabinMarkerSwitch == 1) &&
		(_state.clockTowerMarkerSwitch == 1) &&
		(_state.dockMarkerSwitch == 1) &&
		(_state.gearsMarkerSwitch == 1) &&
		(_state.generatorMarkerSwitch == 1) &&
		(_state.observatoryMarkerSwitch == 1) &&
		(_state.poolMarkerSwitch == 1) &&
		(_state.rocketshipMarkerSwitch == 1)) {
		if (_dockVaultState == 1 || _dockVaultState == 2)
			_dockVaultState = 0;

		_vm->_sound->replaceSoundMyst(soundId);
		_vm->redrawArea(41, false);
		animatedUpdate(directionalUpdateDataSize, &argv[3], delay);
	}
}

void Myst::o_bookGivePage(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	uint16 cardIdLose = argv[0];
	uint16 cardIdBookCover = argv[1];
	uint16 soundIdAddPage = argv[2];

	debugC(kDebugScript, "Opcode %d: Red and Blue Book/Page Interaction", op);
	debugC(kDebugScript, "Var: %d", var);
	debugC(kDebugScript, "Card Id (Lose): %d", cardIdLose);
	debugC(kDebugScript, "Card Id (Book Cover): %d", cardIdBookCover);
	debugC(kDebugScript, "SoundId (Add Page): %d", soundIdAddPage);

	// No page or white page
	if (!_globals.heldPage || _globals.heldPage == 13) {
		_vm->changeToCard(cardIdBookCover, kTransitionDissolve);
		return;
	}

	uint16 bookVar = 101;
	uint16 mask = 0;

	switch (_globals.heldPage) {
	case 7:
		bookVar = 100;
	case 1:
		mask = 1;
		break;
	case 8:
		bookVar = 100;
	case 2:
		mask = 2;
		break;
	case 9:
		bookVar = 100;
	case 3:
		mask = 4;
		break;
	case 10:
		bookVar = 100;
	case 4:
		mask = 8;
		break;
	case 11:
		bookVar = 100;
	case 5:
		mask = 16;
		break;
	case 12:
		bookVar = 100;
	case 6:
		mask = 32;
		break;
	}

	// Wrong book
	if (bookVar != var) {
		_vm->changeToCard(cardIdBookCover, kTransitionDissolve);
		return;
	}

	_vm->_cursor->hideCursor();
	_vm->_sound->playSoundBlocking(soundIdAddPage);
	_vm->setMainCursor(kDefaultMystCursor);

	// Add page to book
	if (var == 100)
		_globals.redPagesInBook |= mask;
	else
		_globals.bluePagesInBook |= mask;

	// Remove page from hand
	_globals.heldPage = 0;

	_vm->_cursor->showCursor();

	if (mask == 32) {
		// You lose!
		if (var == 100)
			_globals.currentAge = 9;
		else
			_globals.currentAge = 10;

		_vm->changeToCard(cardIdLose, kTransitionDissolve);
	} else {
		_vm->changeToCard(cardIdBookCover, kTransitionDissolve);
	}
}

void Myst::o_clockWheelsExecute(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	// Used on Card 4006 (Clock Tower Time Controls)
	uint16 soundId = argv[0];

	debugC(kDebugScript, "Opcode %d: Clock Tower Bridge Puzzle Execute Button", op);

	// Correct time is 2:40
	bool correctTime = _state.clockTowerHourPosition == 2
						&& _state.clockTowerMinutePosition == 40;

	if (!_state.clockTowerBridgeOpen && correctTime) {
		_vm->_sound->replaceSoundMyst(soundId);
		_vm->_system->delayMillis(500);

		// Gears rise up
		VideoHandle gears = _vm->_video->playMovie(_vm->wrapMovieFilename("gears", kMystStack));
		if (!gears)
			error("Failed to open gears movie");

		gears->moveTo(305, 33);
		gears->setBounds(Audio::Timestamp(0, 0, 600), Audio::Timestamp(0, 650, 600));
		_vm->_video->waitUntilMovieEnds(gears);

		_state.clockTowerBridgeOpen = 1;
		_vm->redrawArea(12);
	} else if (_state.clockTowerBridgeOpen && !correctTime) {
		_vm->_sound->replaceSoundMyst(soundId);
		_vm->_system->delayMillis(500);

		// Gears sink down
		VideoHandle gears = _vm->_video->playMovie(_vm->wrapMovieFilename("gears", kMystStack));
		if (!gears)
			error("Failed to open gears movie");

		gears->moveTo(305, 33);
		gears->setBounds(Audio::Timestamp(0, 700, 600), Audio::Timestamp(0, 1300, 600));
		_vm->_video->waitUntilMovieEnds(gears);

		_state.clockTowerBridgeOpen = 0;
		_vm->redrawArea(12);
	}
}

void Myst::o_imagerPlayButton(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Imager play button", op);

	uint16 video = getVar(51);

	// Press button
	_vm->_sound->replaceSoundMyst(4698);

	Common::Rect src = Common::Rect(0, 0, 32, 75);
	Common::Rect dest = Common::Rect(261, 257, 293, 332);
	_vm->_gfx->copyImageSectionToScreen(4699, src, dest);
	_vm->_system->updateScreen();

	_vm->_system->delayMillis(200);

	_vm->_gfx->copyBackBufferToScreen(dest);
	_vm->_system->updateScreen();

	_vm->_cursor->hideCursor();


	// Play selected video
	if (!_state.imagerActive && video != 3)
		_vm->_sound->replaceSoundMyst(argv[0]);

	switch (video) {
	case 0: // Nothing
	case 3: // Atrus
	case 4: // Marker
		_imagerMovie->playMovie();
		break;
	case 1: // Mountain
		if (_state.imagerActive) {
			// Mountains disappearing
			Common::String file = _vm->wrapMovieFilename("vltmntn", kMystStack);
			VideoHandle mountain = _vm->_video->playMovie(file);
			if (!mountain)
				error("Failed to open '%s'", file.c_str());

			mountain->moveTo(159, 96);
			mountain->setBounds(Audio::Timestamp(0, 11180, 600), Audio::Timestamp(0, 16800, 600));

			_state.imagerActive = 0;
		} else {
			// Mountains appearing
			Common::String file = _vm->wrapMovieFilename("vltmntn", kMystStack);
			VideoHandle mountain = _vm->_video->playMovie(file);
			if (!mountain)
				error("Failed to open '%s'", file.c_str());

			mountain->moveTo(159, 96);
			mountain->setBounds(Audio::Timestamp(0, 0, 600), Audio::Timestamp(0, 11180, 600));

			_state.imagerActive = 1;
		}
		break;
	case 2: // Water
		_imagerMovie->setBlocking(false);

		if (_state.imagerActive) {
			_vm->_sound->replaceSoundMyst(argv[1]);

			// Water disappearing
			VideoHandle water = _imagerMovie->playMovie();
			water->setBounds(Audio::Timestamp(0, 4204, 600), Audio::Timestamp(0, 6040, 600));
			water->setLooping(false);

			_state.imagerActive = 0;
		} else {
			// Water appearing
			VideoHandle water = _imagerMovie->playMovie();
			water->setBounds(Audio::Timestamp(0, 0, 600), Audio::Timestamp(0, 1814, 600));
			_vm->_video->waitUntilMovieEnds(water);

			// Water looping
			water = _imagerMovie->playMovie();
			water->setBounds(Audio::Timestamp(0, 1814, 600), Audio::Timestamp(0, 4204, 600));
			water->setLooping(true);

			_state.imagerActive = 1;
		}
		break;
	}

	_vm->_cursor->showCursor();
}

void Myst::o_imagerEraseButton(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Imager erase button", op);

	_imagerRedButton = static_cast<MystAreaImageSwitch *>(getInvokingResource<MystArea>()->_parent);
	for (uint i = 0; i < 4; i++)
		_imagerSound[i] = argv[i];
	_imagerValidationCard = argv[4];

	if (_imagerValidationStep == 0) {
		// Validation script is not running, run it
		_startTime = _vm->_system->getMillis() + 100;
		_imagerValidationRunning = true;
		return;
	} else if (_imagerValidationStep < 7) {
		// Too early
		_vm->_sound->playSoundBlocking(_imagerSound[2]);
		_imagerValidationStep = 0;
		return;
	} else if (_imagerValidationStep < 11) {
		_vm->_sound->playSoundBlocking(_imagerSound[3]);

		// Erase selected video from imager
		switch (_state.imagerSelection) {
		case 8:
			_state.imagerAtrusErased = 1;
			break;
		case 40:
			_state.imagerMountainErased = 1;
			break;
		case 47:
			_state.imagerMarkerErased = 1;
			break;
		case 67:
			_state.imagerWaterErased = 1;
			break;
		}

		_state.imagerActive = 0;
		_imagerValidationStep = 0;
		return;
	} else if (_imagerValidationStep == 11) {
		// Too late
		_imagerValidationStep = 0;
		return;
	}
}

void Myst::imagerValidation_run() {
	uint32 time = _vm->_system->getMillis();

	if (time > _startTime) {
		_imagerRedButton->drawConditionalDataToScreen(1);

		if (_imagerValidationStep < 6)
			_vm->_sound->replaceSoundMyst(_imagerSound[0]);
		else if (_imagerValidationStep < 10)
			_vm->_sound->replaceSoundMyst(_imagerSound[1]);
		else if (_imagerValidationStep == 10)
			_vm->_sound->replaceSoundMyst(_imagerSound[2]);

		_imagerValidationStep++;

		_vm->_system->delayMillis(50);

		_imagerRedButton->drawConditionalDataToScreen(0);

		if (_imagerValidationStep == 11) {
			_imagerValidationStep = 0;
			_vm->changeToCard(_imagerValidationCard, kTransitionBottomToTop);
		} else {
			_startTime = time + 100;
		}
	}
}

void Myst::o_towerElevatorAnimation(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Tower elevator animation", op);

	_treeStopped = true;

	_vm->_cursor->hideCursor();
	_vm->_sound->stopSound();
	_vm->_sound->pauseBackgroundMyst();

	switch (argv[0]) {
	case 0:
		_vm->_video->playMovieBlocking(_vm->wrapMovieFilename("libdown", kMystStack), 216, 78);
		break;
	case 1:
		_vm->_video->playMovieBlocking(_vm->wrapMovieFilename("libup", kMystStack), 216, 78);
		break;
	default:
		break;
	}

	_vm->_sound->resumeBackgroundMyst();
	_vm->_cursor->showCursor();
	_treeStopped = false;
}

void Myst::o_generatorButtonPressed(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Generator button pressed", op);

	MystArea *button = getInvokingResource<MystArea>()->_parent;

	generatorRedrawRocket();

	_generatorVoltage = _state.generatorVoltage;

	uint16 mask = 0;
	uint16 value = 0;
	generatorButtonValue(button, mask, value);

	// Button pressed
	if (_state.generatorButtons & mask) {
		_state.generatorButtons &= ~mask;
		_state.generatorVoltage -= value;

		if (_state.generatorVoltage)
			_vm->_sound->replaceSoundMyst(8297);
		else {
			_vm->_sound->replaceSoundMyst(9297);
			_vm->_sound->stopBackgroundMyst();
		}
	} else {
		if (_generatorVoltage)
			_vm->_sound->replaceSoundMyst(6297);
		else {
			_vm->_sound->replaceSoundMyst(7297);
			_vm->_sound->replaceBackgroundMyst(4297);
		}

		_state.generatorButtons |= mask;
		_state.generatorVoltage += value;
	}

	// Redraw button
	_vm->redrawArea(button->getImageSwitchVar());

	// Blow breaker
	if (_state.generatorVoltage > 59)
		_state.generatorBreakers = _vm->_rnd->getRandomNumberRng(1, 2);
}

void Myst::generatorRedrawRocket() {
	_vm->redrawArea(64);
	_vm->redrawArea(65);
	_vm->redrawArea(97);
}

void Myst::generatorButtonValue(MystArea *button, uint16 &mask, uint16 &value) {
	switch (button->getImageSwitchVar()) {
	case 52: // Generator Switch #1
		mask = 1;
		value = 10;
		break;
	case 53: // Generator Switch #2
		mask = 2;
		value = 7;
		break;
	case 54: // Generator Switch #3
		mask = 4;
		value = 8;
		break;
	case 55: // Generator Switch #4
		mask = 8;
		value = 16;
		break;
	case 56: // Generator Switch #5
		mask = 16;
		value = 5;
		break;
	case 57: // Generator Switch #6
		mask = 32;
		value = 1;
		break;
	case 58: // Generator Switch #7
		mask = 64;
		value = 2;
		break;
	case 59: // Generator Switch #8
		mask = 128;
		value = 22;
		break;
	case 60: // Generator Switch #9
		mask = 256;
		value = 19;
		break;
	case 61: // Generator Switch #10
		mask = 512;
		value = 9;
		break;
	}
}

void Myst::o_cabinSafeChangeDigit(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Cabin safe change digit", op);

	uint16 d1 = _state.cabinSafeCombination / 100;
	uint16 d2 = (_state.cabinSafeCombination / 10) % 10;
	uint16 d3 = _state.cabinSafeCombination % 10;

	if (var == 67)
		d1 = (d1 + 1) % 10;
	else if (var == 68)
		d2 = (d2 + 1) % 10;
	else
		d3 = (d3 + 1) % 10;

	_state.cabinSafeCombination = 100 * d1 + 10 * d2 + d3;

	_vm->redrawArea(var);
}

void Myst::o_cabinSafeHandleStartMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Cabin safe handle start move", op);

	// Used on Card 4100
	MystVideoInfo *handle = getInvokingResource<MystVideoInfo>();
	handle->drawFrame(0);
	_vm->_cursor->setCursor(700);
	_tempVar = 0;
}

void Myst::o_cabinSafeHandleMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Cabin safe handle move", op);

	// Used on Card 4100
	MystVideoInfo *handle = getInvokingResource<MystVideoInfo>();

	if (handle->pullLeverV()) {
		// Sound not played yet
		if (_tempVar == 0) {
			uint16 soundId = handle->getList2(0);
			if (soundId)
				_vm->_sound->replaceSoundMyst(soundId);
		}
		// Combination is right
		if (_state.cabinSafeCombination == 724) {
			uint16 soundId = handle->getList2(1);
			if (soundId)
				_vm->_sound->replaceSoundMyst(soundId);

			_vm->changeToCard(4103, kNoTransition);

			Common::Rect screenRect = Common::Rect(544, 333);
			_vm->_gfx->runTransition(kTransitionLeftToRight, screenRect, 2, 5);
		}
		_tempVar = 1;
	} else {
		_tempVar = 0;
	}
}

void Myst::o_cabinSafeHandleEndMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Cabin safe handle end move", op);

	// Used on Card 4100
	MystVideoInfo *handle = getInvokingResource<MystVideoInfo>();
	handle->drawFrame(0);
	_vm->checkCursorHints();
}

void Myst::o_observatoryMonthChangeStart(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Observatory month change start", op);

	_vm->_sound->pauseBackgroundMyst();

	if (op == 129 || op == 131) {
		// Increase
		if (observatoryIsDDMMYYYY2400())
			_vm->_gfx->copyImageSectionToScreen(11098, Common::Rect(36, 0, 48, 9), Common::Rect(351, 70, 363, 79));
		else
			_vm->_gfx->copyImageSectionToScreen(11098, Common::Rect(0, 0, 12, 9), Common::Rect(315, 70, 327, 79));

		_observatoryIncrement = -1;
	} else {
		// Decrease
		if (observatoryIsDDMMYYYY2400())
			_vm->_gfx->copyImageSectionToScreen(11097, Common::Rect(36, 0, 48, 9), Common::Rect(351, 204, 363, 213));
		else
			_vm->_gfx->copyImageSectionToScreen(11097, Common::Rect(0, 0, 12, 9), Common::Rect(315, 204, 327, 213));

		_observatoryIncrement = 1;
	}

	// Highlight slider
	_observatoryMonthSlider->drawConditionalDataToScreen(2);
	_observatoryCurrentSlider = _observatoryMonthSlider;

	// First increment
	observatoryIncrementMonth(_observatoryIncrement);

	// Start persistent script
	_startTime = _vm->_system->getMillis();
	_observatoryMonthChanging = true;
}

void Myst::observatoryIncrementMonth(int16 increment) {
	int16 newMonth = _state.observatoryMonthSetting + increment;

	if (newMonth >= 0 && newMonth <= 11) {
		_state.observatoryMonthSetting = newMonth;

		// Redraw digits
		_vm->redrawArea(73);

		// Update slider
		_observatoryMonthSlider->setPosition(94 + 94 * _state.observatoryMonthSetting / 11);
		_observatoryMonthSlider->restoreBackground();
		_observatoryMonthSlider->drawConditionalDataToScreen(2);
		_state.observatoryMonthSlider = _observatoryMonthSlider->_pos.y;
	}

	_vm->_sound->replaceSoundMyst(8500);
}

void Myst::observatoryMonthChange_run() {
	if (_startTime + 500 < _vm->_system->getMillis())
		observatoryIncrementMonth(_observatoryIncrement);
}

void Myst::o_observatoryDayChangeStart(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Observatory day change start", op);

	_vm->_sound->pauseBackgroundMyst();

	if (op == 129 || op == 131) {
		// Increase
		if (observatoryIsDDMMYYYY2400())
			_vm->_gfx->copyImageSectionToScreen(11098, Common::Rect(0, 0, 12, 9), Common::Rect(315, 70, 327, 79));
		else
			_vm->_gfx->copyImageSectionToScreen(11098, Common::Rect(36, 0, 48, 9), Common::Rect(351, 70, 363, 79));

		_observatoryIncrement = -1;
	} else {
		// Decrease
		if (observatoryIsDDMMYYYY2400())
			_vm->_gfx->copyImageSectionToScreen(11097, Common::Rect(0, 0, 12, 9), Common::Rect(315, 204, 327, 213));
		else
			_vm->_gfx->copyImageSectionToScreen(11097, Common::Rect(36, 0, 48, 9), Common::Rect(351, 204, 363, 213));

		_observatoryIncrement = 1;
	}

	// Highlight slider
	_observatoryDaySlider->drawConditionalDataToScreen(2);
	_observatoryCurrentSlider = _observatoryDaySlider;

	// First increment
	observatoryIncrementDay(_observatoryIncrement);

	// Start persistent script
	_startTime = _vm->_system->getMillis();
	_observatoryDayChanging = true;
}

void Myst::observatoryIncrementDay(int16 increment) {
	int16 newDay = _state.observatoryDaySetting + increment;

	if (newDay >= 1 && newDay <= 31) {
		_state.observatoryDaySetting = newDay;

		// Redraw digits
		_vm->redrawArea(75);
		_vm->redrawArea(74);

		// Update slider
		_observatoryDaySlider->setPosition(91 + 3 * _state.observatoryDaySetting);
		_observatoryDaySlider->restoreBackground();
		_observatoryDaySlider->drawConditionalDataToScreen(2);
		_state.observatoryDaySlider = _observatoryDaySlider->_pos.y;
	}

	_vm->_sound->replaceSoundMyst(8500);
}

void Myst::observatoryDayChange_run() {
	if (_startTime + 500 < _vm->_system->getMillis())
		observatoryIncrementDay(_observatoryIncrement);
}

void Myst::o_observatoryYearChangeStart(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Observatory year change start", op);

	_vm->_sound->pauseBackgroundMyst();

	if (op == 196) {
		// Increase
		_vm->_gfx->copyImageSectionToScreen(11098, Common::Rect(72, 0, 84, 9), Common::Rect(387, 70, 399, 79));
		_observatoryIncrement = -1;
	} else {
		// Decrease
		_vm->_gfx->copyImageSectionToScreen(11097, Common::Rect(72, 0, 84, 9), Common::Rect(387, 204, 399, 213));
		_observatoryIncrement = 1;
	}

	// Highlight slider
	_observatoryYearSlider->drawConditionalDataToScreen(2);
	_observatoryCurrentSlider = _observatoryYearSlider;

	// First increment
	observatoryIncrementYear(_observatoryIncrement);

	// Start persistent script
	_startTime = _vm->_system->getMillis();
	_observatoryYearChanging = true;
}

void Myst::observatoryIncrementYear(int16 increment) {
	int16 newYear = _state.observatoryYearSetting + increment;

	if (newYear >= 0 && newYear <= 9999) {
		_state.observatoryYearSetting = newYear;

		// Redraw digits
		_vm->redrawArea(79);
		_vm->redrawArea(78);
		_vm->redrawArea(77);
		_vm->redrawArea(76);

		// Update slider
		_observatoryYearSlider->setPosition(94 + 94 * _state.observatoryYearSetting / 9999);
		_observatoryYearSlider->restoreBackground();
		_observatoryYearSlider->drawConditionalDataToScreen(2);
		_state.observatoryYearSlider = _observatoryYearSlider->_pos.y;
	}

	_vm->_sound->replaceSoundMyst(8500);
}

void Myst::observatoryYearChange_run() {
	if (_startTime + 500 < _vm->_system->getMillis())
		observatoryIncrementYear(_observatoryIncrement);
}

void Myst::o_observatoryTimeChangeStart(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Observatory time change start", op);

	_vm->_sound->pauseBackgroundMyst();

	if (op == 192) {
		// Increase
		_vm->_gfx->copyImageSectionToScreen(11098, Common::Rect(109, 0, 121, 9), Common::Rect(424, 70, 436, 79));
		_observatoryIncrement = -1;
	} else {
		// Decrease
		_vm->_gfx->copyImageSectionToScreen(11097, Common::Rect(109, 0, 121, 9), Common::Rect(424, 204, 436, 213));
		_observatoryIncrement = 1;
	}

	// Highlight slider
	_observatoryTimeSlider->drawConditionalDataToScreen(2);
	_observatoryCurrentSlider = _observatoryTimeSlider;

	// First increment
	observatoryIncrementTime(_observatoryIncrement);

	// Start persistent script
	_startTime = _vm->_system->getMillis();
	_observatoryTimeChanging = true;
}

void Myst::observatoryIncrementTime(int16 increment) {
	int16 newTime = _state.observatoryTimeSetting + increment;

	if (newTime >= 0 && newTime <= 1439) {
		_state.observatoryTimeSetting = newTime;

		// Redraw digits
		_vm->redrawArea(80);
		_vm->redrawArea(81);
		_vm->redrawArea(82);
		_vm->redrawArea(83);

		// Draw AM/PM
		if (!observatoryIsDDMMYYYY2400()) {
			_vm->redrawArea(88);
		}

		// Update slider
		_observatoryTimeSlider->setPosition(94 + 94 * _state.observatoryTimeSetting / 1439);
		_observatoryTimeSlider->restoreBackground();
		_observatoryTimeSlider->drawConditionalDataToScreen(2);
		_state.observatoryTimeSlider = _observatoryTimeSlider->_pos.y;
	}

	_vm->_sound->replaceSoundMyst(8500);
}

void Myst::observatoryTimeChange_run() {
	if (_startTime + 500 < _vm->_system->getMillis())
		observatoryIncrementTime(_observatoryIncrement);
}

void Myst::o_observatoryGoButton(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Observatory go button", op);

	// Setting not at target
	if (_state.observatoryDayTarget != _state.observatoryDaySetting
			|| _state.observatoryMonthTarget != _state.observatoryMonthSetting
			|| _state.observatoryYearTarget != _state.observatoryYearSetting
			|| _state.observatoryTimeTarget != _state.observatoryTimeSetting) {
		uint16 soundId = argv[0];
		_vm->_sound->replaceSoundMyst(soundId);

		int16 distance = _state.observatoryYearTarget - _state.observatoryYearSetting;
		uint32 end = _vm->_system->getMillis() + 32 * ABS(distance) / 50 + 800;

		while (end > _vm->_system->getMillis()) {
			_vm->_system->delayMillis(50);

			observatoryUpdateVisualizer(_vm->_rnd->getRandomNumber(409), _vm->_rnd->getRandomNumber(409));

			_vm->redrawResource(_observatoryVisualizer);
		}

		_vm->_sound->resumeBackgroundMyst();

		// Redraw visualizer
		observatorySetTargetToSetting();
		_vm->redrawResource(_observatoryVisualizer);

		// Redraw button
		_tempVar = 0;
		_vm->redrawArea(105);
	}
}

void Myst::o_observatoryMonthSliderMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Month slider move", op);

	observatoryUpdateMonth();
}

void Myst::o_observatoryDaySliderMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Day slider move", op);

	observatoryUpdateDay();
}

void Myst::o_observatoryYearSliderMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Year slider move", op);

	observatoryUpdateYear();
}

void Myst::o_observatoryTimeSliderMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Time slider move", op);

	observatoryUpdateTime();
}

void Myst::o_circuitBreakerStartMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Circuit breaker start move", op);

	MystVideoInfo *breaker = getInvokingResource<MystVideoInfo>();
	breaker->drawFrame(0);
	_vm->_cursor->setCursor(700);
	_tempVar = 0;
}

void Myst::o_circuitBreakerMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Circuit breaker move", op);

	MystVideoInfo *breaker = getInvokingResource<MystVideoInfo>();
	const Common::Point &mouse = _vm->_system->getEventManager()->getMousePos();

	int16 maxStep = breaker->getStepsV() - 1;
	int16 step = ((mouse.y - 80) * breaker->getStepsV()) / 65;
	step = CLIP<uint16>(step, 0, maxStep);

	breaker->drawFrame(step);

	if (_tempVar != step) {
		_tempVar = step;

		// Breaker switched
		if (step == maxStep) {
			// Choose breaker
			if (breaker->getImageSwitchVar() == 93) {
				// Voltage is still too high or not broken
				if (_state.generatorVoltage > 59 || _state.generatorBreakers != 1) {
					uint16 soundId = breaker->getList2(1);
					if (soundId)
						_vm->_sound->replaceSoundMyst(soundId);
				} else {
					uint16 soundId = breaker->getList2(0);
					if (soundId)
						_vm->_sound->replaceSoundMyst(soundId);

					// Reset breaker state
					_state.generatorBreakers = 0;
				}
			} else {
				// Voltage is still too high or not broken
				if (_state.generatorVoltage > 59 || _state.generatorBreakers != 2) {
					uint16 soundId = breaker->getList2(1);
					if (soundId)
						_vm->_sound->replaceSoundMyst(soundId);
				} else {
					uint16 soundId = breaker->getList2(0);
					if (soundId)
						_vm->_sound->replaceSoundMyst(soundId);

					// Reset breaker state
					_state.generatorBreakers = 0;
				}
			}
		}
	}
}

void Myst::o_circuitBreakerEndMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Circuit breaker end move", op);

	MystVideoInfo *breaker = getInvokingResource<MystVideoInfo>();
	_vm->redrawArea(breaker->getImageSwitchVar());
	_vm->checkCursorHints();
}

void Myst::o_boilerIncreasePressureStart(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Boiler increase pressure start", op);

	_treeStopped = true;
	if (_state.cabinValvePosition < 25)
		_vm->_sound->stopBackgroundMyst();

	_boilerPressureIncreasing = true;
}

void Myst::o_boilerLightPilot(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Boiler light pilot", op);

	// Match is lit
	if (_cabinMatchState == 1) {
		_state.cabinPilotLightLit = 1;
		_vm->redrawArea(98);

		boilerFireUpdate(false);

		// Put out match
		_matchGoOutTime = _vm->_system->getMillis();

		if (_state.cabinValvePosition > 0)
			_vm->_sound->replaceBackgroundMyst(8098, 49152);

		if (_state.cabinValvePosition > 12) {
			// Compute the speed of the gauge to synchronize it with the next tree move
			uint32 delay = treeNextMoveDelay(_state.cabinValvePosition);
			Common::Rational rate = boilerComputeGaugeRate(_state.cabinValvePosition, delay);
			boilerResetGauge(rate);

			_state.treeLastMoveTime = _vm->_system->getMillis();
		}
	}
}

Common::Rational Myst::boilerComputeGaugeRate(uint16 pressure, uint32 delay) {
	Common::Rational rate = Common::Rational(2088, delay);
	if (pressure < 12)
		return -rate;
	else
		return rate;
}

void Myst::boilerResetGauge(const Common::Rational &rate) {
	if (!_cabinGaugeMovie || _cabinGaugeMovie->endOfVideo()) {
		if (_vm->getCurCard() == 4098) {
			_cabinGaugeMovie = _vm->_video->playMovie(_vm->wrapMovieFilename("cabingau", kMystStack));
			if (!_cabinGaugeMovie)
				error("Failed to open cabingau movie");

			_cabinGaugeMovie->moveTo(243, 96);
		} else {
			_cabinGaugeMovie = _vm->_video->playMovie(_vm->wrapMovieFilename("cabcgfar", kMystStack));
			if (!_cabinGaugeMovie)
				error("Failed to open cabingau movie");

			_cabinGaugeMovie->moveTo(254, 136);
		}
	}

	Audio::Timestamp goTo;
	if (rate > 0)
		goTo = Audio::Timestamp(0, 0, 600);
	else
		goTo = _cabinGaugeMovie->getDuration();

	_cabinGaugeMovie->seek(goTo);
	_cabinGaugeMovie->setRate(rate);
}

void Myst::o_boilerIncreasePressureStop(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Boiler increase pressure stop", op);

	_treeStopped = false;
	_boilerPressureIncreasing = false;
	_state.treeLastMoveTime = _vm->_system->getMillis();

	if (_state.cabinPilotLightLit == 1) {
		if (_state.cabinValvePosition > 0)
			_vm->_sound->replaceBackgroundMyst(8098, 49152);

		if (_cabinGaugeMovie && !_cabinGaugeMovie->endOfVideo()) {
			uint16 delay = treeNextMoveDelay(_state.cabinValvePosition);
			Common::Rational rate = boilerComputeGaugeRate(_state.cabinValvePosition, delay);
			_cabinGaugeMovie->setRate(rate);
		}

	} else if (_state.cabinValvePosition > 0)
		_vm->_sound->replaceBackgroundMyst(4098, _state.cabinValvePosition << 10);
}

void Myst::boilerPressureIncrease_run() {
	// Allow increasing pressure if sound has stopped
	if (!_vm->_sound->isPlaying(5098) && _state.cabinValvePosition < 25) {
		_state.cabinValvePosition++;
		if (_state.cabinValvePosition == 1) {
			// Set fire to high
			boilerFireUpdate(false);

			// Draw fire
			_vm->redrawArea(305);
		} else if (_state.cabinValvePosition == 25) {
			if (_state.cabinPilotLightLit == 1)
				_vm->_sound->replaceBackgroundMyst(8098, 49152);
			else
				_vm->_sound->replaceBackgroundMyst(4098, 25600);
		}

		// Pressure increasing sound
		_vm->_sound->replaceSoundMyst(5098);

		// Redraw wheel
		_vm->redrawArea(99);
	}
}

void Myst::boilerPressureDecrease_run() {
	// Allow decreasing pressure if sound has stopped
	if (!_vm->_sound->isPlaying(5098) && _state.cabinValvePosition > 0) {
		_state.cabinValvePosition--;
		if (_state.cabinValvePosition == 0) {
			// Set fire to low
			boilerFireUpdate(false);

			// Draw fire
			_vm->redrawArea(305);
		}

		// Pressure increasing sound
		_vm->_sound->replaceSoundMyst(5098);

		// Redraw wheel
		_vm->redrawArea(99);
	}
}

void Myst::o_boilerDecreasePressureStart(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Boiler decrease pressure start", op);

	_treeStopped = true;
	_vm->_sound->stopBackgroundMyst();

	_boilerPressureDecreasing = true;
}

void Myst::o_boilerDecreasePressureStop(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Boiler decrease pressure stop", op);

	_treeStopped = false;
	_boilerPressureDecreasing = false;
	_state.treeLastMoveTime = _vm->_system->getMillis();

	if (_state.cabinPilotLightLit == 1) {
		if (_state.cabinValvePosition > 0)
			_vm->_sound->replaceBackgroundMyst(8098, 49152);

		if (_cabinGaugeMovie && !_cabinGaugeMovie->endOfVideo()) {
			uint16 delay = treeNextMoveDelay(_state.cabinValvePosition);
			Common::Rational rate = boilerComputeGaugeRate(_state.cabinValvePosition, delay);
			_cabinGaugeMovie->setRate(rate);
		}

	} else {
		if (_state.cabinValvePosition > 0)
			_vm->_sound->replaceBackgroundMyst(4098, _state.cabinValvePosition << 10);
	}
}

void Myst::o_basementIncreasePressureStart(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Basement increase pressure start", op);

	_treeStopped = true;
	_basementPressureIncreasing = true;
}

void Myst::o_basementIncreasePressureStop(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Basement increase pressure stop", op);

	_treeStopped = false;
	_basementPressureIncreasing = false;
	_state.treeLastMoveTime = _vm->_system->getMillis();
}

void Myst::basementPressureIncrease_run() {
	// Allow increasing pressure if sound has stopped
	if (!_vm->_sound->isPlaying(4642) && _state.cabinValvePosition < 25) {
		_state.cabinValvePosition++;

		// Pressure increasing sound
		_vm->_sound->replaceSoundMyst(4642);

		// Redraw wheel
		_vm->redrawArea(99);
	}
}

void Myst::basementPressureDecrease_run() {
	// Allow decreasing pressure if sound has stopped
	if (!_vm->_sound->isPlaying(4642) && _state.cabinValvePosition > 0) {
		_state.cabinValvePosition--;

		// Pressure decreasing sound
		_vm->_sound->replaceSoundMyst(4642);

		// Redraw wheel
		_vm->redrawArea(99);
	}
}

void Myst::o_basementDecreasePressureStart(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Basement decrease pressure start", op);

	_treeStopped = true;
	_basementPressureDecreasing = true;
}

void Myst::o_basementDecreasePressureStop(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Basement decrease pressure stop", op);

	_treeStopped = false;
	_basementPressureDecreasing = false;
	_state.treeLastMoveTime = _vm->_system->getMillis();
}

void Myst::tree_run() {
	uint16 pressure;
	if (_state.cabinPilotLightLit)
		pressure = _state.cabinValvePosition;
	else
		pressure = 0;

	// 12 means tree is balanced
	if (pressure != 12) {
		bool goingDown = true;
		if (pressure >= 12)
			goingDown = false;

		// Tree is within bounds
		if ((_state.treePosition < 12 && !goingDown)
				|| (_state.treePosition > _treeMinPosition && goingDown)) {
			uint16 delay = treeNextMoveDelay(pressure);
			uint32 time = _vm->_system->getMillis();
			if (delay < time - _state.treeLastMoveTime) {

				// Tree movement
				if (goingDown) {
					_state.treePosition--;
					_vm->_sound->replaceSoundMyst(2);
				} else {
					_state.treePosition++;
					_vm->_sound->replaceSoundMyst(1);
				}

				// Stop background music if going up from book room
				if (_vm->getCurCard() == 4630) {
					if (_state.treePosition > 0)
						_vm->_sound->stopBackgroundMyst();
					else
						_vm->_sound->replaceBackgroundMyst(4630, 24576);
				}

				// Redraw tree
				_vm->redrawArea(72);

				// Check if alcove is accessible
				treeSetAlcoveAccessible();

				if (_cabinGaugeMovieEnabled) {
					Common::Rational rate = boilerComputeGaugeRate(pressure, delay);
					boilerResetGauge(rate);
				}

				_state.treeLastMoveTime = time;
			}
		}
	}
}

void Myst::treeSetAlcoveAccessible() {
	if (_treeAlcove) {
		// Make alcove accessible if the tree is in the correct position
		_treeAlcove->setEnabled(_state.treePosition >= _treeMinAccessiblePosition
					&& _state.treePosition <= _treeMaxAccessiblePosition);
	}
}

uint32 Myst::treeNextMoveDelay(uint16 pressure) {
	if (pressure >= 12)
		return 25000 * (13 - (pressure - 12)) / 12 + 3000;
	else
		return 25000 * pressure / 13 + 3000;
}

void Myst::o_rocketSoundSliderStartMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Rocket slider start move", op);

	_rocketSliderSound = 0;
	_vm->_cursor->setCursor(700);
	_vm->_sound->pauseBackgroundMyst();
	rocketSliderMove();
}

void Myst::o_rocketSoundSliderMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Rocket slider move", op);

	rocketSliderMove();
}

void Myst::o_rocketSoundSliderEndMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Rocket slider end move", op);

	_vm->checkCursorHints();

	if (_state.generatorVoltage == 59 && !_state.generatorBreakers && _rocketSliderSound)
		_vm->_sound->stopSound();

	if (getInvokingResource<MystArea>() == _rocketSlider1)
		_state.rocketSliderPosition[0] = _rocketSlider1->_pos.y;
	else if (getInvokingResource<MystArea>() == _rocketSlider2)
		_state.rocketSliderPosition[1] = _rocketSlider2->_pos.y;
	else if (getInvokingResource<MystArea>() == _rocketSlider3)
		_state.rocketSliderPosition[2] = _rocketSlider3->_pos.y;
	else if (getInvokingResource<MystArea>() == _rocketSlider4)
		_state.rocketSliderPosition[3] = _rocketSlider4->_pos.y;
	else if (getInvokingResource<MystArea>() == _rocketSlider5)
		_state.rocketSliderPosition[4] = _rocketSlider5->_pos.y;

	_vm->_sound->resumeBackgroundMyst();
}

void Myst::rocketSliderMove() {
	MystAreaSlider *slider = getInvokingResource<MystAreaSlider>();

	if (_state.generatorVoltage == 59 && !_state.generatorBreakers) {
		uint16 soundId = rocketSliderGetSound(slider->_pos.y);
		if (soundId != _rocketSliderSound) {
			_rocketSliderSound = soundId;
			_vm->_sound->replaceSoundMyst(soundId, Audio::Mixer::kMaxChannelVolume, true);
		}
	}
}

uint16 Myst::rocketSliderGetSound(uint16 pos) {
	return (uint16)(9530 + (pos - 216) * 35.0 / 61.0);
}

void Myst::rocketCheckSolution() {
	_vm->_cursor->hideCursor();

	uint16 soundId;
	bool solved = true;

	soundId = rocketSliderGetSound(_rocketSlider1->_pos.y);
	_vm->_sound->replaceSoundMyst(soundId);
	_rocketSlider1->drawConditionalDataToScreen(2);
	_vm->_system->delayMillis(250);
	if (soundId != 9558)
		solved = false;

	soundId = rocketSliderGetSound(_rocketSlider2->_pos.y);
	_vm->_sound->replaceSoundMyst(soundId);
	_rocketSlider2->drawConditionalDataToScreen(2);
	_vm->_system->delayMillis(250);
	if (soundId != 9546)
		solved = false;

	soundId = rocketSliderGetSound(_rocketSlider3->_pos.y);
	_vm->_sound->replaceSoundMyst(soundId);
	_rocketSlider3->drawConditionalDataToScreen(2);
	_vm->_system->delayMillis(250);
	if (soundId != 9543)
		solved = false;

	soundId = rocketSliderGetSound(_rocketSlider4->_pos.y);
	_vm->_sound->replaceSoundMyst(soundId);
	_rocketSlider4->drawConditionalDataToScreen(2);
	_vm->_system->delayMillis(250);
	if (soundId != 9553)
		solved = false;

	soundId = rocketSliderGetSound(_rocketSlider5->_pos.y);
	_vm->_sound->replaceSoundMyst(soundId);
	_rocketSlider5->drawConditionalDataToScreen(2);
	_vm->_system->delayMillis(250);
	if (soundId != 9560)
		solved = false;

	_vm->_sound->stopSound();

	if (solved) {
		// Reset lever position
		MystVideoInfo *lever = getInvokingResource<MystVideoInfo>();
		lever->drawFrame(0);

		// Book appearing
		Common::String movieFile = _vm->wrapMovieFilename("selenbok", kMystStack);
		_rocketLinkBook = _vm->_video->playMovie(movieFile);
		if (!_rocketLinkBook)
			error("Failed to open '%s'", movieFile.c_str());

		_rocketLinkBook->moveTo(224, 41);
		_rocketLinkBook->setBounds(Audio::Timestamp(0, 0, 600), Audio::Timestamp(0, 660, 600));
		_vm->_video->waitUntilMovieEnds(_rocketLinkBook);

		// Book looping closed
		_rocketLinkBook = _vm->_video->playMovie(movieFile);
		if (!_rocketLinkBook)
			error("Failed to open '%s'", movieFile.c_str());

		_rocketLinkBook->moveTo(224, 41);
		_rocketLinkBook->setLooping(true);
		_rocketLinkBook->setBounds(Audio::Timestamp(0, 660, 600), Audio::Timestamp(0, 3500, 600));

		_tempVar = 1;
	}

	_rocketSlider1->drawConditionalDataToScreen(1);
	_rocketSlider2->drawConditionalDataToScreen(1);
	_rocketSlider3->drawConditionalDataToScreen(1);
	_rocketSlider4->drawConditionalDataToScreen(1);
	_rocketSlider5->drawConditionalDataToScreen(1);

	_vm->_cursor->showCursor();
}

void Myst::o_rocketPianoStart(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Rocket piano start move", op);

	MystAreaDrag *key = getInvokingResource<MystAreaDrag>();

	// What the hell??
	Common::Rect src = key->getSubImage(1).rect;
	Common::Rect rect = key->getSubImage(0).rect;
	Common::Rect dest = rect;
	dest.top = 332 - rect.bottom;
	dest.bottom = 332 - rect.top;

	// Draw pressed piano key
	_vm->_gfx->copyImageSectionToScreen(key->getSubImage(1).wdib, src, dest);
	_vm->_system->updateScreen();

	// Play note
	if (_state.generatorVoltage == 59 && !_state.generatorBreakers) {
		uint16 soundId = key->getList1(0);
		_vm->_sound->replaceSoundMyst(soundId, Audio::Mixer::kMaxChannelVolume, true);
	}
}

void Myst::o_rocketPianoMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Rocket piano move", op);

	const Common::Point &mouse = _vm->_system->getEventManager()->getMousePos();
	Common::Rect piano = Common::Rect(85, 123, 460, 270);

	// Unpress previous key
	MystAreaDrag *key = getInvokingResource<MystAreaDrag>();

	Common::Rect src = key->getSubImage(0).rect;
	Common::Rect dest = src;
	dest.top = 332 - src.bottom;
	dest.bottom = 332 - src.top;

	// Draw unpressed piano key
	_vm->_gfx->copyImageSectionToScreen(key->getSubImage(0).wdib, src, dest);

	if (piano.contains(mouse)) {
		MystArea *resource = _vm->updateCurrentResource();
		if (resource && resource->type == kMystAreaDrag) {
			// Press new key
			key = static_cast<MystAreaDrag *>(resource);
			src = key->getSubImage(1).rect;
			Common::Rect rect = key->getSubImage(0).rect;
			dest = rect;
			dest.top = 332 - rect.bottom;
			dest.bottom = 332 - rect.top;

			// Draw pressed piano key
			_vm->_gfx->copyImageSectionToScreen(key->getSubImage(1).wdib, src, dest);

			// Play note
			if (_state.generatorVoltage == 59 && !_state.generatorBreakers) {
				uint16 soundId = key->getList1(0);
				_vm->_sound->replaceSoundMyst(soundId, Audio::Mixer::kMaxChannelVolume, true);
			}
		} else {
			// Not pressing a key anymore
			_vm->_sound->stopSound();
			_vm->_sound->resumeBackgroundMyst();
		}
	}

	_vm->_system->updateScreen();
}

void Myst::o_rocketPianoStop(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Rocket piano end move", op);

	MystAreaImageSwitch *key = getInvokingResource<MystAreaImageSwitch>();

	Common::Rect src = key->getSubImage(0).rect;
	Common::Rect dest = src;
	dest.top = 332 - src.bottom;
	dest.bottom = 332 - src.top;

	// Draw unpressed piano key
	_vm->_gfx->copyImageSectionToScreen(key->getSubImage(0).wdib, src, dest);
	_vm->_system->updateScreen();

	_vm->_sound->stopSound();
	_vm->_sound->resumeBackgroundMyst();
}

void Myst::o_rocketLeverStartMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Rocket lever start move", op);

	MystVideoInfo *lever = getInvokingResource<MystVideoInfo>();

	_vm->_cursor->setCursor(700);
	_rocketLeverPosition = 0;
	lever->drawFrame(0);
}

void Myst::o_rocketOpenBook(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Rocket open link book", op);

	// Flyby movie
	_rocketLinkBook->setBounds(Audio::Timestamp(0, 3500, 600), Audio::Timestamp(0, 13100, 600));

	// Set linkable
	_tempVar = 2;
}

void Myst::o_rocketLeverMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Rocket lever move", op);

	MystVideoInfo *lever = getInvokingResource<MystVideoInfo>();
	const Common::Point &mouse = _vm->_system->getEventManager()->getMousePos();

	// Make the lever follow the mouse
	int16 maxStep = lever->getStepsV() - 1;
    Common::Rect rect = lever->getRect();
    int16 step = ((mouse.y - rect.top) * lever->getStepsV()) / rect.height();
	step = CLIP<uint16>(step, 0, maxStep);

	lever->drawFrame(step);

	// If lever pulled
	if (step == maxStep && step != _rocketLeverPosition) {
		uint16 soundId = lever->getList2(0);

		if (soundId)
			_vm->_sound->replaceSoundMyst(soundId);

		// If rocket correctly powered
		if (_state.generatorVoltage == 59 && !_state.generatorBreakers)
			rocketCheckSolution();
	}

	_rocketLeverPosition = step;
}

void Myst::o_rocketLeverEndMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Rocket lever end move", op);

	MystVideoInfo *lever = getInvokingResource<MystVideoInfo>();

	_vm->checkCursorHints();
	_rocketLeverPosition = 0;
	lever->drawFrame(0);
}

void Myst::o_cabinLeave(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Leave cabin", op);

	// If match is lit, put out
	if (_cabinMatchState == 1) {
		_matchGoOutTime = _vm->_system->getMillis();
	} else if (_cabinMatchState == 0) {
		_vm->setMainCursor(_savedCursorId);
		_cabinMatchState = 2;
	}
}

void Myst::o_treePressureReleaseStart(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Tree pressure release start", op);

	Common::Rect src = Common::Rect(0, 0, 49, 86);
	Common::Rect dest = Common::Rect(78, 46, 127, 132);
	_vm->_gfx->copyImageSectionToScreen(4631, src, dest);
	_vm->_system->updateScreen();

	_tempVar = _state.cabinValvePosition;

	if (_state.treePosition >= 4) {
		_state.cabinValvePosition = 0;
		_treeMinPosition = 4;
		_state.treeLastMoveTime = 0;
	}
}

void Myst::o_treePressureReleaseStop(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Tree pressure release stop", op);

	Common::Rect rect = Common::Rect(78, 46, 127, 132);
	_vm->_gfx->copyBackBufferToScreen(rect);
	_vm->_system->updateScreen();

	_state.cabinValvePosition = _tempVar;
	_treeMinPosition = 0;
}

void Myst::o_observatoryMonthSliderStartMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Month slider start move", op);

	_vm->_cursor->setCursor(700);
	_vm->_sound->pauseBackgroundMyst();

	observatoryUpdateMonth();
}

void Myst::o_observatoryMonthSliderEndMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Month slider end move", op);

	_vm->checkCursorHints();
	_vm->_sound->resumeBackgroundMyst();

	observatoryUpdateMonth();
}

void Myst::observatoryUpdateMonth() {
	int16 month = (_observatoryMonthSlider->_pos.y - 94) / 8;

	if (month != _state.observatoryMonthSetting) {
		_state.observatoryMonthSetting = month;
		_state.observatoryMonthSlider = _observatoryMonthSlider->_pos.y;
		_vm->_sound->replaceSoundMyst(8500);

		// Redraw digits
		_vm->redrawArea(73);
	}
}

void Myst::o_observatoryDaySliderStartMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Day slider start move", op);

	_vm->_cursor->setCursor(700);
	_vm->_sound->pauseBackgroundMyst();

	observatoryUpdateDay();
}

void Myst::o_observatoryDaySliderEndMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Day slider end move", op);

	_vm->checkCursorHints();
	_vm->_sound->resumeBackgroundMyst();

	observatoryUpdateDay();
}

void Myst::observatoryUpdateDay() {
	int16 day = (_observatoryDaySlider->_pos.y - 94) * 30 / 94 + 1;

	if (day != _state.observatoryDaySetting) {
		_state.observatoryDaySetting = day;
		_state.observatoryDaySlider = _observatoryDaySlider->_pos.y;
		_vm->_sound->replaceSoundMyst(8500);

		// Redraw digits
		_vm->redrawArea(75);
		_vm->redrawArea(74);
	}
}

void Myst::o_observatoryYearSliderStartMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Year slider start move", op);

	_vm->_cursor->setCursor(700);
	_vm->_sound->pauseBackgroundMyst();

	observatoryUpdateYear();
}

void Myst::o_observatoryYearSliderEndMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Year slider end move", op);

	_vm->checkCursorHints();
	_vm->_sound->resumeBackgroundMyst();

	observatoryUpdateYear();
}

void Myst::observatoryUpdateYear() {
	int16 year = (_observatoryYearSlider->_pos.y - 94) * 9999 / 94;

	if (year != _state.observatoryYearSetting) {
		_state.observatoryYearSetting = year;
		_state.observatoryYearSlider = _observatoryYearSlider->_pos.y;
		_vm->_sound->replaceSoundMyst(8500);

		// Redraw digits
		_vm->redrawArea(79);
		_vm->redrawArea(78);
		_vm->redrawArea(77);
		_vm->redrawArea(76);
	}
}

void Myst::o_observatoryTimeSliderStartMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Time slider start move", op);

	_vm->_cursor->setCursor(700);
	_vm->_sound->pauseBackgroundMyst();

	observatoryUpdateTime();
}

void Myst::o_observatoryTimeSliderEndMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Time slider end move", op);

	_vm->checkCursorHints();
	_vm->_sound->resumeBackgroundMyst();

	observatoryUpdateTime();
}

void Myst::observatoryUpdateTime() {
	int16 time = (_observatoryTimeSlider->_pos.y - 94) * 1439 / 94;

	if (time != _state.observatoryTimeSetting) {
		_state.observatoryTimeSetting = time;
		_state.observatoryTimeSlider = _observatoryTimeSlider->_pos.y;
		_vm->_sound->replaceSoundMyst(8500);

		// Redraw digits
		_vm->redrawArea(80);
		_vm->redrawArea(81);
		_vm->redrawArea(82);
		_vm->redrawArea(83);

		// Draw AM/PM
		if (!observatoryIsDDMMYYYY2400())
			_vm->redrawArea(88);
	}
}

void Myst::o_libraryCombinationBookStop(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Combination book stop turning pages", op);
	_libraryCombinationBookPagesTurning = false;
}

void Myst::o_cabinMatchLight(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	if (!_cabinMatchState) {
		_vm->_sound->replaceSoundMyst(4103);

		// Match is lit
		_cabinMatchState = 1;
		_matchBurning = true;
		_matchGoOutCnt = 0;
		_vm->setMainCursor(kLitMatchCursor);

		// Match will stay lit for one minute
		_matchGoOutTime = _vm->_system->getMillis() + 60 * 1000;
	}
}

void Myst::matchBurn_run() {
	uint32 time = _vm->_system->getMillis();

	if (time > _matchGoOutTime) {
		_matchGoOutTime = time + 150;

		// Switch between lit match and dead match every 150 ms when match is dying
		if (_matchGoOutCnt % 2)
			_vm->setMainCursor(kLitMatchCursor);
		else
			_vm->setMainCursor(kDeadMatchCursor);

		_matchGoOutCnt++;

		// Match is dead
		if (_matchGoOutCnt >= 5) {
			_matchBurning = false;
			_vm->setMainCursor(_savedCursorId);

			_cabinMatchState = 2;
		}
	}
}

void Myst::o_courtyardBoxEnter(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Mouse enters courtyard box", op);
	_tempVar = 1;
	_vm->_sound->playSound(_courtyardBoxSound);
	_vm->redrawArea(var);
}

void Myst::o_courtyardBoxLeave(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Mouse leaves courtyard box", op);
	_tempVar = 0;
	_vm->redrawArea(var);
}

void Myst::o_clockMinuteWheelStartTurn(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	// Used on Card 4006
	debugC(kDebugScript, "Opcode %d: Minute wheel start turn", op);

	clockWheelStartTurn(2);
}

void Myst::o_clockWheelEndTurn(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	// Used on Card 4006
	debugC(kDebugScript, "Opcode %d: Wheel end turn", op);

	_clockTurningWheel = 0;
}

void Myst::o_clockHourWheelStartTurn(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	// Used on Card 4006
	debugC(kDebugScript, "Opcode %d: Hour wheel start turn", op);

	clockWheelStartTurn(1);
}

void Myst::clockWheel_run() {
	// Turn wheel one step each second
	uint32 time = _vm->_system->getMillis();

	if (time > _startTime + 1000) {
		_startTime = time;

		if (_clockTurningWheel == 1)
			clockWheelTurn(39);
		else
			clockWheelTurn(38);

		_vm->redrawArea(37);
	}
}

void Myst::clockWheelStartTurn(uint16 wheel) {
	MystAreaDrag *resource = getInvokingResource<MystAreaDrag>();
	uint16 soundId = resource->getList1(0);

	if (soundId)
		_vm->_sound->replaceSoundMyst(soundId);

	// Turn wheel one step
	if (wheel == 1)
		clockWheelTurn(39);
	else
		clockWheelTurn(38);

	_vm->redrawArea(37);

	// Continue turning wheel until mouse button is released
	_clockTurningWheel = wheel;
	_startTime = _vm->_system->getMillis();
}

void Myst::clockWheelTurn(uint16 var) {
	if (var == 38) {
		// Hours
		_state.clockTowerHourPosition = (_state.clockTowerHourPosition + 1) % 12;
	} else {
		// Minutes
		_state.clockTowerMinutePosition = (_state.clockTowerMinutePosition + 5) % 60;
	}
}

void Myst::o_libraryCombinationBookStartRight(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Combination book start turning pages right", op);

	_tempVar = 0;
	libraryCombinationBookTurnRight();
	_startTime = _vm->_system->getMillis();
	_libraryCombinationBookPagesTurning = true;
}

void Myst::o_libraryCombinationBookStartLeft(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Combination book start turning pages left", op);

	_tempVar = 0;
	libraryCombinationBookTurnLeft();
	_startTime = _vm->_system->getMillis();
	_libraryCombinationBookPagesTurning = true;
}

void Myst::libraryCombinationBookTurnLeft() {
	// Turn page left
	if (_libraryBookPage - 1 >= 0) {
		_tempVar--;

		if (_tempVar >= -5) {
			_libraryBookPage--;
		} else {
			_libraryBookPage -= 5;
			_tempVar = -5;
		}

		_libraryBookPage = CLIP<int16>(_libraryBookPage, 0, _libraryBookNumPages - 1);

		Common::Rect rect = Common::Rect(157, 113, 446, 220);
		_vm->_gfx->copyImageToScreen(_libraryBookBaseImage + _libraryBookPage, rect);

		if (_vm->_rnd->getRandomBit())
			_vm->_sound->replaceSoundMyst(_libraryBookSound1);
		else
			_vm->_sound->replaceSoundMyst(_libraryBookSound2);

		_vm->_system->updateScreen();
	}
}

void Myst::libraryCombinationBookTurnRight() {
	// Turn page right
	if (_libraryBookPage + 1 < _libraryBookNumPages) {
		_tempVar++;

		if (_tempVar <= 5) {
			_libraryBookPage++;
		} else {
			_libraryBookPage += 5;
			_tempVar = 5;
		}

		_libraryBookPage = CLIP<uint16>(_libraryBookPage, 0, _libraryBookNumPages - 1);

		Common::Rect rect = Common::Rect(157, 113, 446, 220);
		_vm->_gfx->copyImageToScreen(_libraryBookBaseImage + _libraryBookPage, rect);

		if (_vm->_rnd->getRandomBit())
			_vm->_sound->replaceSoundMyst(_libraryBookSound1);
		else
			_vm->_sound->replaceSoundMyst(_libraryBookSound2);

		_vm->_system->updateScreen();
	}
}

void Myst::libraryCombinationBook_run() {
	uint32 time = _vm->_system->getMillis();
	if (time >= _startTime + 500) {
		if (_tempVar > 0) {
			libraryCombinationBookTurnRight();
			_startTime = time;
		} else if (_tempVar < 0) {
			libraryCombinationBookTurnLeft();
			_startTime = time;
		}
	}
}

void Myst::o_observatoryChangeSettingStop(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Observatory change setting stop", op);

	// Stop persistent scripts
	_observatoryMonthChanging = false;
	_observatoryDayChanging = false;
	_observatoryYearChanging = false;
	_observatoryTimeChanging = false;
	_observatoryIncrement = 0;

	// Restore button and slider
	_vm->_gfx->copyBackBufferToScreen(getInvokingResource<MystArea>()->getRect());
	if (_observatoryCurrentSlider) {
		_vm->redrawResource(_observatoryCurrentSlider);
		_observatoryCurrentSlider = nullptr;
	}
	_vm->_sound->resumeBackgroundMyst();
}

void Myst::o_dockVaultForceClose(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	// Used on Myst 4143 (Dock near Marker Switch)
	uint16 soundId = argv[0];
	uint16 delay = argv[1];
	uint16 directionalUpdateDataSize = argv[2];

	debugC(kDebugScript, "Opcode %d: Vault Force Close", op);
	debugC(kDebugScript, "\tsoundId: %d", soundId);
	debugC(kDebugScript, "\tdirectionalUpdateDataSize: %d", directionalUpdateDataSize);

	if (_dockVaultState) {
		// Open switch
		_state.dockMarkerSwitch = 1;
		_vm->_sound->replaceSoundMyst(4143);
		_vm->redrawArea(4);

		// Close vault
		_dockVaultState = 0;
		_vm->_sound->replaceSoundMyst(soundId);
		_vm->redrawArea(41, false);
		animatedUpdate(directionalUpdateDataSize, &argv[3], delay);
	}
}

void Myst::o_imagerEraseStop(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Imager stop erase", op);
	_imagerValidationRunning = false;
}

void Myst::o_clockLeverStartMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Clock lever start move", op);
	MystVideoInfo *lever = getInvokingResource<MystVideoInfo>();
	lever->drawFrame(0);
	_vm->_cursor->setCursor(700);
	_clockMiddleGearMovedAlone = false;
	_clockLeverPulled = false;
}

void Myst::o_clockLeverMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Clock left lever move", op);

	if (!_clockLeverPulled) {
		MystVideoInfo *lever = getInvokingResource<MystVideoInfo>();

		// If lever pulled
		if (lever->pullLeverV()) {
			// Start videos for first step
			if (_clockWeightPosition < 2214) {
				_vm->_sound->replaceSoundMyst(5113);
				clockGearForwardOneStep(1);

				// Left lever
				if (op == 144)
					clockGearForwardOneStep(2);
				else // Right lever
					clockGearForwardOneStep(0);

				clockWeightDownOneStep();
			}
			_clockLeverPulled = true;
		}
	}
}

void Myst::clockGearForwardOneStep(uint16 gear) {
	static const uint16 startTime[] = { 0, 324, 618 };
	static const uint16 endTime[] = { 324, 618, 950 };
	static const char *videos[] = { "cl1wg1", "cl1wg2", "cl1wg3" };
	static const uint16 x[] = { 224, 224, 224 };
	static const uint16 y[] = { 49, 82, 109 };

	// Increment value by one
	_clockGearsPositions[gear] = _clockGearsPositions[gear] % 3 + 1;

	// Set video bounds
	uint16 gearPosition = _clockGearsPositions[gear] - 1;
	_clockGearsVideos[gear] = _vm->_video->playMovie(_vm->wrapMovieFilename(videos[gear], kMystStack));
	if (!_clockGearsVideos[gear])
		error("Failed to open %s movie", videos[gear]);

	_clockGearsVideos[gear]->moveTo(x[gear], y[gear]);
	_clockGearsVideos[gear]->setBounds(
			Audio::Timestamp(0, startTime[gearPosition], 600),
			Audio::Timestamp(0, endTime[gearPosition], 600));
}

void Myst::clockWeightDownOneStep() {
	// The Myst ME version of this video is encoded faster than the original
	// The weight goes on the floor one step too early. Original ME engine also has this behavior.
	bool updateVideo = !(_vm->getFeatures() & GF_ME) || _clockWeightPosition < (2214 - 246);

	// Set video bounds
	if (updateVideo) {
		_clockWeightVideo = _vm->_video->playMovie(_vm->wrapMovieFilename("cl1wlfch", kMystStack));
		if (!_clockWeightVideo)
			error("Failed to open cl1wlfch movie");

		_clockWeightVideo->moveTo(124, 0);
		_clockWeightVideo->setBounds(
				Audio::Timestamp(0, _clockWeightPosition, 600),
				Audio::Timestamp(0, _clockWeightPosition + 246, 600));
	}

	// Increment value by one step
	_clockWeightPosition += 246;
}

void Myst::clockGears_run() {
	if (!_vm->_video->isVideoPlaying() && _clockWeightPosition < 2214) {
		_clockMiddleGearMovedAlone = true;
		_vm->_sound->replaceSoundMyst(5113);
		clockGearForwardOneStep(1);
		clockWeightDownOneStep();
	}
}

void Myst::o_clockLeverEndMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Clock lever end move", op);
	static const char *videos[] = { "cl1wg1", "cl1wg2", "cl1wg3", "cl1wlfch" };

	_vm->_cursor->hideCursor();
	_clockLeverPulled = false;

	// Let movies stop playing
	for (uint i = 0; i < ARRAYSIZE(videos); i++) {
		VideoHandle handle = _vm->_video->findVideoHandle(_vm->wrapMovieFilename(videos[i], kMystStack));
		if (handle)
			_vm->_video->delayUntilMovieEnds(handle);
	}

	if (_clockMiddleGearMovedAlone)
		_vm->_sound->replaceSoundMyst(8113);

	// Release lever
	MystVideoInfo *lever = getInvokingResource<MystVideoInfo>();
	lever->releaseLeverV();

	// Check if puzzle is solved
	clockGearsCheckSolution();

	_vm->_cursor->showCursor();
}

void Myst::clockGearsCheckSolution() {
	if (_clockGearsPositions[0] == 2
			&& _clockGearsPositions[1] == 2
			&& _clockGearsPositions[2] == 1
			&& !_state.gearsOpen) {

		// Make weight go down
		_vm->_sound->replaceSoundMyst(9113);
		_clockWeightVideo = _vm->_video->playMovie(_vm->wrapMovieFilename("cl1wlfch", kMystStack));
		if (!_clockWeightVideo)
			error("Failed to open cl1wlfch movie");

		_clockWeightVideo->moveTo(124, 0);
		_clockWeightVideo->setBounds(
				Audio::Timestamp(0, _clockWeightPosition, 600),
				Audio::Timestamp(0, 2214, 600));
		_vm->_video->waitUntilMovieEnds(_clockWeightVideo);
		_clockWeightPosition = 2214;

		_vm->_sound->replaceSoundMyst(6113);
		_vm->_system->delayMillis(1000);
		_vm->_sound->replaceSoundMyst(7113);

		// Gear opening video
		_vm->_video->playMovieBlocking(_vm->wrapMovieFilename("cl1wggat", kMystStack), 195, 225);
		_state.gearsOpen = 1;
		_vm->redrawArea(40);

		_vm->_sound->replaceBackgroundMyst(4113, 16384);
	}
}

void Myst::o_clockResetLeverStartMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Clock reset lever start move", op);

	MystVideoInfo *lever = getInvokingResource<MystVideoInfo>();
	lever->drawFrame(0);
	_vm->_cursor->setCursor(700);
}

void Myst::o_clockResetLeverMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Clock reset lever move", op);

	MystVideoInfo *lever = getInvokingResource<MystVideoInfo>();

	// If pulled
	if (lever->pullLeverV() && _clockWeightPosition != 0)
		clockReset();
}

void Myst::clockReset() {
	static const char *videos[] = { "cl1wg1", "cl1wg2", "cl1wg3", "cl1wlfch" };

	_vm->_cursor->hideCursor();

	_vm->_sound->stopBackgroundMyst();
	_vm->_sound->replaceSoundMyst(5113);

	// Play reset videos
	clockResetWeight();
	clockResetGear(0);
	clockResetGear(1);
	clockResetGear(2);

	// Let movies stop playing
	for (uint i = 0; i < ARRAYSIZE(videos); i++) {
		VideoHandle handle = _vm->_video->findVideoHandle(_vm->wrapMovieFilename(videos[i], kMystStack));
		if (handle)
			_vm->_video->delayUntilMovieEnds(handle);
	}

	_vm->_sound->replaceSoundMyst(10113);

	// Close gear
	if (_state.gearsOpen) {
		_vm->_sound->replaceSoundMyst(6113);
		_vm->_system->delayMillis(1000);
		_vm->_sound->replaceSoundMyst(7113);

		// Gear closing movie
		VideoHandle handle = _vm->_video->playMovie(_vm->wrapMovieFilename("cl1wggat", kMystStack));
		if (!handle)
			error("Failed to open cl1wggat movie");

		handle->moveTo(195, 225);
		handle->seek(handle->getDuration());
		handle->setRate(-1);
		_vm->_video->waitUntilMovieEnds(handle);

		// Redraw gear
		_state.gearsOpen = 0;
		_vm->redrawArea(40);
	}

	_vm->_cursor->showCursor();
}

void Myst::clockResetWeight() {
	_vm->_sound->replaceSoundMyst(9113);

	_clockWeightVideo = _vm->_video->playMovie(_vm->wrapMovieFilename("cl1wlfch", kMystStack));
	if (!_clockWeightVideo)
		error("Failed to open cl1wlfch movie");

	_clockWeightVideo->moveTo(124, 0);

	// Play the movie backwards, weight going up
	_clockWeightVideo->seek(Audio::Timestamp(0, _clockWeightPosition, 600));
	_clockWeightVideo->setRate(-1);

	// Reset position
	_clockWeightPosition = 0;
}

void Myst::clockResetGear(uint16 gear) {
	static const uint16 time[] = { 324, 618, 950 };
	static const char *videos[] = { "cl1wg1", "cl1wg2", "cl1wg3" };
	static const uint16 x[] = { 224, 224, 224 };
	static const uint16 y[] = { 49, 82, 109 };

	// Set video bounds, gears going to 3
	uint16 gearPosition = _clockGearsPositions[gear] - 1;
	if (gearPosition != 2) {
		_clockGearsVideos[gear] = _vm->_video->playMovie(_vm->wrapMovieFilename(videos[gear], kMystStack));
		if (!_clockGearsVideos[gear])
			error("Failed to open gears movie");

		_clockGearsVideos[gear]->moveTo(x[gear], y[gear]);
		_clockGearsVideos[gear]->setBounds(
				Audio::Timestamp(0, time[gearPosition], 600),
				Audio::Timestamp(0, time[2], 600));
	}

	// Reset gear position
	_clockGearsPositions[gear] = 3;
}

void Myst::o_clockResetLeverEndMove(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Clock reset lever end move", op);

	// Get current lever frame
	MystVideoInfo *lever = getInvokingResource<MystVideoInfo>();

	lever->releaseLeverV();

	_vm->checkCursorHints();
}

void Myst::o_libraryBook_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	_libraryBookPage = 0;
	_libraryBookNumPages = argv[0];
	_libraryBookBaseImage = argv[1];
	_libraryBookSound1 = argv[2];
	_libraryBookSound2 = argv[3];
}

void Myst::o_courtyardBox_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Courtyard box init", op);

	_courtyardBoxSound = argv[0];
}

void Myst::towerRotationMap_run() {
	if (!_towerRotationMapInitialized) {
		_towerRotationMapInitialized = true;
		_vm->_sound->replaceSoundMyst(4378);

		towerRotationDrawBuildings();

		// Draw to screen
		_vm->_gfx->copyBackBufferToScreen(Common::Rect(106, 42, 459, 273));
		_vm->_system->updateScreen();
	}

	uint32 time = _vm->_system->getMillis();
	if (time > _startTime) {
		if (_towerRotationMapClicked) {
			towerRotationMapRotate();
			_startTime = time + 100;
		} else if (_towerRotationBlinkLabel
				&& _vm->_sound->isPlaying(6378)) {
			// Blink tower rotation label while sound is playing
			_towerRotationBlinkLabelCount = (_towerRotationBlinkLabelCount + 1) % 14;

			if (_towerRotationBlinkLabelCount == 7)
				_towerRotationMapLabel->drawConditionalDataToScreen(0);
			else if (_towerRotationBlinkLabelCount == 0)
				_towerRotationMapLabel->drawConditionalDataToScreen(1);

			_startTime = time + 100;
		} else {
			// Stop blinking label
			_towerRotationBlinkLabel = false;
			_towerRotationMapLabel->drawConditionalDataToScreen(0);

			// Blink tower
			_startTime = time + 500;
			_tempVar = (_tempVar + 1) % 2;
			_towerRotationMapTower->drawConditionalDataToScreen(_tempVar);
		}
	}
}

void Myst::o_towerRotationMap_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	_towerRotationMapRunning = true;
	_towerRotationMapTower = getInvokingResource<MystAreaImageSwitch>();
	_towerRotationMapLabel = _vm->getViewResource<MystAreaImageSwitch>(argv[0]);
	_tempVar = 0;
	_startTime = 0;
	_towerRotationMapClicked = false;
}

void Myst::towerRotationDrawBuildings() {
	// Draw library
	_vm->redrawArea(304, false);

	// Draw other resources
	for (uint i = 1; i <= 10; i++) {
		MystAreaImageSwitch *resource = _vm->getViewResource<MystAreaImageSwitch>(i);
		_vm->redrawResource(resource, false);
	}
}

uint16 Myst::towerRotationMapComputeAngle() {
	_towerRotationSpeed++;
	if (_towerRotationSpeed >= 7)
		_towerRotationSpeed = 7;
	else
		_towerRotationSpeed++;

	_state.towerRotationAngle = (_state.towerRotationAngle + _towerRotationSpeed) % 360;
	uint16 angle = _state.towerRotationAngle;
	_towerRotationOverSpot = false;

	if (angle >= 265 && angle <= 277
			&& _state.rocketshipMarkerSwitch) {
		angle = 271;
		_towerRotationOverSpot = true;
		_towerRotationSpeed = 1;
	} else if (angle >= 77 && angle <= 89
			&& _state.gearsMarkerSwitch) {
		angle = 83;
		_towerRotationOverSpot = true;
		_towerRotationSpeed = 1;
	} else if (angle >= 123 && angle <= 135
			&& _state.dockMarkerSwitch) {
		angle = 129;
		_towerRotationOverSpot = true;
		_towerRotationSpeed = 1;
	} else if (angle >= 146 && angle <= 158
			&& _state.cabinMarkerSwitch) {
		angle = 152;
		_towerRotationOverSpot = true;
		_towerRotationSpeed = 1;
	}

	return angle;
}

Common::Point Myst::towerRotationMapComputeCoords(const Common::Point &center, uint16 angle) {
	Common::Point end;

	// Polar to rect coords
	double radians = angle * M_PI / 180.0;
	end.x = (int16)(center.x + cos(radians) * 310.0);
	end.y = (int16)(center.y + sin(radians) * 310.0);

	return end;
}

void Myst::towerRotationMapDrawLine(const Common::Point &center, const Common::Point &end) {
	uint32 color;

	if (_vm->getFeatures() & GF_ME) {
		Graphics::PixelFormat pf = _vm->_system->getScreenFormat();

		if (!_towerRotationOverSpot)
			color = pf.RGBToColor(0xFF, 0xFF, 0xFF); // White
		else
			color = pf.RGBToColor(0xFF, 0, 0); // Red
	} else {
		if (!_towerRotationOverSpot)
			color = 0xFF; // White
		else
			color = 0xF9; // Red
	}

	const Common::Rect rect = Common::Rect(106, 42, 459, 273);

	Common::Rect src;
	src.left = rect.left;
	src.top = 333 - rect.bottom;
	src.right = rect.right;
	src.bottom = 333 - rect.top;

	// Redraw background
	_vm->_gfx->copyImageSectionToBackBuffer(_vm->getCardBackgroundId(), src, rect);

	// Draw buildings
	towerRotationDrawBuildings();

	// Draw tower
	_towerRotationMapTower->drawConditionalDataToScreen(0, false);

	// Draw label
	_towerRotationMapLabel->drawConditionalDataToScreen(1, false);

	// Draw line
	_vm->_gfx->drawLine(center, end, color);
	_vm->_gfx->copyBackBufferToScreen(rect);
	_vm->_system->updateScreen();
}

void Myst::towerRotationMapRotate() {
	const Common::Point center = Common::Point(383, 124);
	uint16 angle = towerRotationMapComputeAngle();
	Common::Point end = towerRotationMapComputeCoords(center, angle);
	towerRotationMapDrawLine(center, end);
}

void Myst::o_forechamberDoor_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	// Used for Card 4138 (Dock Forechamber Door)
	// Set forechamber door to closed
	_tempVar = 0;
}

void Myst::o_shipAccess_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	// Enable acces to the ship
	if (_state.shipFloating) {
		getInvokingResource<MystArea>()->setEnabled(true);
	}
}

void Myst::o_butterflies_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Butterflies movie init", op);

	// Used for Card 4256 (Butterfly Movie Activation)
	if (!_butterfliesMoviePlayed) {
		MystAreaVideo *butterflies = getInvokingResource<MystAreaVideo>();
		butterflies->playMovie();

		_butterfliesMoviePlayed = true;
	}
}

void Myst::o_imager_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Imager init", op);
	debugC(kDebugScript, "Var: %d", var);

	MystAreaActionSwitch *select = getInvokingResource<MystAreaActionSwitch>();
	_imagerMovie = static_cast<MystAreaVideo *>(select->getSubResource(getVar(var)));
	_imagerRunning = true;
}

void Myst::imager_run() {
	_imagerRunning = false;

	if (_state.imagerActive && _state.imagerSelection == 67) {
		VideoHandle water = _imagerMovie->playMovie();
		water->setBounds(Audio::Timestamp(0, 1814, 600), Audio::Timestamp(0, 4204, 600));
		water->setLooping(true);
	}
}

void Myst::libraryBookcaseTransform_run(void) {
	if (_libraryBookcaseChanged) {
		_libraryBookcaseChanged = false;
		_libraryBookcaseMoving = false;

		_vm->_cursor->hideCursor();

		// Play transform sound and video
		_vm->_sound->replaceSoundMyst(_libraryBookcaseSoundId);
		_libraryBookcaseMovie->playMovie();

		if (_state.libraryBookcaseDoor) {
			_vm->_gfx->copyImageSectionToBackBuffer(11179, Common::Rect(0, 0, 106, 81), Common::Rect(0, 72, 106, 153));
			_vm->_gfx->runTransition(kTransitionBottomToTop, Common::Rect(0, 72, 106, 153), 5, 10);
			_vm->_sound->playSoundBlocking(7348);
			_vm->_sound->replaceBackgroundMyst(4348, 16384);
		} else {
			_vm->_gfx->copyImageSectionToBackBuffer(11178, Common::Rect(0, 0, 107, 67), Common::Rect(437, 84, 544, 151));
			_vm->_gfx->copyBackBufferToScreen(Common::Rect(437, 84, 544, 151));
			_vm->_sound->playSoundBlocking(7348);
			_vm->_sound->replaceBackgroundMyst(4334, 16384);
		}

		_vm->_cursor->showCursor();
	}
}

void Myst::o_libraryBookcaseTransform_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	if (_libraryBookcaseChanged) {
		MystAreaActionSwitch *resource = getInvokingResource<MystAreaActionSwitch>();
		_libraryBookcaseMovie = static_cast<MystAreaVideo *>(resource->getSubResource(getVar(0)));
		_libraryBookcaseSoundId = argv[0];
		_libraryBookcaseMoving = true;
	}
}

void Myst::generatorControlRoom_run(void) {
	if (_generatorVoltage == _state.generatorVoltage) {
		generatorRedrawRocket();
	} else {
		// Animate generator gauge
		if (_generatorVoltage > _state.generatorVoltage)
			_generatorVoltage--;
		else
			_generatorVoltage++;

		// Redraw generator gauge
		_vm->redrawArea(62);
		_vm->redrawArea(63);
		_vm->redrawArea(96);
	}
}

void Myst::o_generatorControlRoom_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Generator control room init", op);

	_generatorVoltage = _state.generatorVoltage;
	_generatorControlRoomRunning = true;
}

void Myst::o_fireplace_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Fireplace grid init", op);

	// Clear fireplace grid
	for (uint i = 0; i < 6; i++)
		_fireplaceLines[i] = 0;
}

void Myst::o_clockGears_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	// Used for Card 4113 (Clock Tower Cog Puzzle)
	debugC(kDebugScript, "Opcode %d: Gears puzzle init", op);

	// Set gears position
	if (_state.gearsOpen) {
		_clockGearsPositions[0] = 2;
		_clockGearsPositions[1] = 2;
		_clockGearsPositions[2] = 1;
		_clockWeightPosition = 2214;
	} else {
		_clockGearsPositions[0] = 3;
		_clockGearsPositions[1] = 3;
		_clockGearsPositions[2] = 3;
		_clockWeightPosition = 0;
	}
}

void Myst::o_gulls1_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Gulls init", op);

	if (!_state.shipFloating) {
		_gullsNextTime = _vm->_system->getMillis() + 2000;
		_gullsFlying1 = true;
	}
}

void Myst::gullsFly1_run() {
	static const char* gulls[] = { "birds1", "birds2", "birds3" };
	uint32 time = _vm->_system->getMillis();

	if (time > _gullsNextTime) {
		uint16 video = _vm->_rnd->getRandomNumber(3);
		if (video != 3) {
			uint16 x = 0;
			if (_vm->_rnd->getRandomBit())
				x = _vm->_rnd->getRandomNumber(110);
			else
				x = _vm->_rnd->getRandomNumber(160) + 260;

			VideoHandle handle = _vm->_video->playMovie(_vm->wrapMovieFilename(gulls[video], kMystStack));
			if (!handle)
				error("Failed to open gulls movie");

			handle->moveTo(x, 0);
			_gullsNextTime = time + _vm->_rnd->getRandomNumber(16667) + 13334;
		}
	}
}

void Myst::o_observatory_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Stellar observatory init", op);

	_tempVar = 0;
	_observatoryNotInitialized = true;
	_observatoryVisualizer = getInvokingResource<MystAreaImageSwitch>();
	_observatoryGoButton = _vm->getViewResource<MystAreaImageSwitch>(argv[0]);
	if (observatoryIsDDMMYYYY2400()) {
		_observatoryDaySlider = _vm->getViewResource<MystAreaSlider>(argv[1]);
		_observatoryMonthSlider = _vm->getViewResource<MystAreaSlider>(argv[2]);
	} else {
		_observatoryMonthSlider = _vm->getViewResource<MystAreaSlider>(argv[1]);
		_observatoryDaySlider = _vm->getViewResource<MystAreaSlider>(argv[2]);
	}
	_observatoryYearSlider = _vm->getViewResource<MystAreaSlider>(argv[3]);
	_observatoryTimeSlider = _vm->getViewResource<MystAreaSlider>(argv[4]);

	// Set date selection sliders position
	_observatoryDaySlider->setPosition(_state.observatoryDaySlider);
	_observatoryMonthSlider->setPosition(_state.observatoryMonthSlider);
	_observatoryYearSlider->setPosition(_state.observatoryYearSlider);
	_observatoryTimeSlider->setPosition(_state.observatoryTimeSlider);

	_observatoryLastTime = _vm->_system->getMillis();

	observatorySetTargetToSetting();

	_observatoryRunning = true;
}

bool Myst::observatoryIsDDMMYYYY2400() {
	// TODO: Auto-detect based on the month rect position
	return !(_vm->getFeatures() & GF_ME) && (_vm->getLanguage() == Common::FR_FRA
			|| _vm->getLanguage() == Common::DE_DEU);
}

void Myst::observatoryUpdateVisualizer(uint16 x, uint16 y) {
	Common::Rect visu;
	visu.left = x;
	visu.right = visu.left + 105;
	visu.bottom = 512 - y;
	visu.top = visu.bottom - 106;

	_observatoryVisualizer->setSubImageRect(0, visu);
	_observatoryVisualizer->setSubImageRect(1, visu);
}

void Myst::observatorySetTargetToSetting() {
	uint32 visuX = _state.observatoryTimeSetting * 7 / 25;
	uint32 visuY = 250 * _state.observatoryYearSetting
			+ 65 * (_state.observatoryMonthSetting + 1)
			+ 20 * _state.observatoryDaySetting;

	observatoryUpdateVisualizer(visuX % 407, visuY % 407);

	_state.observatoryDayTarget = _state.observatoryDaySetting;
	_state.observatoryMonthTarget = _state.observatoryMonthSetting;
	_state.observatoryYearTarget = _state.observatoryYearSetting;
	_state.observatoryTimeTarget = _state.observatoryTimeSetting;
}

void Myst::observatory_run() {
	if (_observatoryNotInitialized) {
		_observatoryNotInitialized = false;

		_vm->_cursor->hideCursor();

		// Make sliders "initialize"
		if (observatoryIsDDMMYYYY2400()) {
			_vm->_sound->replaceSoundMyst(8500);
			_observatoryDaySlider->drawConditionalDataToScreen(2);
			_vm->_system->delayMillis(200);
			_vm->redrawResource(_observatoryDaySlider);

			_vm->_sound->replaceSoundMyst(8500);
			_observatoryMonthSlider->drawConditionalDataToScreen(2);
			_vm->_system->delayMillis(200);
			_vm->redrawResource(_observatoryMonthSlider);
		} else {
			_vm->_sound->replaceSoundMyst(8500);
			_observatoryMonthSlider->drawConditionalDataToScreen(2);
			_vm->_system->delayMillis(200);
			_vm->redrawResource(_observatoryMonthSlider);

			_vm->_sound->replaceSoundMyst(8500);
			_observatoryDaySlider->drawConditionalDataToScreen(2);
			_vm->_system->delayMillis(200);
			_vm->redrawResource(_observatoryDaySlider);
		}

		_vm->_sound->replaceSoundMyst(8500);
		_observatoryYearSlider->drawConditionalDataToScreen(2);
		_vm->_system->delayMillis(200);
		_vm->redrawResource(_observatoryYearSlider);

		_vm->_sound->replaceSoundMyst(8500);
		_observatoryTimeSlider->drawConditionalDataToScreen(2);
		_vm->_system->delayMillis(200);
		_vm->redrawResource(_observatoryTimeSlider);

		_vm->_cursor->showCursor();
	}

	// Setting not at target
	if (_state.observatoryDayTarget != _state.observatoryDaySetting
			|| _state.observatoryMonthTarget != _state.observatoryMonthSetting
			|| _state.observatoryYearTarget != _state.observatoryYearSetting
			|| _state.observatoryTimeTarget != _state.observatoryTimeSetting) {

		// Blink the go button
		uint32 time = _vm->_system->getMillis();
		if (time > _observatoryLastTime + 250) {
			_tempVar = (_tempVar + 1) % 2;
			_observatoryGoButton->drawConditionalDataToScreen(_tempVar);
			_observatoryLastTime = time;
		}
	}
}

void Myst::o_gulls2_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Gulls init", op);

	if (!_state.shipFloating) {
		_gullsNextTime = _vm->_system->getMillis() + 2000;
		_gullsFlying2 = true;
	}
}

void Myst::gullsFly2_run() {
	static const char* gulls[] = { "birds1", "birds2", "birds3" };
	uint32 time = _vm->_system->getMillis();

	if (time > _gullsNextTime) {
		uint16 video = _vm->_rnd->getRandomNumber(3);
		if (video != 3) {
			VideoHandle handle = _vm->_video->playMovie(_vm->wrapMovieFilename(gulls[video], kMystStack));
			if (!handle)
				error("Failed to open gulls movie");

			handle->moveTo(424, 0);
			_gullsNextTime = time + _vm->_rnd->getRandomNumber(16667) + 13334;
		}
	}
}

void Myst::o_treeCard_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Enter tree card", op);

	_tree = getInvokingResource<MystAreaImageSwitch>();
}

void Myst::o_treeEntry_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Enter tree card with entry", op);

	_treeAlcove = getInvokingResource<MystArea>();
	_treeMinAccessiblePosition = argv[0];
	_treeMaxAccessiblePosition = argv[1];

	treeSetAlcoveAccessible();
}

void Myst::o_boilerMovies_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Boiler movies init", op);

	boilerFireInit();
	boilerGaugeInit();
}

void Myst::boilerFireInit() {
	if (_vm->getCurCard() == 4098) {
		_cabinFireMovie = _vm->_video->playMovie(_vm->wrapMovieFilename("cabfire", kMystStack));
		if (!_cabinFireMovie)
				error("Failed to open cabfire movie");

		_cabinFireMovie->moveTo(240, 279);
		_cabinFireMovie->setLooping(true);
		_cabinFireMovie->pause(true);

		_vm->redrawArea(305);
		boilerFireUpdate(true);
	} else {
		if (_state.cabinPilotLightLit == 1 && _state.cabinValvePosition >= 1) {
			_cabinFireMovie = _vm->_video->playMovie(_vm->wrapMovieFilename("cabfirfr", kMystStack));
			if (!_cabinFireMovie)
				error("Failed to open cabfirfr movie");

			_cabinFireMovie->moveTo(254, 244);
			_cabinFireMovie->setLooping(true);
		}
	}
}

void Myst::boilerFireUpdate(bool init) {
	uint position = _cabinFireMovie->getTime();

	if (_state.cabinPilotLightLit == 1) {
		if (_state.cabinValvePosition == 0) {
			if (position > (uint)Audio::Timestamp(0, 200, 600).msecs() || init) {
				_cabinFireMovie->setBounds(Audio::Timestamp(0, 0, 600), Audio::Timestamp(0, 100, 600));
				_cabinFireMovie->pause(false);
			}
		} else {
			if (position < (uint)Audio::Timestamp(0, 200, 600).msecs() || init) {
				_cabinFireMovie->setBounds(Audio::Timestamp(0, 201, 600), Audio::Timestamp(0, 1900, 600));
				_cabinFireMovie->pause(false);
			}
		}
	}
}

void Myst::boilerGaugeInit() {
	if (_vm->getCurCard() == 4098) {
		_cabinGaugeMovie = _vm->_video->playMovie(_vm->wrapMovieFilename("cabingau", kMystStack));
		if (!_cabinGaugeMovie)
			error("Failed to open cabingau movie");

		_cabinGaugeMovie->moveTo(243, 96);
	} else {
		_cabinGaugeMovie = _vm->_video->playMovie(_vm->wrapMovieFilename("cabcgfar", kMystStack));
		if (!_cabinGaugeMovie)
			error("Failed to open cabcgfar movie");

		_cabinGaugeMovie->moveTo(254, 136);
	}

	Audio::Timestamp frame;

	if (_state.cabinPilotLightLit == 1 && _state.cabinValvePosition > 12)
		frame = _cabinGaugeMovie->getDuration();
	else
		frame = Audio::Timestamp(0, 0, 600);

	_vm->_video->drawVideoFrame(_cabinGaugeMovie, frame);

	_cabinGaugeMovieEnabled = true;
}

void Myst::o_rocketSliders_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Rocket sliders init", op);

	_rocketSlider1 = _vm->getViewResource<MystAreaSlider>(argv[0]);
	_rocketSlider2 = _vm->getViewResource<MystAreaSlider>(argv[1]);
	_rocketSlider3 = _vm->getViewResource<MystAreaSlider>(argv[2]);
	_rocketSlider4 = _vm->getViewResource<MystAreaSlider>(argv[3]);
	_rocketSlider5 = _vm->getViewResource<MystAreaSlider>(argv[4]);

	// Initialize sliders position
	for (uint i = 0; i < 5; i++)
		if (!_state.rocketSliderPosition[i])
			_state.rocketSliderPosition[i] = 277;

	_rocketSlider1->setPosition(_state.rocketSliderPosition[0]);
	_rocketSlider2->setPosition(_state.rocketSliderPosition[1]);
	_rocketSlider3->setPosition(_state.rocketSliderPosition[2]);
	_rocketSlider4->setPosition(_state.rocketSliderPosition[3]);
	_rocketSlider5->setPosition(_state.rocketSliderPosition[4]);
}

void Myst::o_rocketLinkVideo_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Rocket link video init", op);
	_tempVar = 0;
}

void Myst::o_greenBook_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	// Used for Card 4168 (Green Book Movies)
	debugC(kDebugScript, "Opcode %d: Green book init", op);

	_greenBookRunning = true;
	_tempVar = 1;
}

void Myst::greenBook_run() {
	uint loopStart = 0;
	uint loopEnd = 0;
	Common::String file;

	if (!_state.greenBookOpenedBefore) {
		loopStart = 113200;
		loopEnd = 116400;
		file = _vm->wrapMovieFilename("atrusbk1", kMystStack);
	} else {
		loopStart = 8800;
		loopEnd = 9700;
		file = _vm->wrapMovieFilename("atrusbk2", kMystStack);
	}

	if (_tempVar == 1) {
		_vm->_sound->stopSound();
		_vm->_sound->pauseBackgroundMyst();

		VideoHandle book = _vm->_video->playMovie(file);
		if (!book)
			error("Failed to open '%s'", file.c_str());

		book->moveTo(314, 76);

		if (_globals.ending != 4) {
			_tempVar = 2;
		} else {
			book->setBounds(Audio::Timestamp(0, loopStart, 600), Audio::Timestamp(0, loopEnd, 600));
			book->setLooping(true);
			_tempVar = 0;
		}
	} else if (_tempVar == 2 && !_vm->_video->isVideoPlaying()) {
		VideoHandle book = _vm->_video->playMovie(file);
		if (!book)
			error("Failed to open '%s'", file.c_str());

		book->moveTo(314, 76);
		book->setBounds(Audio::Timestamp(0, loopStart, 600), Audio::Timestamp(0, loopEnd, 600));
		book->setLooping(true);
		_tempVar = 0;
	}
}

void Myst::o_gulls3_init(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Gulls init", op);

	if (!_state.shipFloating) {
		_gullsNextTime = _vm->_system->getMillis() + 2000;
		_gullsFlying3 = true;
	}
}

void Myst::gullsFly3_run() {
	static const char* gulls[] = { "birds1", "birds2", "birds3" };
	uint32 time = _vm->_system->getMillis();

	if (time > _gullsNextTime) {
		uint16 video = _vm->_rnd->getRandomNumber(3);
		if (video != 3) {
			uint16 x = _vm->_rnd->getRandomNumber(280) + 135;

			VideoHandle handle = _vm->_video->playMovie(_vm->wrapMovieFilename(gulls[video], kMystStack));
			if (!handle)
				error("Failed to open gulls movie");

			handle->moveTo(x, 0);
			_gullsNextTime = time + _vm->_rnd->getRandomNumber(16667) + 13334;
		}
	}
}

void Myst::o_bookAddSpecialPage_exit(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Book Exit Function", op);

	uint16 numPages = bookCountPages(var);

	// Add special page
	if (numPages == 5) {
		if (var == 100)
			_globals.redPagesInBook |= 64;
		else
			_globals.bluePagesInBook |= 64;
	}
}

void Myst::o_treeCard_exit(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Exit tree card", op);

	_tree = nullptr;
}

void Myst::o_treeEntry_exit(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Exit tree card with entry", op);

	_treeAlcove = nullptr;
}

void Myst::o_boiler_exit(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Exit boiler card", op);

	_cabinGaugeMovie = VideoHandle();
	_cabinFireMovie = VideoHandle();

	_cabinGaugeMovieEnabled = false;
}

void Myst::o_generatorControlRoom_exit(uint16 op, uint16 var, uint16 argc, uint16 *argv) {
	debugC(kDebugScript, "Opcode %d: Generator room exit", op);

	_generatorVoltage = _state.generatorVoltage;
}

} // End of namespace MystStacks
} // End of namespace Mohawk