~random-stuff/random-stuff/snes9x-OLD

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
/***********************************************************************************
  Snes9x - Portable Super Nintendo Entertainment System (TM) emulator.

  (c) Copyright 1996 - 2002  Gary Henderson (gary.henderson@ntlworld.com),
                             Jerremy Koot (jkoot@snes9x.com)

  (c) Copyright 2002 - 2004  Matthew Kendora

  (c) Copyright 2002 - 2005  Peter Bortas (peter@bortas.org)

  (c) Copyright 2004 - 2005  Joel Yliluoma (http://iki.fi/bisqwit/)

  (c) Copyright 2001 - 2006  John Weidman (jweidman@slip.net)

  (c) Copyright 2002 - 2006  funkyass (funkyass@spam.shaw.ca),
                             Kris Bleakley (codeviolation@hotmail.com)

  (c) Copyright 2002 - 2010  Brad Jorsch (anomie@users.sourceforge.net),
                             Nach (n-a-c-h@users.sourceforge.net),

  (c) Copyright 2002 - 2011  zones (kasumitokoduck@yahoo.com)

  (c) Copyright 2006 - 2007  nitsuja

  (c) Copyright 2009 - 2016  BearOso,
                             OV2


  BS-X C emulator code
  (c) Copyright 2005 - 2006  Dreamer Nom,
                             zones

  C4 x86 assembler and some C emulation code
  (c) Copyright 2000 - 2003  _Demo_ (_demo_@zsnes.com),
                             Nach,
                             zsKnight (zsknight@zsnes.com)

  C4 C++ code
  (c) Copyright 2003 - 2006  Brad Jorsch,
                             Nach

  DSP-1 emulator code
  (c) Copyright 1998 - 2006  _Demo_,
                             Andreas Naive (andreasnaive@gmail.com),
                             Gary Henderson,
                             Ivar (ivar@snes9x.com),
                             John Weidman,
                             Kris Bleakley,
                             Matthew Kendora,
                             Nach,
                             neviksti (neviksti@hotmail.com)

  DSP-2 emulator code
  (c) Copyright 2003         John Weidman,
                             Kris Bleakley,
                             Lord Nightmare (lord_nightmare@users.sourceforge.net),
                             Matthew Kendora,
                             neviksti

  DSP-3 emulator code
  (c) Copyright 2003 - 2006  John Weidman,
                             Kris Bleakley,
                             Lancer,
                             z80 gaiden

  DSP-4 emulator code
  (c) Copyright 2004 - 2006  Dreamer Nom,
                             John Weidman,
                             Kris Bleakley,
                             Nach,
                             z80 gaiden

  OBC1 emulator code
  (c) Copyright 2001 - 2004  zsKnight,
                             pagefault (pagefault@zsnes.com),
                             Kris Bleakley
                             Ported from x86 assembler to C by sanmaiwashi

  SPC7110 and RTC C++ emulator code used in 1.39-1.51
  (c) Copyright 2002         Matthew Kendora with research by
                             zsKnight,
                             John Weidman,
                             Dark Force

  SPC7110 and RTC C++ emulator code used in 1.52+
  (c) Copyright 2009         byuu,
                             neviksti

  S-DD1 C emulator code
  (c) Copyright 2003         Brad Jorsch with research by
                             Andreas Naive,
                             John Weidman

  S-RTC C emulator code
  (c) Copyright 2001 - 2006  byuu,
                             John Weidman

  ST010 C++ emulator code
  (c) Copyright 2003         Feather,
                             John Weidman,
                             Kris Bleakley,
                             Matthew Kendora

  Super FX x86 assembler emulator code
  (c) Copyright 1998 - 2003  _Demo_,
                             pagefault,
                             zsKnight

  Super FX C emulator code
  (c) Copyright 1997 - 1999  Ivar,
                             Gary Henderson,
                             John Weidman

  Sound emulator code used in 1.5-1.51
  (c) Copyright 1998 - 2003  Brad Martin
  (c) Copyright 1998 - 2006  Charles Bilyue'

  Sound emulator code used in 1.52+
  (c) Copyright 2004 - 2007  Shay Green (gblargg@gmail.com)

  S-SMP emulator code used in 1.54+
  (c) Copyright 2016         byuu

  SH assembler code partly based on x86 assembler code
  (c) Copyright 2002 - 2004  Marcus Comstedt (marcus@mc.pp.se)

  2xSaI filter
  (c) Copyright 1999 - 2001  Derek Liauw Kie Fa

  HQ2x, HQ3x, HQ4x filters
  (c) Copyright 2003         Maxim Stepin (maxim@hiend3d.com)

  NTSC filter
  (c) Copyright 2006 - 2007  Shay Green

  GTK+ GUI code
  (c) Copyright 2004 - 2016  BearOso

  Win32 GUI code
  (c) Copyright 2003 - 2006  blip,
                             funkyass,
                             Matthew Kendora,
                             Nach,
                             nitsuja
  (c) Copyright 2009 - 2016  OV2

  Mac OS GUI code
  (c) Copyright 1998 - 2001  John Stiles
  (c) Copyright 2001 - 2011  zones


  Specific ports contains the works of other authors. See headers in
  individual files.


  Snes9x homepage: http://www.snes9x.com/

  Permission to use, copy, modify and/or distribute Snes9x in both binary
  and source form, for non-commercial purposes, is hereby granted without
  fee, providing that this license information and copyright notice appear
  with all copies and any derived work.

  This software is provided 'as-is', without any express or implied
  warranty. In no event shall the authors be held liable for any damages
  arising from the use of this software or it's derivatives.

  Snes9x is freeware for PERSONAL USE only. Commercial users should
  seek permission of the copyright holders first. Commercial use includes,
  but is not limited to, charging money for Snes9x or software derived from
  Snes9x, including Snes9x or derivatives in commercial game bundles, and/or
  using Snes9x as a promotion for your commercial product.

  The copyright holders request that bug fixes and improvements to the code
  should be forwarded to them so everyone can benefit from the modifications
  in future versions.

  Super NES and Super Nintendo Entertainment System are trademarks of
  Nintendo Co., Limited and its subsidiary companies.
 ***********************************************************************************/


#include <map>
#include <set>
#include <vector>
#include <string>
#include <algorithm>
#include <assert.h>
#include <ctype.h>

#include "snes9x.h"
#include "memmap.h"
#include "apu/apu.h"
#include "snapshot.h"
#include "controls.h"
#include "crosshairs.h"
#include "movie.h"
#include "display.h"
#ifdef NETPLAY_SUPPORT
#include "netplay.h"
#endif

using namespace	std;

#define NONE					(-2)
#define MP5						(-1)
#define JOYPAD0					0
#define JOYPAD1					1
#define JOYPAD2					2
#define JOYPAD3					3
#define JOYPAD4					4
#define JOYPAD5					5
#define JOYPAD6					6
#define JOYPAD7					7
#define MOUSE0					8
#define MOUSE1					9
#define SUPERSCOPE				10
#define ONE_JUSTIFIER			11
#define TWO_JUSTIFIERS			12
#define NUMCTLS					13 // This must be LAST

#define POLL_ALL				NUMCTLS

#define SUPERSCOPE_FIRE			0x80
#define SUPERSCOPE_CURSOR		0x40
#define SUPERSCOPE_TURBO		0x20
#define SUPERSCOPE_PAUSE		0x10
#define SUPERSCOPE_OFFSCREEN	0x02

#define JUSTIFIER_TRIGGER		0x80
#define JUSTIFIER_START			0x20
#define JUSTIFIER_SELECT		0x08

#define MAP_UNKNOWN				(-1)
#define MAP_NONE				0
#define MAP_BUTTON				1
#define MAP_AXIS				2
#define MAP_POINTER				3

#define FLAG_IOBIT0				(Memory.FillRAM[0x4213] & 0x40)
#define FLAG_IOBIT1				(Memory.FillRAM[0x4213] & 0x80)
#define FLAG_IOBIT(n)			((n) ? (FLAG_IOBIT1) : (FLAG_IOBIT0))

bool8	pad_read = 0, pad_read_last = 0;
uint8	read_idx[2 /* ports */][2 /* per port */];

struct exemulti
{
	int32				pos;
	bool8				data1;
	s9xcommand_t		*script;
};

struct crosshair
{
	uint8				set;
	uint8				img;
	uint8				fg, bg;
};

static struct
{
	int16				x, y;
	int16				V_adj;
	bool8				V_var;
	int16				H_adj;
	bool8				H_var;
	bool8				mapped;
}	pseudopointer[8];

static struct
{
	uint16				buttons;
	uint16				turbos;
	uint16				toggleturbo;
	uint16				togglestick;
	uint8				turbo_ct;
}	joypad[8];

static struct
{
	uint8				delta_x, delta_y;
	int16				old_x, old_y;
	int16				cur_x, cur_y;
	uint8				buttons;
	uint32				ID;
	struct crosshair	crosshair;
}	mouse[2];

static struct
{
	int16				x, y;
	uint8				phys_buttons;
	uint8				next_buttons;
	uint8				read_buttons;
	uint32				ID;
	struct crosshair	crosshair;
}	superscope;

static struct
{
	int16				x[2], y[2];
	uint8				buttons;
	bool8				offscreen[2];
	uint32				ID[2];
	struct crosshair	crosshair[2];
}	justifier;

static struct
{
	int8				pads[4];
}	mp5[2];

static set<struct exemulti *>		exemultis;
static set<uint32>					pollmap[NUMCTLS + 1];
static map<uint32, s9xcommand_t>	keymap;
static vector<s9xcommand_t *>		multis;
static uint8						turbo_time;
static uint8						pseudobuttons[256];
static bool8						FLAG_LATCH = FALSE;
static int32						curcontrollers[2] = { NONE,    NONE };
static int32						newcontrollers[2] = { JOYPAD0, NONE };
static char							buf[256];

static const char	*color_names[32] =
{
	"Trans",
	"Black",
	"25Grey",
	"50Grey",
	"75Grey",
	"White",
	"Red",
	"Orange",
	"Yellow",
	"Green",
	"Cyan",
	"Sky",
	"Blue",
	"Violet",
	"MagicPink",
	"Purple",
	NULL,
	"tBlack",
	"t25Grey",
	"t50Grey",
	"t75Grey",
	"tWhite",
	"tRed",
	"tOrange",
	"tYellow",
	"tGreen",
	"tCyan",
	"tSky",
	"tBlue",
	"tViolet",
	"tMagicPink",
	"tPurple"
};

static const char	*speed_names[4] =
{
	"Var",
	"Slow",
	"Med",
	"Fast"
};

static const int	ptrspeeds[4] = { 1, 1, 4, 8 };

// Note: these should be in asciibetical order!
#define THE_COMMANDS \
	S(BeginRecordingMovie), \
	S(ClipWindows), \
	S(Debugger), \
	S(DecEmuTurbo), \
	S(DecFrameRate), \
	S(DecFrameTime), \
	S(DecTurboSpeed), \
	S(EmuTurbo), \
	S(EndRecordingMovie), \
	S(ExitEmu), \
	S(IncEmuTurbo), \
	S(IncFrameRate), \
	S(IncFrameTime), \
	S(IncTurboSpeed), \
	S(LoadFreezeFile), \
	S(LoadMovie), \
	S(LoadOopsFile), \
	S(Pause), \
	S(QuickLoad000), \
	S(QuickLoad001), \
	S(QuickLoad002), \
	S(QuickLoad003), \
	S(QuickLoad004), \
	S(QuickLoad005), \
	S(QuickLoad006), \
	S(QuickLoad007), \
	S(QuickLoad008), \
	S(QuickLoad009), \
	S(QuickLoad010), \
	S(QuickSave000), \
	S(QuickSave001), \
	S(QuickSave002), \
	S(QuickSave003), \
	S(QuickSave004), \
	S(QuickSave005), \
	S(QuickSave006), \
	S(QuickSave007), \
	S(QuickSave008), \
	S(QuickSave009), \
	S(QuickSave010), \
	S(Reset), \
	S(SaveFreezeFile), \
	S(SaveSPC), \
	S(Screenshot), \
	S(SeekToFrame), \
	S(SoftReset), \
	S(SoundChannel0), \
	S(SoundChannel1), \
	S(SoundChannel2), \
	S(SoundChannel3), \
	S(SoundChannel4), \
	S(SoundChannel5), \
	S(SoundChannel6), \
	S(SoundChannel7), \
	S(SoundChannelsOn), \
	S(SwapJoypads), \
	S(ToggleBG0), \
	S(ToggleBG1), \
	S(ToggleBG2), \
	S(ToggleBG3), \
	S(ToggleEmuTurbo), \
	S(ToggleSprites), \
	S(ToggleTransparency) \

#define S(x)	x

enum command_numbers
{
	THE_COMMANDS,
	LAST_COMMAND
};

#undef S
#define S(x)	#x

static const char	*command_names[LAST_COMMAND + 1] =
{
	THE_COMMANDS,
	NULL
};

#undef S
#undef THE_COMMANDS

static void DisplayStateChange (const char *, bool8);
static void DoGunLatch (int, int);
static int maptype (int);
static bool strless (const char *, const char *);
static int findstr (const char *, const char **, int);
static int get_threshold (const char **);
static const char * maptypename (int);
static int32 ApplyMulti (s9xcommand_t *, int32, int16);
static void do_polling (int);
static void UpdatePolledMouse (int);


static string& operator += (string &s, int i)
{
	snprintf(buf, sizeof(buf), "%d", i);
	s.append(buf);
	return (s);
}

static string& operator += (string &s, double d)
{
	snprintf(buf, sizeof(buf), "%g", d);
	s.append(buf);
	return (s);
}

static void DisplayStateChange (const char *str, bool8 on)
{
	snprintf(buf, sizeof(buf), "%s: %s", str, on ? "on":"off");
	S9xSetInfoString(buf);
}

static void DoGunLatch (int x, int y)
{
	x += 40;

	if (x > 295)
		x = 295;
	else
	if (x < 40)
		x = 40;

	if (y > PPU.ScreenHeight - 1)
		y = PPU.ScreenHeight - 1;
	else
	if (y < 0)
		y = 0;

	PPU.GunVLatch = (uint16) (y + 1);
	PPU.GunHLatch = (uint16) x;
}

static int maptype (int t)
{
	switch (t)
	{
		case S9xNoMapping:
			return (MAP_NONE);

		case S9xButtonJoypad:
		case S9xButtonMouse:
		case S9xButtonSuperscope:
		case S9xButtonJustifier:
		case S9xButtonCommand:
		case S9xButtonPseudopointer:
		case S9xButtonPort:
		case S9xButtonMulti:
			return (MAP_BUTTON);

		case S9xAxisJoypad:
		case S9xAxisPseudopointer:
		case S9xAxisPseudobuttons:
		case S9xAxisPort:
			return (MAP_AXIS);

		case S9xPointer:
		case S9xPointerPort:
			return (MAP_POINTER);

		default:
			return (MAP_UNKNOWN);
	}
}

void S9xControlsReset (void)
{
	S9xControlsSoftReset();
	mouse[0].buttons  &= ~0x30;
	mouse[1].buttons  &= ~0x30;
	justifier.buttons &= ~JUSTIFIER_SELECT;
}

void S9xControlsSoftReset (void)
{
	for (set<struct exemulti *>::iterator it = exemultis.begin(); it != exemultis.end(); it++)
		delete *it;
	exemultis.clear();

	for (int i = 0; i < 2; i++)
		for (int j = 0; j < 2; j++)
			read_idx[i][j]=0;

	FLAG_LATCH = FALSE;
}

void S9xUnmapAllControls (void)
{
	S9xControlsReset();

	keymap.clear();

	for (int i = 0; i < (int) multis.size(); i++)
		free(multis[i]);
	multis.clear();

	for (int i = 0; i < NUMCTLS + 1; i++)
		pollmap[i].clear();

	for (int i = 0; i < 8; i++)
	{
		pseudopointer[i].x = 0;
		pseudopointer[i].y = 0;
		pseudopointer[i].H_adj = 0;
		pseudopointer[i].V_adj = 0;
		pseudopointer[i].H_var = 0;
		pseudopointer[i].V_var = 0;
		pseudopointer[i].mapped = false;

		joypad[i].buttons  = 0;
		joypad[i].turbos   = 0;
		joypad[i].turbo_ct = 0;
	}

	for (int i = 0; i < 2; i++)
	{
		mouse[i].old_x = mouse[i].old_y = 0;
		mouse[i].cur_x = mouse[i].cur_y = 0;
		mouse[i].buttons = 1;
		mouse[i].ID = InvalidControlID;

		if (!(mouse[i].crosshair.set & 1))
			mouse[i].crosshair.img = 0; // no image for mouse because its only logical position is game-specific, not known by the emulator
		if (!(mouse[i].crosshair.set & 2))
			mouse[i].crosshair.fg  = 5;
		if (!(mouse[i].crosshair.set & 4))
			mouse[i].crosshair.bg  = 1;

		justifier.x[i] = justifier.y[i] = 0;
		justifier.offscreen[i] = 0;
		justifier.ID[i] = InvalidControlID;

		if (!(justifier.crosshair[i].set & 1))
			justifier.crosshair[i].img = 4;
		if (!(justifier.crosshair[i].set & 2))
			justifier.crosshair[i].fg  = i ? 14 : 12;
		if (!(justifier.crosshair[i].set & 4))
			justifier.crosshair[i].bg  = 1;
	}

	justifier.buttons = 0;

	superscope.x = superscope.y = 0;
	superscope.phys_buttons = 0;
	superscope.next_buttons = 0;
	superscope.read_buttons = 0;
	superscope.ID = InvalidControlID;

	if (!(superscope.crosshair.set & 1))
		superscope.crosshair.img = 2;
	if (!(superscope.crosshair.set & 2))
		superscope.crosshair.fg  = 5;
	if (!(superscope.crosshair.set & 4))
		superscope.crosshair.bg  = 1;

	memset(pseudobuttons, 0, sizeof(pseudobuttons));

	turbo_time = 1;
}

void S9xSetController (int port, enum controllers controller, int8 id1, int8 id2, int8 id3, int8 id4)
{
	if (port < 0 || port > 1)
		return;

	switch (controller)
	{
		case CTL_NONE:
			break;

		case CTL_JOYPAD:
			if (id1 < 0 || id1 > 7)
				break;

			newcontrollers[port] = JOYPAD0 + id1;
			return;

		case CTL_MOUSE:
			if (id1 < 0 || id1 > 1)
				break;
			if (!Settings.MouseMaster)
			{
				S9xMessage(S9X_CONFIG_INFO, S9X_ERROR, "Cannot select SNES Mouse: MouseMaster disabled");
				break;
			}

			newcontrollers[port] = MOUSE0 + id1;
			return;

		case CTL_SUPERSCOPE:
			if (!Settings.SuperScopeMaster)
			{
				S9xMessage(S9X_CONFIG_INFO, S9X_ERROR, "Cannot select SNES Superscope: SuperScopeMaster disabled");
				break;
			}

			newcontrollers[port] = SUPERSCOPE;
			return;

		case CTL_JUSTIFIER:
			if (id1 < 0 || id1 > 1)
				break;
			if (!Settings.JustifierMaster)
			{
				S9xMessage(S9X_CONFIG_INFO, S9X_ERROR, "Cannot select Konami Justifier: JustifierMaster disabled");
				break;
			}

			newcontrollers[port] = ONE_JUSTIFIER + id1;
			return;

		case CTL_MP5:
			if (id1 < -1 || id1 > 7)
				break;
			if (id2 < -1 || id2 > 7)
				break;
			if (id3 < -1 || id3 > 7)
				break;
			if (id4 < -1 || id4 > 7)
				break;
			if (!Settings.MultiPlayer5Master)
			{
				S9xMessage(S9X_CONFIG_INFO, S9X_ERROR, "Cannot select MP5: MultiPlayer5Master disabled");
				break;
			}

			newcontrollers[port] = MP5;
			mp5[port].pads[0] = (id1 < 0) ? NONE : JOYPAD0 + id1;
			mp5[port].pads[1] = (id2 < 0) ? NONE : JOYPAD0 + id2;
			mp5[port].pads[2] = (id3 < 0) ? NONE : JOYPAD0 + id3;
			mp5[port].pads[3] = (id4 < 0) ? NONE : JOYPAD0 + id4;
			return;

		default:
			fprintf(stderr, "Unknown controller type %d\n", controller);
			break;
	}

	newcontrollers[port] = NONE;
}

bool S9xVerifyControllers (void)
{
	bool	ret = false;
	int		port, i, used[NUMCTLS];

	for (i = 0; i < NUMCTLS; used[i++] = 0) ;

	for (port = 0; port < 2; port++)
	{
		switch (i = newcontrollers[port])
		{
			case MOUSE0:
			case MOUSE1:
				if (!Settings.MouseMaster)
				{
					S9xMessage(S9X_CONFIG_INFO, S9X_ERROR, "Cannot select SNES Mouse: MouseMaster disabled");
					newcontrollers[port] = NONE;
					ret = true;
					break;
				}

				if (used[i]++ > 0)
				{
					snprintf(buf, sizeof(buf), "Mouse%d used more than once! Disabling extra instances", i - MOUSE0 + 1);
					S9xMessage(S9X_CONFIG_INFO, S9X_ERROR, buf);
					newcontrollers[port] = NONE;
					ret = true;
					break;
				}

				break;

			case SUPERSCOPE:
				if (!Settings.SuperScopeMaster)
				{
					S9xMessage(S9X_CONFIG_INFO, S9X_ERROR, "Cannot select SNES Superscope: SuperScopeMaster disabled");
					newcontrollers[port] = NONE;
					ret = true;
					break;
				}

				if (used[i]++ > 0)
				{
					snprintf(buf, sizeof(buf), "Superscope used more than once! Disabling extra instances");
					S9xMessage(S9X_CONFIG_INFO, S9X_ERROR, buf);
					newcontrollers[port] = NONE;
					ret = true;
					break;
				}

				break;

			case ONE_JUSTIFIER:
			case TWO_JUSTIFIERS:
				if (!Settings.JustifierMaster)
				{
					S9xMessage(S9X_CONFIG_INFO, S9X_ERROR, "Cannot select Konami Justifier: JustifierMaster disabled");
					newcontrollers[port] = NONE;
					ret = true;
					break;
				}

				if (used[ONE_JUSTIFIER]++ > 0)
				{
					snprintf(buf, sizeof(buf), "Justifier used more than once! Disabling extra instances");
					S9xMessage(S9X_CONFIG_INFO, S9X_ERROR, buf);
					newcontrollers[port] = NONE;
					ret = true;
					break;
				}

				break;

			case MP5:
				if (!Settings.MultiPlayer5Master)
				{
					S9xMessage(S9X_CONFIG_INFO, S9X_ERROR, "Cannot select MP5: MultiPlayer5Master disabled");
					newcontrollers[port] = NONE;
					ret = true;
					break;
				}

				for (i = 0; i < 4; i++)
				{
					if (mp5[port].pads[i] != NONE)
					{
						if (used[mp5[port].pads[i] - JOYPAD0]++ > 0)
						{
							snprintf(buf, sizeof(buf), "Joypad%d used more than once! Disabling extra instances", mp5[port].pads[i] - JOYPAD0 + 1);
							S9xMessage(S9X_CONFIG_INFO, S9X_ERROR, buf);
							mp5[port].pads[i] = NONE;
							ret = true;
							break;
						}
					}
				}

				break;

			case JOYPAD0:
			case JOYPAD1:
			case JOYPAD2:
			case JOYPAD3:
			case JOYPAD4:
			case JOYPAD5:
			case JOYPAD6:
			case JOYPAD7:
				if (used[i - JOYPAD0]++ > 0)
				{
					snprintf(buf, sizeof(buf), "Joypad%d used more than once! Disabling extra instances", i - JOYPAD0 + 1);
					S9xMessage(S9X_CONFIG_INFO, S9X_ERROR, buf);
					newcontrollers[port] = NONE;
					ret = true;
					break;
				}

				break;

			default:
				break;
		}
	}

	return (ret);
}

void S9xGetController (int port, enum controllers *controller, int8 *id1, int8 *id2, int8 *id3, int8 *id4)
{
	int	i;

	*controller = CTL_NONE;
	*id1 = *id2 = *id3 = *id4 = -1;

	if (port < 0 || port > 1)
		return;

	switch (i = newcontrollers[port])
	{
		case MP5:
			*controller = CTL_MP5;
			*id1 = (mp5[port].pads[0] == NONE) ? -1 : mp5[port].pads[0] - JOYPAD0;
			*id2 = (mp5[port].pads[1] == NONE) ? -1 : mp5[port].pads[1] - JOYPAD0;
			*id3 = (mp5[port].pads[2] == NONE) ? -1 : mp5[port].pads[2] - JOYPAD0;
			*id4 = (mp5[port].pads[3] == NONE) ? -1 : mp5[port].pads[3] - JOYPAD0;
			return;

		case JOYPAD0:
		case JOYPAD1:
		case JOYPAD2:
		case JOYPAD3:
		case JOYPAD4:
		case JOYPAD5:
		case JOYPAD6:
		case JOYPAD7:
			*controller = CTL_JOYPAD;
			*id1 = i - JOYPAD0;
			return;

		case MOUSE0:
		case MOUSE1:
			*controller = CTL_MOUSE;
			*id1 = i - MOUSE0;
			return;

		case SUPERSCOPE:
			*controller = CTL_SUPERSCOPE;
			*id1 = 1;
			return;

		case ONE_JUSTIFIER:
		case TWO_JUSTIFIERS:
			*controller = CTL_JUSTIFIER;
			*id1 = i - ONE_JUSTIFIER;
			return;
	}
}

void S9xReportControllers (void)
{
	static char	mes[128];
	char		*c = mes;

	S9xVerifyControllers();

	for (int port = 0; port < 2; port++)
	{
		c += sprintf(c, "Port %d: ", port + 1);

		switch (newcontrollers[port])
		{
			case NONE:
				c += sprintf(c, "<none>. ");
				break;

			case MP5:
				c += sprintf(c, "MP5 with pads");
				for (int i = 0; i < 4; i++)
				{
					if (mp5[port].pads[i] == NONE)
						c += sprintf(c, " <none>. ");
					else
						c += sprintf(c, " #%d. ", mp5[port].pads[i] + 1 - JOYPAD0);
				}

				break;

			case JOYPAD0:
			case JOYPAD1:
			case JOYPAD2:
			case JOYPAD3:
			case JOYPAD4:
			case JOYPAD5:
			case JOYPAD6:
			case JOYPAD7:
				c += sprintf(c, "Pad #%d. ", (int) (newcontrollers[port] - JOYPAD0 + 1));
				break;

			case MOUSE0:
			case MOUSE1:
				c += sprintf(c, "Mouse #%d. ", (int) (newcontrollers[port] - MOUSE0 + 1));
				break;

			case SUPERSCOPE:
				if (port == 0)
					c += sprintf(c, "Superscope (cannot fire). ");
				else
					c += sprintf(c, "Superscope. ");
				break;

			case ONE_JUSTIFIER:
				if (port == 0)
					c += sprintf(c, "Blue Justifier (cannot fire). ");
				else
					c += sprintf(c, "Blue Justifier. ");
				break;

			case TWO_JUSTIFIERS:
				if (port == 0)
					c += sprintf(c, "Blue and Pink Justifiers (cannot fire). ");
				else
					c += sprintf(c, "Blue and Pink Justifiers. ");
				break;
		}
	}

	S9xMessage(S9X_INFO, S9X_CONFIG_INFO, mes);
}

char * S9xGetCommandName (s9xcommand_t command)
{
	string	s;
	char	c;

	switch (command.type)
	{
		case S9xButtonJoypad:
			if (command.button.joypad.buttons == 0)
				return (strdup("None"));
			if (command.button.joypad.buttons & 0x000f)
				return (strdup("None"));

			s = "Joypad";
			s += command.button.joypad.idx + 1;

			c = ' ';
			if (command.button.joypad.toggle)	{ if (c) s += c; s += "Toggle"; c = 0; }
			if (command.button.joypad.sticky)	{ if (c) s += c; s += "Sticky"; c = 0; }
			if (command.button.joypad.turbo )	{ if (c) s += c; s += "Turbo";  c = 0; }

			c = ' ';
			if (command.button.joypad.buttons & SNES_UP_MASK    )	{ s += c; s += "Up";     c = '+'; }
			if (command.button.joypad.buttons & SNES_DOWN_MASK  )	{ s += c; s += "Down";   c = '+'; }
			if (command.button.joypad.buttons & SNES_LEFT_MASK  )	{ s += c; s += "Left";   c = '+'; }
			if (command.button.joypad.buttons & SNES_RIGHT_MASK )	{ s += c; s += "Right";  c = '+'; }
			if (command.button.joypad.buttons & SNES_A_MASK     )	{ s += c; s += "A";      c = '+'; }
			if (command.button.joypad.buttons & SNES_B_MASK     )	{ s += c; s += "B";      c = '+'; }
			if (command.button.joypad.buttons & SNES_X_MASK     )	{ s += c; s += "X";      c = '+'; }
			if (command.button.joypad.buttons & SNES_Y_MASK     )	{ s += c; s += "Y";      c = '+'; }
			if (command.button.joypad.buttons & SNES_TL_MASK    )	{ s += c; s += "L";      c = '+'; }
			if (command.button.joypad.buttons & SNES_TR_MASK    )	{ s += c; s += "R";      c = '+'; }
			if (command.button.joypad.buttons & SNES_START_MASK )	{ s += c; s += "Start";  c = '+'; }
			if (command.button.joypad.buttons & SNES_SELECT_MASK)	{ s += c; s += "Select"; c = '+'; }

			break;

		case S9xButtonMouse:
			if (!command.button.mouse.left && !command.button.mouse.right)
				return (strdup("None"));

			s = "Mouse";
			s += command.button.mouse.idx + 1;
			s += " ";

			if (command.button.mouse.left )	s += "L";
			if (command.button.mouse.right)	s += "R";

			break;

		case S9xButtonSuperscope:
			if (!command.button.scope.fire && !command.button.scope.cursor && !command.button.scope.turbo && !command.button.scope.pause && !command.button.scope.aim_offscreen)
				return (strdup("None"));

			s = "Superscope";

			if (command.button.scope.aim_offscreen)	s += " AimOffscreen";

			c = ' ';
			if (command.button.scope.fire  )	{ s += c; s += "Fire";        c = '+'; }
			if (command.button.scope.cursor)	{ s += c; s += "Cursor";      c = '+'; }
			if (command.button.scope.turbo )	{ s += c; s += "ToggleTurbo"; c = '+'; }
			if (command.button.scope.pause )	{ s += c; s += "Pause";       c = '+'; }

			break;

		case S9xButtonJustifier:
			if (!command.button.justifier.trigger && !command.button.justifier.start && !command.button.justifier.aim_offscreen)
				return (strdup("None"));

			s = "Justifier";
			s += command.button.justifier.idx + 1;

			if (command.button.justifier.aim_offscreen)	s += " AimOffscreen";

			c = ' ';
			if (command.button.justifier.trigger)	{ s += c; s += "Trigger"; c = '+'; }
			if (command.button.justifier.start  )	{ s += c; s += "Start";   c = '+'; }

			break;

		case S9xButtonCommand:
			if (command.button.command >= LAST_COMMAND)
				return (strdup("None"));

			return (strdup(command_names[command.button.command]));

		case S9xPointer:
			if (!command.pointer.aim_mouse0 && !command.pointer.aim_mouse1 && !command.pointer.aim_scope && !command.pointer.aim_justifier0 && !command.pointer.aim_justifier1)
				return (strdup("None"));

			s = "Pointer";

			c = ' ';
			if (command.pointer.aim_mouse0    )	{ s += c; s += "Mouse1";     c = '+'; }
			if (command.pointer.aim_mouse1    )	{ s += c; s += "Mouse2";     c = '+'; }
			if (command.pointer.aim_scope     )	{ s += c; s += "Superscope"; c = '+'; }
			if (command.pointer.aim_justifier0)	{ s += c; s += "Justifier1"; c = '+'; }
			if (command.pointer.aim_justifier1)	{ s += c; s += "Justifier2"; c = '+'; }

			break;

		case S9xButtonPseudopointer:
			if (!command.button.pointer.UD && !command.button.pointer.LR)
				return (strdup("None"));
			if (command.button.pointer.UD == -2 || command.button.pointer.LR == -2)
				return (strdup("None"));

			s = "ButtonToPointer ";
			s += command.button.pointer.idx + 1;

			if (command.button.pointer.UD)	s += (command.button.pointer.UD == 1) ? 'd' : 'u';
			if (command.button.pointer.LR)	s += (command.button.pointer.LR == 1) ? 'r' : 'l';

			s += " ";
			s += speed_names[command.button.pointer.speed_type];

			break;

		case S9xAxisJoypad:
			s = "Joypad";
			s += command.axis.joypad.idx + 1;
			s += " Axis ";

			switch (command.axis.joypad.axis)
			{
				case 0:	s += (command.axis.joypad.invert ? "Right/Left" : "Left/Right");	break;
				case 1:	s += (command.axis.joypad.invert ? "Down/Up"    : "Up/Down"   );	break;
				case 2:	s += (command.axis.joypad.invert ? "A/Y"        : "Y/A"       );	break;
				case 3:	s += (command.axis.joypad.invert ? "B/X"        : "X/B"       );	break;
				case 4:	s += (command.axis.joypad.invert ? "R/L"        : "L/R"       );	break;
				default:	return (strdup("None"));
			}

			s += " T=";
			s += int((command.axis.joypad.threshold + 1) * 1000 / 256) / 10.0;
			s += "%";

			break;

		case S9xAxisPseudopointer:
			s = "AxisToPointer ";
			s += command.axis.pointer.idx + 1;
			s += command.axis.pointer.HV ? 'v' : 'h';
			s += " ";

			if (command.axis.pointer.invert)	s += "-";

			s += speed_names[command.axis.pointer.speed_type];

			break;

		case S9xAxisPseudobuttons:
			s = "AxisToButtons ";
			s += command.axis.button.negbutton;
			s += "/";
			s += command.axis.button.posbutton;
			s += " T=";
			s += int((command.axis.button.threshold + 1) * 1000 / 256) / 10.0;
			s += "%";

			break;

		case S9xButtonPort:
		case S9xAxisPort:
		case S9xPointerPort:
			return (strdup("BUG: Port should have handled this instead of calling S9xGetCommandName()"));

		case S9xNoMapping:
			return (strdup("None"));

		case S9xButtonMulti:
		{
			if (command.button.multi_idx >= (int) multis.size())
				return (strdup("None"));

			s = "{";
			if (multis[command.button.multi_idx]->multi_press)	s = "+{";

			bool	sep = false;

			for (s9xcommand_t *m = multis[command.button.multi_idx]; m->multi_press != 3; m++)
			{
				if (m->type == S9xNoMapping)
				{
					s += ";";
					sep = false;
				}
				else
				{
					if (sep)					s += ",";
					if (m->multi_press == 1)	s += "+";
					if (m->multi_press == 2)	s += "-";

					s += S9xGetCommandName(*m);
					sep = true;
				}
			}

			s += "}";

			break;
		}

		default:
			return (strdup("BUG: Unknown command type"));
	}

	return (strdup(s.c_str()));
}

static bool strless (const char *a, const char *b)
{
	return (strcmp(a, b) < 0);
}

static int findstr (const char *needle, const char **haystack, int numstr)
{
	const char	**r;

	r = lower_bound(haystack, haystack + numstr, needle, strless);
	if (r >= haystack + numstr || strcmp(needle, *r))
		return (-1);

	return (r - haystack);
}

static int get_threshold (const char **ss)
{
	const char	*s = *ss;
	int			i;

	if (s[0] != 'T' || s[1] != '=')
		return (-1);

	s += 2;
	i = 0;

	if (s[0] == '0')
	{
		if (s[1] != '.')
			return (-1);

		s++;
	}
	else
	{
		do
		{
			if (*s < '0' || *s > '9')
				return (-1);

			i = i * 10 + 10 * (*s - '0');
			if (i > 1000)
				return (-1);

			s++;
		}
		while (*s != '.' && *s != '%');
	}

	if (*s == '.')
	{
		if (s[1] < '0' || s[1] > '9' || s[2] != '%')
			return (-1);

		i += s[1] - '0';
	}

	if (i > 1000)
		return (-1);

	*ss = s;

	return (i);
}

s9xcommand_t S9xGetCommandT (const char *name)
{
	s9xcommand_t	cmd;
	int				i, j;
	const char		*s;

	memset(&cmd, 0, sizeof(cmd));
	cmd.type         = S9xBadMapping;
	cmd.multi_press  = 0;
	cmd.button_norpt = 0;

	if (!strcmp(name, "None"))
		cmd.type = S9xNoMapping;
	else
	if (!strncmp(name, "Joypad", 6))
	{
		if (name[6] < '1' || name[6] > '8' || name[7] != ' ')
			return (cmd);

		if (!strncmp(name + 8, "Axis ", 5))
		{
			cmd.axis.joypad.idx = name[6] - '1';
			s = name + 13;

			if (!strncmp(s, "Left/Right ", 11))	{ j = 0; i = 0; s += 11; }
			else
			if (!strncmp(s, "Right/Left ", 11))	{ j = 0; i = 1; s += 11; }
			else
			if (!strncmp(s, "Up/Down ",     8))	{ j = 1; i = 0; s +=  8; }
			else
			if (!strncmp(s, "Down/Up ",     8))	{ j = 1; i = 1; s +=  8; }
			else
			if (!strncmp(s, "Y/A ",         4))	{ j = 2; i = 0; s +=  4; }
			else
			if (!strncmp(s, "A/Y ",         4))	{ j = 2; i = 1; s +=  4; }
			else
			if (!strncmp(s, "X/B ",         4))	{ j = 3; i = 0; s +=  4; }
			else
			if (!strncmp(s, "B/X ",         4))	{ j = 3; i = 1; s +=  4; }
			else
			if (!strncmp(s, "L/R ",         4))	{ j = 4; i = 0; s +=  4; }
			else
			if (!strncmp(s, "R/L ",         4))	{ j = 4; i = 1; s +=  4; }
			else
				return (cmd);

			cmd.axis.joypad.axis      = j;
			cmd.axis.joypad.invert    = i;
			i = get_threshold(&s);
			if (i < 0)
				return (cmd);
			cmd.axis.joypad.threshold = (i - 1) * 256 / 1000;

			cmd.type = S9xAxisJoypad;
		}
		else
		{
			cmd.button.joypad.idx = name[6] - '1';
			s = name + 8;
			i = 0;

			if ((cmd.button.joypad.toggle = strncmp(s, "Toggle", 6) ? 0 : 1))	s += i = 6;
			if ((cmd.button.joypad.sticky = strncmp(s, "Sticky", 6) ? 0 : 1))	s += i = 6;
			if ((cmd.button.joypad.turbo  = strncmp(s, "Turbo",  5) ? 0 : 1))	s += i = 5;

			if (cmd.button.joypad.toggle && !(cmd.button.joypad.sticky || cmd.button.joypad.turbo))
				return (cmd);

			if (i)
			{
				if (*s != ' ')
					return (cmd);
				s++;
			}

			i = 0;

			if (!strncmp(s, "Up",     2))	{ i |= SNES_UP_MASK;     s += 2; if (*s == '+') s++; }
			if (!strncmp(s, "Down",   4))	{ i |= SNES_DOWN_MASK;   s += 4; if (*s == '+') s++; }
			if (!strncmp(s, "Left",   4))	{ i |= SNES_LEFT_MASK;   s += 4; if (*s == '+') s++; }
			if (!strncmp(s, "Right",  5))	{ i |= SNES_RIGHT_MASK;  s += 5; if (*s == '+') s++; }

			if (*s == 'A')	{ i |= SNES_A_MASK;  s++; if (*s == '+') s++; }
			if (*s == 'B')	{ i |= SNES_B_MASK;  s++; if (*s == '+') s++; }
			if (*s == 'X')	{ i |= SNES_X_MASK;  s++; if (*s == '+') s++; }
			if (*s == 'Y')	{ i |= SNES_Y_MASK;  s++; if (*s == '+') s++; }
			if (*s == 'L')	{ i |= SNES_TL_MASK; s++; if (*s == '+') s++; }
			if (*s == 'R')	{ i |= SNES_TR_MASK; s++; if (*s == '+') s++; }

			if (!strncmp(s, "Start",  5))	{ i |= SNES_START_MASK;  s += 5; if (*s == '+') s++; }
			if (!strncmp(s, "Select", 6))	{ i |= SNES_SELECT_MASK; s += 6; }

			if (i == 0 || *s != 0 || *(s - 1) == '+')
				return (cmd);

			cmd.button.joypad.buttons = i;

			cmd.type = S9xButtonJoypad;
		}
	}
	else
	if (!strncmp(name, "Mouse", 5))
	{
		if (name[5] < '1' || name[5] > '2' || name[6] != ' ')
			return (cmd);

		cmd.button.mouse.idx = name[5] - '1';
		s = name + 7;
		i = 0;

		if ((cmd.button.mouse.left  = (*s == 'L')))	s += i = 1;
		if ((cmd.button.mouse.right = (*s == 'R')))	s += i = 1;

		if (i == 0 || *s != 0)
			return (cmd);

		cmd.type = S9xButtonMouse;
	}
	else
	if (!strncmp(name, "Superscope ", 11))
	{
		s = name + 11;
		i = 0;

		if ((cmd.button.scope.aim_offscreen     = strncmp(s, "AimOffscreen", 12) ? 0 : 1))	{ s += i = 12; if (*s == ' ') s++; else if (*s != 0) return (cmd); }
		if ((cmd.button.scope.fire              = strncmp(s, "Fire",          4) ? 0 : 1))	{ s += i =  4; if (*s == '+') s++; }
		if ((cmd.button.scope.cursor            = strncmp(s, "Cursor",        6) ? 0 : 1))	{ s += i =  6; if (*s == '+') s++; }
		if ((cmd.button.scope.turbo             = strncmp(s, "ToggleTurbo",  11) ? 0 : 1))	{ s += i = 11; if (*s == '+') s++; }
		if ((cmd.button.scope.pause             = strncmp(s, "Pause",         5) ? 0 : 1))	{ s += i =  5; }

		if (i == 0 || *s != 0 || *(s - 1) == '+')
			return (cmd);

		cmd.type = S9xButtonSuperscope;
	}
	else
	if (!strncmp(name, "Justifier", 9))
	{
		if (name[9] < '1' || name[9] > '2' || name[10] != ' ')
			return (cmd);

		cmd.button.justifier.idx = name[9] - '1';
		s = name + 11;
		i = 0;

		if ((cmd.button.justifier.aim_offscreen = strncmp(s, "AimOffscreen", 12) ? 0 : 1))	{ s += i = 12; if (*s == ' ') s++; else if (*s != 0) return (cmd); }
		if ((cmd.button.justifier.trigger       = strncmp(s, "Trigger",       7) ? 0 : 1))	{ s += i =  7; if (*s == '+') s++; }
		if ((cmd.button.justifier.start         = strncmp(s, "Start",         5) ? 0 : 1))	{ s += i =  5; }

		if (i == 0 || *s != 0 || *(s - 1) == '+')
			return (cmd);

		cmd.type = S9xButtonJustifier;
	}
	else
	if (!strncmp(name, "Pointer ", 8))
	{
		s = name + 8;
		i = 0;

		if ((cmd.pointer.aim_mouse0     = strncmp(s, "Mouse1",      6) ? 0 : 1))	{ s += i =  6; if (*s == '+') s++; }
		if ((cmd.pointer.aim_mouse1     = strncmp(s, "Mouse2",      6) ? 0 : 1))	{ s += i =  6; if (*s == '+') s++; }
		if ((cmd.pointer.aim_scope      = strncmp(s, "Superscope", 10) ? 0 : 1))	{ s += i = 10; if (*s == '+') s++; }
		if ((cmd.pointer.aim_justifier0 = strncmp(s, "Justifier1", 10) ? 0 : 1))	{ s += i = 10; if (*s == '+') s++; }
		if ((cmd.pointer.aim_justifier1 = strncmp(s, "Justifier2", 10) ? 0 : 1))	{ s += i = 10; }

		if (i == 0 || *s != 0 || *(s - 1) == '+')
			return (cmd);

		cmd.type = S9xPointer;
	}
	else
	if (!strncmp(name, "ButtonToPointer ", 16))
	{
		if (name[16] < '1' || name[16] > '8')
			return (cmd);

		cmd.button.pointer.idx = name[16] - '1';
		s = name + 17;
		i = 0;

		if ((cmd.button.pointer.UD = (*s == 'u' ? -1 : (*s == 'd' ? 1 : 0))))	s += i = 1;
		if ((cmd.button.pointer.LR = (*s == 'l' ? -1 : (*s == 'r' ? 1 : 0))))	s += i = 1;

		if (i == 0 || *(s++) != ' ')
			return (cmd);

		for (i = 0; i < 4; i++)
			if (!strcmp(s, speed_names[i]))
				break;
		if (i > 3)
			return (cmd);

		cmd.button.pointer.speed_type = i;

		cmd.type = S9xButtonPseudopointer;
	}
	else
	if (!strncmp(name, "AxisToPointer ", 14))
	{
		if (name[14] < '1' || name[14] > '8')
			return (cmd);

		cmd.axis.pointer.idx = name[14] - '1';
		s= name + 15;
		i = 0;

		if (*s == 'h')
			cmd.axis.pointer.HV = 0;
		else
		if (*s == 'v')
			cmd.axis.pointer.HV = 1;
		else
			return (cmd);

		if (s[1] != ' ')
			return (cmd);

		s += 2;
		if ((cmd.axis.pointer.invert = *s == '-'))
			s++;

		for (i = 0; i < 4; i++)
			if (!strcmp(s, speed_names[i]))
				break;
		if (i > 3)
			return (cmd);

		cmd.axis.pointer.speed_type = i;

		cmd.type = S9xAxisPseudopointer;
	}
	else
	if (!strncmp(name, "AxisToButtons ", 14))
	{
		s = name + 14;

		if (s[0] == '0')
		{
			if (s[1] != '/')
				return (cmd);

			cmd.axis.button.negbutton = 0;
			s += 2;
		}
		else
		{
			i = 0;
			do
			{
				if (*s < '0' || *s > '9')
					return (cmd);

				i = i * 10 + *s - '0';
				if (i > 255)
					return (cmd);
			}
			while (*++s != '/');

			cmd.axis.button.negbutton = i;
			s++;
		}

		if (s[0] == '0')
		{
			if (s[1] != ' ')
				return (cmd);

			cmd.axis.button.posbutton = 0;
			s += 2;
		}
		else
		{
			i = 0;
			do
			{
				if (*s < '0' || *s > '9')
					return (cmd);

				i = i * 10 + *s - '0';
				if (i > 255)
					return (cmd);
			}
			while (*++s != ' ');

			cmd.axis.button.posbutton = i;
			s++;
		}

		i = get_threshold(&s);
		if (i < 0)
			return (cmd);
		cmd.axis.button.threshold = (i - 1) * 256 / 1000;

		cmd.type = S9xAxisPseudobuttons;
	}
	else
	if (!strncmp(name, "MULTI#", 6))
	{
		i = strtol(name + 6, (char **) &s, 10);
		if (s != NULL && *s != '\0')
			return (cmd);
		if (i >= (int) multis.size())
			return (cmd);

		cmd.button.multi_idx = i;
		cmd.type = S9xButtonMulti;
	}
	else
	if (((name[0] == '+' && name[1] == '{') || name[0] == '{') && name[strlen(name) - 1] == '}')
	{
		if (multis.size() > 2147483640)
		{
			fprintf(stderr, "Too many multis!");
			return (cmd);
		}

		string	x;
		int		n;

		j = 2;
		for (i = (name[0] == '+') ? 2 : 1; name[i] != '\0'; i++)
		{
			if (name[i] == ',' || name[i] == ';')
			{
				if (name[i] == ';')
					j++;
				if (++j > 2147483640)
				{
					fprintf(stderr, "Multi too long!");
					return (cmd);
				}
			}

			if (name[i] == '{')
				return (cmd);
		}

		s9xcommand_t	*c = (s9xcommand_t *) calloc(j, sizeof(s9xcommand_t));
		if (c == NULL)
		{
			perror("malloc error while parsing multi");
			return (cmd);
		}

		n = 0;
		i = (name[0] == '+') ? 2 : 1;

		do
		{
			if (name[i] == ';')
			{
				c[n].type         = S9xNoMapping;
				c[n].multi_press  = 0;
				c[n].button_norpt = 0;

				j = i;
			}
			else
			if (name[i] == ',')
			{
				free(c);
				return (cmd);
			}
			else
			{
				uint8	press = 0;

				if (name[0] == '+')
				{
					if (name[i] == '+')
						press = 1;
					else
					if (name[i] == '-')
						press = 2;
					else
					{
						free(c);
						return (cmd);
					}

					i++;
				}

				for (j = i; name[j] != ';' && name[j] != ',' && name[j] != '}'; j++) ;

				x.assign(name + i, j - i);
				c[n] = S9xGetCommandT(x.c_str());
				c[n].multi_press = press;

				if (maptype(c[n].type) != MAP_BUTTON)
				{
					free(c);
					return (cmd);
				}

				if (name[j] == ';')
					j--;
			}

			i = j + 1;
			n++;
		}
		while (name[i] != '\0');

		c[n].type        = S9xNoMapping;
		c[n].multi_press = 3;

		multis.push_back(c);

		cmd.button.multi_idx = multis.size() - 1;
		cmd.type = S9xButtonMulti;
	}
	else
	{
		i = findstr(name, command_names, LAST_COMMAND);
		if (i < 0)
			return (cmd);

		cmd.type = S9xButtonCommand;
		cmd.button.command = i;
	}

	return (cmd);
}

const char ** S9xGetAllSnes9xCommands (void)
{
	return (command_names);
}

s9xcommand_t S9xGetMapping (uint32 id)
{
	if (keymap.count(id) == 0)
	{
		s9xcommand_t	cmd;
		cmd.type = S9xNoMapping;
		return (cmd);
	}
	else
		return (keymap[id]);
}

static const char * maptypename (int t)
{
	switch (t)
	{
		case MAP_NONE:		return ("unmapped");
		case MAP_BUTTON:	return ("button");
		case MAP_AXIS:		return ("axis");
		case MAP_POINTER:	return ("pointer");
		default:			return ("unknown");
	}
}

void S9xUnmapID (uint32 id)
{
	for (int i = 0; i < NUMCTLS + 1; i++)
		pollmap[i].erase(id);

	if (mouse[0].ID     == id)	mouse[0].ID     = InvalidControlID;
	if (mouse[1].ID     == id)	mouse[1].ID     = InvalidControlID;
	if (superscope.ID   == id)	superscope.ID   = InvalidControlID;
	if (justifier.ID[0] == id)	justifier.ID[0] = InvalidControlID;
	if (justifier.ID[1] == id)	justifier.ID[1] = InvalidControlID;

	if (id >= PseudoPointerBase)
		pseudopointer[id - PseudoPointerBase].mapped = false;

	keymap.erase(id);
}

bool S9xMapButton (uint32 id, s9xcommand_t mapping, bool poll)
{
	int	t;

	if (id == InvalidControlID)
	{
		fprintf(stderr, "Cannot map InvalidControlID\n");
		return (false);
	}

	t = maptype(mapping.type);

	if (t == MAP_NONE)
	{
		S9xUnmapID(id);
		return (true);
	}

	if (t != MAP_BUTTON)
		return (false);

	t = maptype(S9xGetMapping(id).type);

	if (t != MAP_NONE && t != MAP_BUTTON)
		fprintf(stderr, "WARNING: Remapping ID 0x%08x from %s to button\n", id, maptypename(t));

	if (id >= PseudoPointerBase)
	{
		fprintf(stderr, "ERROR: Refusing to map pseudo-pointer #%d as a button\n", id - PseudoPointerBase);
		return (false);
	}

	t = -1;

	if (poll)
	{
		if (id >= PseudoButtonBase)
			fprintf(stderr, "INFO: Ignoring attempt to set pseudo-button #%d to polling\n", id - PseudoButtonBase);
		else
		{
			switch (mapping.type)
			{
				case S9xButtonJoypad:
					t = JOYPAD0 + mapping.button.joypad.idx;
					break;

				case S9xButtonMouse:
					t = MOUSE0 + mapping.button.mouse.idx;
					break;

				case S9xButtonSuperscope:
					t = SUPERSCOPE;
					break;

				case S9xButtonJustifier:
					t = ONE_JUSTIFIER + mapping.button.justifier.idx;
					break;

				case S9xButtonCommand:
				case S9xButtonPseudopointer:
				case S9xButtonPort:
				case S9xButtonMulti:
					t = POLL_ALL;
					break;
			}
		}
	}

	S9xUnmapID(id);

	keymap[id] = mapping;

	if (t >= 0)
		pollmap[t].insert(id);

	return (true);
}

void S9xReportButton (uint32 id, bool pressed)
{
	if (keymap.count(id) == 0)
		return;

	if (keymap[id].type == S9xNoMapping)
		return;

	if (maptype(keymap[id].type) != MAP_BUTTON)
	{
		fprintf(stderr, "ERROR: S9xReportButton called on %s ID 0x%08x\n", maptypename(maptype(keymap[id].type)), id);
		return;
	}

	if (keymap[id].type == S9xButtonCommand)	// skips the "already-pressed check" unless it's a command, as a hack to work around the following problem:
		if (keymap[id].button_norpt == pressed)	// FIXME: this makes the controls "stick" after loading a savestate while recording a movie and holding any button
			return;

	keymap[id].button_norpt = pressed;

	S9xApplyCommand(keymap[id], pressed, 0);
}

bool S9xMapPointer (uint32 id, s9xcommand_t mapping, bool poll)
{
	int	t;

	if (id == InvalidControlID)
	{
		fprintf(stderr, "Cannot map InvalidControlID\n");
		return (false);
	}

	t = maptype(mapping.type);

	if (t == MAP_NONE)
	{
		S9xUnmapID(id);
		return (true);
	}

	if (t != MAP_POINTER)
		return (false);

	t = maptype(S9xGetMapping(id).type);

	if (t != MAP_NONE && t != MAP_POINTER)
		fprintf(stderr, "WARNING: Remapping ID 0x%08x from %s to pointer\n", id, maptypename(t));

	if (id < PseudoPointerBase && id >= PseudoButtonBase)
	{
		fprintf(stderr, "ERROR: Refusing to map pseudo-button #%d as a pointer\n", id - PseudoButtonBase);
		return (false);
	}

	if (mapping.type == S9xPointer)
	{
		if (mapping.pointer.aim_mouse0 && mouse[0].ID != InvalidControlID && mouse[0].ID != id)
		{
			fprintf(stderr, "ERROR: Rejecting attempt to control Mouse1 with two pointers\n");
			return (false);
		}

		if (mapping.pointer.aim_mouse1 && mouse[1].ID != InvalidControlID && mouse[1].ID != id)
		{
			fprintf(stderr, "ERROR: Rejecting attempt to control Mouse2 with two pointers\n");
			return (false);
		}

		if (mapping.pointer.aim_scope && superscope.ID != InvalidControlID && superscope.ID != id)
		{
			fprintf(stderr, "ERROR: Rejecting attempt to control SuperScope with two pointers\n");
			return (false);
		}

		if (mapping.pointer.aim_justifier0 && justifier.ID[0] != InvalidControlID && justifier.ID[0] != id)
		{
			fprintf(stderr, "ERROR: Rejecting attempt to control Justifier1 with two pointers\n");
			return (false);
		}

		if (mapping.pointer.aim_justifier1 && justifier.ID[1] != InvalidControlID && justifier.ID[1] != id)
		{
			fprintf(stderr, "ERROR: Rejecting attempt to control Justifier2 with two pointers\n");
			return (false);
		}
	}

	S9xUnmapID(id);

	if (poll)
	{
		if (id >= PseudoPointerBase)
			fprintf(stderr, "INFO: Ignoring attempt to set pseudo-pointer #%d to polling\n", id - PseudoPointerBase);
		else
		{
			switch (mapping.type)
			{
				case S9xPointer:
					if (mapping.pointer.aim_mouse0    )	pollmap[MOUSE0        ].insert(id);
					if (mapping.pointer.aim_mouse1    )	pollmap[MOUSE1        ].insert(id);
					if (mapping.pointer.aim_scope     )	pollmap[SUPERSCOPE    ].insert(id);
					if (mapping.pointer.aim_justifier0)	pollmap[ONE_JUSTIFIER ].insert(id);
					if (mapping.pointer.aim_justifier1)	pollmap[TWO_JUSTIFIERS].insert(id);
					break;

				case S9xPointerPort:
					pollmap[POLL_ALL].insert(id);
					break;
			}
		}
	}

	if (id >= PseudoPointerBase)
		pseudopointer[id - PseudoPointerBase].mapped = true;

	keymap[id] = mapping;

	if (mapping.pointer.aim_mouse0    )	mouse[0].ID     = id;
	if (mapping.pointer.aim_mouse1    )	mouse[1].ID     = id;
	if (mapping.pointer.aim_scope     )	superscope.ID   = id;
	if (mapping.pointer.aim_justifier0)	justifier.ID[0] = id;
	if (mapping.pointer.aim_justifier1)	justifier.ID[1] = id;

	return (true);
}

void S9xReportPointer (uint32 id, int16 x, int16 y)
{
	if (keymap.count(id) == 0)
		return;

	if (keymap[id].type == S9xNoMapping)
		return;

	if (maptype(keymap[id].type) != MAP_POINTER)
	{
		fprintf(stderr, "ERROR: S9xReportPointer called on %s ID 0x%08x\n", maptypename(maptype(keymap[id].type)), id);
		return;
	}

	S9xApplyCommand(keymap[id], x, y);
}

bool S9xMapAxis (uint32 id, s9xcommand_t mapping, bool poll)
{
	int	t;

	if (id == InvalidControlID)
	{
		fprintf(stderr, "Cannot map InvalidControlID\n");
		return (false);
	}

	t = maptype(mapping.type);

	if (t == MAP_NONE)
	{
		S9xUnmapID(id);
		return (true);
	}

	if (t != MAP_AXIS)
		return (false);

	t = maptype(S9xGetMapping(id).type);

	if (t != MAP_NONE && t != MAP_AXIS)
		fprintf(stderr, "WARNING: Remapping ID 0x%08x from %s to axis\n", id, maptypename(t));

	if (id >= PseudoPointerBase)
	{
		fprintf(stderr, "ERROR: Refusing to map pseudo-pointer #%d as an axis\n", id - PseudoPointerBase);
		return (false);
	}

	t = -1;

	if (poll)
	{
		switch (mapping.type)
		{
			case S9xAxisJoypad:
				t = JOYPAD0 + mapping.axis.joypad.idx;
				break;

			case S9xAxisPseudopointer:
			case S9xAxisPseudobuttons:
			case S9xAxisPort:
				t=POLL_ALL;
				break;
		}
	}

	S9xUnmapID(id);

	keymap[id] = mapping;

	if (t >= 0)
		pollmap[t].insert(id);

	return (true);
}

void S9xReportAxis (uint32 id, int16 value)
{
	if (keymap.count(id) == 0)
		return;

	if (keymap[id].type == S9xNoMapping)
		return;

	if (maptype(keymap[id].type) != MAP_AXIS)
	{
		fprintf(stderr, "ERROR: S9xReportAxis called on %s ID 0x%08x\n", maptypename(maptype(keymap[id].type)), id);
		return;
	}

	S9xApplyCommand(keymap[id], value, 0);
}

static int32 ApplyMulti (s9xcommand_t *multi, int32 pos, int16 data1)
{
	while (1)
	{
		if (multi[pos].multi_press == 3)
			return (-1);

		if (multi[pos].type == S9xNoMapping)
			break;

		if (multi[pos].multi_press)
			S9xApplyCommand(multi[pos], multi[pos].multi_press == 1, 0);
		else
			S9xApplyCommand(multi[pos], data1, 0);

		pos++;
	}

	return (pos + 1);
}

void S9xApplyCommand (s9xcommand_t cmd, int16 data1, int16 data2)
{
	int	i;

	switch (cmd.type)
	{
		case S9xNoMapping:
			return;

		case S9xButtonJoypad:
			if (cmd.button.joypad.toggle)
			{
				if (!data1)
					return;

				uint16	r = cmd.button.joypad.buttons;

				if (cmd.button.joypad.turbo)	joypad[cmd.button.joypad.idx].toggleturbo ^= r;
				if (cmd.button.joypad.sticky)	joypad[cmd.button.joypad.idx].togglestick ^= r;
			}
			else
			{
				uint16	r, s, t, st;

				r = cmd.button.joypad.buttons;
				st = r & joypad[cmd.button.joypad.idx].togglestick & joypad[cmd.button.joypad.idx].toggleturbo;
				r ^= st;
				t  = r & joypad[cmd.button.joypad.idx].toggleturbo;
				r ^= t;
				s  = r & joypad[cmd.button.joypad.idx].togglestick;
				r ^= s;

				if (cmd.button.joypad.turbo && cmd.button.joypad.sticky)
				{
					uint16	x = r; r = st; st = x;
					x = s; s = t; t = x;
				}
				else
				if (cmd.button.joypad.turbo)
				{
					uint16	x = r; r = t; t = x;
					x = s; s = st; st = x;
				}
				else
				if (cmd.button.joypad.sticky)
				{
					uint16	x = r; r = s; s = x;
					x = t; t = st; st = x;
				}

				if (data1)
				{
					if (!Settings.UpAndDown && !S9xMoviePlaying()) // if up+down isn't allowed AND we are NOT playing a movie,
					{
						if (cmd.button.joypad.buttons & (SNES_LEFT_MASK | SNES_RIGHT_MASK))
						{
							// if we're pressing left or right, then unpress and unturbo them both first
							// so we don't end up hittnig left AND right accidentally.
							// Note though that the user can still do it on purpose, if Settings.UpAndDown = true.
							// This is a feature, look up glitches in tLoZ:aLttP to find out why.
							joypad[cmd.button.joypad.idx].buttons &= ~(SNES_LEFT_MASK | SNES_RIGHT_MASK);
							joypad[cmd.button.joypad.idx].turbos  &= ~(SNES_LEFT_MASK | SNES_RIGHT_MASK);
						}

						if (cmd.button.joypad.buttons & (SNES_UP_MASK | SNES_DOWN_MASK))
						{
							// and ditto for up/down
							joypad[cmd.button.joypad.idx].buttons &= ~(SNES_UP_MASK | SNES_DOWN_MASK);
							joypad[cmd.button.joypad.idx].turbos  &= ~(SNES_UP_MASK | SNES_DOWN_MASK);
						}
					}

					joypad[cmd.button.joypad.idx].buttons |= r;
					joypad[cmd.button.joypad.idx].turbos  |= t;
					joypad[cmd.button.joypad.idx].buttons ^= s;
					joypad[cmd.button.joypad.idx].buttons &= ~(joypad[cmd.button.joypad.idx].turbos & st);
					joypad[cmd.button.joypad.idx].turbos  ^= st;
				}
				else
				{
					joypad[cmd.button.joypad.idx].buttons &= ~r;
					joypad[cmd.button.joypad.idx].buttons &= ~(joypad[cmd.button.joypad.idx].turbos & t);
					joypad[cmd.button.joypad.idx].turbos  &= ~t;
				}
			}

			return;

		case S9xButtonMouse:
			i = 0;
			if (cmd.button.mouse.left )	i |= 0x40;
			if (cmd.button.mouse.right)	i |= 0x80;

			if (data1)
				mouse[cmd.button.mouse.idx].buttons |=  i;
			else
				mouse[cmd.button.mouse.idx].buttons &= ~i;

			return;

		case S9xButtonSuperscope:
			i = 0;
			if (cmd.button.scope.fire         )	i |= SUPERSCOPE_FIRE;
			if (cmd.button.scope.cursor       )	i |= SUPERSCOPE_CURSOR;
			if (cmd.button.scope.pause        )	i |= SUPERSCOPE_PAUSE;
			if (cmd.button.scope.aim_offscreen)	i |= SUPERSCOPE_OFFSCREEN;

			if (data1)
			{
				superscope.phys_buttons |= i;

				if (cmd.button.scope.turbo)
				{
					superscope.phys_buttons ^= SUPERSCOPE_TURBO;

					if (superscope.phys_buttons & SUPERSCOPE_TURBO)
						superscope.next_buttons |= superscope.phys_buttons & (SUPERSCOPE_FIRE | SUPERSCOPE_CURSOR);
					else
						superscope.next_buttons &= ~(SUPERSCOPE_FIRE | SUPERSCOPE_CURSOR);
				}

				superscope.next_buttons |= i & (SUPERSCOPE_FIRE | SUPERSCOPE_CURSOR | SUPERSCOPE_PAUSE);

				if (!S9xMovieActive()) // PPU modification during non-recordable command screws up movie synchronization
					if ((superscope.next_buttons & (SUPERSCOPE_FIRE | SUPERSCOPE_CURSOR)) && curcontrollers[1] == SUPERSCOPE && !(superscope.phys_buttons & SUPERSCOPE_OFFSCREEN))
						DoGunLatch(superscope.x, superscope.y);
			}
			else
			{
				superscope.phys_buttons &= ~i;
				superscope.next_buttons &= SUPERSCOPE_OFFSCREEN | ~i;
			}

			return;

		case S9xButtonJustifier:
			i = 0;
			if (cmd.button.justifier.trigger)	i |= JUSTIFIER_TRIGGER;
			if (cmd.button.justifier.start  )	i |= JUSTIFIER_START;
			if (cmd.button.justifier.aim_offscreen)	justifier.offscreen[cmd.button.justifier.idx] = data1 ? 1 : 0;
			i >>= cmd.button.justifier.idx;

			if (data1)
				justifier.buttons |=  i;
			else
				justifier.buttons &= ~i;

			return;

		case S9xButtonCommand:
			if (((enum command_numbers) cmd.button.command) >= LAST_COMMAND)
			{
				fprintf(stderr, "Unknown command %04x\n", cmd.button.command);
				return;
			}

			if (!data1)
			{
				switch (i = cmd.button.command)
				{
					case EmuTurbo:
						Settings.TurboMode = FALSE;
						break;
				}
			}
			else
			{
				switch ((enum command_numbers) (i = cmd.button.command))
				{
					case ExitEmu:
						S9xExit();
						break;

					case Reset:
						S9xReset();
						break;

					case SoftReset:
						S9xMovieUpdateOnReset();
						if (S9xMoviePlaying())
							S9xMovieStop(TRUE);
						S9xSoftReset();
						break;

					case EmuTurbo:
						Settings.TurboMode = TRUE;
						break;

					case ToggleEmuTurbo:
						Settings.TurboMode = !Settings.TurboMode;
						DisplayStateChange("Turbo mode", Settings.TurboMode);
						break;

					case ClipWindows:
						Settings.DisableGraphicWindows = !Settings.DisableGraphicWindows;
						DisplayStateChange("Graphic clip windows", !Settings.DisableGraphicWindows);
						break;

					case Debugger:
					#ifdef DEBUGGER
						CPU.Flags |= DEBUG_MODE_FLAG;
					#endif
						break;

					case IncFrameRate:
						if (Settings.SkipFrames == AUTO_FRAMERATE)
							Settings.SkipFrames = 1;
						else
						if (Settings.SkipFrames < 10)
							Settings.SkipFrames++;

						if (Settings.SkipFrames == AUTO_FRAMERATE)
							S9xSetInfoString("Auto frame skip");
						else
						{
							sprintf(buf, "Frame skip: %d", Settings.SkipFrames - 1);
							S9xSetInfoString(buf);
						}

						break;

					case DecFrameRate:
						if (Settings.SkipFrames <= 1)
							Settings.SkipFrames = AUTO_FRAMERATE;
						else
						if (Settings.SkipFrames != AUTO_FRAMERATE)
							Settings.SkipFrames--;

						if (Settings.SkipFrames == AUTO_FRAMERATE)
							S9xSetInfoString("Auto frame skip");
						else
						{
							sprintf(buf, "Frame skip: %d", Settings.SkipFrames - 1);
							S9xSetInfoString(buf);
						}

						break;

					case IncEmuTurbo:
						if (Settings.TurboSkipFrames < 20)
							Settings.TurboSkipFrames += 1;
						else
						if (Settings.TurboSkipFrames < 200)
							Settings.TurboSkipFrames += 5;
						sprintf(buf, "Turbo frame skip: %d", Settings.TurboSkipFrames);
						S9xSetInfoString(buf);
						break;

					case DecEmuTurbo:
						if (Settings.TurboSkipFrames > 20)
							Settings.TurboSkipFrames -= 5;
						else
						if (Settings.TurboSkipFrames > 0)
							Settings.TurboSkipFrames -= 1;
						sprintf(buf, "Turbo frame skip: %d", Settings.TurboSkipFrames);
						S9xSetInfoString(buf);
						break;

					case IncFrameTime: // Increase emulated frame time by 1ms
						Settings.FrameTime += 1000;
						sprintf(buf, "Emulated frame time: %dms", Settings.FrameTime / 1000);
						S9xSetInfoString(buf);
						break;

					case DecFrameTime: // Decrease emulated frame time by 1ms
						if (Settings.FrameTime >= 1000)
							Settings.FrameTime -= 1000;
						sprintf(buf, "Emulated frame time: %dms", Settings.FrameTime / 1000);
						S9xSetInfoString(buf);
						break;

					case IncTurboSpeed:
						if (turbo_time >= 120)
							break;
						turbo_time++;
						sprintf(buf, "Turbo speed: %d", turbo_time);
						S9xSetInfoString(buf);
						break;

					case DecTurboSpeed:
						if (turbo_time <= 1)
							break;
						turbo_time--;
						sprintf(buf, "Turbo speed: %d", turbo_time);
						S9xSetInfoString(buf);
						break;

					case LoadFreezeFile:
						S9xUnfreezeGame(S9xChooseFilename(TRUE));
						break;

					case SaveFreezeFile:
						S9xFreezeGame(S9xChooseFilename(FALSE));
						break;

					case LoadOopsFile:
					{
						char	filename[PATH_MAX + 1];
						char	drive[_MAX_DRIVE + 1], dir[_MAX_DIR + 1], def[_MAX_FNAME + 1], ext[_MAX_EXT + 1];

						_splitpath(Memory.ROMFilename, drive, dir, def, ext);
						snprintf(filename, PATH_MAX + 1, "%s%s%s.%.*s", S9xGetDirectory(SNAPSHOT_DIR), SLASH_STR, def, _MAX_EXT - 1, "oops");

						if (S9xUnfreezeGame(filename))
						{
							sprintf(buf, "%s.%.*s loaded", def, _MAX_EXT - 1, "oops");
							S9xSetInfoString (buf);
						}
						else
							S9xMessage(S9X_ERROR, S9X_FREEZE_FILE_NOT_FOUND, "Oops file not found");

						break;
					}

					case Pause:
						Settings.Paused = !Settings.Paused;
						DisplayStateChange("Pause", Settings.Paused);
					#if defined(NETPLAY_SUPPORT) && !defined(__WIN32__)
						S9xNPSendPause(Settings.Paused);
					#endif
						break;

					case QuickLoad000:
					case QuickLoad001:
					case QuickLoad002:
					case QuickLoad003:
					case QuickLoad004:
					case QuickLoad005:
					case QuickLoad006:
					case QuickLoad007:
					case QuickLoad008:
					case QuickLoad009:
					case QuickLoad010:
					{
						char	filename[PATH_MAX + 1];
						char	drive[_MAX_DRIVE + 1], dir[_MAX_DIR + 1], def[_MAX_FNAME + 1], ext[_MAX_EXT + 1];

						_splitpath(Memory.ROMFilename, drive, dir, def, ext);
						snprintf(filename, PATH_MAX + 1, "%s%s%s.%03d", S9xGetDirectory(SNAPSHOT_DIR), SLASH_STR, def, i - QuickLoad000);

						if (S9xUnfreezeGame(filename))
						{
							sprintf(buf, "%s.%03d loaded", def, i - QuickLoad000);
							S9xSetInfoString(buf);
						}
						else
							S9xMessage(S9X_ERROR, S9X_FREEZE_FILE_NOT_FOUND, "Freeze file not found");

						break;
					}

					case QuickSave000:
					case QuickSave001:
					case QuickSave002:
					case QuickSave003:
					case QuickSave004:
					case QuickSave005:
					case QuickSave006:
					case QuickSave007:
					case QuickSave008:
					case QuickSave009:
					case QuickSave010:
					{
						char	filename[PATH_MAX + 1];
						char	drive[_MAX_DRIVE + 1], dir[_MAX_DIR + 1], def[_MAX_FNAME + 1], ext[_MAX_EXT + 1];

						_splitpath(Memory.ROMFilename, drive, dir, def, ext);
						snprintf(filename, PATH_MAX + 1, "%s%s%s.%03d", S9xGetDirectory(SNAPSHOT_DIR), SLASH_STR, def, i - QuickSave000);

						sprintf(buf, "%s.%03d saved", def, i - QuickSave000);
						S9xSetInfoString(buf);

						S9xFreezeGame(filename);
						break;
					}

					case SaveSPC:
						S9xDumpSPCSnapshot();
						break;

					case Screenshot:
						Settings.TakeScreenshot = TRUE;
						break;

					case SoundChannel0:
					case SoundChannel1:
					case SoundChannel2:
					case SoundChannel3:
					case SoundChannel4:
					case SoundChannel5:
					case SoundChannel6:
					case SoundChannel7:
						S9xToggleSoundChannel(i - SoundChannel0);
						sprintf(buf, "Sound channel %d toggled", i - SoundChannel0);
						S9xSetInfoString(buf);
						break;

					case SoundChannelsOn:
						S9xToggleSoundChannel(8);
						S9xSetInfoString("All sound channels on");
						break;

					case ToggleBG0:
						Settings.BG_Forced ^= 1;
						DisplayStateChange("BG#0", !(Settings.BG_Forced & 1));
						break;

					case ToggleBG1:
						Settings.BG_Forced ^= 2;
						DisplayStateChange("BG#1", !(Settings.BG_Forced & 2));
						break;

					case ToggleBG2:
						Settings.BG_Forced ^= 4;
						DisplayStateChange("BG#2", !(Settings.BG_Forced & 4));
						break;

					case ToggleBG3:
						Settings.BG_Forced ^= 8;
						DisplayStateChange("BG#3", !(Settings.BG_Forced & 8));
						break;

					case ToggleSprites:
						Settings.BG_Forced ^= 16;
						DisplayStateChange("Sprites", !(Settings.BG_Forced & 16));
						break;

					case ToggleTransparency:
						Settings.Transparency = !Settings.Transparency;
						DisplayStateChange("Transparency effects", Settings.Transparency);
						break;

					case BeginRecordingMovie:
						if (S9xMovieActive())
							S9xMovieStop(FALSE);
						S9xMovieCreate(S9xChooseMovieFilename(FALSE), 0xFF, MOVIE_OPT_FROM_RESET, NULL, 0);
						break;

					case LoadMovie:
						if (S9xMovieActive())
							S9xMovieStop(FALSE);
						S9xMovieOpen(S9xChooseMovieFilename(TRUE), FALSE);
						break;

					case EndRecordingMovie:
						if (S9xMovieActive())
							S9xMovieStop(FALSE);
						break;

					case SwapJoypads:
						if ((curcontrollers[0] != NONE && !(curcontrollers[0] >= JOYPAD0 && curcontrollers[0] <= JOYPAD7)))
						{
							S9xSetInfoString("Cannot swap pads: port 1 is not a joypad");
							break;
						}

						if ((curcontrollers[1] != NONE && !(curcontrollers[1] >= JOYPAD0 && curcontrollers[1] <= JOYPAD7)))
						{
							S9xSetInfoString("Cannot swap pads: port 2 is not a joypad");
							break;
						}

						newcontrollers[1] = curcontrollers[0];
						newcontrollers[0] = curcontrollers[1];

						strcpy(buf, "Swap pads: P1=");
						i = 14;
						if (newcontrollers[0] == NONE)
						{
							strcpy(buf + i, "<none>");
							i += 6;
						}
						else
						{
							sprintf(buf + i, "Joypad%d", newcontrollers[0] - JOYPAD0 + 1);
							i += 7;
						}

						strcpy(buf + i, " P2=");
						i += 4;
						if (newcontrollers[1] == NONE)
							strcpy(buf + i, "<none>");
						else
							sprintf(buf + i, "Joypad%d", newcontrollers[1] - JOYPAD0 + 1);

						S9xSetInfoString(buf);
						break;

					case SeekToFrame:
						if (S9xMovieActive())
						{
							sprintf(buf, "Select frame number (current: %d)", S9xMovieGetFrameCounter());
							const char	*frameno = S9xStringInput(buf);
							if (!frameno)
								return;

							int	frameDest = atoi(frameno);
							if (frameDest > 0 && frameDest > (int) S9xMovieGetFrameCounter())
							{
								int	distance = frameDest - S9xMovieGetFrameCounter();
								Settings.HighSpeedSeek = distance;
							}
						}

						break;

					case LAST_COMMAND:
						break;
				}
			}

			return;

		case S9xPointer:
			if (cmd.pointer.aim_mouse0)
			{
				mouse[0].cur_x = data1;
				mouse[0].cur_y = data2;
			}

			if (cmd.pointer.aim_mouse1)
			{
				mouse[1].cur_x = data1;
				mouse[1].cur_y = data2;
			}

			if (cmd.pointer.aim_scope)
			{
				superscope.x   = data1;
				superscope.y   = data2;
			}

			if (cmd.pointer.aim_justifier0)
			{
				justifier.x[0] = data1;
				justifier.y[0] = data2;
			}

			if (cmd.pointer.aim_justifier1)
			{
				justifier.x[1] = data1;
				justifier.y[1] = data2;
			}

			return;

		case S9xButtonPseudopointer:
			if (data1)
			{
				if (cmd.button.pointer.UD)
				{
					if (!pseudopointer[cmd.button.pointer.idx].V_adj)
						pseudopointer[cmd.button.pointer.idx].V_adj = cmd.button.pointer.UD * ptrspeeds[cmd.button.pointer.speed_type];
					pseudopointer[cmd.button.pointer.idx].V_var = (cmd.button.pointer.speed_type == 0);
				}

				if (cmd.button.pointer.LR)
				{
					if (!pseudopointer[cmd.button.pointer.idx].H_adj)
						pseudopointer[cmd.button.pointer.idx].H_adj = cmd.button.pointer.LR * ptrspeeds[cmd.button.pointer.speed_type];
					pseudopointer[cmd.button.pointer.idx].H_var = (cmd.button.pointer.speed_type == 0);
				}
			}
			else
			{
				if (cmd.button.pointer.UD)
				{
					pseudopointer[cmd.button.pointer.idx].V_adj = 0;
					pseudopointer[cmd.button.pointer.idx].V_var = false;
				}

				if (cmd.button.pointer.LR)
				{
					pseudopointer[cmd.button.pointer.idx].H_adj = 0;
					pseudopointer[cmd.button.pointer.idx].H_var = false;
				}
			}

			return;

		case S9xAxisJoypad:
		{
			uint16	pos, neg;

			switch (cmd.axis.joypad.axis)
			{
				case 0: neg = SNES_LEFT_MASK;	pos = SNES_RIGHT_MASK;	break;
				case 1: neg = SNES_UP_MASK;		pos = SNES_DOWN_MASK;	break;
				case 2: neg = SNES_Y_MASK;		pos = SNES_A_MASK;		break;
				case 3: neg = SNES_X_MASK;		pos = SNES_B_MASK;		break;
				case 4: neg = SNES_TL_MASK;		pos = SNES_TR_MASK;		break;
				default: return;
			}

			if (cmd.axis.joypad.invert)
				data1 = -data1;

			uint16	p, r;

			p = r = 0;
			if (data1 >  ((cmd.axis.joypad.threshold + 1) *  127))
				p |= pos;
			else
				r |= pos;

			if (data1 <= ((cmd.axis.joypad.threshold + 1) * -127))
				p |= neg;
			else
				r |= neg;

			joypad[cmd.axis.joypad.idx].buttons |= p;
			joypad[cmd.axis.joypad.idx].buttons &= ~r;
			joypad[cmd.axis.joypad.idx].turbos  &= ~(p | r);

			return;
		}

		case S9xAxisPseudopointer:
			if (data1 == 0)
			{
				if (cmd.axis.pointer.HV)
				{
					pseudopointer[cmd.axis.pointer.idx].V_adj = 0;
					pseudopointer[cmd.axis.pointer.idx].V_var = false;
				}
				else
				{
					pseudopointer[cmd.axis.pointer.idx].H_adj = 0;
					pseudopointer[cmd.axis.pointer.idx].H_var = false;
				}
			}
			else
			{
				if (cmd.axis.pointer.invert)
					data1 = -data1;

				if (cmd.axis.pointer.HV)
				{
					if (!pseudopointer[cmd.axis.pointer.idx].V_adj)
						pseudopointer[cmd.axis.pointer.idx].V_adj = (int16) ((int32) data1 * ptrspeeds[cmd.axis.pointer.speed_type] / 32767);
					pseudopointer[cmd.axis.pointer.idx].V_var = (cmd.axis.pointer.speed_type == 0);
				}
				else
				{
					if (!pseudopointer[cmd.axis.pointer.idx].H_adj)
						pseudopointer[cmd.axis.pointer.idx].H_adj = (int16) ((int32) data1 * ptrspeeds[cmd.axis.pointer.speed_type] / 32767);
					pseudopointer[cmd.axis.pointer.idx].H_var = (cmd.axis.pointer.speed_type == 0);
				}
			}

			return;

		case S9xAxisPseudobuttons:
			if (data1 >  ((cmd.axis.button.threshold + 1) *  127))
			{
				if (!pseudobuttons[cmd.axis.button.posbutton])
				{
					pseudobuttons[cmd.axis.button.posbutton] = 1;
					S9xReportButton(PseudoButtonBase + cmd.axis.button.posbutton, true);
				}
			}
			else
			{
				if (pseudobuttons[cmd.axis.button.posbutton])
				{
					pseudobuttons[cmd.axis.button.posbutton] = 0;
					S9xReportButton(PseudoButtonBase + cmd.axis.button.posbutton, false);
				}
			}

			if (data1 <= ((cmd.axis.button.threshold + 1) * -127))
			{
				if (!pseudobuttons[cmd.axis.button.negbutton])
				{
					pseudobuttons[cmd.axis.button.negbutton] = 1;
					S9xReportButton(PseudoButtonBase + cmd.axis.button.negbutton, true);
				}
			}
			else
			{
				if (pseudobuttons[cmd.axis.button.negbutton])
				{
					pseudobuttons[cmd.axis.button.negbutton] = 0;
					S9xReportButton(PseudoButtonBase + cmd.axis.button.negbutton, false);
				}
			}

			return;

		case S9xButtonPort:
		case S9xAxisPort:
		case S9xPointerPort:
			S9xHandlePortCommand(cmd, data1, data2);
			return;

		case S9xButtonMulti:
			if (cmd.button.multi_idx >= (int) multis.size())
				return;

			if (multis[cmd.button.multi_idx]->multi_press && !data1)
				return;

			i = ApplyMulti(multis[cmd.button.multi_idx], 0, data1);
			if (i >= 0)
			{
				struct exemulti	*e = new struct exemulti;
				e->pos    = i;
				e->data1  = data1 != 0;
				e->script = multis[cmd.button.multi_idx];
				exemultis.insert(e);
			}

			return;

		default:
			fprintf(stderr, "WARNING: Unknown command type %d\n", cmd.type);
			return;
	}
}

static void do_polling (int mp)
{
	set<uint32>::iterator	itr;

	if (S9xMoviePlaying())
		return;

	if (pollmap[mp].empty())
		return;

	for (itr = pollmap[mp].begin(); itr != pollmap[mp].end(); itr++)
	{
		switch (maptype(keymap[*itr].type))
		{
			case MAP_BUTTON:
			{
				bool	pressed;
				if (S9xPollButton(*itr, &pressed))
					S9xReportButton(*itr, pressed);
				break;
			}

			case MAP_AXIS:
			{
				int16	value;
				if (S9xPollAxis(*itr, &value))
					S9xReportAxis(*itr, value);
				break;
			}

			case MAP_POINTER:
			{
				int16	x, y;
				if (S9xPollPointer(*itr, &x, &y))
					S9xReportPointer(*itr, x, y);
				break;
			}

			default:
				break;
		}
	}
}

static void UpdatePolledMouse (int i)
{
	int16	j;

	j = mouse[i - MOUSE0].cur_x - mouse[i - MOUSE0].old_x;

	if (j < -127)
	{
		mouse[i - MOUSE0].delta_x = 0xff;
		mouse[i - MOUSE0].old_x -= 127;
	}
	else
	if (j < 0)
	{
		mouse[i - MOUSE0].delta_x = 0x80 | -j;
		mouse[i - MOUSE0].old_x = mouse[i - MOUSE0].cur_x;
	}
	else
	if (j > 127)
	{
		mouse[i - MOUSE0].delta_x = 0x7f;
		mouse[i - MOUSE0].old_x += 127;
	}
	else
	{
		mouse[i - MOUSE0].delta_x = (uint8) j;
		mouse[i - MOUSE0].old_x = mouse[i - MOUSE0].cur_x;
	}

	j = mouse[i - MOUSE0].cur_y - mouse[i - MOUSE0].old_y;

	if (j < -127)
	{
		mouse[i - MOUSE0].delta_y = 0xff;
		mouse[i - MOUSE0].old_y -= 127;
	}
	else
	if (j < 0)
	{
		mouse[i - MOUSE0].delta_y = 0x80 | -j;
		mouse[i - MOUSE0].old_y = mouse[i - MOUSE0].cur_y;
	}
	else
	if (j > 127)
	{
		mouse[i - MOUSE0].delta_y = 0x7f;
		mouse[i - MOUSE0].old_y += 127;
	}
	else
	{
		mouse[i - MOUSE0].delta_y = (uint8) j;
		mouse[i - MOUSE0].old_y = mouse[i - MOUSE0].cur_y;
	}
}

void S9xSetJoypadLatch (bool latch)
{
	if (!latch && FLAG_LATCH)
	{
		// 1 written, 'plug in' new controllers now
		curcontrollers[0] = newcontrollers[0];
		curcontrollers[1] = newcontrollers[1];
	}

	if (latch && !FLAG_LATCH)
	{
		int	i;

		for (int n = 0; n < 2; n++)
		{
			for (int j = 0; j < 2; j++)
				read_idx[n][j] = 0;

			switch (i = curcontrollers[n])
			{
				case MP5:
					for (int j = 0, k = mp5[n].pads[j]; j < 4; k = mp5[n].pads[++j])
					{
						if (k == NONE)
							continue;
						do_polling(k);
					}

					break;

				case JOYPAD0:
				case JOYPAD1:
				case JOYPAD2:
				case JOYPAD3:
				case JOYPAD4:
				case JOYPAD5:
				case JOYPAD6:
				case JOYPAD7:
					do_polling(i);
					break;

				case MOUSE0:
				case MOUSE1:
					do_polling(i);
					if (!S9xMoviePlaying())
						UpdatePolledMouse(i);
					break;

				case SUPERSCOPE:
					if (superscope.next_buttons & SUPERSCOPE_FIRE)
					{
						superscope.next_buttons &= ~SUPERSCOPE_TURBO;
						superscope.next_buttons |= superscope.phys_buttons & SUPERSCOPE_TURBO;
					}

					if (superscope.next_buttons & (SUPERSCOPE_FIRE | SUPERSCOPE_CURSOR))
					{
						superscope.next_buttons &= ~SUPERSCOPE_OFFSCREEN;
						superscope.next_buttons |= superscope.phys_buttons & SUPERSCOPE_OFFSCREEN;
					}

					superscope.read_buttons = superscope.next_buttons;

					superscope.next_buttons &= ~SUPERSCOPE_PAUSE;
					if (!(superscope.phys_buttons & SUPERSCOPE_TURBO))
						superscope.next_buttons &= ~(SUPERSCOPE_CURSOR | SUPERSCOPE_FIRE);

					do_polling(i);
					break;

				case TWO_JUSTIFIERS:
					do_polling(TWO_JUSTIFIERS);
					// fall through

				case ONE_JUSTIFIER:
					justifier.buttons ^= JUSTIFIER_SELECT;
					do_polling(ONE_JUSTIFIER);
					break;

				default:
					break;
			}
		}
	}

	FLAG_LATCH = latch;
}

uint8 S9xReadJOYSERn (int n)
{
	int	i, j, r;

	if (n > 1)
		n -= 0x4016;
	assert(n == 0 || n == 1);

	uint8	bits = (OpenBus & ~3) | ((n == 1) ? 0x1c : 0);

	if (FLAG_LATCH)
	{
		switch (i = curcontrollers[n])
		{
			case MP5:
				return (bits | 2);

			case JOYPAD0:
			case JOYPAD1:
			case JOYPAD2:
			case JOYPAD3:
			case JOYPAD4:
			case JOYPAD5:
			case JOYPAD6:
			case JOYPAD7:
				return (bits | ((joypad[i - JOYPAD0].buttons & 0x8000) ? 1 : 0));

			case MOUSE0:
			case MOUSE1:
				mouse[i - MOUSE0].buttons += 0x10;
				if ((mouse[i - MOUSE0].buttons & 0x30) == 0x30)
					mouse[i - MOUSE0].buttons &= 0xcf;
				return (bits);

			case SUPERSCOPE:
				return (bits | ((superscope.read_buttons & 0x80) ? 1 : 0));

			case ONE_JUSTIFIER:
			case TWO_JUSTIFIERS:
				return (bits);

			default:
				return (bits);
		}
	}
	else
	{
		switch (i = curcontrollers[n])
		{
			case MP5:
				r = read_idx[n][FLAG_IOBIT(n) ? 0 : 1]++;
				j = FLAG_IOBIT(n) ? 0 : 2;

				for (i = 0; i < 2; i++, j++)
				{
					if (mp5[n].pads[j] == NONE)
						continue;
					if (r >= 16)
						bits |= 1 << i;
					else
						bits |= ((joypad[mp5[n].pads[j] - JOYPAD0].buttons & (0x8000 >> r)) ? 1 : 0) << i;
				}

				return (bits);

			case JOYPAD0:
			case JOYPAD1:
			case JOYPAD2:
			case JOYPAD3:
			case JOYPAD4:
			case JOYPAD5:
			case JOYPAD6:
			case JOYPAD7:
				if (read_idx[n][0] >= 16)
				{
					read_idx[n][0]++;
					return (bits | 1);
				}
				else
					return (bits | ((joypad[i - JOYPAD0].buttons & (0x8000 >> read_idx[n][0]++)) ? 1 : 0));

			case MOUSE0:
			case MOUSE1:
				if (read_idx[n][0] < 8)
				{
					read_idx[n][0]++;
					return (bits);
				}
				else
				if (read_idx[n][0] < 16)
					return (bits | ((mouse[i - MOUSE0].buttons & (0x8000     >> read_idx[n][0]++)) ? 1 : 0));
				else
				if (read_idx[n][0] < 24)
					return (bits | ((mouse[i - MOUSE0].delta_y & (0x800000   >> read_idx[n][0]++)) ? 1 : 0));
				else
				if (read_idx[n][0] < 32)
					return (bits | ((mouse[i - MOUSE0].delta_x & (0x80000000 >> read_idx[n][0]++)) ? 1 : 0));
				else
				{
					read_idx[n][0]++;
					return (bits | 1);
				}

			case SUPERSCOPE:
				if (read_idx[n][0] < 8)
					return (bits | ((superscope.read_buttons & (0x80 >> read_idx[n][0]++)) ? 1 : 0));
				else
				{
					read_idx[n][0]++;
					return (bits | 1);
				}

			case ONE_JUSTIFIER:
				if (read_idx[n][0] < 24)
					return (bits | ((0xaa7000 >> read_idx[n][0]++) & 1));
				else
				if (read_idx[n][0] < 32)
					return (bits | ((justifier.buttons & (JUSTIFIER_TRIGGER | JUSTIFIER_START | JUSTIFIER_SELECT) & (0x80000000 >> read_idx[n][0]++)) ? 1 : 0));
				else
				{
					read_idx[n][0]++;
					return (bits | 1);
				}

			case TWO_JUSTIFIERS:
				if (read_idx[n][0] < 24)
					return (bits | ((0xaa7000 >> read_idx[n][0]++) & 1));
				else
				if (read_idx[n][0] < 32)
					return (bits | ((justifier.buttons & (0x80000000 >> read_idx[n][0]++)) ? 1 : 0));
				else
				{
					read_idx[n][0]++;
					return (bits | 1);
				}

			default:
				read_idx[n][0]++;
				return (bits);
		}
	}
}

void S9xDoAutoJoypad (void)
{
	int	i, j;

	S9xSetJoypadLatch(1);
	S9xSetJoypadLatch(0);

	S9xMovieUpdate(false);

	for (int n = 0; n < 2; n++)
	{
		switch (i = curcontrollers[n])
		{
			case MP5:
				j = FLAG_IOBIT(n) ? 0 : 2;
				for (i = 0; i < 2; i++, j++)
				{
					if (mp5[n].pads[j] == NONE)
						WRITE_WORD(Memory.FillRAM + 0x4218 + n * 2 + i * 4, 0);
					else
						WRITE_WORD(Memory.FillRAM + 0x4218 + n * 2 + i * 4, joypad[mp5[n].pads[j] - JOYPAD0].buttons);
				}

				read_idx[n][FLAG_IOBIT(n) ? 0 : 1] = 16;
				break;

			case JOYPAD0:
			case JOYPAD1:
			case JOYPAD2:
			case JOYPAD3:
			case JOYPAD4:
			case JOYPAD5:
			case JOYPAD6:
			case JOYPAD7:
				read_idx[n][0] = 16;
				WRITE_WORD(Memory.FillRAM + 0x4218 + n * 2, joypad[i - JOYPAD0].buttons);
				WRITE_WORD(Memory.FillRAM + 0x421c + n * 2, 0);
				break;

			case MOUSE0:
			case MOUSE1:
				read_idx[n][0] = 16;
				WRITE_WORD(Memory.FillRAM + 0x4218 + n * 2, mouse[i - MOUSE0].buttons);
				WRITE_WORD(Memory.FillRAM + 0x421c + n * 2, 0);
				break;

			case SUPERSCOPE:
				read_idx[n][0] = 16;
				Memory.FillRAM[0x4218 + n * 2] = 0xff;
				Memory.FillRAM[0x4219 + n * 2] = superscope.read_buttons;
				WRITE_WORD(Memory.FillRAM + 0x421c + n * 2, 0);
				break;

			case ONE_JUSTIFIER:
			case TWO_JUSTIFIERS:
				read_idx[n][0] = 16;
				WRITE_WORD(Memory.FillRAM + 0x4218 + n * 2, 0x000e);
				WRITE_WORD(Memory.FillRAM + 0x421c + n * 2, 0);
				break;

			default:
				WRITE_WORD(Memory.FillRAM + 0x4218 + n * 2, 0);
				WRITE_WORD(Memory.FillRAM + 0x421c + n * 2, 0);
				break;
		}
	}
}

void S9xControlEOF (void)
{
	struct crosshair	*c;
	int					i, j;

	PPU.GunVLatch = 1000; // i.e., never latch
	PPU.GunHLatch = 0;

	for (int n = 0; n < 2; n++)
	{
		switch (i = curcontrollers[n])
		{
			case MP5:
				for (j = 0, i = mp5[n].pads[j]; j < 4; i = mp5[n].pads[++j])
				{
					if (i == NONE)
						continue;

					if (++joypad[i - JOYPAD0].turbo_ct >= turbo_time)
					{
						joypad[i - JOYPAD0].turbo_ct = 0;
						joypad[i - JOYPAD0].buttons ^= joypad[i - JOYPAD0].turbos;
					}
				}

				break;

			case JOYPAD0:
			case JOYPAD1:
			case JOYPAD2:
			case JOYPAD3:
			case JOYPAD4:
			case JOYPAD5:
			case JOYPAD6:
			case JOYPAD7:
				if (++joypad[i - JOYPAD0].turbo_ct >= turbo_time)
				{
					joypad[i - JOYPAD0].turbo_ct = 0;
					joypad[i - JOYPAD0].buttons ^= joypad[i - JOYPAD0].turbos;
				}

				break;

			case MOUSE0:
			case MOUSE1:
				c = &mouse[i - MOUSE0].crosshair;
				if (IPPU.RenderThisFrame)
					S9xDrawCrosshair(S9xGetCrosshair(c->img), c->fg, c->bg, mouse[i - MOUSE0].cur_x, mouse[i - MOUSE0].cur_y);
				break;

			case SUPERSCOPE:
				if (n == 1 && !(superscope.phys_buttons & SUPERSCOPE_OFFSCREEN))
				{
					if (superscope.next_buttons & (SUPERSCOPE_FIRE | SUPERSCOPE_CURSOR))
						DoGunLatch(superscope.x, superscope.y);

					c = &superscope.crosshair;
					if (IPPU.RenderThisFrame)
						S9xDrawCrosshair(S9xGetCrosshair(c->img), c->fg, c->bg, superscope.x, superscope.y);
				}

				break;

			case TWO_JUSTIFIERS:
				if (n == 1 && !justifier.offscreen[1])
				{
					c = &justifier.crosshair[1];
					if (IPPU.RenderThisFrame)
						S9xDrawCrosshair(S9xGetCrosshair(c->img), c->fg, c->bg, justifier.x[1], justifier.y[1]);
				}

				i = (justifier.buttons & JUSTIFIER_SELECT) ?  1 : 0;
				goto do_justifier;

			case ONE_JUSTIFIER:
				i = (justifier.buttons & JUSTIFIER_SELECT) ? -1 : 0;

			do_justifier:
				if (n == 1)
				{
					if (i >= 0 && !justifier.offscreen[i])
						DoGunLatch(justifier.x[i], justifier.y[i]);

					if (!justifier.offscreen[0])
					{
						c = &justifier.crosshair[0];
						if (IPPU.RenderThisFrame)
							S9xDrawCrosshair(S9xGetCrosshair(c->img), c->fg, c->bg, justifier.x[0], justifier.y[0]);
					}
				}

				break;

			default:
				break;
		}
	}

	for (int n = 0; n < 8; n++)
	{
		if (!pseudopointer[n].mapped)
			continue;

		if (pseudopointer[n].H_adj)
		{
			pseudopointer[n].x += pseudopointer[n].H_adj;
			if (pseudopointer[n].x < 0)
				pseudopointer[n].x = 0;
			else
			if (pseudopointer[n].x > 255)
				pseudopointer[n].x = 255;

			if (pseudopointer[n].H_var)
			{
				if (pseudopointer[n].H_adj < 0)
				{
					if (pseudopointer[n].H_adj > -ptrspeeds[3])
						pseudopointer[n].H_adj--;
				}
				else
				{
					if (pseudopointer[n].H_adj <  ptrspeeds[3])
						pseudopointer[n].H_adj++;
				}
			}
		}

		if (pseudopointer[n].V_adj)
		{
			pseudopointer[n].y += pseudopointer[n].V_adj;
			if (pseudopointer[n].y < 0)
				pseudopointer[n].y = 0;
			else
			if (pseudopointer[n].y > PPU.ScreenHeight - 1)
				pseudopointer[n].y = PPU.ScreenHeight - 1;

			if (pseudopointer[n].V_var)
			{
				if (pseudopointer[n].V_adj < 0)
				{
					if (pseudopointer[n].V_adj > -ptrspeeds[3])
						pseudopointer[n].V_adj--;
				}
				else
				{
					if (pseudopointer[n].V_adj <  ptrspeeds[3])
						pseudopointer[n].V_adj++;
				}
			}
		}

		S9xReportPointer(PseudoPointerBase + n, pseudopointer[n].x, pseudopointer[n].y);
	}

	set<struct exemulti *>::iterator	it, jt;

	for (it = exemultis.begin(); it != exemultis.end(); it++)
	{
		i = ApplyMulti((*it)->script, (*it)->pos, (*it)->data1);

		if (i >= 0)
			(*it)->pos = i;
		else
		{
			jt = it;
			it--;
			delete *jt;
			exemultis.erase(jt);
		}
	}

	do_polling(POLL_ALL);

	S9xMovieUpdate();

	pad_read_last = pad_read;
	pad_read      = false;
}

void S9xSetControllerCrosshair (enum crosscontrols ctl, int8 idx, const char *fg, const char *bg)
{
	struct crosshair	*c;
	int8				fgcolor = -1, bgcolor = -1;
	int					i, j;

	if (idx < -1 || idx > 31)
	{
		fprintf(stderr, "S9xSetControllerCrosshair() called with invalid index\n");
		return;
	}

	switch (ctl)
	{
		case X_MOUSE1:		c = &mouse[0].crosshair;		break;
		case X_MOUSE2:		c = &mouse[1].crosshair;		break;
		case X_SUPERSCOPE:	c = &superscope.crosshair;		break;
		case X_JUSTIFIER1:	c = &justifier.crosshair[0];	break;
		case X_JUSTIFIER2:	c = &justifier.crosshair[1];	break;
		default:
			fprintf(stderr, "S9xSetControllerCrosshair() called with an invalid controller ID %d\n", ctl);
			return;
	}

	if (fg)
	{
		fgcolor = 0;
		if (*fg == 't')
		{
			fg++;
			fgcolor = 16;
		}

		for (i = 0; i < 16; i++)
		{
			for (j = 0; color_names[i][j] && fg[j] == color_names[i][j]; j++) ;
				if (isalnum(fg[j]))
					continue;

			if (!color_names[i][j])
				break;
		}

		fgcolor |= i;
		if (i > 15 || fgcolor == 16)
		{
			fprintf(stderr, "S9xSetControllerCrosshair() called with invalid fgcolor\n");
			return;
		}
	}

	if (bg)
	{
		bgcolor = 0;
		if (*bg == 't')
		{
			bg++;
			bgcolor = 16;
		}

		for (i = 0; i < 16; i++)
		{
			for (j = 0; color_names[i][j] && bg[j] == color_names[i][j]; j++) ;
				if (isalnum(bg[j]))
					continue;

			if (!color_names[i][j])
				break;
		}

		bgcolor |= i;
		if (i > 15 || bgcolor == 16)
		{
			fprintf(stderr, "S9xSetControllerCrosshair() called with invalid bgcolor\n");
			return;
		}
	}

	if (idx != -1)
	{
		c->set |= 1;
		c->img = idx;
	}

	if (fgcolor != -1)
	{
		c->set |= 2;
		c->fg = fgcolor;
	}

	if (bgcolor != -1)
	{
		c->set |= 4;
		c->bg = bgcolor;
	}
}

void S9xGetControllerCrosshair (enum crosscontrols ctl, int8 *idx, const char **fg, const char **bg)
{
	struct crosshair	*c;

	switch (ctl)
	{
		case X_MOUSE1:		c = &mouse[0].crosshair;		break;
		case X_MOUSE2:		c = &mouse[1].crosshair;		break;
		case X_SUPERSCOPE:	c = &superscope.crosshair;		break;
		case X_JUSTIFIER1:	c = &justifier.crosshair[0];	break;
		case X_JUSTIFIER2:	c = &justifier.crosshair[1];	break;
		default:
			fprintf(stderr, "S9xGetControllerCrosshair() called with an invalid controller ID %d\n", ctl);
			return;
	}

	if (idx)
		*idx = c->img;

	if (fg)
		*fg = color_names[c->fg];

	if (bg)
		*bg = color_names[c->bg];
}

void S9xControlPreSaveState (struct SControlSnapshot *s)
{
	memset(s, 0, sizeof(*s));
	s->ver = 3;

	for (int j = 0; j < 2; j++)
	{
		s->port1_read_idx[j] = read_idx[0][j];
		s->port2_read_idx[j] = read_idx[1][j];
	}

	for (int j = 0; j < 2; j++)
		s->mouse_speed[j] = (mouse[j].buttons & 0x30) >> 4;

	s->justifier_select = ((justifier.buttons & JUSTIFIER_SELECT) ? 1 : 0);

#define COPY(x)	{ memcpy((char *) s->internal + i, &(x), sizeof(x)); i += sizeof(x); }

	int	i = 0;

	for (int j = 0; j < 8; j++)
		COPY(joypad[j].buttons);

	for (int j = 0; j < 2; j++)
	{
		COPY(mouse[j].delta_x);
		COPY(mouse[j].delta_y);
		COPY(mouse[j].old_x);
		COPY(mouse[j].old_y);
		COPY(mouse[j].cur_x);
		COPY(mouse[j].cur_y);
		COPY(mouse[j].buttons);
	}

	COPY(superscope.x);
	COPY(superscope.y);
	COPY(superscope.phys_buttons);
	COPY(superscope.next_buttons);
	COPY(superscope.read_buttons);

	for (int j = 0; j < 2; j++)
		COPY(justifier.x[j]);
	for (int j = 0; j < 2; j++)
		COPY(justifier.y[j]);
	COPY(justifier.buttons);
	for (int j = 0; j < 2; j++)
		COPY(justifier.offscreen[j]);

	for (int j = 0; j < 2; j++)
		for (int k = 0; k < 2; k++)
			COPY(mp5[j].pads[k]);

	assert(i == sizeof(s->internal));

#undef COPY

	s->pad_read      = pad_read;
	s->pad_read_last = pad_read_last;
}

void S9xControlPostLoadState (struct SControlSnapshot *s)
{
	if (curcontrollers[0] == MP5 && s->ver < 1)
	{
		// Crap. Old snes9x didn't support this.
		S9xMessage(S9X_WARNING, S9X_FREEZE_FILE_INFO, "Old savestate has no support for MP5 in port 1.");
		newcontrollers[0] = curcontrollers[0];
		curcontrollers[0] = mp5[0].pads[0];
	}

	for (int j = 0; j < 2; j++)
	{
		read_idx[0][j] = s->port1_read_idx[j];
		read_idx[1][j] = s->port2_read_idx[j];
	}

	for (int j = 0; j < 2; j++)
		mouse[j].buttons |= (s->mouse_speed[j] & 3) << 4;

	if (s->justifier_select & 1)
		justifier.buttons |=  JUSTIFIER_SELECT;
	else
		justifier.buttons &= ~JUSTIFIER_SELECT;

	FLAG_LATCH = (Memory.FillRAM[0x4016] & 1) == 1;

	if (s->ver > 1)
	{
	#define COPY(x)	{ memcpy(&(x), (char *) s->internal + i, sizeof(x)); i += sizeof(x); }

		int	i = 0;

		for (int j = 0; j < 8; j++)
			COPY(joypad[j].buttons);

		for (int j = 0; j < 2; j++)
		{
			COPY(mouse[j].delta_x);
			COPY(mouse[j].delta_y);
			COPY(mouse[j].old_x);
			COPY(mouse[j].old_y);
			COPY(mouse[j].cur_x);
			COPY(mouse[j].cur_y);
			COPY(mouse[j].buttons);
		}

		COPY(superscope.x);
		COPY(superscope.y);
		COPY(superscope.phys_buttons);
		COPY(superscope.next_buttons);
		COPY(superscope.read_buttons);

		for (int j = 0; j < 2; j++)
			COPY(justifier.x[j]);
		for (int j = 0; j < 2; j++)
			COPY(justifier.y[j]);
		COPY(justifier.buttons);
		for (int j = 0; j < 2; j++)
			COPY(justifier.offscreen[j]);
		for (int j = 0; j < 2; j++)
			for (int k = 0; k < 2; k++)
				COPY(mp5[j].pads[k]);

		assert(i == sizeof(s->internal));

	#undef COPY
	}

	if (s->ver > 2)
	{
		pad_read      = s->pad_read;
		pad_read_last = s->pad_read_last;
	}
}

uint16 MovieGetJoypad (int i)
{
	if (i < 0 || i > 7)
		return (0);

	return (joypad[i].buttons);
}

void MovieSetJoypad (int i, uint16 buttons)
{
	if (i < 0 || i > 7)
		return;

	joypad[i].buttons = buttons;
}

bool MovieGetMouse (int i, uint8 out[5])
{
	if (i < 0 || i > 1 || (curcontrollers[i] != MOUSE0 && curcontrollers[i] != MOUSE1))
		return (false);

	int		n = curcontrollers[i] - MOUSE0;
	uint8	*ptr = out;

	WRITE_WORD(ptr, mouse[n].cur_x); ptr += 2;
	WRITE_WORD(ptr, mouse[n].cur_y); ptr += 2;
	*ptr = mouse[n].buttons;

	return (true);
}

void MovieSetMouse (int i, uint8 in[5], bool inPolling)
{
	if (i < 0 || i > 1 || (curcontrollers[i] != MOUSE0 && curcontrollers[i] != MOUSE1))
		return;

	int		n = curcontrollers[i] - MOUSE0;
	uint8	*ptr = in;

	mouse[n].cur_x = READ_WORD(ptr); ptr += 2;
	mouse[n].cur_y = READ_WORD(ptr); ptr += 2;
	mouse[n].buttons = *ptr;

	if (inPolling)
		UpdatePolledMouse(curcontrollers[i]);
}

bool MovieGetScope (int i, uint8 out[6])
{
	if (i < 0 || i > 1 || curcontrollers[i] != SUPERSCOPE)
		return (false);

	uint8	*ptr = out;

	WRITE_WORD(ptr, superscope.x); ptr += 2;
	WRITE_WORD(ptr, superscope.y); ptr += 2;
	*ptr++ = superscope.phys_buttons;
	*ptr   = superscope.next_buttons;

	return (true);
}

void MovieSetScope (int i, uint8 in[6])
{
	if (i < 0 || i > 1 || curcontrollers[i] != SUPERSCOPE)
		return;

	uint8	*ptr = in;

	superscope.x = READ_WORD(ptr); ptr += 2;
	superscope.y = READ_WORD(ptr); ptr += 2;
	superscope.phys_buttons = *ptr++;
	superscope.next_buttons = *ptr;
}

bool MovieGetJustifier (int i, uint8 out[11])
{
	if (i < 0 || i > 1 || (curcontrollers[i] != ONE_JUSTIFIER && curcontrollers[i] != TWO_JUSTIFIERS))
		return (false);

	uint8	*ptr = out;

	WRITE_WORD(ptr, justifier.x[0]); ptr += 2;
	WRITE_WORD(ptr, justifier.x[1]); ptr += 2;
	WRITE_WORD(ptr, justifier.y[0]); ptr += 2;
	WRITE_WORD(ptr, justifier.y[1]); ptr += 2;
	*ptr++ = justifier.buttons;
	*ptr++ = justifier.offscreen[0];
	*ptr   = justifier.offscreen[1];

	return (true);
}

void MovieSetJustifier (int i, uint8 in[11])
{
	if (i < 0 || i > 1 || (curcontrollers[i] != ONE_JUSTIFIER && curcontrollers[i] != TWO_JUSTIFIERS))
		return;

	uint8	*ptr = in;

	justifier.x[0] = READ_WORD(ptr); ptr += 2;
	justifier.x[1] = READ_WORD(ptr); ptr += 2;
	justifier.y[0] = READ_WORD(ptr); ptr += 2;
	justifier.y[1] = READ_WORD(ptr); ptr += 2;
	justifier.buttons      = *ptr++;
	justifier.offscreen[0] = *ptr++;
	justifier.offscreen[1] = *ptr;
}