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

    ioport.c

    Input/output port handling.

****************************************************************************

    Theory of operation

    ------------
    OSD controls
    ------------

    There are three types of controls that the OSD can provide as potential
    input devices: digital controls, absolute analog controls, and relative
    analog controls.

    Digital controls have only two states: on or off. They are generally
    mapped to buttons and digital joystick directions (like a gamepad or a
    joystick hat). The OSD layer must return either 0 (off) or 1 (on) for
    these types of controls.

    Absolute analog controls are analog in the sense that they return a
    range of values depending on how much a given control is moved, but they
    are physically bounded. This means that there is a minimum and maximum
    limit to how far the control can be moved. They are generally mapped to
    analog joystick axes, lightguns, most PC steering wheels, and pedals.
    The OSD layer must determine the minimum and maximum range of each
    analog device and scale that to a value between -65536 and +65536
    representing the position of the control. -65536 generally refers to
    the topmost or leftmost position, while +65536 refers to the bottommost
    or rightmost position. Note that pedals are a special case here, the
    OSD layer needs to return half axis as full -65536 to + 65536 range.

    Relative analog controls are analog as well, but are not physically
    bounded. They can be moved continually in one direction without limit.
    They are generally mapped to trackballs and mice. Because they are
    unbounded, the OSD layer can only return delta values since the last
    read. Because of this, it is difficult to scale appropriately. For
    MAME's purposes, when mapping a mouse devices to a relative analog
    control, one pixel of movement should correspond to 512 units. Other
    analog control types should be scaled to return values of a similar
    magnitude. Like absolute analog controls, negative values refer to
    upward or leftward movement, while positive values refer to downward
    or rightward movement.

    -------------
    Game controls
    -------------

    Similarly, the types of controls used by arcade games fall into the same
    three categories: digital, absolute analog, and relative analog. The
    tricky part is how to map any arbitrary type of OSD control to an
    arbitrary type of game control.

    Digital controls: used for game buttons and standard 4/8-way joysticks,
    as well as many other types of game controls. Mapping an OSD digital
    control to a game's OSD control is trivial. For OSD analog controls,
    the MAME core does not directly support mapping any OSD analog devices
    to digital controls. However, the OSD layer is free to enumerate digital
    equivalents for analog devices. For example, each analog axis in the
    Windows OSD code enumerates to two digital controls, one for the
    negative direction (up/left) and one for the position direction
    (down/right). When these "digital" inputs are queried, the OSD layer
    checks the axis position against the center, adding in a dead zone,
    and returns 0 or 1 to indicate its position.

    Absolute analog controls: used for analog joysticks, lightguns, pedals,
    and wheel controls. Mapping an OSD absolute analog control to this type
    is easy. OSD relative analog controls can be mapped here as well by
    accumulating the deltas and bounding the results. OSD digital controls
    are mapped to these types of controls in pairs, one for a decrement and
    one for an increment, but apart from that, operate the same as the OSD
    relative analog controls by accumulating deltas and applying bounds.
    The speed of the digital delta is user-configurable per analog input.
    In addition, most absolute analog control types have an autocentering
    feature that is activated when using the digital increment/decrement
    sequences, which returns the control back to the center at a user-
    controllable speed if no digital sequences are pressed.

    Relative analog controls: used for trackballs and dial controls. Again,
    mapping an OSD relative analog control to this type is straightforward.
    OSD absolute analog controls can't map directly to these, but if the OSD
    layer provides a digital equivalent for each direction, it can be done.
    OSD digital controls map just like they do for absolute analog controls,
    except that the accumulated deltas are not bounded, but rather wrap.

***************************************************************************/

#include "emu.h"
#include "emuopts.h"
#include "config.h"
#include "xmlfile.h"
#include "profiler.h"
#include "ui/uimain.h"
#include "inputdev.h"
#include "natkeyboard.h"

#include "osdepend.h"

#include <ctype.h>
#include <time.h>


namespace {

// temporary: set this to 1 to enable the originally defined behavior that
// a field specified via PORT_MODIFY which intersects a previously-defined
// field completely wipes out the previous definition
#define INPUT_PORT_OVERRIDE_FULLY_NUKES_PREVIOUS    1


//**************************************************************************
//  CONSTANTS
//**************************************************************************

const int SPACE_COUNT = 3;



//**************************************************************************
//  INLINE FUNCTIONS
//**************************************************************************

//-------------------------------------------------
//  compute_scale -- compute an 8.24 scale value
//  from a numerator and a denominator
//-------------------------------------------------

inline s64 compute_scale(s32 num, s32 den)
{
	return (s64(num) << 24) / den;
}


//-------------------------------------------------
//  recip_scale -- compute an 8.24 reciprocal of
//  an 8.24 scale value
//-------------------------------------------------

inline s64 recip_scale(s64 scale)
{
	return (s64(1) << 48) / scale;
}


//-------------------------------------------------
//  apply_scale -- apply an 8.24 scale value to
//  a 32-bit value
//-------------------------------------------------

inline s32 apply_scale(s32 value, s64 scale)
{
	return (s64(value) * scale) / (1 << 24);
}



//**************************************************************************
//  COMMON SHARED STRINGS
//**************************************************************************

const struct
{
	u32 id;
	const char *string;
} input_port_default_strings[] =
{
	{ INPUT_STRING_Off, "Off" },
	{ INPUT_STRING_On, "On" },
	{ INPUT_STRING_No, "No" },
	{ INPUT_STRING_Yes, "Yes" },
	{ INPUT_STRING_Lives, "Lives" },
	{ INPUT_STRING_Bonus_Life, "Bonus Life" },
	{ INPUT_STRING_Difficulty, "Difficulty" },
	{ INPUT_STRING_Demo_Sounds, "Demo Sounds" },
	{ INPUT_STRING_Coinage, "Coinage" },
	{ INPUT_STRING_Coin_A, "Coin A" },
	{ INPUT_STRING_Coin_B, "Coin B" },
	{ INPUT_STRING_9C_1C, "9 Coins/1 Credit" },
	{ INPUT_STRING_8C_1C, "8 Coins/1 Credit" },
	{ INPUT_STRING_7C_1C, "7 Coins/1 Credit" },
	{ INPUT_STRING_6C_1C, "6 Coins/1 Credit" },
	{ INPUT_STRING_5C_1C, "5 Coins/1 Credit" },
	{ INPUT_STRING_4C_1C, "4 Coins/1 Credit" },
	{ INPUT_STRING_3C_1C, "3 Coins/1 Credit" },
	{ INPUT_STRING_8C_3C, "8 Coins/3 Credits" },
	{ INPUT_STRING_4C_2C, "4 Coins/2 Credits" },
	{ INPUT_STRING_2C_1C, "2 Coins/1 Credit" },
	{ INPUT_STRING_5C_3C, "5 Coins/3 Credits" },
	{ INPUT_STRING_3C_2C, "3 Coins/2 Credits" },
	{ INPUT_STRING_4C_3C, "4 Coins/3 Credits" },
	{ INPUT_STRING_4C_4C, "4 Coins/4 Credits" },
	{ INPUT_STRING_3C_3C, "3 Coins/3 Credits" },
	{ INPUT_STRING_2C_2C, "2 Coins/2 Credits" },
	{ INPUT_STRING_1C_1C, "1 Coin/1 Credit" },
	{ INPUT_STRING_4C_5C, "4 Coins/5 Credits" },
	{ INPUT_STRING_3C_4C, "3 Coins/4 Credits" },
	{ INPUT_STRING_2C_3C, "2 Coins/3 Credits" },
	{ INPUT_STRING_4C_7C, "4 Coins/7 Credits" },
	{ INPUT_STRING_2C_4C, "2 Coins/4 Credits" },
	{ INPUT_STRING_1C_2C, "1 Coin/2 Credits" },
	{ INPUT_STRING_2C_5C, "2 Coins/5 Credits" },
	{ INPUT_STRING_2C_6C, "2 Coins/6 Credits" },
	{ INPUT_STRING_1C_3C, "1 Coin/3 Credits" },
	{ INPUT_STRING_2C_7C, "2 Coins/7 Credits" },
	{ INPUT_STRING_2C_8C, "2 Coins/8 Credits" },
	{ INPUT_STRING_1C_4C, "1 Coin/4 Credits" },
	{ INPUT_STRING_1C_5C, "1 Coin/5 Credits" },
	{ INPUT_STRING_1C_6C, "1 Coin/6 Credits" },
	{ INPUT_STRING_1C_7C, "1 Coin/7 Credits" },
	{ INPUT_STRING_1C_8C, "1 Coin/8 Credits" },
	{ INPUT_STRING_1C_9C, "1 Coin/9 Credits" },
	{ INPUT_STRING_Free_Play, "Free Play" },
	{ INPUT_STRING_Cabinet, "Cabinet" },
	{ INPUT_STRING_Upright, "Upright" },
	{ INPUT_STRING_Cocktail, "Cocktail" },
	{ INPUT_STRING_Flip_Screen, "Flip Screen" },
	{ INPUT_STRING_Service_Mode, "Service Mode" },
	{ INPUT_STRING_Pause, "Pause" },
	{ INPUT_STRING_Test, "Test" },
	{ INPUT_STRING_Tilt, "Tilt" },
	{ INPUT_STRING_Version, "Version" },
	{ INPUT_STRING_Region, "Region" },
	{ INPUT_STRING_International, "International" },
	{ INPUT_STRING_Japan, "Japan" },
	{ INPUT_STRING_USA, "USA" },
	{ INPUT_STRING_Europe, "Europe" },
	{ INPUT_STRING_Asia, "Asia" },
	{ INPUT_STRING_China, "China" },
	{ INPUT_STRING_Hong_Kong, "Hong Kong" },
	{ INPUT_STRING_Korea, "Korea" },
	{ INPUT_STRING_Southeast_Asia, "Southeast Asia" },
	{ INPUT_STRING_Taiwan, "Taiwan" },
	{ INPUT_STRING_World, "World" },
	{ INPUT_STRING_Language, "Language" },
	{ INPUT_STRING_English, "English" },
	{ INPUT_STRING_Japanese, "Japanese" },
	{ INPUT_STRING_Chinese, "Chinese" },
	{ INPUT_STRING_French, "French" },
	{ INPUT_STRING_German, "German" },
	{ INPUT_STRING_Italian, "Italian" },
	{ INPUT_STRING_Korean, "Korean" },
	{ INPUT_STRING_Spanish, "Spanish" },
	{ INPUT_STRING_Very_Easy, "Very Easy" },
	{ INPUT_STRING_Easiest, "Easiest" },
	{ INPUT_STRING_Easier, "Easier" },
	{ INPUT_STRING_Easy, "Easy" },
	{ INPUT_STRING_Medium_Easy, "Medium Easy" },
	{ INPUT_STRING_Normal, "Normal" },
	{ INPUT_STRING_Medium, "Medium" },
	{ INPUT_STRING_Medium_Hard, "Medium Hard" },
	{ INPUT_STRING_Hard, "Hard" },
	{ INPUT_STRING_Harder, "Harder" },
	{ INPUT_STRING_Hardest, "Hardest" },
	{ INPUT_STRING_Very_Hard, "Very Hard" },
	{ INPUT_STRING_Medium_Difficult, "Medium Difficult" },
	{ INPUT_STRING_Difficult, "Difficult" },
	{ INPUT_STRING_Very_Difficult, "Very Difficult" },
	{ INPUT_STRING_Very_Low, "Very Low" },
	{ INPUT_STRING_Low, "Low" },
	{ INPUT_STRING_High, "High" },
	{ INPUT_STRING_Higher, "Higher" },
	{ INPUT_STRING_Highest, "Highest" },
	{ INPUT_STRING_Very_High, "Very High" },
	{ INPUT_STRING_Players, "Players" },
	{ INPUT_STRING_Controls, "Controls" },
	{ INPUT_STRING_Dual, "Dual" },
	{ INPUT_STRING_Single, "Single" },
	{ INPUT_STRING_Game_Time, "Game Time" },
	{ INPUT_STRING_Continue_Price, "Continue Price" },
	{ INPUT_STRING_Controller, "Controller" },
	{ INPUT_STRING_Light_Gun, "Light Gun" },
	{ INPUT_STRING_Joystick, "Joystick" },
	{ INPUT_STRING_Trackball, "Trackball" },
	{ INPUT_STRING_Continues, "Continues" },
	{ INPUT_STRING_Allow_Continue, "Allow Continue" },
	{ INPUT_STRING_Level_Select, "Level Select" },
	{ INPUT_STRING_Infinite, "Infinite" },
	{ INPUT_STRING_Stereo, "Stereo" },
	{ INPUT_STRING_Mono, "Mono" },
	{ INPUT_STRING_Unused, "Unused" },
	{ INPUT_STRING_Unknown, "Unknown" },
	{ INPUT_STRING_Standard, "Standard" },
	{ INPUT_STRING_Reverse, "Reverse" },
	{ INPUT_STRING_Alternate, "Alternate" },
	{ INPUT_STRING_None, "None" },
};

} // anonymous namespace


// XML attributes for the different types
const char *const ioport_manager::seqtypestrings[] = { "standard", "increment", "decrement" };


u8 const inp_header::MAGIC[inp_header::OFFS_BASETIME - inp_header::OFFS_MAGIC] = { 'M', 'A', 'M', 'E', 'I', 'N', 'P', 0 };



//**************************************************************************
//  BUILT-IN CORE MAPPINGS
//**************************************************************************

#include "inpttype.h"



//**************************************************************************
//  PORT CONFIGURATIONS
//**************************************************************************

//**************************************************************************
//  I/O PORT LIST
//**************************************************************************

//-------------------------------------------------
//  append - append the given device's input ports
//  to the current list
//-------------------------------------------------

void ioport_list::append(device_t &device, std::string &errorbuf)
{
	// no constructor, no list
	ioport_constructor constructor = device.input_ports();
	if (constructor == nullptr)
		return;

	// reset error buffer
	errorbuf.clear();

	// detokenize into the list
	(*constructor)(device, *this, errorbuf);

	// collapse fields and sort the list
	for (auto &port : *this)
		port.second->collapse_fields(errorbuf);
}



//**************************************************************************
//  INPUT TYPE ENTRY
//**************************************************************************

//-------------------------------------------------
//  input_type_entry - constructors
//-------------------------------------------------

input_type_entry::input_type_entry(ioport_type type, ioport_group group, int player, const char *token, const char *name, input_seq standard)
	: m_next(nullptr),
		m_type(type),
		m_group(group),
		m_player(player),
		m_token(token),
		m_name(name)
{
	m_defseq[SEQ_TYPE_STANDARD] = m_seq[SEQ_TYPE_STANDARD] = standard;
}

input_type_entry::input_type_entry(ioport_type type, ioport_group group, int player, const char *token, const char *name, input_seq standard, input_seq decrement, input_seq increment)
	: m_next(nullptr),
		m_type(type),
		m_group(group),
		m_player(player),
		m_token(token),
		m_name(name)
{
	m_defseq[SEQ_TYPE_STANDARD] = m_seq[SEQ_TYPE_STANDARD] = standard;
	m_defseq[SEQ_TYPE_INCREMENT] = m_seq[SEQ_TYPE_INCREMENT] = increment;
	m_defseq[SEQ_TYPE_DECREMENT] = m_seq[SEQ_TYPE_DECREMENT] = decrement;
}


//-------------------------------------------------
//  configure_osd - set the token and name of an
//  OSD entry
//-------------------------------------------------

void input_type_entry::configure_osd(const char *token, const char *name)
{
	assert(m_type >= IPT_OSD_1 && m_type <= IPT_OSD_16);
	m_token = token;
	m_name = name;
}


//-------------------------------------------------
//  restore_default_seq - restores the sequence
//  from the default
//-------------------------------------------------

void input_type_entry::restore_default_seq()
{
	for (input_seq_type seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; ++seqtype)
		m_seq[seqtype] = defseq(seqtype);
}


//**************************************************************************
//  DIGITAL JOYSTICKS
//**************************************************************************

//-------------------------------------------------
//  digital_joystick - constructor
//-------------------------------------------------

digital_joystick::digital_joystick(int player, int number)
	:   m_next(nullptr),
		m_player(player),
		m_number(number),
		m_current(0),
		m_current4way(0),
		m_previous(0)
{
}


//-------------------------------------------------
//  set_axis - configure a single axis of a
//  digital joystick
//-------------------------------------------------

digital_joystick::direction_t digital_joystick::add_axis(ioport_field &field)
{
	direction_t direction = direction_t((field.type() - (IPT_DIGITAL_JOYSTICK_FIRST + 1)) % 4);
	m_field[direction].append(*global_alloc(simple_list_wrapper<ioport_field>(&field)));
	return direction;
}


//-------------------------------------------------
//  frame_update - update the state of digital
//  joysticks prior to accumulating the results
//  in a port
//-------------------------------------------------

void digital_joystick::frame_update()
{
	// remember previous state and reset current state
	m_previous = m_current;
	m_current = 0;

	// read all the associated ports
	running_machine *machine = nullptr;
	for (direction_t direction = JOYDIR_UP; direction < JOYDIR_COUNT; ++direction)
		for (const simple_list_wrapper<ioport_field> &i : m_field[direction])
		{
			machine = &i.object()->machine();
			if (machine->input().seq_pressed(i.object()->seq(SEQ_TYPE_STANDARD)))
				m_current |= 1 << direction;
		}

	// lock out opposing directions (left + right or up + down)
	if ((m_current & (UP_BIT | DOWN_BIT)) == (UP_BIT | DOWN_BIT))
		m_current &= ~(UP_BIT | DOWN_BIT);
	if ((m_current & (LEFT_BIT | RIGHT_BIT)) == (LEFT_BIT | RIGHT_BIT))
		m_current &= ~(LEFT_BIT | RIGHT_BIT);

	// only update 4-way case if joystick has moved
	if (m_current != m_previous)
	{
		m_current4way = m_current;

		//
		//  If joystick is pointing at a diagonal, acknowledge that the player moved
		//  the joystick by favoring a direction change.  This minimizes frustration
		//  and maximizes responsiveness.
		//
		//  For example, if you are holding "left" then switch to "up" (where both left
		//  and up are briefly pressed at the same time), we'll transition immediately
		//  to "up."
		//
		//  Zero any switches that didn't change from the previous to current state.
		//
		if ((m_current4way & (UP_BIT | DOWN_BIT)) &&
			(m_current4way & (LEFT_BIT | RIGHT_BIT)))
		{
			m_current4way ^= m_current4way & m_previous;
		}

		//
		//  If we are still pointing at a diagonal, we are in an indeterminant state.
		//
		//  This could happen if the player moved the joystick from the idle position directly
		//  to a diagonal, or from one diagonal directly to an extreme diagonal.
		//
		//  The chances of this happening with a keyboard are slim, but we still need to
		//  constrain this case. Let's pick the horizontal axis.
		//
		if ((m_current4way & (UP_BIT | DOWN_BIT)) &&
			(m_current4way & (LEFT_BIT | RIGHT_BIT)))
		{
			m_current4way &= ~(UP_BIT | DOWN_BIT);
		}
	}
}



//**************************************************************************
//  I/O PORT CONDITION
//**************************************************************************

//-------------------------------------------------
//  eval - evaluate condition
//-------------------------------------------------

bool ioport_condition::eval() const
{
	// always condition is always true
	if (m_condition == ALWAYS)
		return true;

	// otherwise, read the referenced port and switch off the condition type
	ioport_value condvalue = m_port->read();
	switch (m_condition)
	{
		case ALWAYS:            return true;
		case EQUALS:            return ((condvalue & m_mask) == m_value);
		case NOTEQUALS:         return ((condvalue & m_mask) != m_value);
		case GREATERTHAN:       return ((condvalue & m_mask) > m_value);
		case NOTGREATERTHAN:    return ((condvalue & m_mask) <= m_value);
		case LESSTHAN:          return ((condvalue & m_mask) < m_value);
		case NOTLESSTHAN:       return ((condvalue & m_mask) >= m_value);
	}
	return true;
}


//-------------------------------------------------
//  initialize - create the live state
//-------------------------------------------------

void ioport_condition::initialize(device_t &device)
{
	if (m_tag != nullptr)
		m_port = device.ioport(m_tag);
}



//**************************************************************************
//  I/O PORT SETTING
//**************************************************************************

//-------------------------------------------------
//  ioport_setting - constructor
//-------------------------------------------------

ioport_setting::ioport_setting(ioport_field &field, ioport_value _value, const char *_name)
	: m_next(nullptr),
		m_field(field),
		m_value(_value),
		m_name(_name)
{
}



//**************************************************************************
//  I/O PORT DIP LOCATION
//**************************************************************************

//-------------------------------------------------
//  ioport_diplocation - constructor
//-------------------------------------------------

ioport_diplocation::ioport_diplocation(const char *name, u8 swnum, bool invert)
	: m_next(nullptr),
		m_name(name),
		m_number(swnum),
		m_invert(invert)
{
}



//**************************************************************************
//  I/O PORT FIELD
//**************************************************************************

//-------------------------------------------------
//  ioport_field - constructor
//-------------------------------------------------

ioport_field::ioport_field(ioport_port &port, ioport_type type, ioport_value defvalue, ioport_value maskbits, const char *name)
	: m_next(nullptr),
		m_port(port),
		m_modcount(port.modcount()),
		m_mask(maskbits),
		m_defvalue(defvalue & maskbits),
		m_type(type),
		m_player(0),
		m_flags(0),
		m_impulse(0),
		m_name(name),
		m_read(port.device()),
		m_write(port.device()),
		m_write_param(0),
		m_digital_value(false),
		m_min(0),
		m_max(maskbits),
		m_sensitivity(0),
		m_delta(0),
		m_centerdelta(0),
		m_crosshair_axis(CROSSHAIR_AXIS_NONE),
		m_crosshair_scale(1.0),
		m_crosshair_offset(0),
		m_crosshair_altaxis(0),
		m_crosshair_mapper(port.device()),
		m_full_turn_count(0),
		m_remap_table(nullptr),
		m_way(0)
{
	// reset sequences and chars
	for (input_seq_type seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; ++seqtype)
		m_seq[seqtype].set_default();

	for (int i = 0; i < ARRAY_LENGTH(m_chars); i++)
		std::fill(std::begin(m_chars[i]), std::end(m_chars[i]), char32_t(0));

	// for DIP switches and configs, look for a default value from the owner
	if (type == IPT_DIPSWITCH || type == IPT_CONFIG)
	{
		const input_device_default *def = device().input_ports_defaults();
		if (def != nullptr)
		{
			const char *fulltag = port.tag();
			for ( ; def->tag != nullptr; def++)
				if (device().subtag(def->tag) == fulltag && def->mask == m_mask)
					m_defvalue = def->defvalue & m_mask;
		}

		m_flags |= FIELD_FLAG_TOGGLE;
	}
}

void ioport_field::set_value(ioport_value value)
{
	m_digital_value = value != 0;
}


//-------------------------------------------------
//  ~ioport_field - destructor
//-------------------------------------------------

ioport_field::~ioport_field()
{
}


//-------------------------------------------------
//  name - return the field name for a given input
//  field (this must never return nullptr)
//-------------------------------------------------

const char *ioport_field::name() const
{
	// if we have a non-default name, use that
	if (m_live != nullptr && !m_live->name.empty())
		return m_live->name.c_str();
	if (m_name != nullptr)
		return m_name;

	// otherwise, return the name associated with the type
	return manager().type_name(m_type, m_player);
}


//-------------------------------------------------
//  seq - return the live input sequence for the
//  given input field
//-------------------------------------------------

const input_seq &ioport_field::seq(input_seq_type seqtype) const
{
	// if no live state, return default
	if (m_live == nullptr)
		return defseq(seqtype);

	// if the sequence is the special default code, return the expanded default value
	if (m_live->seq[seqtype].is_default())
		return manager().type_seq(m_type, m_player, seqtype);

	// otherwise, return the sequence as-is
	return m_live->seq[seqtype];
}


//-------------------------------------------------
//  defseq - return the default input sequence for
//  the given input field
//-------------------------------------------------

const input_seq &ioport_field::defseq(input_seq_type seqtype) const
{
	// if the sequence is the special default code, return the expanded default value
	if (m_seq[seqtype].is_default())
		return manager().type_seq(m_type, m_player, seqtype);

	// otherwise, return the sequence as-is
	return m_seq[seqtype];
}


//-------------------------------------------------
//  set_defseq - dynamically alter the default
//  input sequence for the given input field
//-------------------------------------------------

void ioport_field::set_defseq(input_seq_type seqtype, const input_seq &newseq)
{
	const bool was_changed = seq(seqtype) != defseq(seqtype);

	// set the new sequence
	m_seq[seqtype] = newseq;

	// also update live state unless previously customized
	if (m_live != nullptr && !was_changed)
		m_live->seq[seqtype] = newseq;
}


//-------------------------------------------------
//  type_class - return the type class for this
//  field
//-------------------------------------------------

ioport_type_class ioport_field::type_class() const
{
	// inputs associated with specific players
	ioport_group group = manager().type_group(m_type, m_player);
	if (group >= IPG_PLAYER1 && group <= IPG_PLAYER10)
		return INPUT_CLASS_CONTROLLER;

	// keys (names derived from character codes)
	if (m_type == IPT_KEYPAD || m_type == IPT_KEYBOARD)
		return INPUT_CLASS_KEYBOARD;

	// configuration settings (specific names required)
	if (m_type == IPT_CONFIG)
		return INPUT_CLASS_CONFIG;

	// DIP switches (specific names required)
	if (m_type == IPT_DIPSWITCH)
		return INPUT_CLASS_DIPSWITCH;

	// miscellaneous non-player inputs (named and user-mappable)
	if (group == IPG_OTHER || (group == IPG_INVALID && m_name != nullptr))
		return INPUT_CLASS_MISC;

	// internal inputs (these may be anonymous)
	return INPUT_CLASS_INTERNAL;
}


//-------------------------------------------------
//  keyboard_codes - accesses a particular keyboard
//  code list
//-------------------------------------------------

std::vector<char32_t> ioport_field::keyboard_codes(int which) const
{
	if (which >= ARRAY_LENGTH(m_chars))
		throw emu_fatalerror("Tried to access keyboard_code with out-of-range index %d\n", which);

	std::vector<char32_t> result;
	for (int i = 0; i < ARRAY_LENGTH(m_chars[which]) && m_chars[which][i] != 0; i++)
		result.push_back(m_chars[which][i]);

	return result;
}


//-------------------------------------------------
//  key_name - returns the name of a specific key
//-------------------------------------------------

std::string ioport_field::key_name(int which) const
{
	std::vector<char32_t> codes = keyboard_codes(which);
	char32_t ch = codes.empty() ? 0 : codes[0];

	// attempt to get the string from the character info table
	switch (ch)
	{
	case 8: return "Backspace";
	case 9: return "Tab";
	case 12: return "Clear";
	case 13: return "Enter";
	case 27: return "Esc";
	case 32: return "Space";
	case UCHAR_SHIFT_1: return "Shift";
	case UCHAR_SHIFT_2: return "Ctrl";
	case UCHAR_MAMEKEY(ESC): return "Esc";
	case UCHAR_MAMEKEY(INSERT): return "Insert";
	case UCHAR_MAMEKEY(DEL): return "Delete";
	case UCHAR_MAMEKEY(HOME): return "Home";
	case UCHAR_MAMEKEY(END): return "End";
	case UCHAR_MAMEKEY(PGUP): return "Page Up";
	case UCHAR_MAMEKEY(PGDN): return "Page Down";
	case UCHAR_MAMEKEY(LEFT): return "Cursor Left";
	case UCHAR_MAMEKEY(RIGHT): return "Cursor Right";
	case UCHAR_MAMEKEY(UP): return "Cursor Up";
	case UCHAR_MAMEKEY(DOWN): return "Cursor Down";
	case UCHAR_MAMEKEY(SLASH_PAD): return "Keypad /";
	case UCHAR_MAMEKEY(ASTERISK): return "Keypad *";
	case UCHAR_MAMEKEY(MINUS_PAD): return "Keypad -";
	case UCHAR_MAMEKEY(PLUS_PAD): return "Keypad +";
	case UCHAR_MAMEKEY(DEL_PAD): return "Keypad .";
	case UCHAR_MAMEKEY(ENTER_PAD): return "Keypad Enter";
	case UCHAR_MAMEKEY(BS_PAD): return "Keypad Backspace";
	case UCHAR_MAMEKEY(TAB_PAD): return "Keypad Tab";
	case UCHAR_MAMEKEY(00_PAD): return "Keypad 00";
	case UCHAR_MAMEKEY(000_PAD): return "Keypad 000";
	case UCHAR_MAMEKEY(COMMA_PAD): return "Keypad ,";
	case UCHAR_MAMEKEY(EQUALS_PAD): return "Keypad =";
	case UCHAR_MAMEKEY(PRTSCR): return "Print Screen";
	case UCHAR_MAMEKEY(PAUSE): return "Pause";
	case UCHAR_MAMEKEY(LSHIFT): return "Left Shift";
	case UCHAR_MAMEKEY(RSHIFT): return "Right Shift";
	case UCHAR_MAMEKEY(LCONTROL): return "Left Ctrl";
	case UCHAR_MAMEKEY(RCONTROL): return "Right Ctrl";
	case UCHAR_MAMEKEY(LALT): return "Left Alt";
	case UCHAR_MAMEKEY(RALT): return "Right Alt";
	case UCHAR_MAMEKEY(SCRLOCK): return "Scroll Lock";
	case UCHAR_MAMEKEY(NUMLOCK): return "Num Lock";
	case UCHAR_MAMEKEY(CAPSLOCK): return "Caps Lock";
	case UCHAR_MAMEKEY(LWIN): return "Left Win";
	case UCHAR_MAMEKEY(RWIN): return "Right Win";
	case UCHAR_MAMEKEY(MENU): return "Menu";
	case UCHAR_MAMEKEY(CANCEL): return "Break";
	default: break;
	}

	// handle function keys
	if (ch >= UCHAR_MAMEKEY(F1) && ch <= UCHAR_MAMEKEY(F20))
		return util::string_format("F%d", ch - UCHAR_MAMEKEY(F1) + 1);

	// handle 0-9 on numeric keypad
	if (ch >= UCHAR_MAMEKEY(0_PAD) && ch <= UCHAR_MAMEKEY(9_PAD))
		return util::string_format("Keypad %d", ch - UCHAR_MAMEKEY(0_PAD));

	// if that doesn't work, convert to UTF-8
	if (ch > 0x7F || isprint(ch))
		return utf8_from_uchar(ch);

	// otherwise, opt for question marks
	return "???";
}


//-------------------------------------------------
//  get_user_settings - return the current
//  settings for the given input field
//-------------------------------------------------

void ioport_field::get_user_settings(user_settings &settings)
{
	// zap the entire structure
	memset(&settings, 0, sizeof(settings));

	// copy the basics
	for (input_seq_type seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; ++seqtype)
		settings.seq[seqtype] = seq(seqtype);

	// if there's a list of settings or we're an adjuster, copy the current value
	if (!m_settinglist.empty() || m_type == IPT_ADJUSTER)
		settings.value = m_live->value;

	if (m_live->analog != nullptr)
	{
		// if there's analog data, extract the analog settings
		settings.sensitivity = m_live->analog->sensitivity();
		settings.delta = m_live->analog->delta();
		settings.centerdelta = m_live->analog->centerdelta();
		settings.reverse = m_live->analog->reverse();
	}
	else
	{
		// non-analog settings
		settings.toggle = m_live->toggle;
	}
}


//-------------------------------------------------
//  set_user_settings - modify the current
//  settings for the given input field
//-------------------------------------------------

void ioport_field::set_user_settings(const user_settings &settings)
{
	// copy the basics
	for (input_seq_type seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; ++seqtype)
	{
		const input_seq &defseq = manager().type_seq(m_type, m_player, input_seq_type(seqtype));
		if (defseq == settings.seq[seqtype])
			m_live->seq[seqtype].set_default();
		else
			m_live->seq[seqtype] = settings.seq[seqtype];
	}

	// if there's a list of settings or we're an adjuster, copy the current value
	if (!m_settinglist.empty() || m_type == IPT_ADJUSTER)
		m_live->value = settings.value;

	if (m_live->analog != nullptr)
	{
		// if there's analog data, extract the analog settings
		m_live->analog->m_sensitivity = settings.sensitivity;
		m_live->analog->m_delta = settings.delta;
		m_live->analog->m_centerdelta = settings.centerdelta;
		m_live->analog->m_reverse = settings.reverse;
	}
	else
	{
		// non-analog settings
		m_live->toggle = settings.toggle;
	}
}


//-------------------------------------------------
//  setting_name - return the expanded setting
//  name for a field
//-------------------------------------------------

const char *ioport_field::setting_name() const
{
	// only makes sense if we have settings
	assert(!m_settinglist.empty());

	// scan the list of settings looking for a match on the current value
	for (ioport_setting &setting : m_settinglist)
		if (setting.enabled())
			if (setting.value() == m_live->value)
				return setting.name();

	return "INVALID";
}


//-------------------------------------------------
//  has_previous_setting - return true if the
//  given field has a "previous" setting
//-------------------------------------------------

bool ioport_field::has_previous_setting() const
{
	// only makes sense if we have settings
	assert(!m_settinglist.empty());

	// scan the list of settings looking for a match on the current value
	for (ioport_setting &setting : m_settinglist)
		if (setting.enabled())
			return (setting.value() != m_live->value);

	return false;
}


//-------------------------------------------------
//  select_previous_setting - select the previous
//  item for a DIP switch or configuration field
//-------------------------------------------------

void ioport_field::select_previous_setting()
{
	// only makes sense if we have settings
	assert(!m_settinglist.empty());

	// scan the list of settings looking for a match on the current value
	ioport_setting *prevsetting = nullptr;
	bool found_match = false;
	for (ioport_setting &setting : m_settinglist)
		if (setting.enabled())
		{
			if (setting.value() == m_live->value)
			{
				found_match = true;
				if (prevsetting != nullptr)
					break;
			}
			prevsetting = &setting;
		}

	// if we didn't find a matching value, select the first
	if (!found_match)
	{
		for (prevsetting = m_settinglist.first(); prevsetting != nullptr; prevsetting = prevsetting->next())
			if (prevsetting->enabled())
				break;
	}

	// update the value to the previous one
	if (prevsetting != nullptr)
		m_live->value = prevsetting->value();
}


//-------------------------------------------------
//  has_next_setting - return true if the given
//  field has a "next" setting
//-------------------------------------------------

bool ioport_field::has_next_setting() const
{
	// only makes sense if we have settings
	assert(!m_settinglist.empty());

	// scan the list of settings looking for a match on the current value
	bool found = false;
	for (ioport_setting &setting : m_settinglist)
		if (setting.enabled())
		{
			if (found)
				return true;
			if (setting.value() == m_live->value)
				found = true;
		}

	return false;
}


//-------------------------------------------------
//  select_next_setting - select the next item for
//  a DIP switch or configuration field
//-------------------------------------------------

void ioport_field::select_next_setting()
{
	// only makes sense if we have settings
	assert(!m_settinglist.empty());

	// scan the list of settings looking for a match on the current value
	ioport_setting *nextsetting = nullptr;
	ioport_setting *setting;
	for (setting = m_settinglist.first(); setting != nullptr; setting = setting->next())
		if (setting->enabled())
			if (setting->value() == m_live->value)
				break;

	// if we found one, scan forward for the next valid one
	if (setting != nullptr)
		for (nextsetting = setting->next(); nextsetting != nullptr; nextsetting = nextsetting->next())
			if (nextsetting->enabled())
				break;

	// if we hit the end, search from the beginning
	if (nextsetting == nullptr)
		for (nextsetting = m_settinglist.first(); nextsetting != nullptr; nextsetting = nextsetting->next())
			if (nextsetting->enabled())
				break;

	// update the value to the previous one
	if (nextsetting != nullptr)
		m_live->value = nextsetting->value();
}


//-------------------------------------------------
//  frame_update_digital - get the state of a
//  digital field
//-------------------------------------------------

void ioport_field::frame_update(ioport_value &result)
{
	// skip if not enabled
	if (!enabled())
		return;

	// handle analog inputs first
	if (m_live->analog != nullptr)
	{
		m_live->analog->frame_update(machine());
		return;
	}

	// if UI is active, ignore digital inputs
	if (machine().ui().is_menu_active())
		return;

	// if user input is locked out here, bail
	if (m_live->lockout)
	{
		// use just the digital value
		if (m_digital_value)
			result |= m_mask;
		return;
	}

	// if the state changed, look for switch down/switch up
	bool curstate = m_digital_value || machine().input().seq_pressed(seq());
	bool changed = false;
	if (curstate != m_live->last)
	{
		m_live->last = curstate;
		changed = true;
	}

	// coin impulse option
	int effective_impulse = m_impulse;
	int impulse_option_val = machine().options().coin_impulse();
	if (impulse_option_val != 0)
	{
		if (impulse_option_val < 0)
			effective_impulse = 0;
		else if ((m_type >= IPT_COIN1 && m_type <= IPT_COIN12) || m_impulse != 0)
			effective_impulse = impulse_option_val;
	}

	// if this is a switch-down event, handle impulse and toggle
	if (changed && curstate)
	{
		// impulse controls: reset the impulse counter
		if (effective_impulse != 0 && m_live->impulse == 0)
			m_live->impulse = effective_impulse;

		// toggle controls: flip the toggle state or advance to the next setting
		if (m_live->toggle)
		{
			if (m_settinglist.count() == 0)
				m_live->value ^= m_mask;
			else
				select_next_setting();
		}
	}

	// update the current state with the impulse state
	if (effective_impulse != 0)
	{
		curstate = (m_live->impulse != 0);
		if (curstate)
			m_live->impulse--;
	}

	// for toggle switches, the current value is folded into the port's default value
	// so we always return false here
	if (m_live->toggle)
		curstate = false;

	// additional logic to restrict digital joysticks
	if (curstate && !m_digital_value && m_live->joystick != nullptr && m_way != 16 && !machine().options().joystick_contradictory())
	{
		u8 mask = (m_way == 4) ? m_live->joystick->current4way() : m_live->joystick->current();
		if (!(mask & (1 << m_live->joydir)))
			curstate = false;
	}

	// skip locked-out coin inputs
	if (curstate && m_type >= IPT_COIN1 && m_type <= IPT_COIN12 && machine().bookkeeping().coin_lockout_get_state(m_type - IPT_COIN1))
	{
		bool verbose = machine().options().verbose();
#ifdef MAME_DEBUG
		verbose = true;
#endif
		if (machine().options().coin_lockout())
		{
			if (verbose)
				machine().ui().popup_time(3, "Coinlock disabled %s.", name());
			curstate = false;
		}
		else
			if (verbose)
				machine().ui().popup_time(3, "Coinlock disabled, but broken through %s.", name());
	}

	// if we're active, set the appropriate bits in the digital state
	if (curstate)
		result |= m_mask;
}


//-------------------------------------------------
//  crosshair_position - compute the crosshair
//  position
//-------------------------------------------------

void ioport_field::crosshair_position(float &x, float &y, bool &gotx, bool &goty)
{
	double value = m_live->analog->crosshair_read();

	// apply the scale and offset
	if (m_crosshair_scale < 0)
		value = -(1.0 - value) * m_crosshair_scale;
	else
		value *= m_crosshair_scale;
	value += m_crosshair_offset;

	// apply custom mapping if necessary
	if (!m_crosshair_mapper.isnull())
		value = m_crosshair_mapper(value);

	// handle X axis
	if (m_crosshair_axis == CROSSHAIR_AXIS_X)
	{
		x = value;
		gotx = true;
		if (m_crosshair_altaxis != 0)
		{
			y = m_crosshair_altaxis;
			goty = true;
		}
	}

	// handle Y axis
	else
	{
		y = value;
		goty = true;
		if (m_crosshair_altaxis != 0)
		{
			x = m_crosshair_altaxis;
			gotx = true;
		}
	}
}


//-------------------------------------------------
//  expand_diplocation - expand a string-based
//  DIP location into a linked list of
//  descriptions
//-------------------------------------------------

void ioport_field::expand_diplocation(const char *location, std::string &errorbuf)
{
	// if nothing present, bail
	if (location == nullptr)
		return;

	m_diploclist.reset();

	// parse the string
	std::string name; // Don't move this variable inside the loop, lastname's lifetime depends on it being outside
	const char *lastname = nullptr;
	const char *curentry = location;
	int entries = 0;
	while (*curentry != 0)
	{
		// find the end of this entry
		const char *comma = strchr(curentry, ',');
		if (comma == nullptr)
			comma = curentry + strlen(curentry);

		// extract it to tempbuf
		std::string tempstr;
		tempstr.assign(curentry, comma - curentry);

		// first extract the switch name if present
		const char *number = tempstr.c_str();
		const char *colon = strchr(tempstr.c_str(), ':');

		// allocate and copy the name if it is present
		if (colon != nullptr)
		{
			lastname = name.assign(number, colon - number).c_str();
			number = colon + 1;
		}

		// otherwise, just copy the last name
		else
		{
			if (lastname == nullptr)
			{
				errorbuf.append(string_format("Switch location '%s' missing switch name!\n", location));
				lastname = (char *)"UNK";
			}
			name.assign(lastname);
		}

		// if the number is preceded by a '!' it's active high
		bool invert = false;
		if (*number == '!')
		{
			invert = true;
			number++;
		}

		// now scan the switch number
		int swnum = -1;
		if (sscanf(number, "%d", &swnum) != 1)
			errorbuf.append(string_format("Switch location '%s' has invalid format!\n", location));

		// allocate a new entry
		m_diploclist.append(*global_alloc(ioport_diplocation(name.c_str(), swnum, invert)));
		entries++;

		// advance to the next item
		curentry = comma;
		if (*curentry != 0)
			curentry++;
	}

	// then verify the number of bits in the mask matches
	ioport_value temp;
	int bits;
	for (bits = 0, temp = m_mask; temp != 0 && bits < 32; bits++)
		temp &= temp - 1;
	if (bits != entries)
		errorbuf.append(string_format("Switch location '%s' does not describe enough bits for mask %X\n", location, m_mask));
}


//-------------------------------------------------
//  init_live_state - create live state structures
//-------------------------------------------------

void ioport_field::init_live_state(analog_field *analog)
{
	// resolve callbacks
	m_read.resolve();
	m_write.resolve();
	m_crosshair_mapper.resolve();

	// allocate live state
	m_live = std::make_unique<ioport_field_live>(*this, analog);

	m_condition.initialize(device());

	for (ioport_setting &setting : m_settinglist)
		setting.condition().initialize(setting.device());
}



//**************************************************************************
//  I/O PORT FIELD LIVE
//**************************************************************************

//-------------------------------------------------
//  ioport_field_live - constructor
//-------------------------------------------------

ioport_field_live::ioport_field_live(ioport_field &field, analog_field *analog)
	: analog(analog),
		joystick(nullptr),
		value(field.defvalue()),
		impulse(0),
		last(0),
		toggle(field.toggle()),
		joydir(digital_joystick::JOYDIR_COUNT),
		lockout(false)
{
	// fill in the basic values
	for (input_seq_type seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; ++seqtype)
		seq[seqtype] = field.defseq_unresolved(seqtype);

	// if this is a digital joystick field, make a note of it
	if (field.is_digital_joystick())
	{
		joystick = &field.manager().digjoystick(field.player(), (field.type() - (IPT_DIGITAL_JOYSTICK_FIRST + 1)) / 4);
		joydir = joystick->add_axis(field);
	}

	// Name keyboard key names
	if (field.type_class() == INPUT_CLASS_KEYBOARD && field.specific_name() == nullptr)
	{
		// loop through each character on the field
		for (int which = 0; which < 4; which++)
		{
			std::vector<char32_t> const codes = field.keyboard_codes(which);
			if (codes.empty())
				break;
			name.append(string_format("%-*s ", std::max(SPACE_COUNT - 1, 0), field.key_name(which)));
		}

		// trim extra spaces
		strtrimspace(name);

		// special case
		if (name.empty())
			name.assign("Unnamed Key");
	}
}



//**************************************************************************
//  I/O PORT
//**************************************************************************

//-------------------------------------------------
//  ioport_port - constructor
//-------------------------------------------------

ioport_port::ioport_port(device_t &owner, const char *tag)
	: m_next(nullptr),
		m_device(owner),
		m_tag(tag),
		m_modcount(0),
		m_active(0)
{
}


//-------------------------------------------------
//  ~ioport_port - destructor
//-------------------------------------------------

ioport_port::~ioport_port()
{
}


//-------------------------------------------------
//  machine - return a reference to the running
//  machine
//-------------------------------------------------

running_machine &ioport_port::machine() const
{
	return m_device.machine();
}


//-------------------------------------------------
//  manager - return a reference to the
//  ioport_manager on the running machine
//-------------------------------------------------

ioport_manager &ioport_port::manager() const
{
	return machine().ioport();
}


//-------------------------------------------------
//  field - return a pointer to the first field
//  that intersects the given mask
//-------------------------------------------------

ioport_field *ioport_port::field(ioport_value mask) const
{
	// if we got the port, look for the field
	for (ioport_field &field : fields())
		if ((field.mask() & mask) != 0 && field.enabled())
			return &field;
	return nullptr;
}


//-------------------------------------------------
//  read - return the value of an I/O port
//-------------------------------------------------

ioport_value ioport_port::read()
{
	if (!manager().safe_to_read())
		throw emu_fatalerror("Input ports cannot be read at init time!");

	// start with the digital state
	ioport_value result = m_live->digital;

	// insert dynamic read values
	for (dynamic_field &dynfield : m_live->readlist)
		dynfield.read(result);

	// apply active high/low state to digital and dynamic read inputs
	result ^= m_live->defvalue;

	// insert analog portions
	for (analog_field &analog : m_live->analoglist)
		analog.read(result);

	return result;
}


//-------------------------------------------------
//  write - write a value to a port
//-------------------------------------------------

void ioport_port::write(ioport_value data, ioport_value mem_mask)
{
	// call device line write handlers
	COMBINE_DATA(&m_live->outputvalue);
	for (dynamic_field &dynfield : m_live->writelist)
		if (dynfield.field().type() == IPT_OUTPUT)
			dynfield.write(m_live->outputvalue ^ dynfield.field().defvalue());
}


//-------------------------------------------------
//  frame_update - once/frame update
//-------------------------------------------------

void ioport_port::frame_update()
{
	// start with 0 values for the digital bits
	m_live->digital = 0;

	// now loop back and modify based on the inputs
	for (ioport_field &field : fields())
		field.frame_update(m_live->digital);
}


//-------------------------------------------------
//  collapse_fields - remove any fields that are
//  wholly overlapped by other fields
//-------------------------------------------------

void ioport_port::collapse_fields(std::string &errorbuf)
{
	ioport_value maskbits = 0;
	int lastmodcount = -1;

	// remove the whole list and start from scratch
	ioport_field *field = m_fieldlist.detach_all();
	while (field != nullptr)
	{
		// if this modcount doesn't match, reset
		if (field->modcount() != lastmodcount)
		{
			lastmodcount = field->modcount();
			maskbits = 0;
		}

		// reinsert this field
		ioport_field *current = field;
		field = field->next();
		insert_field(*current, maskbits, errorbuf);
	}
}


//-------------------------------------------------
//  insert_field - insert a new field, checking
//  for errors
//-------------------------------------------------

void ioport_port::insert_field(ioport_field &newfield, ioport_value &disallowedbits, std::string &errorbuf)
{
	// verify against the disallowed bits, but only if we are condition-free
	if (newfield.condition().none())
	{
		if ((newfield.mask() & disallowedbits) != 0)
			errorbuf.append(string_format("INPUT_TOKEN_FIELD specifies duplicate port bits (port=%s mask=%X)\n", tag(), newfield.mask()));
		disallowedbits |= newfield.mask();
	}

	// first modify/nuke any entries that intersect our maskbits
	ioport_field *nextfield;
	for (ioport_field *field = m_fieldlist.first(); field != nullptr; field = nextfield)
	{
		nextfield = field->next();
		if ((field->mask() & newfield.mask()) != 0 &&
			(newfield.condition().none() || field->condition().none() || field->condition() == newfield.condition()))
		{
			// reduce the mask of the field we found
			field->reduce_mask(newfield.mask());

			// if the new entry fully overrides the previous one, we nuke
			if (INPUT_PORT_OVERRIDE_FULLY_NUKES_PREVIOUS || field->mask() == 0)
				m_fieldlist.remove(*field);
		}
	}

	// make a mask of just the low bit
	ioport_value lowbit = (newfield.mask() ^ (newfield.mask() - 1)) & newfield.mask();

	// scan forward to find where to insert ourselves
	ioport_field *field;
	for (field = m_fieldlist.first(); field != nullptr; field = field->next())
		if (field->mask() > lowbit)
			break;

	// insert it into the list
	m_fieldlist.insert_before(newfield, field);
}


//-------------------------------------------------
//  init_live_state - create the live state
//-------------------------------------------------

void ioport_port::init_live_state()
{
	m_live = std::make_unique<ioport_port_live>(*this);
}


//-------------------------------------------------
//  update_defvalue - force an update to the input
//  port values based on current conditions
//-------------------------------------------------

void ioport_port::update_defvalue(bool flush_defaults)
{
	// only clear on the first pass
	if (flush_defaults)
		m_live->defvalue = 0;

	// recompute the default value for the entire port
	for (ioport_field &field : m_fieldlist)
		if (field.enabled())
			m_live->defvalue = (m_live->defvalue & ~field.mask()) | (field.live().value & field.mask());
}



//**************************************************************************
//  I/O PORT LIVE STATE
//**************************************************************************

//-------------------------------------------------
//  ioport_port_live - constructor
//-------------------------------------------------

ioport_port_live::ioport_port_live(ioport_port &port)
	: defvalue(0),
		digital(0),
		outputvalue(0)
{
	// iterate over fields
	for (ioport_field &field : port.fields())
	{
		// allocate analog state if it's analog
		analog_field *analog = nullptr;
		if (field.is_analog())
			analog = &analoglist.append(*global_alloc(analog_field(field)));

		// allocate a dynamic field for reading
		if (field.has_dynamic_read())
			readlist.append(*global_alloc(dynamic_field(field)));

		// allocate a dynamic field for writing
		if (field.has_dynamic_write())
			writelist.append(*global_alloc(dynamic_field(field)));

		// let the field initialize its live state
		field.init_live_state(analog);
	}
}



//**************************************************************************
//  I/O PORT MANAGER
//**************************************************************************

//-------------------------------------------------
//  ioport_manager - constructor
//-------------------------------------------------

ioport_manager::ioport_manager(running_machine &machine)
	: m_machine(machine),
		m_safe_to_read(false),
		m_last_frame_time(attotime::zero),
		m_last_delta_nsec(0),
		m_record_file(machine.options().input_directory(), OPEN_FLAG_WRITE | OPEN_FLAG_CREATE | OPEN_FLAG_CREATE_PATHS),
		m_playback_file(machine.options().input_directory(), OPEN_FLAG_READ),
		m_playback_accumulated_speed(0),
		m_playback_accumulated_frames(0),
		m_timecode_file(machine.options().input_directory(), OPEN_FLAG_WRITE | OPEN_FLAG_CREATE | OPEN_FLAG_CREATE_PATHS),
		m_timecode_count(0),
		m_timecode_last_time(attotime::zero)
{
	memset(m_type_to_entry, 0, sizeof(m_type_to_entry));
}


//-------------------------------------------------
//  initialize - walk the configured ports and
//  create live state information
//-------------------------------------------------

time_t ioport_manager::initialize()
{
	// add an exit callback and a frame callback
	machine().add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(&ioport_manager::exit, this));
	machine().add_notifier(MACHINE_NOTIFY_FRAME, machine_notify_delegate(&ioport_manager::frame_update_callback, this));

	// initialize the default port info from the OSD
	init_port_types();

	// if we have a token list, proceed
	device_iterator iter(machine().root_device());
	for (device_t &device : iter)
	{
		std::string errors;
		m_portlist.append(device, errors);
		if (!errors.empty())
			osd_printf_error("Input port errors:\n%s", errors);
	}

	// renumber player numbers for controller ports
	int player_offset = 0;
	for (device_t &device : iter)
	{
		int players = 0;
		for (auto &port : m_portlist)
		{
			if (&port.second->device() == &device)
			{
				for (ioport_field &field : port.second->fields())
					if (field.type_class()==INPUT_CLASS_CONTROLLER)
					{
						if (players < field.player() + 1) players = field.player() + 1;
						field.set_player(field.player() + player_offset);
					}
			}
		}
		player_offset += players;
	}

	// allocate live structures to mirror the configuration
	for (auto &port : m_portlist)
		port.second->init_live_state();

	// handle autoselection of devices
	init_autoselect_devices(IPT_AD_STICK_X,  IPT_AD_STICK_Y,   IPT_AD_STICK_Z, OPTION_ADSTICK_DEVICE,    "analog joystick");
	init_autoselect_devices(IPT_PADDLE,      IPT_PADDLE_V,     0,              OPTION_PADDLE_DEVICE,     "paddle");
	init_autoselect_devices(IPT_PEDAL,       IPT_PEDAL2,       IPT_PEDAL3,     OPTION_PEDAL_DEVICE,      "pedal");
	init_autoselect_devices(IPT_LIGHTGUN_X,  IPT_LIGHTGUN_Y,   0,              OPTION_LIGHTGUN_DEVICE,   "lightgun");
	init_autoselect_devices(IPT_POSITIONAL,  IPT_POSITIONAL_V, 0,              OPTION_POSITIONAL_DEVICE, "positional");
	init_autoselect_devices(IPT_DIAL,        IPT_DIAL_V,       0,              OPTION_DIAL_DEVICE,       "dial");
	init_autoselect_devices(IPT_TRACKBALL_X, IPT_TRACKBALL_Y,  0,              OPTION_TRACKBALL_DEVICE,  "trackball");
	init_autoselect_devices(IPT_MOUSE_X,     IPT_MOUSE_Y,      0,              OPTION_MOUSE_DEVICE,      "mouse");

	// look for 4-way diagonal joysticks and change the default map if we find any
	const char *joystick_map_default = machine().options().joystick_map();
	if (joystick_map_default[0] == 0 || strcmp(joystick_map_default, "auto") == 0)
		for (auto &port : m_portlist)
			for (ioport_field &field : port.second->fields())
				if (field.live().joystick != nullptr && field.rotated())
				{
					input_class_joystick &devclass = downcast<input_class_joystick &>(machine().input().device_class(DEVICE_CLASS_JOYSTICK));
					devclass.set_global_joystick_map(input_class_joystick::map_4way_diagonal);
					break;
				}

	// initialize natural keyboard
	m_natkeyboard = std::make_unique<natural_keyboard>(machine());

	// register callbacks for when we load configurations
	machine().configuration().config_register("input", config_load_delegate(&ioport_manager::load_config, this), config_save_delegate(&ioport_manager::save_config, this));

	// open playback and record files if specified
	time_t basetime = playback_init();
	record_init();
	timecode_init();
	return basetime;
}


//-------------------------------------------------
//  init_port_types - initialize the default
//  type list
//-------------------------------------------------

void ioport_manager::init_port_types()
{
	// convert the array into a list of type states that can be modified
	construct_core_types(m_typelist);

	// ask the OSD to customize the list
	machine().osd().customize_input_type_list(m_typelist);

	// now iterate over the OSD-modified types
	for (input_type_entry &curtype : m_typelist)
	{
		// first copy all the OSD-updated sequences into our current state
		curtype.restore_default_seq();

		// also make a lookup table mapping type/player to the appropriate type list entry
		m_type_to_entry[curtype.type()][curtype.player()] = &curtype;
	}
}


//-------------------------------------------------
//  init_autoselect_devices - autoselect a single
//  device based on the input port list passed
//  in and the corresponding option
//-------------------------------------------------

void ioport_manager::init_autoselect_devices(int type1, int type2, int type3, const char *option, const char *ananame)
{
	// if nothing specified, ignore the option
	const char *stemp = machine().options().value(option);
	if (stemp[0] == 0 || strcmp(stemp, "none") == 0)
		return;

	// extract valid strings
	input_class *autoenable_class = nullptr;
	for (input_device_class devclass = DEVICE_CLASS_FIRST_VALID; devclass <= DEVICE_CLASS_LAST_VALID; ++devclass)
		if (strcmp(stemp, machine().input().device_class(devclass).name()) == 0)
		{
			autoenable_class = &machine().input().device_class(devclass);
			break;
		}
	if (autoenable_class == nullptr)
	{
		osd_printf_error("Invalid %s value %s; reverting to keyboard\n", option, stemp);
		autoenable_class = &machine().input().device_class(DEVICE_CLASS_KEYBOARD);
	}

	// only scan the list if we haven't already enabled this class of control
	if (!autoenable_class->enabled())
		for (auto &port : m_portlist)
			for (ioport_field &field : port.second->fields())

				// if this port type is in use, apply the autoselect criteria
				if ((type1 != 0 && field.type() == type1) || (type2 != 0 && field.type() == type2) || (type3 != 0 && field.type() == type3))
				{
					osd_printf_verbose("Input: Autoenabling %s due to presence of a %s\n", autoenable_class->name(), ananame);
					autoenable_class->enable();
					break;
				}
}


//-------------------------------------------------
//  exit - exit callback to ensure we clean up
//  and close our files
//-------------------------------------------------

void ioport_manager::exit()
{
	// close any playback or recording files
	playback_end();
	record_end();
	timecode_end();
}


//-------------------------------------------------
//  ~ioport_manager - destructor
//-------------------------------------------------

ioport_manager::~ioport_manager()
{
}


//-------------------------------------------------
//  type_name - return the name for the given
//  type/player
//-------------------------------------------------

const char *ioport_manager::type_name(ioport_type type, u8 player)
{
	// if we have a machine, use the live state and quick lookup
	input_type_entry *entry = m_type_to_entry[type][player];
	if (entry != nullptr && entry->name() != nullptr)
		return entry->name();

	// if we find nothing, return a default string (not a null pointer)
	return "???";
}


//-------------------------------------------------
//  type_group - return the group for the given
//  type/player
//-------------------------------------------------

ioport_group ioport_manager::type_group(ioport_type type, int player)
{
	input_type_entry *entry = m_type_to_entry[type][player];
	if (entry != nullptr)
		return entry->group();

	// if we find nothing, return an invalid group
	return IPG_INVALID;
}


//-------------------------------------------------
//  type_seq - return the input sequence for the
//  given type/player
//-------------------------------------------------

const input_seq &ioport_manager::type_seq(ioport_type type, int player, input_seq_type seqtype)
{
	assert(type >= 0 && type < IPT_COUNT);
	assert(player >= 0 && player < MAX_PLAYERS);

	// if we have a machine, use the live state and quick lookup
	input_type_entry *entry = m_type_to_entry[type][player];
	if (entry != nullptr)
		return entry->seq(seqtype);

	// if we find nothing, return an empty sequence
	return input_seq::empty_seq;
}


//-------------------------------------------------
//  set_type_seq - change the input sequence for
//  the given type/player
//-------------------------------------------------

void ioport_manager::set_type_seq(ioport_type type, int player, input_seq_type seqtype, const input_seq &newseq)
{
	input_type_entry *entry = m_type_to_entry[type][player];
	if (entry != nullptr)
		entry->m_seq[seqtype] = newseq;
}


//-------------------------------------------------
//  type_pressed - return true if the sequence for
//  the given input type/player is pressed
//-------------------------------------------------

bool ioport_manager::type_pressed(ioport_type type, int player)
{
	return machine().input().seq_pressed(type_seq(type, player));
}


//-------------------------------------------------
//  type_class_present - return true if the given
//  ioport_type_class exists in at least one port
//-------------------------------------------------

bool ioport_manager::type_class_present(ioport_type_class inputclass)
{
	for (auto &port : m_portlist)
		for (ioport_field &field : port.second->fields())
			if (field.type_class() == inputclass)
				return true;
	return false;
}


//-------------------------------------------------
//  count_players - counts the number of active
//  players
//-------------------------------------------------

int ioport_manager::count_players() const
{
	int max_player = 0;
	for (auto &port : m_portlist)
		for (ioport_field &field : port.second->fields())
			if (field.type_class() == INPUT_CLASS_CONTROLLER && max_player <= field.player() + 1)
				max_player = field.player() + 1;

	return max_player;
}


//-------------------------------------------------
//  crosshair_position - return the extracted
//  crosshair values for the given player
//-------------------------------------------------

bool ioport_manager::crosshair_position(int player, float &x, float &y)
{
	// read all the lightgun values
	bool gotx = false, goty = false;
	for (auto &port : m_portlist)
		for (ioport_field &field : port.second->fields())
			if (field.player() == player && field.crosshair_axis() != CROSSHAIR_AXIS_NONE && field.enabled())
			{
				field.crosshair_position(x, y, gotx, goty);

				// if we got both, stop
				if (gotx && goty)
					break;
			}

	return (gotx && goty);
}


//-------------------------------------------------
//  frame_update - core logic for per-frame input
//  port updating
//-------------------------------------------------

digital_joystick &ioport_manager::digjoystick(int player, int number)
{
	// find it in the list
	for (digital_joystick &joystick : m_joystick_list)
		if (joystick.player() == player && joystick.number() == number)
			return joystick;

	// create a new one
	return m_joystick_list.append(*global_alloc(digital_joystick(player, number)));
}


//-------------------------------------------------
//  frame_update - callback for once/frame updating
//-------------------------------------------------

void ioport_manager::frame_update_callback()
{
	// if we're paused, don't do anything
	if (!machine().paused())
		frame_update();
}


//-------------------------------------------------
//  frame_update_internal - core logic for
//  per-frame input port updating
//-------------------------------------------------

void ioport_manager::frame_update()
{
	g_profiler.start(PROFILER_INPUT);

	// record/playback information about the current frame
	attotime curtime = machine().time();
	playback_frame(curtime);
	record_frame(curtime);

	// track the duration of the previous frame
	m_last_delta_nsec = (curtime - m_last_frame_time).as_attoseconds() / ATTOSECONDS_PER_NANOSECOND;
	m_last_frame_time = curtime;

	// update the digital joysticks
	for (digital_joystick &joystick : m_joystick_list)
		joystick.frame_update();

	// compute default values for all the ports
	// two passes to catch conditionals properly
	for (auto &port : m_portlist)
		port.second->update_defvalue(true);
	for (auto &port : m_portlist)
		port.second->update_defvalue(false);

	// loop over all input ports
	for (auto &port : m_portlist)
	{
		port.second->frame_update();

		// handle playback/record
		playback_port(*port.second.get());
		record_port(*port.second.get());

		// call device line write handlers
		ioport_value newvalue = port.second->read();
		for (dynamic_field &dynfield : port.second->live().writelist)
			if (dynfield.field().type() != IPT_OUTPUT)
				dynfield.write(newvalue);
	}

	g_profiler.stop();
}


//-------------------------------------------------
//  frame_interpolate - interpolate between two
//  values based on the time between frames
//-------------------------------------------------

s32 ioport_manager::frame_interpolate(s32 oldval, s32 newval)
{
	// if no last delta, just use new value
	if (m_last_delta_nsec == 0)
		return newval;

	// otherwise, interpolate
	attoseconds_t nsec_since_last = (machine().time() - m_last_frame_time).as_attoseconds() / ATTOSECONDS_PER_NANOSECOND;
	return oldval + (s64(newval - oldval) * nsec_since_last / m_last_delta_nsec);
}


//-------------------------------------------------
//  load_config - callback to extract configuration
//  data from the XML nodes
//-------------------------------------------------

void ioport_manager::load_config(config_type cfg_type, util::xml::data_node const *parentnode)
{
	// in the completion phase, we finish the initialization with the final ports
	if (cfg_type == config_type::FINAL)
	{
		m_safe_to_read = true;
		frame_update();
	}

	// early exit if no data to parse
	if (parentnode == nullptr)
		return;

	// iterate over all the remap nodes for controller configs only
	if (cfg_type == config_type::CONTROLLER)
		load_remap_table(parentnode);

	// load device map table for controller configs only
	if (cfg_type == config_type::CONTROLLER)
	{
		std::unique_ptr<devicemap_table_type> devicemap_table = std::make_unique<devicemap_table_type>();
		for (util::xml::data_node const *mapdevice_node = parentnode->get_child("mapdevice"); mapdevice_node != nullptr; mapdevice_node = mapdevice_node->get_next_sibling("mapdevice"))
		{
			const char *devicename = mapdevice_node->get_attribute_string("device", nullptr);
			const char *controllername = mapdevice_node->get_attribute_string("controller", nullptr);
			if (devicename != nullptr && controllername != nullptr)
			{
				devicemap_table->insert(std::make_pair(std::string(devicename), std::string(controllername)));
			}
		}

		// map device to controller if we have a device map
		if (!devicemap_table->empty())
		{
			machine().input().map_device_to_controller(devicemap_table.get());
		}
	}

	// iterate over all the port nodes
	for (util::xml::data_node const *portnode = parentnode->get_child("port"); portnode; portnode = portnode->get_next_sibling("port"))
	{
		// get the basic port info from the attributes
		int player;
		int type = token_to_input_type(portnode->get_attribute_string("type", ""), player);

		// initialize sequences to invalid defaults
		input_seq newseq[SEQ_TYPE_TOTAL];
		for (input_seq_type seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; ++seqtype)
			newseq[seqtype].set(INPUT_CODE_INVALID);

		// loop over new sequences
		for (util::xml::data_node const *seqnode = portnode->get_child("newseq"); seqnode; seqnode = seqnode->get_next_sibling("newseq"))
		{
			// with a valid type, parse out the new sequence
			input_seq_type seqtype = token_to_seq_type(seqnode->get_attribute_string("type", ""));
			if (seqtype != -1 && seqnode->get_value() != nullptr)
			{
				if (strcmp(seqnode->get_value(), "NONE") == 0)
					newseq[seqtype].set();
				else
					machine().input().seq_from_tokens(newseq[seqtype], seqnode->get_value());
			}
		}

		// if we're loading default ports, apply to the defaults
		if (cfg_type != config_type::GAME)
			load_default_config(portnode, type, player, newseq);
		else
			load_game_config(portnode, type, player, newseq);
	}

	// after applying the controller config, push that back into the backup, since that is
	// what we will diff against
	if (cfg_type == config_type::CONTROLLER)
		for (input_type_entry &entry : m_typelist)
			for (input_seq_type seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; ++seqtype)
				entry.defseq(seqtype) = entry.seq(seqtype);
}


//-------------------------------------------------
//  load_remap_table - extract and apply the
//  global remapping table
//-------------------------------------------------

void ioport_manager::load_remap_table(util::xml::data_node const *parentnode)
{
	// count items first so we can allocate
	int count = 0;
	for (util::xml::data_node const *remapnode = parentnode->get_child("remap"); remapnode != nullptr; remapnode = remapnode->get_next_sibling("remap"))
		count++;

	// if we have some, deal with them
	if (count > 0)
	{
		// allocate tables
		std::vector<input_code> oldtable(count);
		std::vector<input_code> newtable(count);

		// build up the remap table
		count = 0;
		for (util::xml::data_node const *remapnode = parentnode->get_child("remap"); remapnode != nullptr; remapnode = remapnode->get_next_sibling("remap"))
		{
			input_code origcode = machine().input().code_from_token(remapnode->get_attribute_string("origcode", ""));
			input_code newcode = machine().input().code_from_token(remapnode->get_attribute_string("newcode", ""));
			if (origcode != INPUT_CODE_INVALID && newcode != INPUT_CODE_INVALID)
			{
				oldtable[count] = origcode;
				newtable[count] = newcode;
				count++;
			}
		}

		// loop over the remapping table, then over default ports, replacing old with new
		for (int remapnum = 0; remapnum < count; remapnum++)
			for (input_type_entry &entry : m_typelist)
				for (input_seq_type seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; ++seqtype)
					entry.m_seq[seqtype].replace(oldtable[remapnum], newtable[remapnum]);
	}
}


//-------------------------------------------------
//  load_default_config - apply configuration
//  data to the default mappings
//-------------------------------------------------

bool ioport_manager::load_default_config(util::xml::data_node const *portnode, int type, int player, const input_seq *newseq)
{
	// find a matching port in the list
	for (input_type_entry &entry : m_typelist)
		if (entry.type() == type && entry.player() == player)
		{
			for (input_seq_type seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; ++seqtype)
				if (newseq[seqtype][0] != INPUT_CODE_INVALID)
					entry.m_seq[seqtype] = newseq[seqtype];
			return true;
		}

	return false;
}


//-------------------------------------------------
//  load_game_config - apply configuration
//  data to the current set of input ports
//-------------------------------------------------

bool ioport_manager::load_game_config(util::xml::data_node const *portnode, int type, int player, const input_seq *newseq)
{
	// read the mask, index, and defvalue attributes
	const char *tag = portnode->get_attribute_string("tag", nullptr);
	ioport_value mask = portnode->get_attribute_int("mask", 0);
	ioport_value defvalue = portnode->get_attribute_int("defvalue", 0);

	// find the port we want; if no tag, search them all
	for (auto &port : m_portlist)
		if (tag == nullptr || strcmp(port.second->tag(), tag) == 0)
			for (ioport_field &field : port.second->fields())

				// find the matching mask and defvalue
				if (field.type() == type && field.player() == player &&
					field.mask() == mask && (field.defvalue() & mask) == (defvalue & mask))
				{
					// if a sequence was specified, copy it in
					for (input_seq_type seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; ++seqtype)
						if (newseq[seqtype][0] != INPUT_CODE_INVALID)
							field.live().seq[seqtype] = newseq[seqtype];

					// fetch configurable attributes
					// for non-analog fields
					if (field.live().analog == nullptr)
					{
						// fetch the value
						field.live().value = portnode->get_attribute_int("value", field.defvalue());

						// fetch yes/no for toggle setting
						const char *togstring = portnode->get_attribute_string("toggle", nullptr);
						if (togstring != nullptr)
							field.live().toggle = (strcmp(togstring, "yes") == 0);
					}

					// for analog fields
					else
					{
						// get base attributes
						field.live().analog->m_delta = portnode->get_attribute_int("keydelta", field.delta());
						field.live().analog->m_centerdelta = portnode->get_attribute_int("centerdelta", field.centerdelta());
						field.live().analog->m_sensitivity = portnode->get_attribute_int("sensitivity", field.sensitivity());

						// fetch yes/no for reverse setting
						const char *revstring = portnode->get_attribute_string("reverse", nullptr);
						if (revstring != nullptr)
							field.live().analog->m_reverse = (strcmp(revstring, "yes") == 0);
					}
					return true;
				}

	return false;
}



//**************************************************************************
//  SETTINGS SAVE
//**************************************************************************

//-------------------------------------------------
//  save_config - config callback for saving input
//  port configuration
//-------------------------------------------------

void ioport_manager::save_config(config_type cfg_type, util::xml::data_node *parentnode)
{
	// if no parentnode, ignore
	if (parentnode == nullptr)
		return;

	// default ports save differently
	if (cfg_type == config_type::DEFAULT)
		save_default_inputs(*parentnode);
	else
		save_game_inputs(*parentnode);
}


//-------------------------------------------------
//  save_sequence - add a node for an input
//  sequence
//-------------------------------------------------

void ioport_manager::save_sequence(util::xml::data_node &parentnode, input_seq_type type, ioport_type porttype, const input_seq &seq)
{
	// get the string for the sequence
	std::string seqstring;
	if (seq.length() == 0)
		seqstring.assign("NONE");
	else
		seqstring = machine().input().seq_to_tokens(seq);

	// add the new node
	util::xml::data_node *const seqnode = parentnode.add_child("newseq", seqstring.c_str());
	if (seqnode != nullptr)
		seqnode->set_attribute("type", seqtypestrings[type]);
}


//-------------------------------------------------
//  save_this_input_field_type - determine if the
//  given port type is worth saving
//-------------------------------------------------

bool ioport_manager::save_this_input_field_type(ioport_type type)
{
	switch (type)
	{
		case IPT_UNUSED:
		case IPT_END:
		case IPT_PORT:
		case IPT_UNKNOWN:
			return false;

		default:
			break;
	}
	return true;
}


//-------------------------------------------------
//  save_default_inputs - add nodes for any default
//  mappings that have changed
//-------------------------------------------------

void ioport_manager::save_default_inputs(util::xml::data_node &parentnode)
{
	// iterate over ports
	for (input_type_entry &entry : m_typelist)
	{
		// only save if this port is a type we save
		if (save_this_input_field_type(entry.type()))
		{
			// see if any of the sequences have changed
			input_seq_type seqtype;
			for (seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; ++seqtype)
				if (entry.seq(seqtype) != entry.defseq(seqtype))
					break;

			// if so, we need to add a node
			if (seqtype < SEQ_TYPE_TOTAL)
			{
				// add a new port node
				util::xml::data_node *const portnode = parentnode.add_child("port", nullptr);
				if (portnode != nullptr)
				{
					// add the port information and attributes
					portnode->set_attribute("type", input_type_to_token(entry.type(), entry.player()).c_str());

					// add only the sequences that have changed from the defaults
					for (input_seq_type type = SEQ_TYPE_STANDARD; type < SEQ_TYPE_TOTAL; ++type)
						if (entry.seq(type) != entry.defseq(type))
							save_sequence(*portnode, type, entry.type(), entry.seq(type));
				}
			}
		}
	}
}


//-------------------------------------------------
//  save_game_inputs - add nodes for any game
//  mappings that have changed
//-------------------------------------------------

void ioport_manager::save_game_inputs(util::xml::data_node &parentnode)
{
	// iterate over ports
	for (auto &port : m_portlist)
		for (ioport_field &field : port.second->fields())
			if (save_this_input_field_type(field.type()))
			{
				// determine if we changed
				bool changed = false;
				for (input_seq_type seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; ++seqtype)
					changed |= (field.seq(seqtype) != field.defseq(seqtype));

				// non-analog changes
				if (!field.is_analog())
				{
					changed |= ((field.live().value & field.mask()) != (field.defvalue() & field.mask()));
					changed |= (field.live().toggle != field.toggle());
				}

				// analog changes
				else
				{
					changed |= (field.live().analog->m_delta != field.delta());
					changed |= (field.live().analog->m_centerdelta != field.centerdelta());
					changed |= (field.live().analog->m_sensitivity != field.sensitivity());
					changed |= (field.live().analog->m_reverse != field.analog_reverse());
				}

				// if we did change, add a new node
				if (changed)
				{
					// add a new port node
					util::xml::data_node *const portnode = parentnode.add_child("port", nullptr);
					if (portnode != nullptr)
					{
						// add the identifying information and attributes
						portnode->set_attribute("tag", port.second->tag());
						portnode->set_attribute("type", input_type_to_token(field.type(), field.player()).c_str());
						portnode->set_attribute_int("mask", field.mask());
						portnode->set_attribute_int("defvalue", field.defvalue() & field.mask());

						// add sequences if changed
						for (input_seq_type seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; ++seqtype)
							if (field.seq(seqtype) != field.defseq(seqtype))
								save_sequence(*portnode, seqtype, field.type(), field.seq(seqtype));

						// write out non-analog changes
						if (!field.is_analog())
						{
							if ((field.live().value & field.mask()) != (field.defvalue() & field.mask()))
								portnode->set_attribute_int("value", field.live().value & field.mask());
							if (field.live().toggle != field.toggle())
								portnode->set_attribute("toggle", field.live().toggle ? "yes" : "no");
						}

						// write out analog changes
						else
						{
							if (field.live().analog->m_delta != field.delta())
								portnode->set_attribute_int("keydelta", field.live().analog->m_delta);
							if (field.live().analog->m_centerdelta != field.centerdelta())
								portnode->set_attribute_int("centerdelta", field.live().analog->m_centerdelta);
							if (field.live().analog->m_sensitivity != field.sensitivity())
								portnode->set_attribute_int("sensitivity", field.live().analog->m_sensitivity);
							if (field.live().analog->m_reverse != field.analog_reverse())
								portnode->set_attribute("reverse", field.live().analog->m_reverse ? "yes" : "no");
						}
					}
				}
			}
}



//**************************************************************************
//  INPUT PLAYBACK
//**************************************************************************

//-------------------------------------------------
//  playback_read - read a value from the playback
//  file
//-------------------------------------------------

template<typename _Type>
_Type ioport_manager::playback_read(_Type &result)
{
	// protect against nullptr handles if previous reads fail
	if (!m_playback_file.is_open())
		result = 0;

	// read the value; if we fail, end playback
	else if (m_playback_file.read(&result, sizeof(result)) != sizeof(result))
	{
		playback_end("End of file");
		result = 0;
	}

	// return the appropriate value
	else if (sizeof(result) == 8)
		result = little_endianize_int64(result);
	else if (sizeof(result) == 4)
		result = little_endianize_int32(result);
	else if (sizeof(result) == 2)
		result = little_endianize_int16(result);
	return result;
}

template<>
bool ioport_manager::playback_read<bool>(bool &result)
{
	u8 temp;
	playback_read(temp);
	return result = bool(temp);
}


//-------------------------------------------------
//  playback_init - initialize INP playback
//-------------------------------------------------

time_t ioport_manager::playback_init()
{
	// if no file, nothing to do
	const char *filename = machine().options().playback();
	if (filename[0] == 0)
		return 0;

	// open the playback file
	osd_file::error filerr = m_playback_file.open(filename);

	// return an explicit error if file isn't found in given path
	if(filerr == osd_file::error::NOT_FOUND)
		fatalerror("Input file %s not found\n",filename);

	// TODO: bail out any other error laconically for now
	if(filerr != osd_file::error::NONE)
		fatalerror("Failed to open file %s for playback (code error=%d)\n",filename,int(filerr));

	// read the header and verify that it is a modern version; if not, print an error
	inp_header header;
	if (!header.read(m_playback_file))
		fatalerror("Input file is corrupt or invalid (missing header)\n");
	if (!header.check_magic())
		fatalerror("Input file invalid or in an older, unsupported format\n");
	if (header.get_majversion() != inp_header::MAJVERSION)
		fatalerror("Input file format version mismatch\n");

	// output info to console
	osd_printf_info("Input file: %s\n", filename);
	osd_printf_info("INP version %u.%u\n", header.get_majversion(), header.get_minversion());
	time_t basetime = header.get_basetime();
	osd_printf_info("Created %s\n", ctime(&basetime));
	osd_printf_info("Recorded using %s\n", header.get_appdesc());

	// verify the header against the current game
	std::string const sysname = header.get_sysname();
	if (sysname != machine().system().name)
		osd_printf_info("Input file is for machine '%s', not for current machine '%s'\n", sysname, machine().system().name);

	// enable compression
	m_playback_file.compress(FCOMPRESS_MEDIUM);
	return basetime;
}


//-------------------------------------------------
//  playback_end - end INP playback
//-------------------------------------------------

void ioport_manager::playback_end(const char *message)
{
	// only applies if we have a live file
	if (m_playback_file.is_open())
	{
		// close the file
		m_playback_file.close();

		// pop a message
		if (message != nullptr)
			machine().popmessage("Playback Ended\nReason: %s", message);

		// display speed stats
		if (m_playback_accumulated_speed > 0)
			m_playback_accumulated_speed /= m_playback_accumulated_frames;
		osd_printf_info("Total playback frames: %d\n", u32(m_playback_accumulated_frames));
		osd_printf_info("Average recorded speed: %d%%\n", u32((m_playback_accumulated_speed * 200 + 1) >> 21));

		// close the program at the end of inp file playback
		if (machine().options().exit_after_playback()) {
			osd_printf_info("Exiting MAME now...\n");
			machine().schedule_exit();
		}
	}
}


//-------------------------------------------------
//  playback_frame - start of frame callback for
//  playback
//-------------------------------------------------

void ioport_manager::playback_frame(const attotime &curtime)
{
	// if playing back, fetch the information and verify
	if (m_playback_file.is_open())
	{
		// first the absolute time
		seconds_t seconds_temp;
		attoseconds_t attoseconds_temp;
		playback_read(seconds_temp);
		playback_read(attoseconds_temp);
		attotime readtime(seconds_temp, attoseconds_temp);
		if (readtime != curtime)
			playback_end("Out of sync");

		// then the speed
		u32 curspeed;
		m_playback_accumulated_speed += playback_read(curspeed);
		m_playback_accumulated_frames++;
	}
}


//-------------------------------------------------
//  playback_port - per-port callback for playback
//-------------------------------------------------

void ioport_manager::playback_port(ioport_port &port)
{
	// if playing back, fetch information about this port
	if (m_playback_file.is_open())
	{
		// read the default value and the digital state
		playback_read(port.live().defvalue);
		playback_read(port.live().digital);

		// loop over analog ports and save their data
		for (analog_field &analog : port.live().analoglist)
		{
			// read current and previous values
			playback_read(analog.m_accum);
			playback_read(analog.m_previous);

			// read configuration information
			playback_read(analog.m_sensitivity);
			playback_read(analog.m_reverse);
		}
	}
}


//-------------------------------------------------
//  record_write - write a value to the record file
//-------------------------------------------------

template<typename _Type>
void ioport_manager::record_write(_Type value)
{
	// protect against nullptr handles if previous reads fail
	if (!m_record_file.is_open())
		return;

	// read the value; if we fail, end playback
	if (m_record_file.write(&value, sizeof(value)) != sizeof(value))
		record_end("Out of space");
}

template<>
void ioport_manager::record_write<bool>(bool value)
{
	u8 byte = u8(value);
	record_write(byte);
}

template<typename _Type>
void ioport_manager::timecode_write(_Type value)
{
	// protect against nullptr handles if previous reads fail
	if (!m_timecode_file.is_open())
		return;

	// read the value; if we fail, end playback
	if (m_timecode_file.write(&value, sizeof(value)) != sizeof(value))
		timecode_end("Out of space");
}

/*template<>
void ioport_manager::timecode_write<bool>(bool value)
{
    u8 byte = u8(value);
    timecode_write(byte);
}*/
template<>
void ioport_manager::timecode_write<std::string>(std::string value) {
	timecode_write(value.c_str());
}


//-------------------------------------------------
//  record_init - initialize INP recording
//-------------------------------------------------

void ioport_manager::record_init()
{
	// if no file, nothing to do
	const char *filename = machine().options().record();
	if (filename[0] == 0)
		return;

	// open the record file
	osd_file::error filerr = m_record_file.open(filename);
	if (filerr != osd_file::error::NONE)
		throw emu_fatalerror("ioport_manager::record_init: Failed to open file for recording");

	// get the base time
	system_time systime;
	machine().base_datetime(systime);

	// fill in the header
	inp_header header;
	header.set_magic();
	header.set_basetime(systime.time);
	header.set_version();
	header.set_sysname(machine().system().name);
	header.set_appdesc(util::string_format("%s %s", emulator_info::get_appname(), emulator_info::get_build_version()));

	// write it
	header.write(m_record_file);

	// enable compression
	m_record_file.compress(FCOMPRESS_MEDIUM);
}


void ioport_manager::timecode_init()
{
	// check if option -record_timecode is enabled
	if (!machine().options().record_timecode())
	{
		machine().video().set_timecode_enabled(false);
		return;
	}
	// if no file, nothing to do
	const char *record_filename = machine().options().record();
	if (record_filename[0] == 0)
	{
		machine().video().set_timecode_enabled(false);
		return;
	}

	machine().video().set_timecode_enabled(true);

	// open the record file
	std::string filename;
	filename.append(record_filename).append(".timecode");
	osd_printf_info("Record input timecode file: %s\n", record_filename);

	osd_file::error filerr = m_timecode_file.open(filename.c_str());
	if (filerr != osd_file::error::NONE)
		throw emu_fatalerror("ioport_manager::timecode_init: Failed to open file for input timecode recording");

	m_timecode_file.puts(std::string("# ==========================================\n").c_str());
	m_timecode_file.puts(std::string("# TIMECODE FILE FOR VIDEO PREVIEW GENERATION\n").c_str());
	m_timecode_file.puts(std::string("# ==========================================\n").c_str());
	m_timecode_file.puts(std::string("#\n").c_str());
	m_timecode_file.puts(std::string("# VIDEO_PART:     code of video timecode\n").c_str());
	m_timecode_file.puts(std::string("# START:          start time (hh:mm:ss.mmm)\n").c_str());
	m_timecode_file.puts(std::string("# ELAPSED:        elapsed time (hh:mm:ss.mmm)\n").c_str());
	m_timecode_file.puts(std::string("# MSEC_START:     start time (milliseconds)\n").c_str());
	m_timecode_file.puts(std::string("# MSEC_ELAPSED:   elapsed time (milliseconds)\n").c_str());
	m_timecode_file.puts(std::string("# FRAME_START:    start time (frames)\n").c_str());
	m_timecode_file.puts(std::string("# FRAME_ELAPSED:  elapsed time (frames)\n").c_str());
	m_timecode_file.puts(std::string("#\n").c_str());
	m_timecode_file.puts(std::string("# VIDEO_PART======= START======= ELAPSED===== MSEC_START===== MSEC_ELAPSED=== FRAME_START==== FRAME_ELAPSED==\n").c_str());
}

//-------------------------------------------------
//  record_end - end INP recording
//-------------------------------------------------

void ioport_manager::record_end(const char *message)
{
	// only applies if we have a live file
	if (m_record_file.is_open())
	{
		// close the file
		m_record_file.close();

		// pop a message
		if (message != nullptr)
			machine().popmessage("Recording Ended\nReason: %s", message);
	}
}


void ioport_manager::timecode_end(const char *message)
{
	// only applies if we have a live file
	if (m_timecode_file.is_open()) {
		// close the file
		m_timecode_file.close();

		// pop a message
		if (message != nullptr)
			machine().popmessage("Recording Timecode Ended\nReason: %s", message);
	}
}

//-------------------------------------------------
//  record_frame - start of frame callback for
//  recording
//-------------------------------------------------

void ioport_manager::record_frame(const attotime &curtime)
{
	// if recording, record information about the current frame
	if (m_record_file.is_open())
	{
		// first the absolute time
		record_write(curtime.seconds());
		record_write(curtime.attoseconds());

		// then the current speed
		record_write(u32(machine().video().speed_percent() * double(1 << 20)));
	}

	if (m_timecode_file.is_open() && machine().video().get_timecode_write())
	{
		// Display the timecode
		m_timecode_count++;
		std::string const current_time_str = string_format("%02d:%02d:%02d.%03d",
				(int)curtime.seconds() / (60 * 60),
				(curtime.seconds() / 60) % 60,
				curtime.seconds() % 60,
				(int)(curtime.attoseconds()/ATTOSECONDS_PER_MILLISECOND));

		// Elapsed from previous timecode
		attotime const elapsed_time = curtime - m_timecode_last_time;
		m_timecode_last_time = curtime;
		std::string const elapsed_time_str = string_format("%02d:%02d:%02d.%03d",
				elapsed_time.seconds() / (60 * 60),
				(elapsed_time.seconds() / 60) % 60,
				elapsed_time.seconds() % 60,
				int(elapsed_time.attoseconds()/ATTOSECONDS_PER_MILLISECOND));

		// Number of ms from beginning of playback
		int const mseconds_start = curtime.seconds()*1000 + curtime.attoseconds()/ATTOSECONDS_PER_MILLISECOND;
		std::string const mseconds_start_str = string_format("%015d", mseconds_start);

		// Number of ms from previous timecode
		int mseconds_elapsed = elapsed_time.seconds()*1000 + elapsed_time.attoseconds()/ATTOSECONDS_PER_MILLISECOND;
		std::string const mseconds_elapsed_str = string_format("%015d", mseconds_elapsed);

		// Number of frames from beginning of playback
		int const frame_start = mseconds_start * 60 / 1000;
		std::string const frame_start_str = string_format("%015d", frame_start);

		// Number of frames from previous timecode
		int frame_elapsed = mseconds_elapsed * 60 / 1000;
		std::string const frame_elapsed_str = string_format("%015d", frame_elapsed);

		std::string message;
		std::string timecode_text;
		std::string timecode_key;
		bool show_timecode_counter = false;
		if (m_timecode_count==1) {
			message = string_format("TIMECODE: Intro started at %s", current_time_str);
			timecode_key = "INTRO_START";
			timecode_text = "INTRO";
			show_timecode_counter = true;
		}
		else if (m_timecode_count==2) {
			machine().video().add_to_total_time(elapsed_time);
			message = string_format("TIMECODE: Intro duration %s", elapsed_time_str);
			timecode_key = "INTRO_STOP";
			//timecode_text = "INTRO";
		}
		else if (m_timecode_count==3) {
			message = string_format("TIMECODE: Gameplay started at %s", current_time_str);
			timecode_key = "GAMEPLAY_START";
			timecode_text = "GAMEPLAY";
			show_timecode_counter = true;
		}
		else if (m_timecode_count==4) {
			machine().video().add_to_total_time(elapsed_time);
			message = string_format("TIMECODE: Gameplay duration %s", elapsed_time_str);
			timecode_key = "GAMEPLAY_STOP";
			//timecode_text = "GAMEPLAY";
		}
		else if (m_timecode_count % 2 == 1) {
			message = string_format("TIMECODE: Extra %d started at %s", (m_timecode_count-3)/2, current_time_str);
			timecode_key = string_format("EXTRA_START_%03d", (m_timecode_count-3)/2);
			timecode_text = string_format("EXTRA %d", (m_timecode_count-3)/2);
			show_timecode_counter = true;
		}
		else {
			machine().video().add_to_total_time(elapsed_time);
			message = string_format("TIMECODE: Extra %d duration %s", (m_timecode_count-4)/2, elapsed_time_str);
			timecode_key = string_format("EXTRA_STOP_%03d", (m_timecode_count-4)/2);
		}

		osd_printf_info("%s \n", message);
		machine().popmessage("%s \n", message);

		m_timecode_file.printf(
				"%-19s %s %s %s %s %s %s\n",
				timecode_key,
				current_time_str, elapsed_time_str,
				mseconds_start_str, mseconds_elapsed_str,
				frame_start_str, frame_elapsed_str);

		machine().video().set_timecode_write(false);
		machine().video().set_timecode_text(timecode_text);
		machine().video().set_timecode_start(m_timecode_last_time);
		machine().ui().set_show_timecode_counter(show_timecode_counter);
	}
}


//-------------------------------------------------
//  record_port - per-port callback for record
//-------------------------------------------------

void ioport_manager::record_port(ioport_port &port)
{
	// if recording, store information about this port
	if (m_record_file.is_open())
	{
		// store the default value and digital state
		record_write(port.live().defvalue);
		record_write(port.live().digital);

		// loop over analog ports and save their data
		for (analog_field &analog : port.live().analoglist)
		{
			// store current and previous values
			record_write(analog.m_accum);
			record_write(analog.m_previous);

			// store configuration information
			record_write(analog.m_sensitivity);
			record_write(analog.m_reverse);
		}
	}
}



//**************************************************************************
//  I/O PORT CONFIGURER
//**************************************************************************

//-------------------------------------------------
//  ioport_configurer - constructor
//-------------------------------------------------

ioport_configurer::ioport_configurer(device_t &owner, ioport_list &portlist, std::string &errorbuf)
	: m_owner(owner),
		m_portlist(portlist),
		m_errorbuf(errorbuf),
		m_curport(nullptr),
		m_curfield(nullptr),
		m_cursetting(nullptr)
{
}


//-------------------------------------------------
//  string_from_token - convert an
//  ioport_token to a default string
//-------------------------------------------------

const char *ioport_configurer::string_from_token(const char *string)
{
	// 0 is an invalid index
	if (string == nullptr)
		return nullptr;

	// if the index is greater than the count, assume it to be a pointer
	if (uintptr_t(string) >= INPUT_STRING_COUNT)
		return string;

#if false // Set true, If you want to take care missing-token or wrong-sorting

	// otherwise, scan the list for a matching string and return it
	{
	int index;
	for (index = 0; index < ARRAY_LENGTH(input_port_default_strings); index++)
		if (input_port_default_strings[index].id == uintptr_t(string))
			return input_port_default_strings[index].string;
	}
	return "(Unknown Default)";

#else

	return input_port_default_strings[uintptr_t(string)-1].string;

#endif
}


//-------------------------------------------------
//  port_alloc - allocate a new port
//-------------------------------------------------

ioport_configurer& ioport_configurer::port_alloc(const char *tag)
{
	// create the full tag
	std::string fulltag = m_owner.subtag(tag);

	// add it to the list, and reset current field/setting
	if (m_portlist.count(fulltag) != 0) throw tag_add_exception(fulltag.c_str());
	m_portlist.emplace(std::make_pair(fulltag, std::make_unique<ioport_port>(m_owner, fulltag.c_str())));
	m_curport = m_portlist.find(fulltag)->second.get();
	m_curfield = nullptr;
	m_cursetting = nullptr;
	return *this;
}


//-------------------------------------------------
//  port_modify - find an existing port and
//  modify it
//-------------------------------------------------

ioport_configurer& ioport_configurer::port_modify(const char *tag)
{
	// create the full tag
	std::string fulltag = m_owner.subtag(tag);

	// find the existing port
	m_curport = m_portlist.find(fulltag.c_str())->second.get();
	if (m_curport == nullptr)
		throw emu_fatalerror("Requested to modify nonexistent port '%s'", fulltag.c_str());

	// bump the modification count, and reset current field/setting
	m_curport->m_modcount++;
	m_curfield = nullptr;
	m_cursetting = nullptr;
	return *this;
}


//-------------------------------------------------
//  field_alloc - allocate a new field
//-------------------------------------------------

ioport_configurer& ioport_configurer::field_alloc(ioport_type type, ioport_value defval, ioport_value mask, const char *name)
{
	// make sure we have a port
	if (m_curport == nullptr)
		throw emu_fatalerror("alloc_field called with no active port (mask=%X defval=%X)\n", mask, defval);
	// append the field
	if (type != IPT_UNKNOWN && type != IPT_UNUSED)
		m_curport->m_active |= mask;
	m_curfield = &m_curport->m_fieldlist.append(*global_alloc(ioport_field(*m_curport, type, defval, mask, string_from_token(name))));

	// reset the current setting
	m_cursetting = nullptr;
	return *this;
}


//-------------------------------------------------
//  field_add_char - add a character to a field
//-------------------------------------------------

ioport_configurer& ioport_configurer::field_add_char(std::initializer_list<char32_t> charlist)
{
	for (int index = 0; index < ARRAY_LENGTH(m_curfield->m_chars); index++)
		if (m_curfield->m_chars[index][0] == 0)
		{
			const size_t char_count = ARRAY_LENGTH(m_curfield->m_chars[index]);
			assert(charlist.size() > 0 && charlist.size() <= char_count);

			for (size_t i = 0; i < char_count; i++)
				m_curfield->m_chars[index][i] = i < charlist.size() ? *(charlist.begin() + i) : 0;
			return *this;
		}

	std::ostringstream s;
	bool is_first = true;
	for (char32_t ch : charlist)
	{
		util::stream_format(s, "%s%d", is_first ? "" : ",", (int)ch);
		is_first = false;
	}
	throw emu_fatalerror("PORT_CHAR(%s) could not be added - maximum amount exceeded\n", s.str().c_str());
}


//-------------------------------------------------
//  field_add_code - add a character to a field
//-------------------------------------------------

ioport_configurer& ioport_configurer::field_add_code(input_seq_type which, input_code code)
{
	m_curfield->m_seq[which] |= code;
	return *this;
}


//-------------------------------------------------
//  setting_alloc - allocate a new setting
//-------------------------------------------------

ioport_configurer& ioport_configurer::setting_alloc(ioport_value value, const char *name)
{
	// make sure we have a field
	if (m_curfield == nullptr)
		throw emu_fatalerror("alloc_setting called with no active field (value=%X name=%s)\n", value, name);

	m_cursetting = global_alloc(ioport_setting(*m_curfield, value & m_curfield->mask(), string_from_token(name)));
	// append a new setting
	m_curfield->m_settinglist.append(*m_cursetting);
	return *this;
}


//-------------------------------------------------
//  set_condition - set the condition for either
//  the current setting or field
//-------------------------------------------------

ioport_configurer& ioport_configurer::set_condition(ioport_condition::condition_t condition, const char *tag, ioport_value mask, ioport_value value)
{
	ioport_condition &target = (m_cursetting != nullptr) ? m_cursetting->condition() : m_curfield->condition();
	target.set(condition, tag, mask, value);
	return *this;
}


//-------------------------------------------------
//  onoff_alloc - allocate an on/off DIP switch
//-------------------------------------------------

ioport_configurer& ioport_configurer::onoff_alloc(const char *name, ioport_value defval, ioport_value mask, const char *diplocation)
{
	// allocate a field normally
	field_alloc(IPT_DIPSWITCH, defval, mask, name);

	// expand the diplocation
	if (diplocation != nullptr)
		field_set_diplocation(diplocation);

	// allocate settings
	setting_alloc(defval & mask, DEF_STR(Off));
	setting_alloc(~defval & mask, DEF_STR(On));
	// clear cursettings set by setting_alloc
	m_cursetting = nullptr;
	return *this;
}



/***************************************************************************
    MISCELLANEOUS
***************************************************************************/

//-------------------------------------------------
//  dynamic_field - constructor
//-------------------------------------------------

dynamic_field::dynamic_field(ioport_field &field)
	: m_next(nullptr),
		m_field(field),
		m_shift(0),
		m_oldval(field.defvalue())
{
	// fill in the data
	for (ioport_value mask = field.mask(); !(mask & 1); mask >>= 1)
		m_shift++;
	m_oldval >>= m_shift;
}


//-------------------------------------------------
//  read - read the updated value and merge it
//  into the target
//-------------------------------------------------

void dynamic_field::read(ioport_value &result)
{
	// skip if not enabled
	if (!m_field.enabled())
		return;

	// call the callback to read a new value
	ioport_value newval = m_field.m_read();
	m_oldval = newval;

	// merge in the bits (don't invert yet, as all digitals are inverted together)
	result = (result & ~m_field.mask()) | ((newval << m_shift) & m_field.mask());
}


//-------------------------------------------------
//  write - track a change to a value and call
//  the write callback if there's something new
//-------------------------------------------------

void dynamic_field::write(ioport_value newval)
{
	// skip if not enabled
	if (!m_field.enabled())
		return;

	// if the bits have changed, call the handler
	newval = (newval & m_field.mask()) >> m_shift;
	if (m_oldval != newval)
	{
		m_field.m_write(m_field, m_field.m_write_param, m_oldval, newval);
		m_oldval = newval;
	}
}


//-------------------------------------------------
//  analog_field - constructor
//-------------------------------------------------

analog_field::analog_field(ioport_field &field)
	: m_next(nullptr),
		m_field(field),
		m_shift(0),
		m_adjdefvalue(field.defvalue() & field.mask()),
		m_adjmin(field.minval() & field.mask()),
		m_adjmax(field.maxval() & field.mask()),
		m_sensitivity(field.sensitivity()),
		m_reverse(field.analog_reverse()),
		m_delta(field.delta()),
		m_centerdelta(field.centerdelta()),
		m_accum(0),
		m_previous(0),
		m_previousanalog(0),
		m_minimum(INPUT_ABSOLUTE_MIN),
		m_maximum(INPUT_ABSOLUTE_MAX),
		m_center(0),
		m_reverse_val(0),
		m_scalepos(0),
		m_scaleneg(0),
		m_keyscalepos(0),
		m_keyscaleneg(0),
		m_positionalscale(0),
		m_absolute(false),
		m_wraps(false),
		m_autocenter(false),
		m_single_scale(false),
		m_interpolate(false),
		m_lastdigital(false)
{
	// compute the shift amount and number of bits
	for (ioport_value mask = field.mask(); !(mask & 1); mask >>= 1)
		m_shift++;

	// initialize core data
	m_adjdefvalue >>= m_shift;
	m_adjmin >>= m_shift;
	m_adjmax >>= m_shift;

	// set basic parameters based on the configured type
	switch (field.type())
	{
		// paddles and analog joysticks are absolute and autocenter
		case IPT_AD_STICK_X:
		case IPT_AD_STICK_Y:
		case IPT_AD_STICK_Z:
		case IPT_PADDLE:
		case IPT_PADDLE_V:
			m_absolute = true;
			m_autocenter = true;
			m_interpolate = !field.analog_reset();
			break;

		// pedals start at and autocenter to the min range
		case IPT_PEDAL:
		case IPT_PEDAL2:
		case IPT_PEDAL3:
			m_center = INPUT_ABSOLUTE_MIN;
			m_accum = apply_inverse_sensitivity(m_center);
			m_absolute = true;
			m_autocenter = true;
			m_interpolate = !field.analog_reset();
			break;

		// lightguns are absolute as well, but don't autocenter and don't interpolate their values
		case IPT_LIGHTGUN_X:
		case IPT_LIGHTGUN_Y:
			m_absolute = true;
			m_autocenter = false;
			m_interpolate = false;
			break;

		// positional devices are absolute, but can also wrap like relative devices
		// set each position to be 512 units
		case IPT_POSITIONAL:
		case IPT_POSITIONAL_V:
			m_positionalscale = compute_scale(field.maxval(), INPUT_ABSOLUTE_MAX - INPUT_ABSOLUTE_MIN);
			m_adjmin = 0;
			m_adjmax = field.maxval() - 1;
			m_wraps = field.analog_wraps();
			m_autocenter = !m_wraps;
			break;

		// dials, mice and trackballs are relative devices
		// these have fixed "min" and "max" values based on how many bits are in the port
		// in addition, we set the wrap around min/max values to 512 * the min/max values
		// this takes into account the mapping that one mouse unit ~= 512 analog units
		case IPT_DIAL:
		case IPT_DIAL_V:
		case IPT_TRACKBALL_X:
		case IPT_TRACKBALL_Y:
		case IPT_MOUSE_X:
		case IPT_MOUSE_Y:
			m_absolute = false;
			m_wraps = true;
			m_interpolate = !field.analog_reset();
			break;

		default:
			fatalerror("Unknown analog port type -- don't know if it is absolute or not\n");
	}

	// further processing for absolute controls
	if (m_absolute)
	{
		// if the default value is pegged at the min or max, use a single scale value for the whole axis
		m_single_scale = (m_adjdefvalue == m_adjmin) || (m_adjdefvalue == m_adjmax);

		// if not "single scale", compute separate scales for each side of the default
		if (!m_single_scale)
		{
			// unsigned
			m_scalepos = compute_scale(m_adjmax - m_adjdefvalue, INPUT_ABSOLUTE_MAX - 0);
			m_scaleneg = compute_scale(m_adjdefvalue - m_adjmin, 0 - INPUT_ABSOLUTE_MIN);

			if (m_adjmin > m_adjmax)
				m_scaleneg = -m_scaleneg;

			// reverse point is at center
			m_reverse_val = 0;
		}
		else
		{
			// single axis that increases from default
			m_scalepos = compute_scale(m_adjmax - m_adjmin, INPUT_ABSOLUTE_MAX - INPUT_ABSOLUTE_MIN);

			// make the scaling the same for easier coding when we need to scale
			m_scaleneg = m_scalepos;

			// reverse point is at max
			m_reverse_val = m_maximum;
		}
	}

	// relative and positional controls all map directly with a 512x scale factor
	else
	{
		// The relative code is set up to allow specifing PORT_MINMAX and default values.
		// The validity checks are purposely set up to not allow you to use anything other
		// a default of 0 and PORT_MINMAX(0,mask).  This is in case the need arises to use
		// this feature in the future.  Keeping the code in does not hurt anything.
		if (m_adjmin > m_adjmax)
			// adjust for signed
			m_adjmin = -m_adjmin;

		if (m_wraps)
			m_adjmax++;

		m_minimum = (m_adjmin - m_adjdefvalue) * INPUT_RELATIVE_PER_PIXEL;
		m_maximum = (m_adjmax - m_adjdefvalue) * INPUT_RELATIVE_PER_PIXEL;

		// make the scaling the same for easier coding when we need to scale
		m_scaleneg = m_scalepos = compute_scale(1, INPUT_RELATIVE_PER_PIXEL);

		if (m_field.analog_reset())
			// delta values reverse from center
			m_reverse_val = 0;
		else
		{
			// positional controls reverse from their max range
			m_reverse_val = m_maximum + m_minimum;

			// relative controls reverse from 1 past their max range
			if (m_wraps)
			{
				// FIXME: positional needs -1, using INPUT_RELATIVE_PER_PIXEL skips a position (and reads outside the table array)
				if(field.type() == IPT_POSITIONAL || field.type() == IPT_POSITIONAL_V)
					m_reverse_val --;
				else
					m_reverse_val -= INPUT_RELATIVE_PER_PIXEL;
			}
		}
	}

	// compute scale for keypresses
	m_keyscalepos = recip_scale(m_scalepos);
	m_keyscaleneg = recip_scale(m_scaleneg);
}


//-------------------------------------------------
//  apply_min_max - clamp the given input value to
//  the appropriate min/max for the analog control
//-------------------------------------------------

inline s32 analog_field::apply_min_max(s32 value) const
{
	// take the analog minimum and maximum values and apply the inverse of the
	// sensitivity so that we can clamp against them before applying sensitivity
	s32 adjmin = apply_inverse_sensitivity(m_minimum);
	s32 adjmax = apply_inverse_sensitivity(m_maximum);

	// clamp to the bounds absolutely
	if (value > adjmax)
		value = adjmax;
	else if (value < adjmin)
		value = adjmin;

	return value;
}


//-------------------------------------------------
//  apply_sensitivity - apply a sensitivity
//  adjustment for a current value
//-------------------------------------------------

inline s32 analog_field::apply_sensitivity(s32 value) const
{
	return lround((s64(value) * m_sensitivity) / 100.0);
}


//-------------------------------------------------
//  apply_inverse_sensitivity - reverse-apply the
//  sensitivity adjustment for a current value
//-------------------------------------------------

inline s32 analog_field::apply_inverse_sensitivity(s32 value) const
{
	return s32((s64(value) * 100) / m_sensitivity);
}


//-------------------------------------------------
//  apply_settings - return the value of an
//  analog input
//-------------------------------------------------

s32 analog_field::apply_settings(s32 value) const
{
	// apply the min/max and then the sensitivity
	if (!m_wraps)
		value = apply_min_max(value);
	value = apply_sensitivity(value);

	// apply reversal if needed
	if (m_reverse)
		value = m_reverse_val - value;
	else if (m_single_scale)
		// it's a pedal or the default value is equal to min/max
		// so we need to adjust the center to the minimum
		value -= INPUT_ABSOLUTE_MIN;

	// map differently for positive and negative values
	if (value >= 0)
		value = apply_scale(value, m_scalepos);
	else
		value = apply_scale(value, m_scaleneg);
	value += m_adjdefvalue;

	// for relative devices, wrap around when we go past the edge
	// (this is done last to prevent rounding errors)
	if (m_wraps)
	{
		s32 range = m_adjmax - m_adjmin;
		// rolls to other end when 1 position past end.
		value = (value - m_adjmin) % range;
		if (value < 0)
			value += range;
		value += m_adjmin;
	}

	return value;
}


//-------------------------------------------------
//  frame_update - update the internals of a
//  single analog field periodically
//-------------------------------------------------

void analog_field::frame_update(running_machine &machine)
{
	// clamp the previous value to the min/max range
	if (!m_wraps)
		m_accum = apply_min_max(m_accum);

	// remember the previous value in case we need to interpolate
	m_previous = m_accum;

	// get the new raw analog value and its type
	input_item_class itemclass;
	s32 rawvalue = machine.input().seq_axis_value(m_field.seq(SEQ_TYPE_STANDARD), itemclass);

	// if we got an absolute input, it overrides everything else
	if (itemclass == ITEM_CLASS_ABSOLUTE)
	{
		if (m_previousanalog != rawvalue)
		{
			// only update if analog value changed
			m_previousanalog = rawvalue;

			// apply the inverse of the sensitivity to the raw value so that
			// it will still cover the full min->max range requested after
			// we apply the sensitivity adjustment
			if (m_absolute || m_field.analog_reset())
			{
				// if port is absolute, then just return the absolute data supplied
				m_accum = apply_inverse_sensitivity(rawvalue);
			}
			else if (m_positionalscale != 0)
			{
				// if port is positional, we will take the full analog control and divide it
				// into positions, that way as the control is moved full scale,
				// it moves through all the positions
				rawvalue = apply_scale(rawvalue - INPUT_ABSOLUTE_MIN, m_positionalscale) * INPUT_RELATIVE_PER_PIXEL + m_minimum;

				// clamp the high value so it does not roll over
				rawvalue = std::min(rawvalue, m_maximum);
				m_accum = apply_inverse_sensitivity(rawvalue);
			}
			else
				// if port is relative, we use the value to simulate the speed of relative movement
				// sensitivity adjustment is allowed for this mode
				m_accum += rawvalue;

			m_lastdigital = false;
			// do not bother with other control types if the analog data is changing
			return;
		}
		else
		{
			// we still have to update fake relative from joystick control
			if (!m_absolute && m_positionalscale == 0)
				m_accum += rawvalue;
		}
	}

	// if we got it from a relative device, use that as the starting delta
	// also note that the last input was not a digital one
	s32 delta = 0;
	if (itemclass == ITEM_CLASS_RELATIVE && rawvalue != 0)
	{
		delta = rawvalue;
		m_lastdigital = false;
	}

	s64 keyscale = (m_accum >= 0) ? m_keyscalepos : m_keyscaleneg;

	// if the decrement code sequence is pressed, add the key delta to
	// the accumulated delta; also note that the last input was a digital one
	bool keypressed = false;
	if (machine.input().seq_pressed(m_field.seq(SEQ_TYPE_DECREMENT)))
	{
		keypressed = true;
		if (m_delta != 0)
			delta -= apply_scale(m_delta, keyscale);
		else if (!m_lastdigital)
			// decrement only once when first pressed
			delta -= apply_scale(1, keyscale);
		m_lastdigital = true;
	}

	// same for the increment code sequence
	if (machine.input().seq_pressed(m_field.seq(SEQ_TYPE_INCREMENT)))
	{
		keypressed = true;
		if (m_delta)
			delta += apply_scale(m_delta, keyscale);
		else if (!m_lastdigital)
			// increment only once when first pressed
			delta += apply_scale(1, keyscale);
		m_lastdigital = true;
	}

	// if resetting is requested, clear the accumulated position to 0 before
	// applying the deltas so that we only return this frame's delta
	// note that centering only works for relative controls
	// no need to check if absolute here because it is checked by the validity tests
	if (m_field.analog_reset())
		m_accum = 0;

	// apply the delta to the accumulated value
	m_accum += delta;

	// if our last movement was due to a digital input, and if this control
	// type autocenters, and if neither the increment nor the decrement seq
	// was pressed, apply autocentering
	if (m_autocenter)
	{
		s32 center = apply_inverse_sensitivity(m_center);
		if (m_lastdigital && !keypressed)
		{
			// autocenter from positive values
			if (m_accum >= center)
			{
				m_accum -= apply_scale(m_centerdelta, m_keyscalepos);
				if (m_accum < center)
				{
					m_accum = center;
					m_lastdigital = false;
				}
			}

			// autocenter from negative values
			else
			{
				m_accum += apply_scale(m_centerdelta, m_keyscaleneg);
				if (m_accum > center)
				{
					m_accum = center;
					m_lastdigital = false;
				}
			}
		}
	}
	else if (!keypressed)
		m_lastdigital = false;
}


//-------------------------------------------------
//  read - read the current value and insert into
//  the provided ioport_value
//-------------------------------------------------

void analog_field::read(ioport_value &result)
{
	// do nothing if we're not enabled
	if (!m_field.enabled())
		return;

	// start with the raw value
	s32 value = m_accum;

	// interpolate if appropriate and if time has passed since the last update
	if (m_interpolate)
		value = manager().frame_interpolate(m_previous, m_accum);

	// apply standard analog settings
	value = apply_settings(value);

	// remap the value if needed
	if (m_field.remap_table() != nullptr)
		value = m_field.remap_table()[value];

	// invert bits if needed
	if (m_field.analog_invert())
		value = ~value;

	// insert into the port
	result = (result & ~m_field.mask()) | ((value << m_shift) & m_field.mask());
}


//-------------------------------------------------
//  crosshair_read - read a value for crosshairs,
//  scaled between 0 and 1
//-------------------------------------------------

float analog_field::crosshair_read()
{
	s32 rawvalue = apply_settings(m_accum) & (m_field.mask() >> m_shift);
	return float(rawvalue - m_adjmin) / float(m_adjmax - m_adjmin);
}



/***************************************************************************
    TOKENIZATION HELPERS
***************************************************************************/

//-------------------------------------------------
//  token_to_input_type - convert a string token
//  to an input field type and player
//-------------------------------------------------

ioport_type ioport_manager::token_to_input_type(const char *string, int &player) const
{
	// check for our failsafe case first
	int ipnum;
	if (sscanf(string, "TYPE_OTHER(%d,%d)", &ipnum, &player) == 2)
		return ioport_type(ipnum);

	// find the token in the list
	for (input_type_entry &entry : m_typelist)
		if (entry.token() != nullptr && !strcmp(entry.token(), string))
		{
			player = entry.player();
			return entry.type();
		}

	// if we fail, return IPT_UNKNOWN
	player = 0;
	return IPT_UNKNOWN;
}


//-------------------------------------------------
//  input_type_to_token - convert an input field
//  type and player to a string token
//-------------------------------------------------

std::string ioport_manager::input_type_to_token(ioport_type type, int player)
{
	// look up the port and return the token
	input_type_entry *entry = m_type_to_entry[type][player];
	if (entry != nullptr)
		return std::string(entry->token());

	// if that fails, carry on
	return string_format("TYPE_OTHER(%d,%d)", type, player);
}


//-------------------------------------------------
//  token_to_seq_type - convert a string to
//  a sequence type
//-------------------------------------------------

input_seq_type ioport_manager::token_to_seq_type(const char *string)
{
	// look up the string in the table of possible sequence types and return the index
	for (int seqindex = 0; seqindex < ARRAY_LENGTH(seqtypestrings); seqindex++)
		if (!core_stricmp(string, seqtypestrings[seqindex]))
			return input_seq_type(seqindex);
	return SEQ_TYPE_INVALID;
}