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

#ifdef ENABLE_NES

//Line Content
//37   Supported Mappers
//185  Defines
//211  Variables
//242  Menus
//456  Setup
//486  No-Intro SD Database Functions
//803  Low Level Functions
//1012 File Functions
//1083 Config Functions
//1704 ROM Functions
//3534 RAM Functions
//3934 Eeprom Functions
//4122 NESmaker Flash Cart Functions

struct mapper_NES {
  uint16_t mapper;
  uint8_t prglo;
  uint8_t prghi;
  uint8_t chrlo;
  uint8_t chrhi;
  uint8_t ramlo;
  uint8_t ramhi;
};

/******************************************
  Supported Mappers
 *****************************************/
// Supported Mapper Array (iNES Mapper #s)
// Format = {mapper,prglo,prghi,chrlo,chrhi,ramlo,ramhi}
static const struct mapper_NES PROGMEM mapsize[] = {
  { 0, 0, 1, 0, 1, 0, 2 },   // NROM                                               [sram r/w]
  { 1, 1, 5, 0, 5, 0, 3 },   // MMC1                                               [sram r/w]
  { 2, 2, 4, 0, 0, 0, 0 },   // UxROM
  { 3, 0, 1, 0, 9, 0, 0 },   // CNROM
  { 4, 1, 5, 0, 6, 0, 1 },   // MMC3/MMC6                                          [sram/prgram r/w]
  { 5, 3, 5, 5, 7, 0, 3 },   // MMC5                                               [sram r/w]
  { 7, 2, 4, 0, 0, 0, 0 },   // AxROM
  { 9, 0, 3, 0, 5, 0, 0 },   // MMC2/PxROM
  { 10, 0, 4, 4, 5, 1, 1 },  // MMC4/FxROM                                         [sram r/w]
  { 11, 1, 3, 1, 5, 0, 0 },  // Color Dreams [UNLICENSED]
  { 13, 1, 1, 0, 0, 0, 0 },  // cprom (videomation)
  { 15, 6, 6, 0, 0, 0, 0 },  // K-1029/K-1030P [UNLICENSED]
  { 16, 3, 4, 5, 6, 0, 1 },  // bandai x24c02                                      [eep r/w]
  { 18, 3, 4, 5, 6, 0, 1 },  // jaleco ss8806                                      [sram r/w]
  { 19, 3, 4, 5, 6, 0, 1 },  // namco 106/163                                      [sram/prgram r/w]
  // 20 - bad mapper, not used
  { 21, 4, 4, 5, 6, 0, 1 },  // vrc4a/vrc4c                                        [sram r/w]
  { 22, 3, 3, 5, 5, 0, 0 },  // vrc2a
  { 23, 3, 3, 5, 6, 0, 0 },  // vrc2b/vrc4e
  { 24, 4, 4, 5, 5, 0, 0 },  // vrc6a (akumajou densetsu)
  { 25, 3, 4, 5, 6, 0, 1 },  // vrc2c/vrc4b/vrc4d                                  [sram r/w]
  { 26, 4, 4, 5, 6, 1, 1 },  // vrc6b                                              [sram r/w]
  { 28, 5, 7, 0, 0, 0, 0 },  // Action 53 [UNLICENSED]
  { 30, 4, 5, 0, 0, 0, 0 },  // unrom 512 (NESmaker) [UNLICENSED]
  { 31, 6, 6, 0, 0, 0, 0 },  // NSF music compilations [UNLICENSED]
  { 32, 3, 4, 5, 5, 0, 0 },  // irem g-101
  { 33, 3, 4, 5, 6, 0, 0 },  // taito tc0190
  { 34, 1, 9, 0, 4, 0, 0 },  // BxROM & NINA
  { 35, 0, 7, 1, 8, 0, 0 },  // J.Y. Company ASIC [UNLICENSED]
  { 36, 0, 3, 1, 5, 0, 0 },  // TXC 01-22000-400 Board [UNLICENSED]
  { 37, 4, 4, 6, 6, 0, 0 },  // Nintendo 3-in-1
  { 38, 1, 3, 0, 3, 0, 0 },  // Crime Busters [UNLICENSED]
  { 42, 0, 3, 0, 5, 0, 0 },  // hacked FDS games converted to cartridge [UNLICENSED]
  { 45, 3, 6, 0, 8, 0, 0 },  // ga23c asic multicart [UNLICENSED]
  { 46, 1, 6, 0, 8, 0, 0 },  // Rumble Station [UNLICENSED]
  { 47, 4, 5, 6, 7, 0, 0 },  // Nintendo 2-in-1
  { 48, 3, 4, 6, 6, 0, 0 },  // taito tc0690
  { 52, 0, 5, 0, 7, 0, 0 },  // Realtec 8213 [UNLICENSED]
  { 56, 0, 7, 0, 6, 0, 0 },  // KS202 [UNLICENSED]
  { 57, 0, 3, 0, 5, 0, 0 },  // BMC-GKA [UNLICENSED]
  { 58, 1, 6, 1, 6, 0, 0 },  // BMC-GKB (C)NROM-based multicarts, duplicate of mapper 213 [UNLICENSED]
  { 59, 0, 3, 0, 4, 0, 0 },  // BMC-T3H53 & BMC-D1038 [UNLICENSED]
  { 60, 2, 2, 3, 3, 0, 0 },  // Reset-based NROM-128 4-in-1 multicarts [UNLICENSED]
  { 62, 7, 7, 8, 8, 0, 0 },  // K-1017P [UNLICENSED]
  { 63, 8, 8, 0, 0, 0, 0 },  // NTDEC "Powerful" multicart, 3072K [UNLICENSED]
  { 64, 2, 3, 4, 5, 0, 0 },  // tengen rambo-1 [UNLICENSED]
  { 65, 3, 4, 5, 6, 0, 0 },  // irem h-3001
  { 66, 2, 3, 2, 3, 0, 0 },  // gxrom/mhrom
  { 67, 3, 3, 5, 5, 0, 0 },  // sunsoft 3
  { 68, 3, 3, 5, 6, 0, 1 },  // sunsoft 4                                          [sram r/w]
  { 69, 3, 4, 5, 6, 0, 1 },  // sunsoft fme-7/5a/5b                                [sram r/w]
  { 70, 3, 3, 5, 5, 0, 0 },  // bandai
  { 71, 2, 4, 0, 0, 0, 0 },  // camerica/codemasters [UNLICENSED]
  { 72, 3, 3, 5, 5, 0, 0 },  // jaleco jf-17
  { 73, 3, 3, 0, 0, 0, 0 },  // vrc3 (salamander)
  { 75, 3, 3, 5, 5, 0, 0 },  // vrc1
  { 76, 3, 3, 5, 5, 0, 0 },  // namco 109 variant (megami tensei: digital devil story)
  { 77, 3, 3, 3, 3, 0, 0 },  // (napoleon senki)
  { 78, 3, 3, 5, 5, 0, 0 },  // irem 74hc161/32
  { 79, 1, 2, 2, 3, 0, 0 },  // NINA-03/06 by AVE [UNLICENSED]
  { 80, 3, 3, 5, 6, 0, 1 },  // taito x1-005                                       [prgram r/w]
  { 82, 3, 3, 5, 6, 0, 1 },  // taito x1-017 wrong bank order                      [prgram r/w]
  // 84 - bad mapper, not used
  { 85, 3, 5, 0, 5, 0, 1 },  // vrc7                                               [sram r/w]
  { 86, 3, 3, 4, 4, 0, 0 },  // jaleco jf-13 (moero pro yakyuu)
  { 87, 0, 1, 2, 3, 0, 0 },  // Jaleco/Konami CNROM (DIS_74X139X74)
  { 88, 3, 3, 5, 5, 0, 0 },  // namco (dxrom variant)
  { 89, 3, 3, 5, 5, 0, 0 },  // sunsoft 2 variant (tenka no goikenban: mito koumon)
  { 90, 0, 7, 1, 8, 0, 0 },  // J.Y. Company ASIC [UNLICENSED]
  { 91, 3, 5, 7, 8, 0, 0 },  // JY830623C/YY840238C boards [UNLICENSED]
  { 92, 4, 4, 5, 5, 0, 0 },  // jaleco jf-19/jf-21
  { 93, 3, 3, 0, 0, 0, 0 },  // sunsoft 2
  { 94, 3, 3, 0, 0, 0, 0 },  // hvc-un1rom (senjou no ookami)
  { 95, 3, 3, 3, 3, 0, 0 },  // namcot-3425 (dragon buster)
  { 96, 3, 3, 0, 0, 0, 0 },  // (oeka kids)
  { 97, 4, 4, 0, 0, 0, 0 },  // irem tam-s1 (kaiketsu yanchamaru)
  // 100 - bad mapper, not used
  // 101 - bad mapper, not used
  { 105, 4, 4, 0, 0, 0, 0 },  // (nintendo world Championships 1990) [UNTESTED]
  { 111, 5, 5, 0, 0, 0, 0 },  // GTROM [UNLICENSED]
  { 113, 1, 4, 0, 5, 0, 0 },  // NINA-03/06 [UNLICENSED]
  { 114, 3, 4, 5, 6, 0, 0 },  // SuperGame MMC3-clone [UNLICENSED]
  { 118, 3, 4, 5, 5, 0, 1 },  // txsrom/mmc3                                       [sram r/w]
  { 119, 3, 3, 4, 4, 0, 0 },  // tqrom/mmc3
  { 126, 1, 8, 0, 8, 0, 0 },  // MMC3-based multicart (PJ-008, AT-207) [UNLICENSED]
  { 134, 1, 8, 0, 8, 0, 0 },  // T4A54A, WX-KB4K, or BS-5652 [UNLICENSED]
  { 140, 3, 3, 3, 5, 0, 0 },  // jaleco jf-11/jf-14
  { 142, 1, 3, 0, 0, 0, 0 },  // UNL-KS7032 [UNLICENSED]
  { 146, 1, 2, 2, 3, 0, 0 },  // Sachen 3015 [UNLICENSED]
  { 148, 1, 2, 0, 4, 0, 0 },  // Sachen SA-0037 & Tengen 800008 [UNLICENSED]
  // 151 - bad mapper, not used
  { 152, 2, 3, 5, 5, 0, 0 },  // BANDAI-74*161/161/32
  { 153, 5, 5, 0, 0, 1, 1 },  // (famicom jump ii)                                 [sram r/w]
  { 154, 3, 3, 5, 5, 0, 0 },  // namcot-3453 (devil man)
  { 155, 3, 3, 3, 5, 0, 1 },  // mmc1 variant                                      [sram r/w]
  { 157, 4, 4, 0, 0, 0, 0 },  // Datach
  { 158, 3, 3, 5, 5, 0, 0 },  // tengen rambo-1 variant (alien syndrome (u)) [UNLICENSED]
  { 159, 3, 4, 5, 6, 1, 1 },  // bandai x24c01                                     [eep r/w]
  { 162, 6, 7, 0, 0, 0, 0 },  // Waixing FS304 [UNLICENSED]
  { 163, 6, 7, 0, 0, 0, 0 },  // Nanjing FC-001 [UNLICENSED]
  { 174, 3, 3, 4, 4, 0, 0 },  // NTDEC 5-in-1 [UNLICENSED]
  { 176, 4, 4, 5, 5, 0, 0 },  // 8025 enhanced MMC3 [UNLICENSED]
  { 177, 1, 7, 0, 0, 0, 0 },  // Henggedianzi Super Rich PCB [UNLICENSED]
  { 178, 5, 5, 0, 0, 0, 0 },  // some Waixing PCBs [UNLICENSED]
  { 180, 3, 3, 0, 0, 0, 0 },  // unrom variant (crazy climber)
  { 184, 1, 1, 2, 3, 0, 0 },  // sunsoft 1
  { 185, 0, 1, 1, 1, 0, 0 },  // cnrom lockout
  // 186 - bad mapper, not used
  { 200, 1, 4, 1, 4, 0, 0 },  // HN-02 multicarts [UNLICENSED]
  { 201, 1, 8, 1, 9, 0, 0 },  // NROM-256 multicarts [UNLICENSED]
  { 202, 0, 3, 1, 4, 0, 0 },  // BMC-150IN1 multicarts [UNLICENSED]
  { 203, 1, 4, 1, 4, 0, 0 },  // various NROM-128 multicarts [UNLICENSED]
  { 206, 1, 3, 2, 4, 0, 0 },  // dxrom
  { 207, 4, 4, 5, 5, 0, 0 },  // taito x1-005 variant (fudou myouou den)
  { 209, 0, 7, 1, 8, 0, 0 },  // J.Y. Company ASIC [UNLICENSED]
  { 210, 3, 5, 5, 6, 0, 0 },  // namco 175/340
  { 211, 0, 7, 1, 8, 0, 0 },  // J.Y. Company ASIC [UNLICENSED]
  { 212, 0, 3, 0, 4, 0, 0 },  // BMC Super HiK 300-in-1 [UNLICENSED]
  { 213, 1, 6, 1, 6, 0, 0 },  // BMC-GKB (C)NROM-based multicarts, duplicate of mapper 58 [UNLICENSED]
  { 214, 0, 3, 0, 4, 0, 0 },  // BMC-SUPERGUN-20IN1, BMC-190IN1 [UNLICENSED]
  { 225, 4, 7, 5, 8, 0, 0 },  // ET-4310 (FC) + K-1010 (NES) [UNLICENSED]
  { 226, 6, 7, 0, 0, 0, 0 },  // BMC-76IN1, BMC-SUPER42IN1, BMC-GHOSTBUSTERS63IN1 [UNLICENSED]
  { 227, 1, 5, 0, 0, 0, 0 },  // 810449-C-A1 / FW-01 [UNLICENSED]
  { 228, 4, 7, 5, 7, 0, 0 },  // Action 52 + Cheetahmen II [UNLICENSED]
  { 229, 5, 5, 6, 6, 0, 0 },  // BMC 31-IN-1 [UNLICENSED]
  { 232, 4, 4, 0, 0, 0, 0 },  // Camerica/Codemasters "Quattro" cartridges [UNLICENSED]
  { 235, 6, 8, 0, 0, 0, 0 },  // "Golden Game" multicarts [UNLICENSED]
  { 236, 0, 6, 0, 5, 0, 0 },  // Realtec 8031, 8099, 8106, 8155 [UNLICENSED]
  { 240, 1, 5, 1, 5, 0, 3 },  // C&E Bootleg Board (Sheng Huo Lie Zhuan, Jing Ke Xin Zhuan) [UNLICENSED]
  { 241, 3, 5, 0, 0, 0, 0 },  // BxROM with WRAM [UNLICENSED]
  { 242, 5, 5, 0, 0, 0, 0 },  // ET-113 [UNLICENSED]
  { 246, 5, 5, 7, 7, 0, 0 },  // C&E Feng Shen Bang [UNLICENSED]
  // 248 - bad mapper, not used
  { 255, 4, 7, 5, 8, 0, 0 },   // 110-in-1 multicart (same as 225) [UNLICENSED]
  { 268, 0, 11, 0, 8, 0, 0 },  // 268.0 MindKids/CoolGirl [UNLICENSED]
  { 315, 0, 5, 0, 7, 0, 0 },   // BMC-830134C [UNLICENSED]
  { 329, 1, 7, 0, 0, 0, 3 },   // UNL-EDU2000, same as 177 [UNLICENSED]
  { 366, 0, 6, 0, 8, 0, 0 },   // GN-45 [UNLICENSED]
  { 446, 0, 8, 0, 0, 0, 0 },   // Mindkids SMD172B_FGPA submapper 0 & 1 [UNLICENSED]
  { 470, 0, 11, 0, 0, 0, 0 },  // INX_007T_V01 [UNLICENSED]
  { 552, 0, 5, 0, 6, 0, 0 }    // Taito X1-017 actual bank order
};

const char _file_name_no_number_fmt[] PROGMEM = "%s.%s";
const char _file_name_with_number_fmt[] PROGMEM = "%s.%02d.%s";

/******************************************
  Defines
 *****************************************/
#define ROMSEL_HI PORTF |= (1 << 1)
#define ROMSEL_LOW PORTF &= ~(1 << 1)
#define PHI2_HI PORTF |= (1 << 0)
#define PHI2_LOW PORTF &= ~(1 << 0)
#define PRG_READ PORTF |= (1 << 7)
#define PRG_WRITE PORTF &= ~(1 << 7)
#define CHR_READ_HI PORTF |= (1 << 5)
#define CHR_READ_LOW PORTF &= ~(1 << 5)
#define CHR_WRITE_HI PORTF |= (1 << 2)
#define CHR_WRITE_LOW PORTF &= ~(1 << 2)

#define MODE_READ \
  { \
    PORTK = 0xFF; \
    DDRK = 0; \
  }
#define MODE_WRITE DDRK = 0xFF

#define press 1
#define doubleclick 2
#define hold 3
#define longhold 4

/******************************************
  Variables
*****************************************/
// Mapper
uint8_t mapcount = (sizeof(mapsize) / sizeof(mapsize[0]));
uint16_t mapselect;

const uint16_t PRG[] PROGMEM = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768 };
uint8_t prglo = 0;   // Lowest Entry
uint8_t prghi = 11;  // Highest Entry

const uint16_t CHR[] PROGMEM = { 0, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096 };
uint8_t chrlo = 0;   // Lowest Entry
uint8_t chrhi = 10;  // Highest Entry

const uint8_t RAM[] PROGMEM = { 0, 8, 16, 32 };
uint8_t ramlo = 0;  // Lowest Entry
uint8_t ramhi = 3;  // Highest Entry

uint16_t prg;
uint16_t chr;
uint8_t ram;
bool mmc6 = false;
bool flashfound = false;  // NESmaker 39SF040 Flash Cart

// Cartridge Config
uint16_t mapper;
uint8_t prgsize;
uint8_t chrsize;
uint8_t ramsize;

/******************************************
  Menus
*****************************************/
// NES start menu
static const char nesMenuItem1[] PROGMEM = "Read iNES Rom";
static const char nesMenuItem2[] PROGMEM = "Read PRG/CHR";
static const char nesMenuItem5[] PROGMEM = "Change Mapper";
static const char nesMenuItem6[] PROGMEM = "Flash Repro";
static const char* const menuOptionsNES[] PROGMEM = { nesMenuItem1, nesMenuItem2, FSTRING_READ_SAVE, FSTRING_WRITE_SAVE, nesMenuItem5, nesMenuItem6, FSTRING_RESET };

// NES chips menu
static const char nesChipsMenuItem1[] PROGMEM = "Combined PRG+CHR";
static const char nesChipsMenuItem2[] PROGMEM = "Read only PRG";
static const char nesChipsMenuItem3[] PROGMEM = "Read only CHR";
static const char nesChipsMenuItem4[] PROGMEM = "Back";
static const char* const menuOptionsNESChips[] PROGMEM = { nesChipsMenuItem1, nesChipsMenuItem2, nesChipsMenuItem3, nesChipsMenuItem4 };

#if defined(ENABLE_FLASH)
// Repro Writer Menu
static const char nesFlashMenuItem1[] PROGMEM = "Flash NesMaker";
static const char nesFlashMenuItem2[] PROGMEM = "Flash A29040B-MAPPER0";
static const char nesFlashMenuItem3[] PROGMEM = "Back";
static const char* const menuOptionsNESFlash[] PROGMEM = { nesFlashMenuItem1, nesFlashMenuItem2, nesFlashMenuItem3 };
#endif

// NES start menu
void nesMenu() {
  unsigned char answer;

  // create menu with title "NES CART READER" and 7 options to choose from
  convertPgm(menuOptionsNES, 7);
  answer = question_box(F("NES CART READER"), menuOptions, 7, 0);

  // wait for user choice to come back from the question box menu
  switch (answer) {
    // Read Rom
    case 0:
      display_Clear();
      // Change working dir to root
      sd.chdir("/");
      readRom_NES();
      println_Msg(FS(FSTRING_EMPTY));
      // Prints string out of the common strings array either with or without newline
      print_STR(press_button_STR, 1);
#ifdef ENABLE_GLOBAL_LOG
      save_log();
#endif
      display_Update();
      wait();
      break;

    // Read single chip
    case 1:
      nesChipMenu();
      break;

    // Read RAM
    case 2:
      sd.chdir();
      sprintf(folder, "NES/SAVE");
      sd.mkdir(folder, true);
      sd.chdir(folder);
      readRAM();
      resetROM();
      println_Msg(FS(FSTRING_EMPTY));
      // Prints string out of the common strings array either with or without newline
      print_STR(press_button_STR, 1);
      display_Update();
      wait();
      break;

    // Write RAM
    case 3:
      writeRAM();
      resetROM();
      println_Msg(FS(FSTRING_EMPTY));
      // Prints string out of the common strings array either with or without newline
      print_STR(press_button_STR, 1);
      display_Update();
      wait();
      break;

    // Change Mapper
    case 4:
      setDefaultRomName();
      setMapper();
      checkMapperSize();
      setPRGSize();
      setCHRSize();
      setRAMSize();
      checkStatus_NES();
      break;

#if defined(ENABLE_FLASH)
    // Write FLASH
    case 5:
      nesFlashMenu();
      break;
#endif

    // Reset
    case 6:
      resetArduino();
      break;

    default:
      print_MissingModule();  // does not return
  }
}

void nesChipMenu() {
  // create menu with title "Select NES Chip" and 4 options to choose from
  convertPgm(menuOptionsNESChips, 4);
  unsigned char answer = question_box(F("Select NES Chip"), menuOptions, 4, 0);

  // wait for user choice to come back from the question box menu
  switch (answer) {
    // Read combined PRG/CHR
    case 0:
      display_Clear();
      // Change working dir to root
      sd.chdir("/");
      readRaw_NES();
      println_Msg(FS(FSTRING_EMPTY));
      // Prints string out of the common strings array either with or without newline
      print_STR(press_button_STR, 1);
#ifdef ENABLE_GLOBAL_LOG
      save_log();
#endif
      display_Update();
      wait();
      break;

    // Read PRG
    case 1:
      CreateROMFolderInSD();
      readPRG(false);
      resetROM();
      println_Msg(FS(FSTRING_EMPTY));
      // Prints string out of the common strings array either with or without newline
      print_STR(press_button_STR, 1);
      display_Update();
      wait();
      break;

    // Read CHR
    case 2:
      CreateROMFolderInSD();
      readCHR(false);
      resetROM();
      println_Msg(FS(FSTRING_EMPTY));
      // Prints string out of the common strings array either with or without newline
      print_STR(press_button_STR, 1);
      display_Update();
      wait();
      break;

    // Return to Main Menu
    case 3:
      nesMenu();
      wait();
      break;
  }
}

#if defined(ENABLE_FLASH)
void nesFlashMenu() {
  // create menu with title "Select NES Flash Repro" and 3 options to choose from
  convertPgm(menuOptionsNESFlash, 3);
  unsigned char answer = question_box(F("Select Flash Writer"), menuOptions, 3, 0);
  switch (answer) {
    case 0:

      if (mapper == 30) {
        writeFLASH();
        resetROM();
      } else {
        display_Clear();
        println_Msg(FS(string_error5));
        println_Msg(F("Can't write to this cartridge"));
        println_Msg(FS(FSTRING_EMPTY));
        // Prints string out of the common strings array either with or without newline
        print_STR(press_button_STR, 1);
        display_Update();
      }
      wait();
      break;
    case 1:
      if (mapper == 0) {
        display_Clear();
        A29040B_writeFLASH();
        display_Update();
        wait();
      } else {
        display_Clear();
        println_Msg(FS(string_error5));
        println_Msg(F("Can't write to this cartridge"));
        println_Msg(mapper);
        // Prints string out of the common strings array either with or without newline
        print_STR(press_button_STR, 1);
        display_Update();
        wait();
      }

      break;
    // Return to Main Menu
    case 2:
      nesMenu();
      wait();
      break;
  }
}
#endif

/******************************************
   Setup
 *****************************************/
void setup_NES() {
  // Request 5V
  setVoltage(VOLTS_SET_5V);

  // CPU R/W, IRQ, PPU /RD, PPU /A13, CIRAM /CE, PPU /WR, /ROMSEL, PHI2
  DDRF = 0b10110111;
  // CPU R/W, IRQ, PPU /RD, PPU /A13, CIRAM /CE, PPU /WR, /ROMSEL, PHI2
  PORTF = 0b11111111;

  // A0-A7 to Output
  DDRL = 0xFF;
  // A8-A14 to Output
  DDRA = 0xFF;

  // Set CIRAM A10 to Input
  DDRC &= ~(1 << 2);
  // Activate Internal Pullup Resistors
  PORTC |= (1 << 2);

  // Set D0-D7 to Input
  PORTK = 0xFF;
  DDRK = 0;

  set_address(0);
  rgbLed(black_color);
}

/******************************************
   Get Mapping from SD database
 *****************************************/
uint32_t uppow2(uint32_t n) {
  for (int8_t x = 31; x >= 0; x--)
    if (n & (1u << x)) {
      if ((1u << x) != n)
        return (1u << (x + 1));
      break;
    }
  return n;
}

struct database_entry {
  char filename[128];
  char crc_str[8 + 1 + 8 + 1 + 32 + 1];
  uint32_t crc;
  char* crc512_str;
  uint32_t crc512;
  char* iNES_str;
};

void printPRG(unsigned long myOffset) {
  display_Clear();
  print_Msg(F("Printing PRG at "));
  println_Msg(myOffset);

  char myBuffer[3];

  for (size_t currLine = 0; currLine < 512; currLine += 16) {
    for (uint8_t currByte = 0; currByte < 16; currByte++) {
      itoa(read_prg_byte(myOffset + currLine + currByte), myBuffer, 16);
      for (size_t i = 0; i < 2 - strlen(myBuffer); i++) {
        print_Msg(F("0"));
      }
      // Now print the significant bits
      print_Msg(myBuffer);
      print_Msg(" ");
    }
    println_Msg("");
  }
  display_Update();
}

void setDefaultRomName() {
  romName[0] = 'C';
  romName[1] = 'A';
  romName[2] = 'R';
  romName[3] = 'T';
  romName[4] = '\0';
}

void setRomnameFromString(const char* input) {
  uint8_t myLength = 0;
  for (uint8_t i = 0; i < 20 && myLength < 15; i++) {
    // Stop at first "(" to remove "(Country)"
    if (input[i] == '(') {
      break;
    }
    if (
      (input[i] >= '0' && input[i] <= '9') || (input[i] >= 'A' && input[i] <= 'Z') || (input[i] >= 'a' && input[i] <= 'z')) {
      romName[myLength++] = input[i];
    }
  }

  // If name consists out of all japanese characters use CART as name
  if (myLength == 0) {
    setDefaultRomName();
  }
}

void printDataLine_NES(void* entry) {
  struct database_entry* castEntry = (struct database_entry*)entry;
  uint8_t iNES[16];
  uint8_t* output;
  char* input;

  input = castEntry->iNES_str;
  output = iNES;
  for (uint8_t i = 0; i < sizeof(iNES); i++) {
    unsigned int buf;

    sscanf(input, "%2X", &buf);
    *(output++) = buf;
    input += 2;
  }

  mapper = (iNES[6] >> 4) | (iNES[7] & 0xF0) | ((iNES[8] & 0x0F) << 8);

  if ((iNES[9] & 0x0F) != 0x0F) {
    // simple notation
    prgsize = (iNES[4] | ((iNES[9] & 0x0F) << 8));  //*16
  } else {
    // exponent-multiplier notation
    prgsize = (((1 << (iNES[4] >> 2)) * ((iNES[4] & 0b11) * 2 + 1)) >> 14);  //*16
  }
  if (prgsize != 0)
    prgsize = (int(log(prgsize) / log(2)));

  if ((iNES[9] & 0xF0) != 0xF0) {
    // simple notation
    chrsize = (uppow2(iNES[5] | ((iNES[9] & 0xF0) << 4))) * 2;  //*4
  } else {
    // exponent-multiplier notation
    chrsize = (((1 << (iNES[5] >> 2)) * ((iNES[5] & 0b11) * 2 + 1)) >> 13) * 2;  //*4
  }
  if (chrsize != 0)
    chrsize = (int(log(chrsize) / log(2)));

  ramsize = ((iNES[10] & 0xF0) ? (64 << ((iNES[10] & 0xF0) >> 4)) : 0) / 4096;  //*4
  if (ramsize != 0)
    ramsize = (int(log(ramsize) / log(2)));

  prg = (int_pow(2, prgsize)) * 16;
  if (chrsize == 0)
    chr = 0;  // 0K
  else
    chr = (int_pow(2, chrsize)) * 4;
  if (ramsize == 0)
    ram = 0;  // 0K
  else if (mapper == 82)
    ram = 5;  // 5K
  else
    ram = (int_pow(2, ramsize)) * 4;

  // Mapper Variants
  // Identify variant for use across multiple functions
  if (mapper == 4) {  // Check for MMC6/MMC3
    checkMMC6();
    if (mmc6) {
      ram = 1;      // 1K
      ramsize = 1;  // Must be a non-zero value
    }
  }
  printNESSettings();
}

void getMapping() {
  FsFile database;
  uint32_t oldcrc32 = 0xFFFFFFFF;
  uint32_t oldcrc32MMC3 = 0xFFFFFFFF;
  char crcStr[9];

  display_Clear();

  sd.chdir();
  if (!database.open("nes.txt", O_READ)) {
    print_FatalError(FS(FSTRING_DATABASE_FILE_NOT_FOUND));
    // never reached
  }

  // Read first 512 bytes of first and last block of PRG ROM and compute CRC32
  // Some mappers (like MMC3) map the last 8KB block of PRG ROM to 0xE000 while 0x8000 can contain random data after bootup
  for (size_t c = 0; c < 512; c++) {
    UPDATE_CRC(oldcrc32, read_prg_byte(0x8000 + c));
    UPDATE_CRC(oldcrc32MMC3, read_prg_byte(0xE000 + c));
  }
  oldcrc32 = ~oldcrc32;
  oldcrc32MMC3 = ~oldcrc32MMC3;
  bool browseDatabase;

  // Filter out all 0xFF checksums at 0x8000 and 0xE000
  if (oldcrc32 == 0xBD7BC39F && oldcrc32MMC3 == 0xBD7BC39F) {
    println_Msg(F("No data found."));
    println_Msg(F("Using manual selection"));
    display_Update();
    delay(500);
    setDefaultRomName();
    browseDatabase = selectMapping(database);
  } else {
    println_Msg(F("Searching database"));
    print_Msg(F("for "));
    sprintf(crcStr, "%08lX", oldcrc32);
    print_Msg(crcStr);
    if (oldcrc32 != oldcrc32MMC3) {
      print_Msg(F(" or "));
      sprintf(crcStr, "%08lX", oldcrc32MMC3);
      print_Msg(crcStr);
    }
    println_Msg(F("..."));
    display_Update();
    while (database.available()) {
      struct database_entry entry;

      readDatabaseEntry(database, &entry);
      //if checksum search was successful set mapper and end search, also filter out 0xFF checksum
      if (
        entry.crc512 != 0xBD7BC39F && (entry.crc512 == oldcrc32 || entry.crc512 == oldcrc32MMC3)) {
        // Rewind to start of entry
        rewind_line(database, 3);
        break;
      }
    }
    if (database.available()) {
      browseDatabase = true;
    } else {
      // File searched until end but nothing found
      println_Msg(FS(FSTRING_EMPTY));
      println_Msg(F("CRC not found in database"));
      println_Msg(F("Using manual selection"));
      display_Update();
      delay(500);
      // Print content of PRG for debugging
      //printPRG(0x8000);
      //printPRG(0xE000);

      // Change ROM name to CART
      setDefaultRomName();
      browseDatabase = selectMapping(database);
    }
  }
  if (browseDatabase) {
    struct database_entry entry;

    if (checkCartSelection(database, &readDataLine_NES, &entry, &printDataLine_NES, &setRomnameFromString)) {
      // anything else: select current record
      // Save Mapper
      EEPROM_writeAnything(7, mapper);
      EEPROM_writeAnything(9, prgsize);
      EEPROM_writeAnything(10, chrsize);
      EEPROM_writeAnything(11, ramsize);
    }
  }
  database.close();
}

static void readDatabaseEntry(FsFile& database, struct database_entry* entry) {
  get_line(entry->filename, &database, sizeof(entry->filename));
  readDataLine_NES(database, entry);
  skip_line(&database);
}

void readDataLine_NES(FsFile& database, void* e) {
  struct database_entry* entry = (database_entry*)e;
  get_line(entry->crc_str, &database, sizeof(entry->crc_str));

  entry->crc_str[8] = 0;
  entry->crc512_str = &entry->crc_str[8 + 1];
  entry->crc512_str[8] = 0;
  entry->iNES_str = &entry->crc_str[8 + 1 + 8 + 1];

  // Convert "4E4553" to (0x4E, 0x45, 0x53)
  unsigned int iNES_BUF;
  for (uint8_t j = 0; j < 16; j++) {
    sscanf(entry->iNES_str + j * 2, "%2X", &iNES_BUF);
    iNES_HEADER[j] = iNES_BUF;
  }

  entry->crc = strtoul(entry->crc_str, NULL, 16);
  entry->crc512 = strtoul(entry->crc512_str, NULL, 16);
}

bool selectMapping(FsFile& database) {
  // Select starting letter
  byte myLetter = starting_letter();

  if (myLetter == 27) {
    // Change Mapper
    setMapper();
    checkMapperSize();
    setPRGSize();
    setCHRSize();
    setRAMSize();
    return 0;
  } else {
    seek_first_letter_in_database(database, myLetter);
  }
  return 1;
}

void read_NES(const char* fileSuffix, const byte* header, const uint8_t headersize, const boolean renamerom) {
  // Get name, add extension and convert to char array for sd lib
  createFolderAndOpenFile("NES", "ROM", romName, fileSuffix);

  //Initialize progress bar
  uint32_t processedProgressBar = 0;
  uint32_t totalProgressBar = (uint32_t)(headersize + prgsize * 16 * 1024 + chrsize * 4 * 1024);
  draw_progressbar(0, totalProgressBar);

  //Write header
  if (headersize > 0) {
    myFile.write(header, headersize);

    // update progress bar
    processedProgressBar += headersize;
    draw_progressbar(processedProgressBar, totalProgressBar);
  }

  //Write PRG
  readPRG(true);

  // update progress bar
  processedProgressBar += prgsize * 16 * 1024;
  draw_progressbar(processedProgressBar, totalProgressBar);

  //Write CHR
  readCHR(true);

  // update progress bar
  processedProgressBar += chrsize * 4 * 1024;
  draw_progressbar(processedProgressBar, totalProgressBar);

  // Close the file:
  myFile.close();

  // Compare CRC32 with database
  compareCRC("nes.txt", 0, renamerom, headersize);
}

void readRom_NES() {
  read_NES("nes", iNES_HEADER, 16, true);
}

void readRaw_NES() {
  read_NES("bin", NULL, 0, false);
}

/******************************************
   Low Level Functions
 *****************************************/
static void set_address(unsigned int address) {
  unsigned char l = address & 0xFF;
  unsigned char h = address >> 8;
  PORTL = l;
  PORTA = h;

  // PPU /A13
  if ((address >> 13) & 1)
    PORTF &= ~(1 << 4);
  else
    PORTF |= 1 << 4;
}

static void set_romsel(unsigned int address) {
  if (address & 0x8000) {
    ROMSEL_LOW;
  } else {
    ROMSEL_HI;
  }
}

static unsigned char read_prg_byte(unsigned int address) {
  MODE_READ;
  PRG_READ;
  set_address(address);
  PHI2_HI;
  set_romsel(address);
  _delay_us(1);
  return PINK;
}

static unsigned char read_chr_byte(unsigned int address) {
  MODE_READ;
  PHI2_HI;
  ROMSEL_HI;
  set_address(address);
  CHR_READ_LOW;
  _delay_us(1);
  uint8_t result = PINK;
  CHR_READ_HI;
  return result;
}

static void write_prg_byte(unsigned int address, uint8_t data) {
  PHI2_LOW;
  ROMSEL_HI;
  MODE_WRITE;
  PRG_WRITE;
  PORTK = data;

  set_address(address);  // PHI2 low, ROMSEL always HIGH
  //  _delay_us(1);
  PHI2_HI;
  //_delay_us(10);
  set_romsel(address);  // ROMSEL is low if need, PHI2 high
  _delay_us(1);         // WRITING
  //_delay_ms(1); // WRITING
  // PHI2 low, ROMSEL high
  PHI2_LOW;
  _delay_us(1);
  ROMSEL_HI;
  // Back to read mode
  //  _delay_us(1);
  PRG_READ;
  MODE_READ;
  set_address(0);
  // Set phi2 to high state to keep cartridge unreseted
  //  _delay_us(1);
  PHI2_HI;
  //  _delay_us(1);
}

#if defined(ENABLE_FLASH)
static void write_chr_byte(unsigned int address, uint8_t data) {
  PHI2_LOW;
  ROMSEL_HI;
  MODE_WRITE;
  PORTK = data;
  set_address(address);  // PHI2 low, ROMSEL always HIGH
  _delay_us(1);

  CHR_WRITE_LOW;

  _delay_us(1);  // WRITING

  CHR_WRITE_HI;

  _delay_us(1);

  MODE_READ;
  set_address(0);
  PHI2_HI;

  //_delay_us(1);
}
#endif

void resetROM() {
  set_address(0);
  PHI2_HI;
  ROMSEL_HI;
}

void write_mmc1_byte(unsigned int address, uint8_t data) {  // write loop for 5 bit register
  if (address >= 0xE000) {
    for (uint8_t i = 0; i < 5; i++) {
      write_reg_byte(address, data >> i);  // shift 1 bit into temp register [WRITE RAM SAFE]
    }
  } else {
    for (uint8_t j = 0; j < 5; j++) {
      write_prg_byte(address, data >> j);  // shift 1 bit into temp register
    }
  }
}

// REFERENCE FOR REGISTER WRITE TO 0xE000/0xF000
// PORTF 7 = CPU R/W = 0
// PORTF 6 = /IRQ = 1
// PORTF 5 = PPU /RD = 1
// PORTF 4 = PPU /A13 = 1
// PORTF 3 = CIRAM /CE = 1
// PORTF 2 = PPU /WR = 1
// PORTF 1 = /ROMSEL
// PORTF 0 = PHI2 (M2)

// WRITE RAM SAFE TO REGISTERS 0xE000/0xF000
static void write_reg_byte(unsigned int address, uint8_t data) {  // FIX FOR MMC1 RAM CORRUPTION
  PHI2_LOW;
  ROMSEL_HI;  // A15 HI = E000
  MODE_WRITE;
  PRG_WRITE;  // CPU R/W LO
  PORTK = data;

  set_address(address);  // PHI2 low, ROMSEL always HIGH
  // DIRECT PIN TO PREVENT RAM CORRUPTION
  // DIFFERENCE BETWEEN M2 LO AND ROMSEL HI MUST BE AROUND 33ns
  // IF TIME IS GREATER THAN 33ns THEN WRITES TO 0xE000/0xF000 WILL CORRUPT RAM AT 0x6000/0x7000
  PORTF = 0b01111101;  // ROMSEL LO/M2 HI
  PORTF = 0b01111110;  // ROMSEL HI/M2 LO
  _delay_us(1);
  // Back to read mode
  PRG_READ;
  MODE_READ;
  set_address(0);
  // Set phi2 to high state to keep cartridge unreseted
  PHI2_HI;
}

static void write_ram_byte(unsigned int address, uint8_t data) {  // Mapper 19 (Namco 106/163) WRITE RAM SAFE ($E000-$FFFF)
  PHI2_LOW;
  ROMSEL_HI;
  MODE_WRITE;
  PRG_WRITE;
  PORTK = data;

  set_address(address);  // PHI2 low, ROMSEL always HIGH
  PHI2_HI;
  ROMSEL_LOW;    // SET /ROMSEL LOW OTHERWISE CORRUPTS RAM
  _delay_us(1);  // WRITING
  // PHI2 low, ROMSEL high
  PHI2_LOW;
  _delay_us(1);
  ROMSEL_HI;
  // Back to read mode
  PRG_READ;
  MODE_READ;
  set_address(0);
  // Set phi2 to high state to keep cartridge unreseted
  PHI2_HI;
}

static void write_wram_byte(unsigned int address, uint8_t data) {  // Mapper 5 (MMC5) RAM
  PHI2_LOW;
  ROMSEL_HI;
  set_address(address);
  PORTK = data;

  _delay_us(1);
  MODE_WRITE;
  PRG_WRITE;
  PHI2_HI;
  _delay_us(1);  // WRITING
  PHI2_LOW;
  ROMSEL_HI;
  // Back to read mode
  PRG_READ;
  MODE_READ;
  set_address(0);
  // Set phi2 to high state to keep cartridge unreseted
  PHI2_HI;
}

// Pirate Mapper 59
static void write_reg_m59(unsigned int address) {
  ROMSEL_HI;
  MODE_WRITE;
  PRG_WRITE;
  set_address(address);
  set_romsel(address);
  _delay_us(1);  // WRITING
  ROMSEL_HI;
  PRG_READ;
  MODE_READ;
  set_address(0);
}

/******************************************
   File Functions
 *****************************************/
void CreateROMFolderInSD() {
  sd.chdir();
  sprintf(folder, "NES/ROM");
  sd.mkdir(folder, true);
  sd.chdir(folder);
}

FsFile createNewFile(const char* prefix, const char* extension) {
  char filename[FILENAME_LENGTH];
  snprintf_P(filename, sizeof(filename), _file_name_no_number_fmt, prefix, extension);
  for (uint8_t i = 0; i < 100; i++) {
    if (!sd.exists(filename)) {
      return sd.open(fileName, O_RDWR | O_CREAT);
    }
    snprintf_P(filename, sizeof(filename), _file_name_with_number_fmt, prefix, i, extension);
  }
  // Could not find an available name, recompose the original name and error out.
  snprintf_P(filename, sizeof(filename), _file_name_no_number_fmt, prefix, extension);

  rgbLed(red_color);

  display_Clear();
  print_Msg(filename);
  println_Msg(F(": no available name"));
  display_Update();
  print_FatalError(sd_error_STR);

  rgbLed(black_color);
}

void CreatePRGFileInSD() {
  myFile = createNewFile("PRG", "bin");
}

void CreateCHRFileInSD() {
  myFile = createNewFile("CHR", "bin");
}

//createNewFile fails to dump RAM if ROM isn't dumped first
//void CreateRAMFileInSD() {
//myFile = createNewFile("RAM", "bin");
//}
//Temporary fix
void CreateRAMFileInSD() {
  char fileCount[3];
  strcpy(fileName, "RAM");
  strcat(fileName, ".sav");
  for (uint8_t i = 0; i < 100; i++) {
    if (!sd.exists(fileName)) {
      myFile = sd.open(fileName, O_RDWR | O_CREAT);
      break;
    }
    sprintf(fileCount, "%02d", i);
    strcpy(fileName, "RAM.");
    strcat(fileName, fileCount);
    strcat(fileName, ".sav");
  }
  if (!myFile) {
    rgbLed(red_color);

    display_Clear();
    println_Msg(F("RAM FILE FAILED!"));
    display_Update();
    //print_Error(F("SD Error"), true);

    rgbLed(black_color);
  }
}

/******************************************
   Config Functions
 *****************************************/

#if defined(ENABLE_LCD)
void printMapperSelection_NES(int index) {
  display_Clear();
  mapselect = pgm_read_word(mapsize + index);
  print_Msg(FS(FSTRING_MAPPER));
  println_Msg(mapselect);
}
#endif

void setMapper() {
  uint16_t newmapper;
#ifdef ENABLE_GLOBAL_LOG
  // Disable log to prevent unnecessary logging
  println_Log(F("Set Mapper manually"));
  dont_log = true;
#endif

  // OLED
#if defined(ENABLE_OLED)
chooseMapper:
  // Read stored mapper
  EEPROM_readAnything(7, newmapper);
  if (newmapper > 220)
    newmapper = 0;
  // Split into digits
  uint8_t hundreds = newmapper / 100;
  uint8_t tens = newmapper / 10 - hundreds * 10;
  uint8_t units = newmapper - hundreds * 100 - tens * 10;

  // Cycle through all 3 digits
  uint8_t digit = 0;
  while (digit < 3) {
    display_Clear();
    println_Msg(F("Select Mapper:"));
    display.setCursor(23, 20);
    println_Msg(hundreds);
    display.setCursor(43, 20);
    println_Msg(tens);
    display.setCursor(63, 20);
    println_Msg(units);
    println_Msg("");
    println_Msg("");
    println_Msg("");
    print_STR(press_to_change_STR, 1);
    println_Msg(F("Press right to select"));

    if (digit == 0) {
      display.setDrawColor(1);
      display.drawLine(20, 30, 30, 30);
      display.setDrawColor(0);
      display.drawLine(40, 30, 50, 30);
      display.drawLine(60, 30, 70, 30);
      display.setDrawColor(1);
    } else if (digit == 1) {
      display.setDrawColor(0);
      display.drawLine(20, 30, 30, 30);
      display.setDrawColor(1);
      display.drawLine(40, 30, 50, 30);
      display.setDrawColor(0);
      display.drawLine(60, 30, 70, 30);
      display.setDrawColor(1);
    } else if (digit == 2) {
      display.setDrawColor(0);
      display.drawLine(20, 30, 30, 30);
      display.drawLine(40, 30, 50, 30);
      display.setDrawColor(1);
      display.drawLine(60, 30, 70, 30);
    }
    display.updateDisplay();

    while (1) {
      /* Check Button
         1 click
         2 doubleClick
         3 hold
         4 longHold */
      uint8_t b = checkButton();

      if (b == 1) {
        if (digit == 0) {
          if (hundreds < 2)
            hundreds++;
          else
            hundreds = 0;
        } else if (digit == 1) {
          if (hundreds == 2) {
            if (tens < 1)
              tens++;
            else
              tens = 0;
          } else {
            if (tens < 9)
              tens++;
            else
              tens = 0;
          }
        } else if (digit == 2) {
          if (units < 9)
            units++;
          else
            units = 0;
        }
        break;
      } else if (b == 2) {
        if (digit == 0) {
          if (hundreds > 0)
            hundreds--;
          else
            hundreds = 2;
        } else if (digit == 1) {
          if (hundreds == 2) {
            if (tens > 0)
              tens--;
            else
              tens = 1;
          } else {
            if (tens > 0)
              tens--;
            else
              tens = 9;
          }
        } else if (digit == 2) {
          if (units > 0)
            units--;
          else
            units = 9;
        }
        break;
      } else if (b == 3) {
        digit++;
        break;
      }
    }
  }
  display_Clear();

  newmapper = hundreds * 100 + tens * 10 + units;

  // Check if valid
  bool validMapper = 0;
  for (uint8_t currMaplist = 0; currMaplist < mapcount; currMaplist++) {
    if (pgm_read_word(mapsize + currMaplist) == newmapper)
      validMapper = 1;
  }

  if (!validMapper) {
    errorLvl = 1;
    display.println(F("Mapper not supported"));
    display.updateDisplay();
    wait();
    goto chooseMapper;
  }

  // LCD
#elif defined(ENABLE_LCD)
  navigateMenu(0, mapcount - 1, &printMapperSelection_NES);
  newmapper = mapselect;

  display.setCursor(0, 56 + 8);
  print_Msg(F("MAPPER "));
  print_Msg(newmapper);
  println_Msg(F(" SELECTED"));
  display_Update();
  delay(500);

  // Serial Monitor
#elif defined(ENABLE_SERIAL)
setmapper:
  String newmap;
  bool mapfound = false;
  Serial.println(F("SUPPORTED MAPPERS:"));
  for (int i = 0; i < mapcount; i++) {
    mapselect = pgm_read_word(mapsize + i);
    Serial.print("[");
    Serial.print(mapselect);
    Serial.print("]");
    if (i < mapcount - 1) {
      if ((i != 0) && ((i + 1) % 10 == 0))
        Serial.println(FS(FSTRING_EMPTY));
      else
        Serial.print(F("\t"));
    } else
      Serial.println(FS(FSTRING_EMPTY));
  }
  Serial.print(F("Enter Mapper: "));
  while (Serial.available() == 0) {}
  newmap = Serial.readStringUntil('\n');
  Serial.println(newmap);
  newmapper = newmap.toInt();
  for (uint8_t i = 0; i < mapcount; i++) {
    mapselect = pgm_read_word(mapsize + i);
    if (newmapper == mapselect)
      mapfound = true;
  }
  if (mapfound == false) {
    Serial.println(F("MAPPER NOT SUPPORTED!"));
    Serial.println(FS(FSTRING_EMPTY));
    newmapper = 0;
    goto setmapper;
  }
#endif

  EEPROM_writeAnything(7, newmapper);
  mapper = newmapper;

#ifdef ENABLE_GLOBAL_LOG
  // Enable log again
  dont_log = false;
#endif
}

void checkMapperSize() {
  mapper_NES v;
  for (uint8_t i = 0; i < mapcount; i++) {
    memcpy_P(&v, mapsize + i, sizeof(v));
    if (mapper == v.mapper) {
      prglo = v.prglo;
      prghi = v.prghi;
      chrlo = v.chrlo;
      chrhi = v.chrhi;
      ramlo = v.ramlo;
      ramhi = v.ramhi;
      break;
    }
  }
}

#if (defined(ENABLE_LCD) || defined(ENABLE_OLED))
void printPrgSize_NES(int index) {
  display_Clear();
  print_Msg(F("PRG Size: "));
  println_Msg(pgm_read_word(&(PRG[index])));
}
#endif

void setPRGSize() {
  uint8_t newprgsize;

#ifdef ENABLE_GLOBAL_LOG
  // Disable log to prevent unnecessary logging
  println_Log(F("Set PRG Size"));
  dont_log = true;
#endif

#if (defined(ENABLE_LCD) || defined(ENABLE_OLED))
  display_Clear();
  if (prglo == prghi)
    newprgsize = prglo;
  else {
    newprgsize = navigateMenu(prglo, prghi, &printPrgSize_NES);

    display.setCursor(0, 56);  // Display selection at bottom
  }
  print_Msg(F("PRG SIZE "));
  print_Msg(pgm_read_word(&(PRG[newprgsize])));
  println_Msg(F("K"));
  display_Update();
  delay(500);

#elif defined(ENABLE_SERIAL)
  if (prglo == prghi)
    newprgsize = prglo;
  else {
setprg:
    String sizePRG;
    for (int i = 0; i < (prghi - prglo + 1); i++) {
      Serial.print(F("Select PRG Size:  "));
      Serial.print(i);
      Serial.print(F(" = "));
      Serial.print(pgm_read_word(&(PRG[i + prglo])));
      Serial.println(F("K"));
    }
    Serial.print(F("Enter PRG Size: "));
    while (Serial.available() == 0) {}
    sizePRG = Serial.readStringUntil('\n');
    Serial.println(sizePRG);
    newprgsize = sizePRG.toInt() + prglo;
    if (newprgsize > prghi) {
      Serial.println(F("SIZE NOT SUPPORTED"));
      Serial.println(FS(FSTRING_EMPTY));
      goto setprg;
    }
  }
  Serial.print(F("PRG Size = "));
  Serial.print(pgm_read_word(&(PRG[newprgsize])));
  Serial.println(F("K"));
#endif
  EEPROM_writeAnything(9, newprgsize);
  prgsize = newprgsize;

#ifdef ENABLE_GLOBAL_LOG
  // Enable log again
  dont_log = false;
#endif
}

#if (defined(ENABLE_LCD) || defined(ENABLE_OLED))
void printChrSize_NES(int index) {
  display_Clear();
  print_Msg(F("CHR Size: "));
  println_Msg(pgm_read_word(&(CHR[index])));
}
#endif

void setCHRSize() {
  uint8_t newchrsize;
#ifdef ENABLE_GLOBAL_LOG
  // Disable log to prevent unnecessary logging
  println_Log(F("Set CHR Size"));
  dont_log = true;
#endif

#if (defined(ENABLE_LCD) || defined(ENABLE_OLED))
  display_Clear();
  if (chrlo == chrhi)
    newchrsize = chrlo;
  else {
    newchrsize = navigateMenu(chrlo, chrhi, &printChrSize_NES);

    display.setCursor(0, 56);  // Display selection at bottom
  }
  print_Msg(F("CHR SIZE "));
  print_Msg(pgm_read_word(&(CHR[newchrsize])));
  println_Msg(F("K"));
  display_Update();
  delay(500);

#elif defined(ENABLE_SERIAL)
  if (chrlo == chrhi)
    newchrsize = chrlo;
  else {
setchr:
    String sizeCHR;
    for (int i = 0; i < (chrhi - chrlo + 1); i++) {
      Serial.print(F("Select CHR Size:  "));
      Serial.print(i);
      Serial.print(F(" = "));
      Serial.print(pgm_read_word(&(CHR[i + chrlo])));
      Serial.println(F("K"));
    }
    Serial.print(F("Enter CHR Size: "));
    while (Serial.available() == 0) {}
    sizeCHR = Serial.readStringUntil('\n');
    Serial.println(sizeCHR);
    newchrsize = sizeCHR.toInt() + chrlo;
    if (newchrsize > chrhi) {
      Serial.println(F("SIZE NOT SUPPORTED"));
      Serial.println(FS(FSTRING_EMPTY));
      goto setchr;
    }
  }
  Serial.print(F("CHR Size = "));
  Serial.print(pgm_read_word(&(CHR[newchrsize])));
  Serial.println(F("K"));
#endif
  EEPROM_writeAnything(10, newchrsize);
  chrsize = newchrsize;

#ifdef ENABLE_GLOBAL_LOG
  // Enable log again
  dont_log = false;
#endif
}

#if (defined(ENABLE_LCD) || defined(ENABLE_OLED))
void printRamSize_NES(int index) {
  display_Clear();
  print_Msg(F("RAM Size: "));
  if (mapper == 0)
    println_Msg(pgm_read_byte(&(RAM[index])) / 4);
  else if (mapper == 16)
    println_Msg(pgm_read_byte(&(RAM[index])) * 32);
  else if (mapper == 19) {
    if (index == 2)
      println_Msg(F("128"));
    else
      println_Msg(pgm_read_byte(&(RAM[index])));
  } else if ((mapper == 159) || (mapper == 80))
    println_Msg(pgm_read_byte(&(RAM[index])) * 16);
  else if (mapper == 82)
    println_Msg(index * 5);
  else
    println_Msg(pgm_read_byte(&(RAM[index])));
}
#endif

void setRAMSize() {
  uint8_t newramsize;
#ifdef ENABLE_GLOBAL_LOG
  // Disable log to prevent unnecessary logging
  println_Log(F("Set RAM Size"));
  dont_log = true;
#endif

#if (defined(ENABLE_LCD) || defined(ENABLE_OLED))
  display_Clear();
  if (ramlo == ramhi)
    newramsize = ramlo;
  else {
    newramsize = navigateMenu(0, ramhi, &printRamSize_NES);

    display.setCursor(0, 56);  // Display selection at bottom
  }
  if ((mapper == 16) || (mapper == 159)) {
    int sizeEEP = 0;
    print_Msg(F("EEPROM SIZE "));
    if (mapper == 16)
      sizeEEP = pgm_read_byte(&(RAM[newramsize])) * 32;
    else
      sizeEEP = pgm_read_byte(&(RAM[newramsize])) * 16;
    print_Msg(sizeEEP);
    println_Msg(F("B"));
  } else if (mapper == 19) {
    print_Msg(F("RAM SIZE "));
    if (newramsize == 2)
      println_Msg(F("128B"));
    else {
      print_Msg(pgm_read_byte(&(RAM[newramsize])));
      println_Msg(F("K"));
    }
  } else if (mapper == 80) {
    print_Msg(F("RAM SIZE "));
    print_Msg(pgm_read_byte(&(RAM[newramsize])) * 16);
    println_Msg(F("B"));
  } else {
    print_Msg(F("RAM SIZE "));
    if (mapper == 0)
      print_Msg(newramsize * 2);
    else if (mapper == 82)
      print_Msg(newramsize * 5);
    else
      print_Msg(pgm_read_byte(&(RAM[newramsize])));
    println_Msg(F("K"));
  }
  display_Update();
  delay(500);

#elif defined(ENABLE_SERIAL)
  if (ramlo == ramhi)
    newramsize = ramlo;
  else {
setram:
    String sizeRAM;
    for (int i = 0; i < (ramhi - ramlo + 1); i++) {
      Serial.print(F("Select RAM Size:  "));
      Serial.print(i);
      Serial.print(F(" = "));
      if (mapper == 0) {
        Serial.print(pgm_read_byte(&(RAM[i])) / 4);
        Serial.println(F("K"));
      } else if ((mapper == 16) || (mapper == 159)) {
        if (mapper == 16)
          Serial.print(pgm_read_byte(&(RAM[i + ramlo])) * 32);
        else
          Serial.print(pgm_read_byte(&(RAM[i + ramlo])) * 16);
        Serial.println(F("B"));
      } else if (mapper == 19) {
        if (i == 2)
          Serial.println(F("128B"));
        else {
          Serial.print(pgm_read_byte(&(RAM[i + ramlo])));
          Serial.println(F("K"));
        }
      } else {
        Serial.print(pgm_read_byte(&(RAM[i + ramlo])));
        Serial.println(F("K"));
      }
    }
    Serial.print(F("Enter RAM Size: "));
    while (Serial.available() == 0) {}
    sizeRAM = Serial.readStringUntil('\n');
    Serial.println(sizeRAM);
    newramsize = sizeRAM.toInt() + ramlo;
    if (newramsize > ramhi) {
      Serial.println(F("SIZE NOT SUPPORTED"));
      Serial.println(FS(FSTRING_EMPTY));
      goto setram;
    }
  }
  if ((mapper == 16) || (mapper == 159)) {
    int sizeEEP = 0;
    Serial.print(F("EEPROM Size = "));
    if (mapper == 16)
      sizeEEP = pgm_read_byte(&(RAM[newramsize])) * 32;
    else
      sizeEEP = pgm_read_byte(&(RAM[newramsize])) * 16;
    Serial.print(sizeEEP);
    Serial.println(F("B"));
    Serial.println(FS(FSTRING_EMPTY));
  } else if (mapper == 19) {
    Serial.print(F("RAM Size =  "));
    if (newramsize == 2)
      Serial.println(F("128B"));
    else {
      Serial.print(pgm_read_byte(&(RAM[newramsize])));
      Serial.println(F("K"));
    }
    Serial.println(FS(FSTRING_EMPTY));
  } else if (mapper == 80) {
    Serial.print(F("RAM Size = "));
    Serial.print(pgm_read_byte(&(RAM[newramsize])) * 16);
    Serial.println(F("B"));
    Serial.println(FS(FSTRING_EMPTY));
  } else {
    Serial.print(F("RAM Size = "));
    if (mapper == 0)
      Serial.print(newramsize * 2);
    else if (mapper == 82)
      Serial.print(newramsize * 5);
    else
      Serial.print(pgm_read_byte(&(RAM[newramsize])));
    Serial.println(F("K"));
    Serial.println(FS(FSTRING_EMPTY));
  }
#endif
  EEPROM_writeAnything(11, newramsize);
  ramsize = newramsize;

#ifdef ENABLE_GLOBAL_LOG
  // Enable log again
  dont_log = false;
#endif
}

// MMC6 Detection
// Mapper 4 includes both MMC3 AND MMC6
// RAM is mapped differently between MMC3 and MMC6
void checkMMC6() {               // Detect MMC6 Carts - read PRG 0x3E00A ("STARTROPICS")
  write_prg_byte(0x8000, 6);     // PRG Bank 0 ($8000-$9FFF)
  write_prg_byte(0x8001, 0x1F);  // 0x3E000
  uint8_t prgchk0 = read_prg_byte(0x800A);
  uint8_t prgchk1 = read_prg_byte(0x800B);
  uint8_t prgchk2 = read_prg_byte(0x800C);
  uint8_t prgchk3 = read_prg_byte(0x800D);
  if ((prgchk0 == 0x53) && (prgchk1 == 0x54) && (prgchk2 == 0x41) && (prgchk3 == 0x52))
    mmc6 = true;  // MMC6 Cart
}

void checkStatus_NES() {
  EEPROM_readAnything(7, mapper);
  EEPROM_readAnything(9, prgsize);
  EEPROM_readAnything(10, chrsize);
  EEPROM_readAnything(11, ramsize);
  prg = (int_pow(2, prgsize)) * 16;
  if (chrsize == 0)
    chr = 0;  // 0K
  else
    chr = (int_pow(2, chrsize)) * 4;
  if (ramsize == 0)
    ram = 0;  // 0K
  else if (mapper == 82)
    ram = 5;  // 5K
  else
    ram = (int_pow(2, ramsize)) * 4;

  // Mapper Variants
  // Identify variant for use across multiple functions
  if (mapper == 4) {  // Check for MMC6/MMC3
    checkMMC6();
    if (mmc6) {
      ram = 1;      // 1K
      ramsize = 1;  // Must be a non-zero value
    }
  } else if (mapper == 30) {  // Check for Flashable/Non-Flashable
#if defined(ENABLE_FLASH)
    NESmaker_ID();  // Flash ID
#endif
  }

  display_Clear();
  println_Msg(F("NES CART READER"));
  println_Msg(FS(FSTRING_EMPTY));
  println_Msg(FS(FSTRING_CURRENT_SETTINGS));
  println_Msg(FS(FSTRING_EMPTY));
  printNESSettings();
  println_Msg(FS(FSTRING_EMPTY));
  // Prints string out of the common strings array either with or without newline
  print_STR(press_button_STR, 1);
  display_Update();
  wait();
}

static void printNESSettings(void) {
  print_Msg(F("MAPPER:   "));
  println_Msg(mapper);
  print_Msg(F("PRG SIZE: "));
  print_Msg(prg);
  println_Msg(F("K"));
  print_Msg(F("CHR SIZE: "));
  print_Msg(chr);
  println_Msg(F("K"));
  print_Msg(F("RAM SIZE: "));
  if (mapper == 0) {
    print_Msg(ram / 4);
    println_Msg(F("K"));
  } else if ((mapper == 16) || (mapper == 80) || (mapper == 159)) {
    if (mapper == 16)
      print_Msg(ram * 32);
    else
      print_Msg(ram * 16);
    println_Msg(F("B"));
  } else if (mapper == 19) {
    if (ramsize == 2)
      println_Msg(F("128B"));
    else {
      print_Msg(ram);
      println_Msg(F("K"));
    }
  } else {
    print_Msg(ram);
    println_Msg(F("K"));
  }
}

/******************************************
   ROM Functions
 *****************************************/
void dumpPRG(word base, word address) {
  for (size_t x = 0; x < 512; x++) {
    sdBuffer[x] = read_prg_byte(base + address + x);
  }
  myFile.write(sdBuffer, 512);
}

void dumpCHR(word address) {
  for (size_t x = 0; x < 512; x++) {
    sdBuffer[x] = read_chr_byte(address + x);
  }
  myFile.write(sdBuffer, 512);
}

void dumpCHR_M2(word address) {  // MAPPER 45 - PULSE M2 LO/HI
  for (size_t x = 0; x < 512; x++) {
    PHI2_LOW;
    sdBuffer[x] = read_chr_byte(address + x);
  }
  myFile.write(sdBuffer, 512);
}

void dumpMMC5RAM(word base, word address) {  // MMC5 SRAM DUMP - PULSE M2 LO/HI
  for (size_t x = 0; x < 512; x++) {
    PHI2_LOW;
    sdBuffer[x] = read_prg_byte(base + address + x);
  }
  myFile.write(sdBuffer, 512);
}

void writeMMC5RAM(word base, word address) {  // MMC5 SRAM WRITE
  uint8_t bytecheck;
  myFile.read(sdBuffer, 512);
  for (size_t x = 0; x < 512; x++) {
    do {
      write_prg_byte(0x5102, 2);  // PRG RAM PROTECT1
      write_prg_byte(0x5103, 1);  // PRG RAM PROTECT2
      write_wram_byte(base + address + x, sdBuffer[x]);
      bytecheck = read_prg_byte(base + address + x);
    } while (bytecheck != sdBuffer[x]);  // CHECK WRITTEN BYTE
  }
  write_prg_byte(0x5102, 0);  // PRG RAM PROTECT1
  write_prg_byte(0x5103, 0);  // PRG RAM PROTECT2
}

void dumpBankPRG(const size_t from, const size_t to, const size_t base) {
  for (size_t address = from; address < to; address += 512) {
    dumpPRG(base, address);
  }
}

void dumpBankCHR(const size_t from, const size_t to) {
  for (size_t address = from; address < to; address += 512) {
    dumpCHR(address);
  }
}

void readPRG(bool readrom) {
  if (!readrom) {
    display_Clear();
    display_Update();

    rgbLed(blue_color);
    set_address(0);
    _delay_us(1);
    CreatePRGFileInSD();
  } else {
    set_address(0);
    _delay_us(1);
  }

  word base = 0x8000;
  bool busConflict = false;
  uint16_t banks;

  if (myFile) {
    switch (mapper) {
      case 0:
      case 3:
      case 13:
      case 87:                                                      // 16K/32K
      case 184:                                                     // 32K
      case 185:                                                     // 16K/32K
        dumpBankPRG(0, (((word)prgsize) * 0x4000) + 0x4000, base);  // 16K or 32K
        break;

      case 1:
      case 155:  // 32K/64K/128K/256K/512K
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {  // 16K Banks ($8000-$BFFF)
          write_prg_byte(0x8000, 0x80);       // Clear Register
          write_mmc1_byte(0x8000, 0x0C);      // Switch 16K Bank ($8000-$BFFF) + Fixed Last Bank ($C000-$FFFF)
          if (prgsize > 4)                    // 512K
            write_mmc1_byte(0xA000, 0x00);    // Reset 512K Flag for Lower 256K
          if (i > 15)                         // Switch Upper 256K
            write_mmc1_byte(0xA000, 0x10);    // Set 512K Flag
          write_mmc1_byte(0xE000, i);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 2:   // bus conflicts - fixed last bank
      case 30:  // bus conflicts in non-flashable configuration
        banks = int_pow(2, prgsize);
        busConflict = true;
        for (size_t i = 0; i < banks; i++) {
          for (size_t x = 0; x < 0x8000; x++) {
            if (read_prg_byte(0xC000 + x) == i) {
              write_prg_byte(0xC000 + x, i);
              busConflict = false;
              break;
            }
          }
          if (busConflict) {
            write_prg_byte(0xC000 + i, i);
          }
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 4:
      case 37:
      case 47:
      case 64:
      case 76:
      case 88:
      case 95:
      case 118:
      case 119:
      case 126:
      case 134:
      case 154:  // 128K
      case 158:
      case 176:
      case 206:  // 32/64/128K
      case 268:  // submapper 0
      case 315:
      case 366:
        banks = int_pow(2, prgsize) * 2;
        write_prg_byte(0xA001, 0x80);  // Block Register - PRG RAM Chip Enable, Writable
        if (mapper == 126) {
          write_prg_byte(0x6003, 0x00);  // set MMC3 banking mode
        }
        if (mapper == 134) {
          write_prg_byte(0x6000, 0x00);  // set MMC3 banking mode
        }
        if (mapper == 176) {
          write_prg_byte(0x5FF3, 0);  // extended MMC3 mode: disabled
          write_prg_byte(0x5FF0, 1);  // 256K outer bank mode
        }
        for (size_t i = 0; i < banks; i += 1) {
          if (mapper == 37) {
            if (i == 0) {
              write_prg_byte(0x6000, 0);  // Switch to Lower Block ($0000-$FFFF)
            } else if (i == 8) {
              write_prg_byte(0x6000, 3);  // Switch to 2nd 64K Block ($10000-$1FFFF)
            } else if (i == 16) {
              write_prg_byte(0x6000, 4);  // Switch to 128K Block ($20000-$3FFFF)
            }
          }
          if (mapper == 47) {
            write_prg_byte(0x6000 + (i >> 4), 0);
          }
          if (mapper == 126) {
            write_prg_byte(0x6000, (i & 0x180) >> 3 | (i & 0x70) >> 4);
          }
          if (mapper == 134) {
            write_prg_byte(0x6001, (i & 0x30) >> 4);
          }
          if (mapper == 176) {
            write_prg_byte(0x5FF1, (i & 0xE0) >> 1);
          }
          if (mapper == 268) {
            write_prg_byte(0x5000, ((i & 0x70) >> 4) | ((i & 0xC00) >> 6));
            write_prg_byte(0x5001, ((i & 0x80) >> 3) | ((i & 0x300) >> 6) | 0x60);
            write_prg_byte(0x5002, 0x00);
            write_prg_byte(0x5003, 0x00);
            write_prg_byte(0x6000, ((i & 0x70) >> 4) | ((i & 0xC00) >> 6));
            write_prg_byte(0x6001, ((i & 0x80) >> 3) | ((i & 0x300) >> 6) | 0x60);
            write_prg_byte(0x6002, 0x00);
            write_prg_byte(0x6003, 0x00);
          }
          if (mapper == 315) {
            write_prg_byte(0x6800, (i & 30) >> 3);
          }
          if (mapper == 366) {
            write_prg_byte(0x6800 + (i & 0x70), i);
          }
          write_prg_byte(0x8000, 0x06);  // PRG Bank 0 ($8000-$9FFF)
          write_prg_byte(0x8001, i);
          dumpBankPRG(0x0, 0x2000, base);
        }
        break;

      case 5:  // 128K/256K/512K
        banks = int_pow(2, prgsize) * 2;
        write_prg_byte(0x5100, 3);               // 8K PRG Banks
        for (size_t i = 0; i < banks; i += 2) {  // 128K/256K/512K
          write_prg_byte(0x5114, i | 0x80);
          write_prg_byte(0x5115, (i + 1) | 0x80);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 7:   // 128K/256K
      case 34:  // BxROM/NINA
      case 77:
      case 96:   // 128K
      case 177:  // up to 1024K
      case 241:
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {  // 32K Banks
          if (mapper == 34) {
            write_prg_byte(0x7FFD, i);  // NINA Bank select
            delay(200);                 // NINA seems slow to switch banks
          }
          write_prg_byte(0x8000, i);
          dumpBankPRG(0x0, 0x8000, base);  // 32K Banks ($8000-$FFFF)
        }
        break;

      case 9:
        banks = int_pow(2, prgsize) * 2;  // 8K banks
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0xA000, i);       // Switch bank at $8000
          dumpBankPRG(0x0, 0x2000, base);  //
        }
        break;

      case 10:
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0xA000, i);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 11:
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0xFFB0 + i, i);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 15:
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i += 2) {
          write_prg_byte(0x8000, i);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 16:
      case 159:  // 128K/256K
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x6008, i);       // Submapper 4
          write_prg_byte(0x8008, i);       // Submapper 5
          dumpBankPRG(0x0, 0x4000, base);  // 16K Banks ($8000-$BFFF)
        }
        break;

      case 18:  // 128K/256K
        banks = int_pow(2, prgsize) * 2;
        for (size_t i = 0; i < banks; i += 2) {
          write_prg_byte(0x8000, i & 0xF);
          write_prg_byte(0x8001, (i >> 4) & 0xF);
          write_prg_byte(0x8002, (i + 1) & 0xF);
          write_prg_byte(0x8003, ((i + 1) >> 4) & 0xF);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 19:                             // 128K/256K
        for (size_t j = 0; j < 64; j++) {  // Init Register
          write_ram_byte(0xE000, 0);       // PRG Bank 0 ($8000-$9FFF)
        }
        banks = int_pow(2, prgsize) * 2;
        for (size_t i = 0; i < banks; i++) {
          write_ram_byte(0xE000, i);  // PRG Bank 0 ($8000-$9FFF)
          dumpBankPRG(0x0, 0x2000, base);
        }
        break;

      case 21:  // 256K
        banks = int_pow(2, prgsize) * 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0xA000, i);
          dumpBankPRG(0x2000, 0x4000, base);
        }
        break;

      case 22:
      case 25:
      case 65:
      case 75:  // 128K/256K
        banks = int_pow(2, prgsize) * 2;
        // set vrc4 swap setting for TMNT2
        if (mapper == 25)
          write_prg_byte(0x9005, 0x00);
        for (size_t i = 0; i < banks; i += 2) {
          write_prg_byte(0x8000, i);
          write_prg_byte(0xA000, i + 1);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 23:
        banks = int_pow(2, prgsize) * 2;
        write_prg_byte(0x9002, 0);
        write_prg_byte(0x9008, 0);
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x8000, i);
          dumpBankPRG(0x0, 0x2000, base);
        }
        break;

      case 24:
      case 26:  // 256K
      case 78:  // 128K
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {  // 128K
          write_prg_byte(0x8000, i);
          dumpBankPRG(0x2000, 0x4000, base);  // 16K Banks ($8000-$BFFF)
        }
        break;

      case 28:  // using 32k mode for inner and outer banks, switching only with outer
        banks = int_pow(2, prgsize) / 2;
        write_prg_byte(0x5000, 0x81);
        write_prg_byte(0x8000, 0);
        write_prg_byte(0x5000, 0x80);
        write_prg_byte(0x8000, 0);
        write_prg_byte(0x5000, 0x01);
        write_prg_byte(0x8000, 0);
        write_prg_byte(0x5000, 0x00);
        write_prg_byte(0x8000, 0);
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x5000, 0x81);
          write_prg_byte(0x8000, i);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 31:
        banks = int_pow(2, prgsize) * 4;
        for (size_t i = 0; i < banks; i += 8) {
          write_prg_byte(0x5FF8, i);
          write_prg_byte(0x5FF9, i + 1);
          write_prg_byte(0x5FFA, i + 2);
          write_prg_byte(0x5FFB, i + 3);
          write_prg_byte(0x5FFC, i + 4);
          write_prg_byte(0x5FFD, i + 5);
          write_prg_byte(0x5FFE, i + 6);
          write_prg_byte(0x5FFF, i + 7);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 32:  // 128K/256K
        banks = int_pow(2, prgsize) * 2;
        for (size_t i = 0; i < banks; i++) {  // 128K/256K
          write_prg_byte(0x9000, 1);          // PRG Mode 0 - Read $A000-$BFFF to avoid difference between Modes 0 and 1
          write_prg_byte(0xA000, i);          // PRG Bank
          dumpBankPRG(0x2000, 0x4000, base);  // 8K Banks ($A000-$BFFF)
        }
        break;

      case 33:
      case 48:  // 128K/256K
        banks = int_pow(2, prgsize) * 2;
        for (size_t i = 0; i < banks; i += 2) {
          write_prg_byte(0x8000, i);       // PRG Bank 0 ($8000-$9FFF)
          write_prg_byte(0x8001, i + 1);   // PRG Bank 1 ($A000-$BFFF)
          dumpBankPRG(0x0, 0x4000, base);  // 8K Banks ($A000-$BFFF)
        }
        break;

      case 35:
      case 90:
      case 209:
      case 211:
        banks = int_pow(2, prgsize) * 2;
        write_prg_byte(0xD000, 0x02);
        for (uint8_t i = 0; i < banks; i++) {
          write_prg_byte(0xD003, (((i >> 5) & 0x06) | 0x20));
          write_prg_byte(0x8000, (i & 0x3f));
          dumpBankPRG(0x0, 0x2000, base);
        }
        break;

      case 36:
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0xFFA0 + i, (i << 4));
          write_prg_byte(0x4101, 0);
          write_prg_byte(0x4102, (i << 4));
          write_prg_byte(0x4103, 0);
          write_prg_byte(0x4100, 0);
          write_prg_byte(0x4103, 0xFF);
          write_prg_byte(0xFFFF, 0xFF);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 38:
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x7000, i);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 42:
        banks = int_pow(2, prgsize) * 2;
        base = 0x6000;  // 8k switchable PRG ROM bank at $6000-$7FFF
        for (size_t i = 0; i < banks - 4; i++) {
          write_prg_byte(0xE000, i & 0x0F);
          dumpBankPRG(0x0, 0x2000, base);
        }
        base = 0x8000;  // last 32k fixed to $8000-$FFFF
        dumpBankPRG(0x0, 0x8000, base);
        break;

      case 45:                                    // MMC3 Clone with Outer Registers
        banks = ((int_pow(2, prgsize) * 2)) - 2;  // Set Number of Banks
        for (size_t i = 0; i < banks; i += 2) {   // 128K/256K/512K/1024K
          // set outer bank registers
          write_prg_byte(0x6000, 0x00);               // CHR-OR
          write_prg_byte(0x6000, (i & 0xC0));         // PRG-OR
          write_prg_byte(0x6000, ((i >> 2) & 0xC0));  // CHR-AND,CHR-OR/PRG-OR
          write_prg_byte(0x6000, 0x80);               // PRG-AND
          // set inner bank registers
          write_prg_byte(0x8000, 6);  // PRG Bank 0 ($8000-$9FFF)
          write_prg_byte(0x8001, i);
          dumpBankPRG(0x0, 0x2000, base);
          // set outer bank registers
          write_prg_byte(0x6000, 0x00);                     // CHR-OR
          write_prg_byte(0x6000, ((i + 1) & 0xC0));         // PRG-OR
          write_prg_byte(0x6000, (((i + 1) >> 2) & 0xC0));  // CHR-AND,CHR-OR/PRG-OR
          write_prg_byte(0x6000, 0x80);                     // PRG-AND
          // set inner bank registers
          write_prg_byte(0x8000, 7);  // PRG Bank 1 ($A000-$BFFF)
          write_prg_byte(0x8001, i + 1);
          dumpBankPRG(0x2000, 0x4000, base);
        }
        dumpBankPRG(0x4000, 0x8000, base);  // Final 2 Banks ($C000-$FFFF)
        break;

      case 46:
        banks = int_pow(2, prgsize) / 2;  // 32k banks
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x6000, (i & 0x1E) >> 1);  // high bits
          write_prg_byte(0x8000, i & 0x01);         // low bit
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 56:
        banks = int_pow(2, prgsize) * 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0xE000, 1);
          write_prg_byte(0xF000, i);
          dumpBankPRG(0x0, 0x2000, base);
        }
        break;

      case 57:
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x8800, (i & 0x07) << 5);
          write_prg_byte(0x8000, 0);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 58:
      case 213:
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i += 2) {
          write_prg_byte(0x8000 + (i & 0x07), 0x00);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 59:
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i += 2) {
          write_reg_m59(0x8000 + ((i & 0x07) << 4));
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 60:
        dumpBankPRG(0x0, 0x4000, base);
        for (size_t i = 0; i < 3; i++) {
          write_prg_byte(0x8D8D, i);
          delay(500);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 62:
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x8000 + (i * 512) + ((i & 32) << 1), 0x00);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 66:  // 64K/128K
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {  // 64K/128K
          write_prg_byte(0x8000, i << 4);     // bits 4-5
          dumpBankPRG(0x0, 0x8000, base);     // 32K Banks ($8000-$FFFF)
        }
        break;

      case 63:  // 3072K total
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < 192; i++) {
          write_prg_byte(0x8000 + (i << 2), 0);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 67:  // 128K
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {  // 128K
          write_reg_byte(0xF800, i);          // [WRITE RAM SAFE]
          dumpBankPRG(0x0, 0x4000, base);     // 16K Banks ($8000-$BFFF)
        }
        break;

      case 68:
      case 73:  // 128K
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {  // 128K
          write_prg_byte(0xF000, i);
          dumpBankPRG(0x0, 0x4000, base);  // 16K Banks ($8000-$BFFF)
        }
        break;

      case 69:  // 128K/256K
        banks = int_pow(2, prgsize) * 2;
        write_prg_byte(0x8000, 8);            // Command Register - PRG Bank 0
        write_prg_byte(0xA000, 0);            // Parameter Register - PRG RAM Disabled, PRG ROM, Bank 0 to $6000-$7FFF
        for (size_t i = 0; i < banks; i++) {  // 128K/256K
          write_prg_byte(0x8000, 9);          // Command Register - PRG Bank 1
          write_prg_byte(0xA000, i);          // Parameter Register - ($8000-$9FFF)
          dumpBankPRG(0x0, 0x2000, base);     // 8K Banks ($8000-$9FFF)
        }
        break;

      case 70:
      case 89:
      case 152:  // 64K/128K
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {  // 128K
          write_prg_byte(0x8000, i << 4);
          dumpBankPRG(0x0, 0x4000, base);  // 16K Banks ($8000-$BFFF)
        }
        break;

      case 71:  // 64K/128K/256K
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0xC000, i);
          dumpBankPRG(0x0, 0x4000, base);  // 16K Banks ($8000-$BFFF)
        }
        break;

      case 72:  // 128K
        banks = int_pow(2, prgsize);
        write_prg_byte(0x8000, 0);            // Reset Register
        for (size_t i = 0; i < banks; i++) {  // 128K
          write_prg_byte(0x8000, i | 0x80);   // PRG Command + Bank
          write_prg_byte(0x8000, i);          // PRG Bank
          dumpBankPRG(0x0, 0x4000, base);     // 16K Banks ($8000-$BFFF)
        }
        break;

      case 79:
      case 146:
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x4100, i << 3);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 80:   // 128K
      case 207:  // 256K [CART SOMETIMES NEEDS POWERCYCLE]
        banks = int_pow(2, prgsize) * 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x7EFA, i);  // PRG Bank 0 ($8000-$9FFF)
          dumpBankPRG(0x0, 0x2000, base);
        }
        break;

      case 82:  // 128K
        banks = int_pow(2, prgsize) * 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x7EFA, i << 2);  // PRG Bank 0 ($8000-$9FFF)
          dumpBankPRG(0x0, 0x2000, base);  // 8K Banks ($8000-$BFFF)
        }
        break;

      case 85:  // 128K/512K
        banks = int_pow(2, prgsize) * 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x8000, i);       // PRG Bank 0 ($8000-$9FFF)
          dumpBankPRG(0x0, 0x2000, base);  // 8K Banks ($8000-$9FFF)
        }
        break;

      case 86:
      case 140:  // 128K
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {  // 128K
          write_prg_byte(0x6000, i << 4);     // bits 4-5
          dumpBankPRG(0x0, 0x8000, base);     // 32K Banks ($8000-$FFFF)
        }
        break;

      case 91:
        banks = int_pow(2, prgsize) * 2;
        for (size_t i = 0; i < banks; i += 1) {
          write_prg_byte(0x8000 + ((i & 0x30) >> 3), i);  // PRG A18-A17 (submapper 0 only)
          write_prg_byte(0x7000, i);                      // PRG -A13
          dumpBankPRG(0x0, 0x2000, base);
        }
        break;

      case 92:  // 256K
        banks = int_pow(2, prgsize);
        write_prg_byte(0x8000, 0);            // Reset Register
        for (size_t i = 0; i < banks; i++) {  // 256K
          write_prg_byte(0x8000, i | 0x80);   // PRG Command + Bank
          write_prg_byte(0x8000, i);          // PRG Bank
          dumpBankPRG(0x4000, 0x8000, base);  // 16K Banks ($C000-$FFFF)
        }
        break;

      case 93:
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x6000, i);
          write_prg_byte(0x8000, i << 4 | 0x01);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 94:  // bus conflicts - fixed last bank
        banks = int_pow(2, prgsize);
        busConflict = true;
        for (size_t i = 0; i < banks; i++) {
          for (size_t x = 0; x < 0x4000; x++) {
            if (read_prg_byte(0xC000 + x) == (i << 2)) {
              write_prg_byte(0xC000 + x, i << 2);
              busConflict = false;
              break;
            }
          }
          if (busConflict) {
            write_prg_byte(0x8000 + i, i << 2);
          }
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 97:   // fixed first bank
      case 180:  // bus conflicts - fixed fist bank
        banks = int_pow(2, prgsize);
        dumpBankPRG(0x0, 0x4000, base);
        for (size_t i = 1; i < banks; i++) {
          write_prg_byte(0x8000, i);
          dumpBankPRG(0x4000, 0x8000, base);
        }
        break;

      case 105:                           // 256K
        write_mmc1_byte(0xA000, 0x00);    // Clear PRG Init/IRQ (Bit 4)
        write_mmc1_byte(0xA000, 0x10);    // Set PRG Init/IRQ (Bit 4) to enable bank swapping
        for (size_t i = 0; i < 4; i++) {  // PRG CHIP 1 128K
          write_mmc1_byte(0xA000, i << 1);
          dumpBankPRG(0x0, 0x8000, base);  // 32K Banks ($8000-$FFFF)
        }
        write_mmc1_byte(0x8000, 0x0C);    // Switch 16K Bank ($8000-$BFFF) + Fixed Last Bank ($C000-$FFFF)
        write_mmc1_byte(0xA000, 0x08);    // Select PRG CHIP 2 (Bit 3)
        for (size_t j = 0; j < 8; j++) {  // PRG CHIP 2 128K
          write_mmc1_byte(0xE000, j);
          dumpBankPRG(0x0, 0x4000, base);  // 16K Banks ($8000-$BFFF)
        }
        break;

      case 111:
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x5000, i);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 113:
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x4100, (i & 0x07) << 3);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 114:  // Submapper 0
        banks = int_pow(2, prgsize) * 2;
        write_prg_byte(0x6000, 0);
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0xA000, 4);
          write_prg_byte(0xC000, i);
          dumpBankPRG(0x0, 0x2000, base);
        }
        break;

      case 142:
        banks = int_pow(2, prgsize) * 2;
        base = 0x6000;  // 4x 8k switchable PRG ROM banks at $6000-$DFFF
        for (size_t i = 0; i < banks; i += 4) {
          write_prg_byte(0xE000, 4);  // Select 8 KB PRG bank at CPU $6000-$7FFF
          write_prg_byte(0xF000, i);
          write_prg_byte(0xE000, 1);  // Select 8 KB PRG bank at CPU $8000-$9FFF
          write_prg_byte(0xF000, i + 1);
          write_prg_byte(0xE000, 2);  // Select 8 KB PRG bank at CPU $A000-$BFFF
          write_prg_byte(0xF000, i + 2);
          write_prg_byte(0xE000, 3);  // Select 8 KB PRG bank at CPU $C000-$DFFF
          write_prg_byte(0xF000, i + 3);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 148:  // Sachen SA-008-A and Tengen 800008 -- Bus conflicts
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x8000, i << 3);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 153:  // 512K
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {  // 512K
          write_prg_byte(0x8000, i >> 4);     // PRG Outer Bank (Documentation says duplicate over $8000-$8003 registers)
          write_prg_byte(0x8001, i >> 4);     // PRG Outer Bank
          write_prg_byte(0x8002, i >> 4);     // PRG Outer Bank
          write_prg_byte(0x8003, i >> 4);     // PRG Outer Bank
          write_prg_byte(0x8008, i & 0xF);    // PRG Inner Bank
          dumpBankPRG(0x0, 0x4000, base);     // 16K Banks ($8000-$BFFF)
        }
        break;

      case 157:
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x8008, i);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 162:
        banks = int_pow(2, prgsize) / 2;
        write_prg_byte(0x5300, 0x07);  // A16-A15 controlled by $5000
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x5200, (i & 0x30) >> 4);  // A20-A19
          write_prg_byte(0x5000, i & 0x0F);         // A18-A15
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 163:
        banks = int_pow(2, prgsize) / 2;
        write_prg_byte(0x5300, 0x04);  // disable bit swap on writes to $5000-$5200
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x5200, (i & 0x30) >> 4);  // A20-A19
          write_prg_byte(0x5000, i & 0x0F);         // A18-A15
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 174:  // 128k
        for (size_t i = 0; i < 8; i++) {
          write_prg_byte(0xFF00 + (i << 4), 0);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 178:
        banks = int_pow(2, prgsize);
        write_prg_byte(0x4800, 0);  // NROM-256 mode
        write_prg_byte(0x4803, 0);  // set PRG-RAM
        for (size_t i = 0; i < banks; i += 2) {
          write_prg_byte(0x4802, i >> 3);    // high PRG (up to 8 bits?!)
          write_prg_byte(0x4801, i & 0x07);  // low PRG (3 bits)
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 200:
      case 212:
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x8000 + (i & 0x07), 0);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 201:
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x8000 + (i & 0xFF), 0);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 202:
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x8000 | (i << 1), 0);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 203:
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x8000, (i & 0x1F) << 2);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 210:  // 128K/256K
        banks = int_pow(2, prgsize) * 2;
        for (size_t i = 0; i < banks; i += 2) {
          write_prg_byte(0xE000, i);      // PRG Bank 0 ($8000-$9FFF) [WRITE NO RAM]
          write_prg_byte(0xE800, i + 1);  // PRG Bank 1 ($A000-$BFFF) [WRITE NO RAM]
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 214:
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x8000 | (i << 2), 0);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 225:
      case 255:
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i += 2) {
          write_prg_byte(0x8000 + (((i & 0x40) << 8) | ((i & 0x3F) << 6)), 0);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 226:
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i += 2) {
          write_prg_byte(0x8001, (i & 0x40) >> 6);
          write_prg_byte(0x8000, ((i & 0x20) << 2) | (i & 0x1F));
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 227:
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x8083 + ((i & 0xF) << 3), 0);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 228:
        banks = int_pow(2, prgsize);
        write_prg_byte(0x8000, 0);
        for (size_t i = 0; i < banks; i += 2) {  // up to 1024k PRG
          write_prg_byte(0x8000 + ((i & 0x3F) << 6), 0);
          dumpBankPRG(0x0, 0x8000, base);
        }
        if (prgsize > 5) {  // reading the 3rd 512k PRG chip (Action 52)
          for (size_t i = 0; i < 32; i += 2) {
            write_prg_byte(0x9800 + ((i & 0x1F) << 6), 0);
            dumpBankPRG(0x0, 0x8000, base);
          }
        }
        break;

      case 229:
        write_prg_byte(0x8000, 0);
        dumpBankPRG(0x0, 0x8000, base);
        for (size_t i = 2; i < 32; i++) {
          write_prg_byte(0x8000 + i, i);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 232:
        banks = int_pow(2, prgsize) / 4;
        for (size_t outerbank = 0; outerbank < 4; outerbank++) {
          write_prg_byte(0x8000, outerbank << 3);
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0xC000, i);
            dumpBankPRG(0x0, 0x4000, base);
          }
        }
        break;

      case 235:
        for (size_t i = 0; i < 32; i++) {
          write_prg_byte(0x8000 + i, 0);
          dumpBankPRG(0x0, 0x8000, base);
        }
        if (prgsize > 6) {
          for (size_t i = 32; i < 64; i++) {
            write_prg_byte(0x80E0 + i, 0);
            dumpBankPRG(0x0, 0x8000, base);
          }
          if (prgsize > 7) {
            for (size_t i = 64; i < 96; i++) {
              write_prg_byte(0x81E0 + i, 0);
              dumpBankPRG(0x0, 0x8000, base);
            }
            for (size_t i = 96; i < 128; i++) {
              write_prg_byte(0x82E0 + i, 0);
              dumpBankPRG(0x0, 0x8000, base);
            }
          }
        }
        break;

      case 236:
        banks = int_pow(2, prgsize);
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x8000 | ((i & 0x38) >> 3), 0);  // A19-A17
          write_prg_byte(0xC030 | (i & 0x0F), 0);         // A17-A14
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 240:
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x5FFF, (i & 0xF) << 4);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 242:                            // total size is 640k THIS IS NORMAL
        for (size_t i = 0; i < 32; i++) {  // dump 1st chip of 512k
          write_prg_byte(0x8400 + (i * 4), 0);
          dumpBankPRG(0x0, 0x4000, base);
        }
        for (size_t i = 0; i < 8; i++) {  // dump 2nd chip of 128k
          write_prg_byte(0x8000 + (i * 4), 0);
          dumpBankPRG(0x0, 0x4000, base);
        }
        break;

      case 246:
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i += 4) {
          write_prg_byte(0x6000, (i | 0));
          write_prg_byte(0x6001, (i | 1));
          write_prg_byte(0x6002, (i | 2));
          write_prg_byte(0x6003, (i | 3));
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 446:
        banks = int_pow(2, prgsize) * 2;
        write_prg_byte(0x5003, 0);
        write_prg_byte(0x5005, 0);
        for (uint8_t i = 0; i < banks; i++) {  // 8192 for 64MiB
          write_prg_byte(0x5002, i >> 8);      // outer bank LSB
          write_prg_byte(0x5001, i);           // outer bank MSB
          write_prg_byte(0x8000, 0);
          dumpBankPRG(0x0, 0x2000, base);
        }
        break;

      case 470:
        banks = int_pow(2, prgsize) / 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x5000, i >> 3);
          write_prg_byte(0x8000, i & 0x07);
          dumpBankPRG(0x0, 0x8000, base);
        }
        break;

      case 552:
        banks = int_pow(2, prgsize) * 2;
        for (size_t i = 0; i < banks; i++) {
          write_prg_byte(0x7EFA, ((i & 0x01) << 5) | ((i & 0x02) << 3) | ((i & 0x04) << 1) | ((i & 0x08) >> 1) | ((i & 0x10) >> 3) | ((i & 0x20) >> 5));  // PRG Bank 0 ($8000-$9FFF)
          dumpBankPRG(0x0, 0x2000, base);                                                                                                                 // 8K Banks ($8000-$BFFF)
        }
        break;
    }
    if (!readrom) {
      myFile.flush();
      myFile.close();

      println_Msg(F("PRG FILE DUMPED!"));
      println_Msg(FS(FSTRING_EMPTY));
      display_Update();
    }
  }
  set_address(0);
  PHI2_HI;
  ROMSEL_HI;
  rgbLed(black_color);
}

void readCHR(bool readrom) {
  if (!readrom) {
    display_Clear();
    display_Update();
  }

  uint16_t banks;
  bool busConflict = false;

  rgbLed(green_color);
  set_address(0);
  _delay_us(1);
  if (chrsize == 0) {
    println_Msg(F("CHR SIZE 0K"));
    display_Update();
  } else {
    if (!readrom) {
      CreateCHRFileInSD();
    }
    if (myFile) {
      switch (mapper) {
        case 0:  // 8K
          dumpBankCHR(0x0, 0x2000);
          break;

        case 1:
        case 155:
          banks = int_pow(2, chrsize);
          for (size_t i = 0; i < banks; i += 2) {  // 8K/16K/32K/64K/128K (Bank #s are based on 4K Banks)
            write_prg_byte(0x8000, 0x80);          // Clear Register
            write_mmc1_byte(0xA000, i);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 3:   // 8K/16K/32K - bus conflicts
        case 66:  // 16K/32K
        case 70:
        case 148:  // Sachen SA-008-A and Tengen 800008 - Bus conflicts
        case 152:  // 128K
          banks = int_pow(2, chrsize) / 2;
          busConflict = true;
          for (size_t i = 0; i < banks; i++) {
            for (size_t x = 0; x < 0x8000; x++) {
              if (read_prg_byte(0x8000 + x) == i) {
                write_prg_byte(0x8000 + x, i);
                busConflict = false;
                break;
              }
            }
            if (busConflict) {
              write_prg_byte(0x8000 + i, i);
            }
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 4:
        case 37:
        case 47:
        case 52:
        case 64:
        case 76:
        case 88:  // 128K
        case 95:  // 32K
        case 118:
        case 119:
        case 126:
        case 134:
        case 154:  // 128K
        case 158:
        case 176:
        case 206:  // 16K/32K/64K
        case 315:
        case 366:
          banks = int_pow(2, chrsize) * 4;
          write_prg_byte(0xA001, 0x80);
          if (mapper == 126) {
            write_prg_byte(0x6003, 0x00);  // set MMC3 banking mode
          }
          if (mapper == 134) {
            write_prg_byte(0x6000, 0x00);  // set MMC3 banking mode
          }
          if (mapper == 176) {
            write_prg_byte(0x5FF3, 0);  // extended MMC3 mode: disabled
            write_prg_byte(0x5FF0, 1);  // 256K outer bank mode
          }
          for (size_t i = 0; i < banks; i++) {
            if (mapper == 37) {
              if (i == 0) {
                write_prg_byte(0x6000, 0);
              } else if (i == 64) {
                write_prg_byte(0x6000, 3);
              } else if (i == 128) {
                write_prg_byte(0x6000, 4);
              }
            }
            if (mapper == 47) {
              write_prg_byte(0x6800 + ((i & 0x180) >> 7), 0);
            }
            if (mapper == 52) {
              write_prg_byte(0x6000, (i & 0x180) >> 3 | (i & 0x200) >> 7);
            }
            if (mapper == 126) {
              write_prg_byte(0x6000, (i & 0x200) >> 5 | (i & 0x100) >> 3);  // select outer bank
            }
            if (mapper == 134) {
              write_prg_byte(0x6001, (i & 0x180) >> 3);  // select outer bank
            }
            if (mapper == 176) {
              write_prg_byte(0x5FF2, (i & 0x700) >> 3);  // outer 256k bank
            }
            if (mapper == 268) {
              write_prg_byte(0x5000, ((i & 0x380) >> 4) | ((i & 0xC00) >> 9));
              write_prg_byte(0x6000, ((i & 0x380) >> 4) | ((i & 0xC00) >> 9));
            }
            if (mapper == 315) {
              write_prg_byte(0x6800, ((i & 0x100) >> 8) | ((i & 0x80) >> 6) | ((i & 0x40) >> 3));
            }
            if (mapper == 366) {
              write_prg_byte(0x6800 + ((i & 0x380) >> 3), i);
            }
            write_prg_byte(0x8000, 0x02);
            write_prg_byte(0x8001, i);
            dumpBankCHR(0x1000, 0x1400);
          }
          break;

        case 5:  // 128K/256K/512K
          banks = int_pow(2, chrsize) / 2;
          write_prg_byte(0x5101, 0);  // 8K CHR Banks
          for (size_t i = 0; i < banks; i++) {
            if (i == 0)
              write_prg_byte(0x5130, 0);  // Set Upper 2 bits
            else if (i == 8)
              write_prg_byte(0x5130, 1);  // Set Upper 2 bits
            else if (i == 16)
              write_prg_byte(0x5130, 2);  // Set Upper 2 bits
            else if (i == 24)
              write_prg_byte(0x5130, 3);  // Set Upper 2 bits
            write_prg_byte(0x5127, i);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 9:
        case 10:
          banks = int_pow(2, chrsize);
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0xB000, i);
            write_prg_byte(0xC000, i);
            dumpBankCHR(0x0, 0x1000);
          }
          break;

        case 11:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0xFFB0 + i, i << 4);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 16:
        case 159:  // 128K/256K
          banks = int_pow(2, chrsize) * 4;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x6000, i);  // Submapper 4
            write_prg_byte(0x8000, i);  // Submapper 5
            dumpBankCHR(0x0, 0x400);
          }
          break;

        case 18:  // 128K/256K
          banks = int_pow(2, chrsize) * 4;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0xA000, i & 0xF);         // CHR Bank Lower 4 bits
            write_prg_byte(0xA001, (i >> 4) & 0xF);  // CHR Bank Upper 4 bits
            dumpBankCHR(0x0, 0x400);
          }
          break;

        case 19:                             // 128K/256K
          for (size_t j = 0; j < 64; j++) {  // Init Register
            write_ram_byte(0xE800, 0xC0);    // CHR RAM High/Low Disable (ROM Enable)
          }
          banks = int_pow(2, chrsize) * 4;
          write_ram_byte(0xE800, 0xC0);  // CHR RAM High/Low Disable (ROM Enable)
          for (size_t i = 0; i < banks; i += 8) {
            write_prg_byte(0x8000, i);      // CHR Bank 0
            write_prg_byte(0x8800, i + 1);  // CHR Bank 1
            write_prg_byte(0x9000, i + 2);  // CHR Bank 2
            write_prg_byte(0x9800, i + 3);  // CHR Bank 3
            write_prg_byte(0xA000, i + 4);  // CHR Bank 4
            write_prg_byte(0xA800, i + 5);  // CHR Bank 5
            write_prg_byte(0xB000, i + 6);  // CHR Bank 6
            write_prg_byte(0xB800, i + 7);  // CHR Bank 7
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 21:  // 128K/256K
          banks = int_pow(2, chrsize) * 4;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0xB000, i & 0xF);           // CHR Bank Lower 4 bits
            if (chrsize == 5)                          // Check CHR Size to determine VRC4a (128K) or VRC4c (256K)
              write_prg_byte(0xB002, (i >> 4) & 0xF);  // CHR Bank Upper 4 bits VRC4a (Wai Wai World 2)
            else                                       // banks == 256
              write_prg_byte(0xB040, (i >> 4) & 0xF);  // CHR Bank Upper 4 bits VRC4c (Ganbare Goemon Gaiden 2)
            dumpBankCHR(0x0, 0x400);
          }
          break;

        case 22:  // 128K
          banks = int_pow(2, chrsize) * 4;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0xB000, (i << 1) & 0xF);  // CHR Bank Lower 4 bits
            write_prg_byte(0xB002, (i >> 3) & 0xF);  // CHR Bank Upper 4 bits
            dumpBankCHR(0x0, 0x400);
          }
          break;

        case 23:
          {  // 128K
            banks = int_pow(2, chrsize) * 4;

            // Detect VRC4e Carts - read PRG 0x1FFF6 (DATE)
            // Boku Dracula-kun = 890810, Tiny Toon = 910809
            // Crisis Force = 910701, Parodius Da! = 900916
            write_prg_byte(0x8000, 15);
            uint8_t prgchk0 = read_prg_byte(0x9FF6);
            if (prgchk0 == 0x30) {  // Check for "0" in middle of date. If true, assume VRC4e Cart
              for (size_t i = 0; i < banks; i++) {
                write_prg_byte(0xB000, i & 0xF);         // CHR Bank Lower 4 bits
                write_prg_byte(0xB004, (i >> 4) & 0xF);  // CHR Bank Upper 4 bits VRC4e
                dumpBankCHR(0x0, 0x400);
              }

              break;
            }

            // VRC2b/VRC4f - See https://www.nesdev.org/wiki/VRC2_and_VRC4
            for (size_t i = 0; i < banks; i += 8) {
              write_prg_byte(0xB000, i & 0xF);               // CHR Bank 0: Lower 4 bits
              write_prg_byte(0xB001, (i >> 4) & 0xF);        // CHR Bank 0: Upper 4 bits
              write_prg_byte(0xB002, (i + 1) & 0xF);         // CHR Bank 1: Lower 4 bits
              write_prg_byte(0xB003, ((i + 1) >> 4) & 0xF);  // CHR Bank 1: Upper 4 bits
              write_prg_byte(0xC000, (i + 2) & 0xF);         // CHR Bank 2: Lower 4 bits
              write_prg_byte(0xC001, ((i + 2) >> 4) & 0xF);  // CHR Bank 2: Upper 4 bits
              write_prg_byte(0xC002, (i + 3) & 0xF);         // CHR Bank 3: Lower 4 bits
              write_prg_byte(0xC003, ((i + 3) >> 4) & 0xF);  // CHR Bank 3: Upper 4 bits
              write_prg_byte(0xD000, (i + 4) & 0xF);         // CHR Bank 4: Lower 4 bits
              write_prg_byte(0xD001, ((i + 4) >> 4) & 0xF);  // CHR Bank 4: Upper 4 bits
              write_prg_byte(0xD002, (i + 5) & 0xF);         // CHR Bank 5: Lower 4 bits
              write_prg_byte(0xD003, ((i + 5) >> 4) & 0xF);  // CHR Bank 5: Upper 4 bits
              write_prg_byte(0xE000, (i + 6) & 0xF);         // CHR Bank 6: Lower 4 bits
              write_prg_byte(0xE001, ((i + 6) >> 4) & 0xF);  // CHR Bank 6: Upper 4 bits
              write_prg_byte(0xE002, (i + 7) & 0xF);         // CHR Bank 7: Lower 4 bits
              write_prg_byte(0xE003, ((i + 7) >> 4) & 0xF);  // CHR Bank 7: Upper 4 bits
              dumpBankCHR(0x0, 0x2000);                      // 8 Banks for a total of 8 KiB
            }
            break;
          }
        case 24:  // 128K
          banks = int_pow(2, chrsize) * 4;
          write_prg_byte(0xB003, 0);  // PPU Banking Mode 0
          for (size_t i = 0; i < banks; i += 8) {
            write_prg_byte(0xD000, i);      // CHR Bank 0
            write_prg_byte(0xD001, i + 1);  // CHR Bank 1
            write_prg_byte(0xD002, i + 2);  // CHR Bank 2
            write_prg_byte(0xD003, i + 3);  // CHR Bank 3
            write_prg_byte(0xE000, i + 4);  // CHR Bank 4 [WRITE NO RAM]
            write_prg_byte(0xE001, i + 5);  // CHR Bank 5 [WRITE NO RAM]
            write_prg_byte(0xE002, i + 6);  // CHR Bank 6 [WRITE NO RAM]
            write_prg_byte(0xE003, i + 7);  // CHR Bank 7 [WRITE NO RAM]
            dumpBankCHR(0x0, 0x2000);       // 1K Banks
          }
          break;

        case 25:  // 128K/256K
          banks = int_pow(2, chrsize) * 4;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0xB000, i & 0xF);         // CHR Bank Lower 4 bits
            write_prg_byte(0xB00A, (i >> 4) & 0xF);  // Combine VRC2c and VRC4b, VRC4d reg
            dumpBankCHR(0x0, 0x400);
          }
          break;

        case 26:  // 128K/256K
          banks = int_pow(2, chrsize) * 4;
          write_prg_byte(0xB003, 0x00);
          for (size_t i = 0; i < banks; i += 4) {
            write_prg_byte(0xD000, i + 0);  // CHR Bank 0
            write_prg_byte(0xD002, i + 1);  // CHR Bank 1
            write_prg_byte(0xD001, i + 2);  // CHR Bank 2
            write_prg_byte(0xD003, i + 3);  // CHR Bank 3
            dumpBankCHR(0x0, 0x1000);       // 1K Banks
          }
          break;

        case 32:  // 128K
        case 65:  // 128K/256K
          banks = int_pow(2, chrsize) * 4;
          for (size_t i = 0; i < banks; i += 8) {
            write_prg_byte(0xB000, i);      // CHR Bank 0
            write_prg_byte(0xB001, i + 1);  // CHR Bank 1
            write_prg_byte(0xB002, i + 2);  // CHR Bank 2
            write_prg_byte(0xB003, i + 3);  // CHR Bank 3
            write_prg_byte(0xB004, i + 4);  // CHR Bank 4
            write_prg_byte(0xB005, i + 5);  // CHR Bank 5
            write_prg_byte(0xB006, i + 6);  // CHR Bank 6
            write_prg_byte(0xB007, i + 7);  // CHR Bank 7
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 33:  // 128K/256K
        case 48:  // 256K
          banks = int_pow(2, chrsize) * 2;
          for (size_t i = 0; i < banks; i += 2) {  // 2K Banks
            write_prg_byte(0x8002, i);             // CHR Bank 0
            write_prg_byte(0x8003, i + 1);         // CHR Bank 1
            dumpBankCHR(0x0, 0x1000);
          }
          break;

        case 34:  // NINA
          banks = int_pow(2, chrsize);
          for (size_t i = 0; i < banks; i += 1) {
            write_prg_byte(0x7FFE, i);  // Select 4 KB CHR bank at $0000
            delay(200);                 // NINA seems slow to switch banks
            dumpBankCHR(0x0, 0x1000);
          }
          break;

        case 35:
        case 90:
        case 209:
        case 211:
          banks = int_pow(2, chrsize) / 2;
          write_prg_byte(0xD000, 0x02);

          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0xD003, (((i >> 3) & 0x18) | 0x20));
            write_prg_byte(0x9000, (i & 0x3f));
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 36:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x4200, i);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 38:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x7000, i << 2);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 42:
          banks = int_pow(2, chrsize);
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x8000, i & 0x0F);
            dumpBankCHR(0x0, 0x1000);
          }
          break;

        case 45:  // 128K/256K/512K/1024K
          banks = int_pow(2, chrsize) * 4;
          write_prg_byte(0xA001, 0x80);  // Unlock Write Protection - not used by some carts
          for (size_t i = 0; i < banks; i++) {
            // set outer bank registers
            write_prg_byte(0x6000, 0x00);                       // CHR-OR
            write_prg_byte(0x6000, 0x00);                       // PRG-OR
            write_prg_byte(0x6000, (((i / 256) << 4) | 0x0F));  // CHR-AND,CHR-OR/PRG-OR
            write_prg_byte(0x6000, 0x80);                       // PRG-AND
            // set inner bank registers
            write_prg_byte(0x8000, 0x2);  // CHR Bank 2 ($1000-$13FF)
            write_prg_byte(0x8001, i);
            for (size_t address = 0x1000; address < 0x1200; address += 512) {
              dumpCHR_M2(address);  // Read CHR with M2 Pulse
            }
            // set outer bank registers
            write_prg_byte(0x6000, 0x00);                       // CHR-OR
            write_prg_byte(0x6000, 0x00);                       // PRG-OR
            write_prg_byte(0x6000, (((i / 256) << 4) | 0x0F));  // CHR-AND,CHR-OR/PRG-OR
            write_prg_byte(0x6000, 0x80);                       // PRG-AND
            // set inner bank registers
            write_prg_byte(0x8000, 0x2);  // CHR Bank 2 ($1000-$13FF)
            write_prg_byte(0x8001, i);
            for (size_t address = 0x1200; address < 0x1400; address += 512) {
              dumpCHR_M2(address);  // Read CHR with M2 Pulse
            }
          }
          break;

        case 46:
          banks = int_pow(2, chrsize);  // 8k banks
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x6000, (i & 0x78) << 1);  // high bits
            write_prg_byte(0x8000, (i & 0x07) << 4);  // low bits
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 56:
          banks = int_pow(2, chrsize) * 4;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0xFC00, i);
            dumpBankCHR(0x0, 0x400);
          }
          break;

        case 57:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x8800, i & 0x07);                  // A15-A13
            write_prg_byte(0x8000, 0x80 | ((i & 0x08) << 3));  // A16
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 58:
        case 213:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x8000 + ((i & 0x07) << 3), 0x00);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 59:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_reg_m59(0x8000 + (i & 0x07));
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 60:
          for (size_t i = 0; i < 4; i++) {
            write_prg_byte(0x8D8D, i);
            delay(500);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 62:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x8000 + (i / 4), i & 3);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 67:  // 128K
          banks = int_pow(2, chrsize) * 2;
          for (size_t i = 0; i < banks; i += 4) {  // 2K Banks
            write_prg_byte(0x8800, i);             // CHR Bank 0
            write_prg_byte(0x9800, i + 1);         // CHR Bank 1
            write_prg_byte(0xA800, i + 2);         // CHR Bank 2
            write_prg_byte(0xB800, i + 3);         // CHR Bank 3
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 68:  // 128K/256K
          banks = int_pow(2, chrsize) * 2;
          for (size_t i = 0; i < banks; i += 4) {  // 2K Banks
            write_prg_byte(0x8000, i);             // CHR Bank 0
            write_prg_byte(0x9000, i + 1);         // CHR Bank 1
            write_prg_byte(0xA000, i + 2);         // CHR Bank 2
            write_prg_byte(0xB000, i + 3);         // CHR Bank 3
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 69:  // 128K/256K
          banks = int_pow(2, chrsize) * 4;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x8000, 0);  // Command Register - CHR Bank 0
            write_prg_byte(0xA000, i);  // Parameter Register - ($0000-$03FF)
            dumpBankCHR(0x0, 0x400);    // 1K Banks
          }
          break;

        case 72:  // 128K
          banks = int_pow(2, chrsize) / 2;
          write_prg_byte(0x8000, 0);            // Reset Register
          for (size_t i = 0; i < banks; i++) {  // 8K Banks
            write_prg_byte(0x8000, i | 0x40);   // CHR Command + Bank
            write_prg_byte(0x8000, i);          // CHR Bank
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 75:  // 128K
          banks = int_pow(2, chrsize);
          for (size_t i = 0; i < banks; i++) {        // 4K Banks
            write_reg_byte(0xE000, i);                // CHR Bank Low Bits [WRITE RAM SAFE]
            write_prg_byte(0x9000, (i & 0x10) >> 3);  // High Bit
            dumpBankCHR(0x0, 0x1000);
          }
          break;

        case 77:  // 32K
          banks = int_pow(2, chrsize) * 2;
          for (size_t i = 0; i < banks; i++) {  // 2K Banks
            write_prg_byte(0x8000, i << 4);     // CHR Bank 0
            dumpBankCHR(0x0, 0x800);
          }
          break;

        case 78:  // 128K
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {  // 8K Banks
            write_prg_byte(0x8000, i << 4);     // CHR Bank 0
            dumpBankCHR(0x0, 0x2000);           // 8K Banks ($0000-$1FFF)
          }
          break;

        case 79:
        case 146:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x4100, i);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 80:   // 128K/256K
        case 82:   // 128K/256K
        case 207:  // 128K [CART SOMETIMES NEEDS POWERCYCLE]
        case 552:
          banks = int_pow(2, chrsize) * 2;
          write_prg_byte(0x7EF6, 0x00);  // CHR mode [2x 2KiB banks at $0000-$0FFF]
          for (size_t i = 0; i < banks; i += 2) {
            write_prg_byte(0x7EF0, i << 1);
            write_prg_byte(0x7EF1, (i + 1) << 1);
            dumpBankCHR(0x0, 0x1000);
          }
          break;

        case 85:  // 128K
          banks = int_pow(2, chrsize) * 4;
          for (size_t i = 0; i < banks; i += 8) {
            write_prg_byte(0xA000, i);      // CHR Bank 0
            write_prg_byte(0xA008, i + 1);  // CHR Bank 1
            write_prg_byte(0xB000, i + 2);  // CHR Bank 2
            write_prg_byte(0xB008, i + 3);  // CHR Bank 3
            write_prg_byte(0xC000, i + 4);  // CHR Bank 4
            write_prg_byte(0xC008, i + 5);  // CHR Bank 5
            write_prg_byte(0xD000, i + 6);  // CHR Bank 6
            write_prg_byte(0xD008, i + 7);  // CHR Bank 7
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 86:  // 64K
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {  // 8K Banks
            if (i < 4)
              write_prg_byte(0x6000, i & 0x3);
            else
              write_prg_byte(0x6000, (i | 0x40) & 0x43);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 87:  // 16K/32K
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {  // 16K/32K
            write_prg_byte(0x6000, (((i & 0x1) << 1) | ((i & 0x2) >> 1)));
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 89:  // 128K
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {  // 8K Banks
            if (i < 8)
              write_prg_byte(0x8000, i & 0x7);
            else
              write_prg_byte(0x8000, (i | 0x80) & 0x87);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 91:
          banks = int_pow(2, chrsize) * 2;
          for (size_t i = 0; i < banks; i += 1) {
            write_prg_byte(0x8000 + ((i & 0x100) >> 8), i);  // CHR A19 (submapper 0 only)
            write_prg_byte(0x6000, i);                       // CHR A18-A11
            dumpBankCHR(0x0, 0x0800);
          }
          break;

        case 92:  // 128K
          banks = int_pow(2, chrsize) / 2;
          write_prg_byte(0x8000, 0);            // Reset Register
          for (size_t i = 0; i < banks; i++) {  // 8K Banks
            write_prg_byte(0x8000, i | 0x40);   // CHR Command + Bank
            write_prg_byte(0x8000, i);          // CHR Bank
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 113:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x4100, (i & 0x08) << 3 | (i & 0x07));
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 114:  // Submapper 0
          banks = int_pow(2, chrsize) * 4;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x6000, (i & 0x80) >> 7);
            write_prg_byte(0xA000, 6);
            write_prg_byte(0xC000, i);
            dumpBankCHR(0x1000, 0x1400);
          }
          break;


        case 140:  // 32K/128K
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {  // 8K Banks
            write_prg_byte(0x6000, i);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 174:  // 64k
          for (size_t i = 0; i < 8; i++) {
            write_prg_byte(0xFF00 + (i << 1), 0);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 184:  // 16K/32K
          banks = int_pow(2, chrsize);
          for (size_t i = 0; i < banks; i++) {  // 4K Banks
            write_prg_byte(0x6000, i);          // CHR LOW (Bits 0-2) ($0000-$0FFF)
            dumpBankCHR(0x0, 0x1000);           // 4K Banks ($0000-$0FFF)
          }
          break;

        case 185:                           // 8K [READ 32K TO OVERRIDE LOCKOUT]
          for (size_t i = 0; i < 4; i++) {  // Read 32K to locate valid 8K
            write_prg_byte(0x8000, i);
            uint8_t chrcheck = read_chr_byte(0);
            for (size_t address = 0x0; address < 0x2000; address += 512) {
              for (size_t x = 0; x < 512; x++) {
                sdBuffer[x] = read_chr_byte(address + x);
              }
              if (chrcheck != 0xFF)
                myFile.write(sdBuffer, 512);
            }
          }
          break;

        case 200:
        case 212:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x8000 + (i & 0x07), 0);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 201:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x8000 + (i & 0xFF), 0);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 202:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x8000 | (i << 1), 0);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 203:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x8000, (i & 0x03));
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 210:  // 128K/256K
          banks = int_pow(2, chrsize) * 4;
          write_prg_byte(0xE800, 0xC0);  // CHR RAM DISABLE (Bit 6 and 7) [WRITE NO RAM]
          for (size_t i = 0; i < banks; i += 8) {
            write_prg_byte(0x8000, i);      // CHR Bank 0
            write_prg_byte(0x8800, i + 1);  // CHR Bank 1
            write_prg_byte(0x9000, i + 2);  // CHR Bank 2
            write_prg_byte(0x9800, i + 3);  // CHR Bank 3
            write_prg_byte(0xA000, i + 4);  // CHR Bank 4
            write_prg_byte(0xA800, i + 5);  // CHR Bank 5
            write_prg_byte(0xB000, i + 6);  // CHR Bank 6
            write_prg_byte(0xB800, i + 7);  // CHR Bank 7
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 214:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x8000 | (i << 2), 0);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 225:
        case 255:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x8000 + (((i & 0x40) << 8) | (i & 0x3F)), 0);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 228:
          banks = int_pow(2, chrsize) / 2;
          write_prg_byte(0x8000, 0);
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x8000 + ((i & 0x3C) >> 2), i & 0x03);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 229:
          for (size_t i = 0; i < 32; i++) {
            write_prg_byte(0x8000 + i, i);
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 236:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x8000 | (i & 0x0F), 0);  // A16-A13
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 240:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x5FFF, (i & 0xF));
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 246:
          banks = int_pow(2, chrsize) / 2;
          for (size_t i = 0; i < banks; i += 4) {
            write_prg_byte(0x6004, (i | 0));
            write_prg_byte(0x6005, (i | 1));
            write_prg_byte(0x6006, (i | 2));
            write_prg_byte(0x6007, (i | 3));
            dumpBankCHR(0x0, 0x2000);
          }
          break;

        case 268:  // mapper 268.0
          banks = int_pow(2, chrsize) * 4;
          write_prg_byte(0xA001, 0x80);
          for (size_t i = 0; i < banks; i++) {
            write_prg_byte(0x6000, ((i & 0x380) >> 4) | ((i & 0xC00) >> 9));
            write_prg_byte(0x8000, 0x02);
            write_prg_byte(0x8001, i);
            dumpBankCHR(0x1000, 0x1400);
          }
          break;
      }
      if (!readrom) {
        myFile.flush();
        myFile.close();

        println_Msg(F("CHR FILE DUMPED!"));
        println_Msg(FS(FSTRING_EMPTY));
        display_Update();
      }
    }
  }
  set_address(0);
  PHI2_HI;
  ROMSEL_HI;
  rgbLed(black_color);
}

/******************************************
   RAM Functions
 *****************************************/
void readRAM() {
  display_Clear();
  display_Update();

  uint16_t banks;

  rgbLed(turquoise_color);
  set_address(0);
  _delay_us(1);
  if (ramsize == 0) {

    println_Msg(F("RAM SIZE 0K"));
    display_Update();
  } else {
    CreateRAMFileInSD();
    word base = 0x6000;
    if (myFile) {
      switch (mapper) {
        case 0:                                       // 2K/4K
          dumpBankPRG(0x0, (0x800 * ramsize), base);  // 2K/4K
          break;                                      // SWITCH MUST BE IN OFF POSITION

        case 1:
        case 155:                               // 8K/16K/32K
          banks = int_pow(2, ramsize) / 2;      // banks = 1,2,4
          for (size_t i = 0; i < banks; i++) {  // 8K Banks ($6000-$7FFF)
            write_prg_byte(0x8000, 0x80);       // Clear Register
            write_mmc1_byte(0x8000, 1 << 3);
            write_mmc1_byte(0xE000, 0);
            if (banks == 4)  // 32K
              write_mmc1_byte(0xA000, i << 2);
            else
              write_mmc1_byte(0xA000, i << 3);
            dumpBankPRG(0x0, 0x2000, base);  // 8K
          }
          break;

        case 4:                                                                // 1K/8K (MMC6/MMC3)
          if (mmc6) {                                                          // MMC6 1K
            write_prg_byte(0x8000, 0x20);                                      // PRG RAM ENABLE
            write_prg_byte(0xA001, 0x20);                                      // PRG RAM PROTECT - Enable reading RAM at $7000-$71FF
            for (size_t address = 0x1000; address < 0x1200; address += 512) {  // 512B
              dumpMMC5RAM(base, address);
            }
            write_prg_byte(0x8000, 0x20);                                      // PRG RAM ENABLE
            write_prg_byte(0xA001, 0x80);                                      // PRG RAM PROTECT - Enable reading RAM at $7200-$73FF
            for (size_t address = 0x1200; address < 0x1400; address += 512) {  // 512B
              dumpMMC5RAM(base, address);
            }
            write_prg_byte(0x8000, 6);       // PRG RAM DISABLE
          } else {                           // MMC3 8K
            write_prg_byte(0xA001, 0xC0);    // PRG RAM CHIP ENABLE - Chip Enable, Write Protect
            dumpBankPRG(0x0, 0x2000, base);  // 8K
          }
          break;

        case 5:                                         // 8K/16K/32K
          write_prg_byte(0x5100, 3);                    // 8K PRG Banks
          banks = int_pow(2, ramsize) / 2;              // banks = 1,2,4
          if (banks == 2) {                             // 16K - Split SRAM Chips 8K/8K
            for (size_t i = 0; i < (banks / 2); i++) {  // Chip 1
              write_prg_byte(0x5113, i);
              for (size_t address = 0; address < 0x2000; address += 512) {  // 8K
                dumpMMC5RAM(base, address);
              }
            }
            for (size_t j = 4; j < (banks / 2) + 4; j++) {  // Chip 2
              write_prg_byte(0x5113, j);
              for (size_t address = 0; address < 0x2000; address += 512) {  // 8K
                dumpMMC5RAM(base, address);
              }
            }
          } else {                                // 8K/32K Single SRAM Chip
            for (size_t i = 0; i < banks; i++) {  // banks = 1 or 4
              write_prg_byte(0x5113, i);
              for (size_t address = 0; address < 0x2000; address += 512) {  // 8K
                dumpMMC5RAM(base, address);
              }
            }
          }
          break;

        case 16:  // 256-byte EEPROM 24C02
        case 159:
          {  // 128-byte EEPROM 24C01 [Little Endian]
            size_t eepsize;
            if (mapper == 159)
              eepsize = 128;
            else
              eepsize = 256;
            for (size_t address = 0; address < eepsize; address++) {
              EepromREAD(address);
            }
            myFile.write(sdBuffer, eepsize);
            //          display_Clear(); // TEST PURPOSES - DISPLAY EEPROM DATA
            break;
          }
        case 19:
          if (ramsize == 2) {  // PRG RAM 128B
            for (size_t x = 0; x < 128; x++) {
              write_ram_byte(0xF800, x);            // PRG RAM ENABLE
              sdBuffer[x] = read_prg_byte(0x4800);  // DATA PORT
            }
            myFile.write(sdBuffer, 128);
          } else {                             // SRAM 8K
            for (size_t i = 0; i < 64; i++) {  // Init Register
              write_ram_byte(0xE000, 0);
            }
            dumpBankPRG(0x0, 0x2000, base);  // 8K
          }
          break;

        case 80:                              // 1K
          write_prg_byte(0x7EF8, 0xA3);       // PRG RAM ENABLE 0
          write_prg_byte(0x7EF9, 0xA3);       // PRG RAM ENABLE 1
          for (size_t x = 0; x < 128; x++) {  // PRG RAM 1K ($7F00-$7FFF) MIRRORED ONCE
            sdBuffer[x] = read_prg_byte(0x7F00 + x);
          }
          myFile.write(sdBuffer, 128);
          write_prg_byte(0x7EF8, 0xFF);  // PRG RAM DISABLE 0
          write_prg_byte(0x7EF9, 0xFF);  // PRG RAM DISABLE 1
          break;

        case 82:                                                          // 5K
          write_prg_byte(0x7EF7, 0xCA);                                   // PRG RAM ENABLE 0 ($6000-$67FF)
          write_prg_byte(0x7EF8, 0x69);                                   // PRG RAM ENABLE 1 ($6800-$6FFF)
          write_prg_byte(0x7EF9, 0x84);                                   // PRG RAM ENABLE 2 ($7000-$73FF)
          for (size_t address = 0x0; address < 0x1400; address += 512) {  // PRG RAM 5K ($6000-$73FF)
            dumpMMC5RAM(base, address);
          }
          write_prg_byte(0x7EF7, 0xFF);  // PRG RAM DISABLE 0 ($6000-$67FF)
          write_prg_byte(0x7EF8, 0xFF);  // PRG RAM DISABLE 1 ($6800-$6FFF)
          write_prg_byte(0x7EF9, 0xFF);  // PRG RAM DISABLE 2 ($7000-$73FF)
          break;

        default:
          if (mapper == 118)               // 8K
            write_prg_byte(0xA001, 0xC0);  // PRG RAM CHIP ENABLE - Chip Enable, Write Protect
          else if (mapper == 19) {
            for (size_t i = 0; i < 64; i++) {  // Init Register
              write_ram_byte(0xE000, 0);
            }
          } else if ((mapper == 21) || (mapper == 25))  // 8K
            write_prg_byte(0x8000, 0);
          else if (mapper == 26)           // 8K
            write_prg_byte(0xB003, 0x80);  // PRG RAM ENABLE
          else if (mapper == 68)           // 8K
            write_reg_byte(0xF000, 0x10);  // PRG RAM ENABLE [WRITE RAM SAFE]
          else if (mapper == 69) {         // 8K
            write_prg_byte(0x8000, 8);     // Command Register - PRG Bank 0
            write_prg_byte(0xA000, 0xC0);  // Parameter Register - PRG RAM Enabled, PRG RAM, Bank 0 to $6000-$7FFF
          } else if (mapper == 85)         // 8K
            write_ram_byte(0xE000, 0x80);  // PRG RAM ENABLE
          else if (mapper == 153)          // 8K
            write_prg_byte(0x800D, 0x20);  // PRG RAM Chip Enable
          dumpBankPRG(0x0, 0x2000, base);  // 8K
          if (mapper == 85)                // 8K
            write_reg_byte(0xE000, 0);     // PRG RAM DISABLE [WRITE RAM SAFE]
          break;
      }
      myFile.flush();
      myFile.close();

      println_Msg(F("RAM FILE DUMPED!"));
      println_Msg(FS(FSTRING_EMPTY));
      display_Update();

      if ((mapper == 16) || (mapper == 159))
        printCRC(fileName, NULL, 0);
      else
        printCRC(fileName, NULL, 0);
    }
  }
  set_address(0);
  PHI2_HI;
  ROMSEL_HI;
  rgbLed(black_color);
}

void writeBankPRG(const size_t from, const size_t to, const size_t base) {
  for (size_t address = from; address < to; address += 512) {
    myFile.read(sdBuffer, 512);
    for (size_t x = 0; x < 512; x++) {
      write_prg_byte(base + address + x, sdBuffer[x]);
    }
  }
}

void writeBankWRAM(const size_t from, const size_t to, const size_t base) {
  for (size_t address = from; address < to; address += 512) {
    myFile.read(sdBuffer, 512);
    for (size_t x = 0; x < 512; x++) {
      write_wram_byte(base + address + x, sdBuffer[x]);
    }
  }
}

void writeRAM() {
  display_Clear();

  if (ramsize == 0) {
    print_Error(F("RAM SIZE 0K"));
  } else {
    fileBrowser(F("Select RAM File"));
    word base = 0x6000;
    uint16_t banks;

    sd.chdir();
    sprintf(filePath, "%s/%s", filePath, fileName);

    display_Clear();
    println_Msg(F("Writing File: "));
    println_Msg(filePath);
    println_Msg(fileName);
    display_Update();

    //open file on sd card
    if (myFile.open(filePath, O_READ)) {
      switch (mapper) {
        case 0:                                        // 2K/4K
          writeBankPRG(0x0, (0x800 * ramsize), base);  // 2K/4K
          break;                                       // SWITCH MUST BE IN OFF POSITION

        case 1:
        case 155:
          banks = int_pow(2, ramsize) / 2;      // banks = 1,2,4
          for (size_t i = 0; i < banks; i++) {  // 8K Banks ($6000-$7FFF)
            write_prg_byte(0x8000, 0x80);       // Clear Register
            write_mmc1_byte(0x8000, 1 << 3);    // PRG ROM MODE 32K
            write_mmc1_byte(0xE000, 0);         // PRG RAM ENABLED
            if (banks == 4)                     // 32K
              write_mmc1_byte(0xA000, i << 2);
            else
              write_mmc1_byte(0xA000, i << 3);
            writeBankPRG(0x0, 0x2000, base);  // 8K
          }
          break;

        case 4:                                   // 1K/8K (MMC6/MMC3)
          if (mmc6) {                             // MMC6 1K
            write_prg_byte(0x8000, 0x20);         // PRG RAM ENABLE
            write_prg_byte(0xA001, 0x30);         // PRG RAM PROTECT - Enable reading/writing to RAM at $7000-$71FF
            writeBankWRAM(0x1000, 0x1200, base);  // 512B

            write_prg_byte(0x8000, 0x20);         // PRG RAM ENABLE
            write_prg_byte(0xA001, 0xC0);         // PRG RAM PROTECT - Enable reading/writing to RAM at $7200-$73FF
            writeBankWRAM(0x1200, 0x1400, base);  // 512B

            write_prg_byte(0x8000, 0x6);      // PRG RAM DISABLE
          } else {                            // MMC3 8K
            write_prg_byte(0xA001, 0x80);     // PRG RAM CHIP ENABLE - Chip Enable, Allow Writes
            writeBankPRG(0x0, 0x2000, base);  // 8K
            write_prg_byte(0xA001, 0xC0);     // PRG RAM CHIP ENABLE - Chip Enable, Write Protect
          }
          break;

        case 5:                                         // 8K/16K/32K
          write_prg_byte(0x5100, 3);                    // 8K PRG Banks
          banks = int_pow(2, ramsize) / 2;              // banks = 1,2,4
          if (banks == 2) {                             // 16K - Split SRAM Chips 8K/8K [ETROM = 16K (ONLY 1ST 8K BATTERY BACKED)]
            for (size_t i = 0; i < (banks / 2); i++) {  // Chip 1
              write_prg_byte(0x5113, i);
              for (size_t address = 0; address < 0x2000; address += 512) {  // 8K
                writeMMC5RAM(base, address);
              }
            }
            for (size_t j = 4; j < (banks / 2) + 4; j++) {  // Chip 2
              write_prg_byte(0x5113, j);
              for (size_t address = 0; address < 0x2000; address += 512) {  // 8K
                writeMMC5RAM(base, address);
              }
            }
          } else {                                // 8K/32K Single SRAM Chip [EKROM = 8K BATTERY BACKED, EWROM = 32K BATTERY BACKED]
            for (size_t i = 0; i < banks; i++) {  // banks = 1 or 4
              write_prg_byte(0x5113, i);
              for (size_t address = 0; address < 0x2000; address += 512) {  // 8K
                writeMMC5RAM(base, address);
              }
            }
          }
          break;

        case 16:  // 256-byte EEPROM 24C02
        case 159:
          {  // 128-byte EEPROM 24C01 [Little Endian]
            size_t eepsize;
            if (mapper == 159)
              eepsize = 128;
            else
              eepsize = 256;
            myFile.read(sdBuffer, eepsize);
            for (size_t address = 0; address < eepsize; address++) {
              EepromWRITE(address);
              if ((address % 128) == 0)
                display_Clear();
              print_Msg(F("."));
              display_Update();
            }
            break;
          }
        case 19:
          if (ramsize == 2) {  // PRG RAM 128B
            myFile.read(sdBuffer, 128);
            for (size_t x = 0; x < 128; x++) {
              write_ram_byte(0xF800, x);            // PRG RAM ENABLE
              write_prg_byte(0x4800, sdBuffer[x]);  // DATA PORT
            }
          } else {                             // SRAM 8K
            for (size_t i = 0; i < 64; i++) {  // Init Register
              write_ram_byte(0xF800, 0x40);    // PRG RAM WRITE ENABLE
            }
            write_ram_byte(0xF800, 0x40);     // PRG RAM WRITE ENABLE
            writeBankPRG(0x0, 0x2000, base);  // 8K
            write_ram_byte(0xF800, 0x0F);     // PRG RAM WRITE PROTECT
          }
          break;

        case 80:                                                             // 1K
          write_prg_byte(0x7EF8, 0xA3);                                      // PRG RAM ENABLE 0
          write_prg_byte(0x7EF9, 0xA3);                                      // PRG RAM ENABLE 1
          for (size_t address = 0x1F00; address < 0x2000; address += 512) {  // PRG RAM 1K ($7F00-$7FFF)
            myFile.read(sdBuffer, 128);
            for (size_t x = 0; x < 128; x++) {
              write_prg_byte(base + address + x, sdBuffer[x]);
            }
          }
          write_prg_byte(0x7EF8, 0xFF);  // PRG RAM DISABLE 0
          write_prg_byte(0x7EF9, 0xFF);  // PRG RAM DISABLE 1
          break;

        case 82:                                                           // 5K
          write_prg_byte(0x7EF7, 0xCA);                                    // PRG RAM ENABLE 0 ($6000-$67FF)
          write_prg_byte(0x7EF8, 0x69);                                    // PRG RAM ENABLE 1 ($6800-$6FFF)
          write_prg_byte(0x7EF9, 0x84);                                    // PRG RAM ENABLE 2 ($7000-$73FF)
          for (size_t address = 0x0; address < 0x1400; address += 1024) {  // PRG RAM 5K ($6000-$73FF)
            myFile.read(sdBuffer, 512);
            uint8_t firstbyte = sdBuffer[0];
            for (size_t x = 0; x < 512; x++)
              write_prg_byte(base + address + x, sdBuffer[x]);
            myFile.read(sdBuffer, 512);
            for (size_t x = 0; x < 512; x++)
              write_prg_byte(base + address + x + 512, sdBuffer[x]);
            write_prg_byte(base + address, firstbyte);  // REWRITE 1ST BYTE
          }
          write_prg_byte(0x7EF7, 0xFF);  // PRG RAM DISABLE 0 ($6000-$67FF)
          write_prg_byte(0x7EF8, 0xFF);  // PRG RAM DISABLE 1 ($6800-$6FFF)
          write_prg_byte(0x7EF9, 0xFF);  // PRG RAM DISABLE 2 ($7000-$73FF)
          break;

        default:
          if (mapper == 118)                          // 8K
            write_prg_byte(0xA001, 0x80);             // PRG RAM CHIP ENABLE - Chip Enable, Allow Writes
          else if ((mapper == 21) || (mapper == 25))  // 8K
            write_prg_byte(0x8000, 0);
          else if (mapper == 26)           // 8K
            write_prg_byte(0xB003, 0x80);  // PRG RAM ENABLE
          //            else if (mapper == 68) // 8K
          //              write_reg_byte(0xF000, 0x10); // PRG RAM ENABLE [WRITE RAM SAFE]
          else if (mapper == 69) {         // 8K
            write_prg_byte(0x8000, 8);     // Command Register - PRG Bank 0
            write_prg_byte(0xA000, 0xC0);  // Parameter Register - PRG RAM Enabled, PRG RAM, Bank 0 to $6000-$7FFF
          } else if (mapper == 85)         // 8K
            write_ram_byte(0xE000, 0x80);  // PRG RAM ENABLE
          else if (mapper == 153)          // 8K
            write_prg_byte(0x800D, 0x20);  // PRG RAM Chip Enable
          writeBankPRG(0x0, 0x2000, base);

          if (mapper == 118)               // 8K
            write_prg_byte(0xA001, 0xC0);  // PRG RAM CHIP ENABLE - Chip Enable, Write Protect
          else if (mapper == 26)           // 8K
            write_prg_byte(0xB003, 0);     // PRG RAM DISABLE
          //            else if (mapper == 68) // 8K
          //              write_reg_byte(0xF000, 0x00); // PRG RAM DISABLE [WRITE RAM SAFE]
          else if (mapper == 69) {      // 8K
            write_prg_byte(0x8000, 8);  // Command Register - PRG Bank 0
            write_prg_byte(0xA000, 0);  // Parameter Register - PRG RAM Disabled, PRG ROM, Bank 0 to $6000-$7FFF
          } else if (mapper == 85)      // 8K
            write_reg_byte(0xE000, 0);  // PRG RAM DISABLE [WRITE RAM SAFE]
          break;
      }
      myFile.close();
      rgbLed(green_color);

      println_Msg(FS(FSTRING_EMPTY));
      println_Msg(F("RAM FILE WRITTEN!"));
      display_Update();

    } else {
      print_FatalError(sd_error_STR);
    }
  }

  rgbLed(black_color);
  sd.chdir();          // root
  filePath[0] = '\0';  // Reset filePath
}

/******************************************
   Eeprom Functions
 *****************************************/
// EEPROM MAPPING
// 00-01 FOLDER #
// 02-05 SNES/GB READER SETTINGS
// 06 LED - ON/OFF [SNES/GB]
// 07 MAPPER
// 08 PRG SIZE
// 09 CHR SIZE
// 10 RAM SIZE

void resetEEPROM() {
  EEPROM_writeAnything(0, 0);   // FOLDER #
  EEPROM_writeAnything(2, 0);   // CARTMODE
  EEPROM_writeAnything(3, 0);   // RETRY
  EEPROM_writeAnything(4, 0);   // STATUS
  EEPROM_writeAnything(5, 0);   // UNKNOWNCRC
  EEPROM_writeAnything(6, 1);   // LED (RESET TO ON)
  EEPROM_writeAnything(7, 0);   // MAPPER
  EEPROM_writeAnything(9, 0);   // PRG SIZE
  EEPROM_writeAnything(10, 0);  // CHR SIZE
  EEPROM_writeAnything(11, 0);  // RAM SIZE
}

void EepromStart_NES() {
  write_prg_byte(0x800D, 0x00);  // sda low, scl low
  write_prg_byte(0x800D, 0x60);  // sda, scl high
  write_prg_byte(0x800D, 0x20);  // sda low, scl high
  write_prg_byte(0x800D, 0x00);  // START
}

void EepromStop_NES() {
  write_prg_byte(0x800D, 0x00);  // sda, scl low
  write_prg_byte(0x800D, 0x20);  // sda low, scl high
  write_prg_byte(0x800D, 0x60);  // sda, scl high
  write_prg_byte(0x800D, 0x40);  // sda high, scl low
  write_prg_byte(0x800D, 0x00);  // STOP
}

void EepromSet0_NES() {
  write_prg_byte(0x800D, 0x00);  // sda low, scl low
  write_prg_byte(0x800D, 0x20);  // sda low, scl high // 0
  write_prg_byte(0x800D, 0x00);  // sda low, scl low
}

void EepromSet1_NES() {
  write_prg_byte(0x800D, 0x40);  // sda high, scl low
  write_prg_byte(0x800D, 0x60);  // sda high, scl high // 1
  write_prg_byte(0x800D, 0x40);  // sda high, scl low
  write_prg_byte(0x800D, 0x00);  // sda low, scl low
}

void EepromStatus_NES() {        // ACK
  write_prg_byte(0x800D, 0x40);  // sda high, scl low
  write_prg_byte(0x800D, 0x60);  // sda high, scl high
  write_prg_byte(0x800D, 0xE0);  // sda high, scl high, read high
  uint8_t eepStatus = 1;
  do {
    eepStatus = (read_prg_byte(0x6000) & 0x10) >> 4;
    delayMicroseconds(4);
  } while (eepStatus == 1);
  write_prg_byte(0x800D, 0x40);  // sda high, scl low
}

void EepromReadData_NES() {
  // read serial data into buffer
  for (uint8_t i = 0; i < 8; i++) {
    write_prg_byte(0x800D, 0x60);                     // sda high, scl high, read low
    write_prg_byte(0x800D, 0xE0);                     // sda high, scl high, read high
    eepbit[i] = (read_prg_byte(0x6000) & 0x10) >> 4;  // Read 0x6000 with Mask 0x10 (bit 4)
    write_prg_byte(0x800D, 0x40);                     // sda high, scl low
  }
}

void EepromDevice_NES() {  // 24C02 ONLY
  EepromSet1_NES();
  EepromSet0_NES();
  EepromSet1_NES();
  EepromSet0_NES();
  EepromSet0_NES();  // A2
  EepromSet0_NES();  // A1
  EepromSet0_NES();  // A0
}

void EepromReadMode_NES() {
  EepromSet1_NES();    // READ
  EepromStatus_NES();  // ACK
}
void EepromWriteMode_NES() {
  EepromSet0_NES();    // WRITE
  EepromStatus_NES();  // ACK
}

void EepromFinish_NES() {
  write_prg_byte(0x800D, 0x00);  // sda low, scl low
  write_prg_byte(0x800D, 0x40);  // sda high, scl low
  write_prg_byte(0x800D, 0x60);  // sda high, scl high
  write_prg_byte(0x800D, 0x40);  // sda high, scl low
  write_prg_byte(0x800D, 0x00);  // sda low, scl low
}

void EepromSetAddress01(uint8_t address) {  // 24C01 [Little Endian]
  for (uint8_t i = 0; i < 7; i++) {
    if (address & 0x1)  // Bit is HIGH
      EepromSet1_NES();
    else  // Bit is LOW
      EepromSet0_NES();
    address >>= 1;  // rotate to the next bit
  }
}

void EepromSetAddress02(uint8_t address) {  // 24C02
  for (uint8_t i = 0; i < 8; i++) {
    if ((address >> 7) & 0x1)  // Bit is HIGH
      EepromSet1_NES();
    else  // Bit is LOW
      EepromSet0_NES();
    address <<= 1;  // rotate to the next bit
  }
  EepromStatus_NES();  // ACK
}

void EepromWriteData01() {  // 24C01 [Little Endian]
  for (uint8_t i = 0; i < 8; i++) {
    if (eeptemp & 0x1)  // Bit is HIGH
      EepromSet1_NES();
    else  // Bit is LOW
      EepromSet0_NES();
    eeptemp >>= 1;  // rotate to the next bit
  }
  EepromStatus_NES();  // ACK
}

void EepromWriteData02() {  // 24C02
  for (uint8_t i = 0; i < 8; i++) {
    if ((eeptemp >> 7) & 0x1)  // Bit is HIGH
      EepromSet1_NES();
    else  // Bit is LOW
      EepromSet0_NES();
    eeptemp <<= 1;  // rotate to the next bit
  }
  EepromStatus_NES();  // ACK
}

void EepromREAD(uint8_t address) {
  EepromStart_NES();              // START
  if (mapper == 159) {            // 24C01
    EepromSetAddress01(address);  // 24C01 [Little Endian]
    EepromReadMode_NES();
    EepromReadData_NES();
    EepromFinish_NES();
    EepromStop_NES();  // STOP
    // OR 8 bits into byte
    eeptemp = eepbit[7] << 7 | eepbit[6] << 6 | eepbit[5] << 5 | eepbit[4] << 4 | eepbit[3] << 3 | eepbit[2] << 2 | eepbit[1] << 1 | eepbit[0];
  } else {               // 24C02
    EepromDevice_NES();  // DEVICE [1010] + ADDR [A2-A0]
    EepromWriteMode_NES();
    EepromSetAddress02(address);
    EepromStart_NES();   // START
    EepromDevice_NES();  // DEVICE [1010] + ADDR [A2-A0]
    EepromReadMode_NES();
    EepromReadData_NES();
    EepromFinish_NES();
    EepromStop_NES();  // STOP
    // OR 8 bits into byte
    eeptemp = eepbit[0] << 7 | eepbit[1] << 6 | eepbit[2] << 5 | eepbit[3] << 4 | eepbit[4] << 3 | eepbit[5] << 2 | eepbit[6] << 1 | eepbit[7];
  }
  sdBuffer[address] = eeptemp;
}

void EepromWRITE(uint8_t address) {
  eeptemp = sdBuffer[address];
  EepromStart_NES();              // START
  if (mapper == 159) {            // 24C01
    EepromSetAddress01(address);  // 24C01 [Little Endian]
    EepromWriteMode_NES();
    EepromWriteData01();  // 24C01 [Little Endian]
  } else {                // 24C02
    EepromDevice_NES();   // DEVICE [1010] + ADDR [A2-A0]
    EepromWriteMode_NES();
    EepromSetAddress02(address);
    EepromWriteData02();
  }
  EepromStop_NES();  // STOP
}

#if defined(ENABLE_FLASH)
/******************************************
   NESmaker Flash Cart [SST 39SF40]
 *****************************************/
void NESmaker_Cmd(byte cmd) {
  write_prg_byte(0xC000, 0x01);
  write_prg_byte(0x9555, 0xAA);
  write_prg_byte(0xC000, 0x00);
  write_prg_byte(0xAAAA, 0x55);
  write_prg_byte(0xC000, 0x01);
  write_prg_byte(0x9555, cmd);
}

// SST 39SF040 Software ID
void NESmaker_ID() {   // Read Flash ID
  NESmaker_Cmd(0xFF);  // Reset
  NESmaker_Cmd(0x90);  // Software ID Entry
  flashid = read_prg_byte(0x8000) << 8;
  flashid |= read_prg_byte(0x8001);
  sprintf(flashid_str, "%04X", flashid);
  NESmaker_Cmd(0xF0);     // Software ID Exit
  if (flashid == 0xBFB7)  // SST 39SF040
    flashfound = 1;
}

void NESmaker_SectorErase(uint8_t bank, word address) {
  NESmaker_Cmd(0x80);
  write_prg_byte(0xC000, 0x01);
  write_prg_byte(0x9555, 0xAA);
  write_prg_byte(0xC000, 0x00);
  write_prg_byte(0xAAAA, 0x55);
  write_prg_byte(0xC000, bank);   // $00-$1F
  write_prg_byte(address, 0x30);  // Sector Erase ($8000/$9000/$A000/$B000)
}

void NESmaker_ByteProgram(uint8_t bank, word address, uint8_t data) {
  NESmaker_Cmd(0xA0);
  write_prg_byte(0xC000, bank);   // $00-$1F
  write_prg_byte(address, data);  // $8000-$BFFF
}

// SST 39SF040 Chip Erase [NOT IMPLEMENTED]
void NESmaker_ChipErase() {  // Typical 70ms
  NESmaker_Cmd(0x80);
  NESmaker_Cmd(0x10);  // Chip Erase
}

void writeFLASH() {
  display_Clear();
  if (!flashfound) {
    rgbLed(red_color);
    println_Msg(F("FLASH NOT DETECTED"));
    display_Update();
  } else {
    print_Msg(F("Flash ID: "));
    println_Msg(flashid_str);
    println_Msg(FS(FSTRING_EMPTY));
    println_Msg(F("NESmaker Flash Found"));
    println_Msg(FS(FSTRING_EMPTY));
    display_Update();
    delay(100);

    fileBrowser(F("Select FLASH File"));
    word base = 0x8000;

    sd.chdir();
    sprintf(filePath, "%s/%s", filePath, fileName);

    rgbLed(red_color);
    display_Clear();
    println_Msg(F("Writing File: "));
    println_Msg(filePath);
    println_Msg(fileName);
    display_Update();

    uint8_t bytecheck;
    uint16_t banks;

    //open file on sd card
    if (myFile.open(filePath, O_READ)) {
      banks = int_pow(2, prgsize);                                    // 256K/512K
      for (size_t i = 0; i < banks; i++) {                            // 16K Banks
        for (size_t sector = 0; sector < 0x4000; sector += 0x1000) {  // 4K Sectors ($8000/$9000/$A000/$B000)
          // Sector Erase
          NESmaker_SectorErase(i, base + sector);
          delay(18);                         // Typical 18ms
          for (uint8_t j = 0; j < 2; j++) {  // Confirm erase twice
            do {
              bytecheck = read_prg_byte(base + sector);
              delay(18);
            } while (bytecheck != 0xFF);
          }
          // Program Byte
          for (size_t addr = 0x0; addr < 0x1000; addr += 512) {
            myFile.read(sdBuffer, 512);
            for (size_t x = 0; x < 512; x++) {
              word location = base + sector + addr + x;
              NESmaker_ByteProgram(i, location, sdBuffer[x]);
              delayMicroseconds(14);             // Typical 14us
              for (uint8_t k = 0; k < 2; k++) {  // Confirm write twice
                do {
                  bytecheck = read_prg_byte(location);
                  delayMicroseconds(14);
                } while (bytecheck != sdBuffer[x]);
              }
            }
          }
        }

#if (defined(ENABLE_LCD) || defined(ENABLE_OLED))
        display.print(F("*"));
        display.updateDisplay();
#else
        Serial.print(F("*"));
        if ((i != 0) && ((i + 1) % 16 == 0))
          Serial.println(FS(FSTRING_EMPTY));
#endif
      }
      myFile.close();
      rgbLed(green_color);

      println_Msg(FS(FSTRING_EMPTY));
      println_Msg(F("FLASH FILE WRITTEN!"));
      display_Update();
    } else {
      rgbLed(red_color);
      println_Msg(F("SD ERROR"));
      display_Update();
    }
  }
  display_Clear();
  rgbLed(black_color);
  sd.chdir();          // root
  filePath[0] = '\0';  // Reset filePath
}


/******************************************
   A29040B Flash Cart [A29040B]
 *****************************************/

// A29040B Software ID
void A29040B_ID() {  // Read Flash ID
  write_prg_byte(0x9555, 0xAA);
  write_prg_byte(0xAAAA, 0x55);
  write_prg_byte(0x9555, 0x90);

  flashid = read_prg_byte(0x8000) << 8;
  flashid |= read_prg_byte(0x8001);
  sprintf(flashid_str, "%04X", flashid);
  if (flashid == 0x3786)  // A29040B
    flashfound = 1;

  A29040B_PRG_ResetFlash();
}

void A29040B_PRG_ResetFlash() {  // Reset Flash
  write_prg_byte(0x9555, 0xAA);
  write_prg_byte(0xAAAA, 0x55);
  write_prg_byte(0x9555, 0xF0);  // Reset
  delayMicroseconds(14);         // Typical 14us
}


void A29040B_PRG_Write(uint16_t address, uint8_t data) {
  write_prg_byte(0x9555, 0xAA);
  write_prg_byte(0xAAAA, 0x55);
  write_prg_byte(0x9555, 0xA0);
  write_prg_byte(address, data);  // $8000-$BFFF
  delayMicroseconds(20);          // Typical 14us
}

void A29040B_PRG_SectorErase(uint16_t sec) {
  if (flashfound) {
    write_prg_byte(0x9555, 0xAA);
    write_prg_byte(0xAAAA, 0x55);
    write_prg_byte(0x9555, 0x80);  //->setup
    write_prg_byte(0x9555, 0xAA);
    write_prg_byte(0xAAAA, 0x55);
    write_prg_byte(sec, 0x30);  //->erase
    delay(1000);                // WAIT MORE
  } else {
    println_Msg(F("FLASH NOT DETECTED OR SECTOR PROTECTED"));
  }
}

void A29040B_PRG_ChipErase() {
  if (flashfound) {
    write_prg_byte(0x9555, 0xAA);
    write_prg_byte(0xAAAA, 0x55);
    write_prg_byte(0x9555, 0x80);  //->setup
    write_prg_byte(0x9555, 0xAA);
    write_prg_byte(0xAAAA, 0x55);
    write_prg_byte(0x9555, 0x10);  //->erase
    delay(8000);                   // WAIT MORE
  } else {
    println_Msg(F("FLASH NOT DETECTED OR SECTOR PROTECTED"));
  }
}

// CHR ================================================

void A29040B_CHR_ResetFlash() {  // Reset Flash
  write_chr_byte(0x0555, 0xAA);  // Original address for CHR
  write_chr_byte(0x02AA, 0x55);  // Original address for CHR
  write_chr_byte(0x0555, 0xF0);  // Reset command with original address
  delayMicroseconds(14);         // Typical 14us
}

void A29040B_CHR_Write(uint16_t address, uint8_t data) {
  write_chr_byte(0x0555, 0xAA);   // Original address for CHR
  write_chr_byte(0x02AA, 0x55);   // Original address for CHR
  write_chr_byte(0x0555, 0xA0);   // Program command with original address
  write_chr_byte(address, data);  // CHR address range (0x0000 - 0x1FFF)
  delayMicroseconds(20);          // Typical 14us
}


void A29040B_CHR_SectorErase(uint16_t sec) {
  if (flashfound) {
    write_chr_byte(0x0555, 0xAA);  // Original address for CHR
    write_chr_byte(0x02AA, 0x55);  // Original address for CHR
    write_chr_byte(0x0555, 0x80);  // Erase Setup with original address
    write_chr_byte(0x0555, 0xAA);  // Original address for CHR
    write_chr_byte(0x02AA, 0x55);  // Original address for CHR
    write_chr_byte(sec, 0x30);     // Sector Erase Command with sector address
    delay(1000);                   // WAIT MORE
  } else {
    println_Msg(F("FLASH NOT DETECTED OR SECTOR PROTECTED"));
  }
}

void A29040B_CHR_ChipErase() {
  if (flashfound) {
    write_chr_byte(0x0555, 0xAA);  // Original address for CHR
    write_chr_byte(0x02AA, 0x55);  // Original address for CHR
    write_chr_byte(0x0555, 0x80);  // Erase Setup with original address
    write_chr_byte(0x0555, 0xAA);  // Original address for CHR
    write_chr_byte(0x02AA, 0x55);  // Original address for CHR
    write_chr_byte(0x0555, 0x10);  // Chip Erase Command with original address
    delay(8000);                   // WAIT MORE
  } else {
    println_Msg(F("FLASH NOT DETECTED OR SECTOR PROTECTED"));
  }
}
#define A29040B_TITLE "FLASH A29040B MAPPER 0"
void A29040B_writeFLASH() {

  display_Clear();
  A29040B_ID();

  char data_str[10];
  uint32_t prgSize = 0;
  uint32_t chrSize = 0;

  if (!flashfound) {
    rgbLed(red_color);
    println_Msg(F(A29040B_TITLE));
    println_Msg(FS(FSTRING_EMPTY));
    print_Msg(F("Flash ID: "));
    println_Msg(flashid_str);
    println_Msg(FS(FSTRING_EMPTY));
    println_Msg(F("FLASH NOT FOUND"));
    display_Update();
    wait();
  } else {
    println_Msg(F(A29040B_TITLE));
    println_Msg(FS(FSTRING_EMPTY));
    print_Msg(F("Flash ID: "));
    println_Msg(flashid_str);
    println_Msg(FS(FSTRING_EMPTY));
    println_Msg(F("Flash Found"));
    println_Msg(FS(FSTRING_EMPTY));
    display_Update();
    delay(3000);
    fileBrowser(F("Select FLASH File"));
    sd.chdir();
    sprintf(filePath, "%s/%s", filePath, fileName);

    if (myFile.open(filePath, O_READ)) {
      // Step 1: Read the header and extract PRG and CHR sizes
      uint8_t header[16];
      myFile.read(header, 16);  // Read the 16-byte header
      uint32_t prgAddress = 0x8000;

      prgSize = (uint32_t)header[4] * 16384;  // PRG size in bytes (header[4] gives size in 16 KB units)
      chrSize = (uint32_t)header[5] * 8192;   // CHR size in bytes (header[5] gives size in 8 KB units)

      // Output the sizes for verification
      display_Clear();
      println_Msg(F(A29040B_TITLE));
      println_Msg(FS(FSTRING_EMPTY));
      println_Msg(F("PRG Size:"));
      sprintf(data_str, "%lu", prgSize);
      println_Msg(data_str);

      println_Msg(F("CHR Size:"));
      sprintf(data_str, "%lu", chrSize);
      println_Msg(data_str);
      display_Update();
      delay(3000);

      // Step 2: Erase the entire PRG space
      rgbLed(red_color);
      display_Clear();
      println_Msg(F(A29040B_TITLE));
      println_Msg(FS(FSTRING_EMPTY));
      A29040B_PRG_ResetFlash();
      println_Msg(F("ERASING PRG..."));
      display_Update();
      A29040B_PRG_ChipErase();


      uint8_t readByte = read_prg_byte(prgAddress);
      if (readByte != 0xFF) {
        println_Msg(F("Erase Error!"));
      } else {
        println_Msg(F("Erase OK!"));
      }

      display_Update();

      // Verify that the first byte has been erased
      uint8_t erase_check = read_prg_byte(0x8000);
      if (erase_check != 0xFF) {
        println_Msg(F("SECTOR NOT ERASED"));
        sprintf(data_str, "%02X", erase_check);
        println_Msg(data_str);
        return;
      }

      delay(18);  // Adjust delay as needed

      rgbLed(red_color);
      println_Msg(FS(FSTRING_EMPTY));
      println_Msg(F("Writing PRG Data..."));
      display_Update();

      A29040B_PRG_ResetFlash();

      // Step 3: Write PRG data
      uint32_t bytesProcessed = 0;
      uint8_t buffer[512];
      myFile.seek(16);  // Skip header to start of PRG data

      while (bytesProcessed < prgSize) {
        int bytesRead = myFile.read(buffer, sizeof(buffer));
        if (bytesRead <= 0) break;

        for (int i = 0; i < bytesRead; i++) {
          A29040B_PRG_Write(prgAddress++, buffer[i]);
          delayMicroseconds(14);  // Typical 14us

          uint8_t readByte = read_prg_byte(prgAddress - 1);
          delayMicroseconds(14);  // Typical 14us
          if (readByte != buffer[i]) {
            println_Msg(F("Write Error!"));
            sprintf(data_str, "%02X", readByte);
            println_Msg(data_str);
            myFile.close();
            break;
          }
        }
        bytesProcessed += bytesRead;
      }

      // Step 4: Erase and Write CHR data
      A29040B_CHR_ResetFlash();
      display_Clear();
      println_Msg(F(A29040B_TITLE));
      println_Msg(FS(FSTRING_EMPTY));
      println_Msg(F("ERASING CHR..."));
      display_Update();
      A29040B_CHR_ChipErase();
      delay(20);
      display_Clear();

      uint32_t chrAddress = 0x0000;
      bytesProcessed = 0;
      myFile.seek(16 + prgSize);  // Seek to the start of CHR data

      readByte = read_chr_byte(chrAddress);
      if (readByte != 0xFF) {
        println_Msg(F("Erase Error!"));
      } else {
        println_Msg(F("Erase OK!"));
      }
      display_Update();

      println_Msg(F("Writing CHR Data..."));
      display_Update();


      while (bytesProcessed < chrSize) {
        int bytesRead = myFile.read(buffer, sizeof(buffer));
        if (bytesRead <= 0) break;

        for (int i = 0; i < bytesRead; i++) {
          A29040B_CHR_Write(chrAddress++, buffer[i]);
          delayMicroseconds(14);  // Typical 14us

          uint8_t readByte = read_chr_byte(chrAddress - 1);
          delayMicroseconds(14);  // Typical 14us
          if (readByte != buffer[i]) {
            println_Msg(F("Write Error!"));
            sprintf(data_str, "%02X", readByte);
            println_Msg(data_str);
            myFile.close();
            break;
          }
        }
        bytesProcessed += bytesRead;
      }
      delay(3000);
      myFile.close();
      rgbLed(green_color);
      display_Clear();
      println_Msg(F(A29040B_TITLE));
      println_Msg(FS(FSTRING_EMPTY));
      println_Msg(F("FLASH FILE WRITTEN!"));
      display_Update();
    } else {
      rgbLed(red_color);
      println_Msg(F("SD ERROR"));
      display_Update();
    }

    display_Update();
  }
}
#endif

// avoid warnings
#undef MODE_READ
#undef MODE_WRITE

#endif
//******************************************
// End of File
//******************************************