Source

pokecrystal / extras / crystal.py

Full commit
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
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
# -*- coding: utf-8 -*-
#utilities to help disassemble pokémon crystal
import sys, os, inspect, md5, json
from copy import copy, deepcopy
import subprocess
from new import classobj
import random

#for IntervalMap
from bisect import bisect_left, bisect_right
from itertools import izip

#for testing all this crap
try:
    import unittest2 as unittest
except ImportError:
    import unittest

# Check for things we need in unittest.
if not hasattr(unittest.TestCase, 'setUpClass'):
    print "The unittest2 module or Python 2.7 is required to run this script."
    sys.exit(1)

if not hasattr(json, "dumps"):
    json.dumps = json.write

#table of pointers to map groups
#each map group contains some number of map headers
map_group_pointer_table = 0x94000
map_group_count = 26
map_group_offsets = []
map_header_byte_size = 9
second_map_header_byte_size = 12

#event segment sizes
warp_byte_size = 5
trigger_byte_size = 8
signpost_byte_size = 5
people_event_byte_size = 13

#a message to show with NotImplementedErrors
bryan_message = "bryan hasn't got to this yet"

max_texts = 3
text_count = 0
texts = []

#this is straight out of ../textpre.py because i'm lazy
#see jap_chars for overrides if you are in japanese mode?
chars = {
    0x50: "@",
    0x54: "#",
    0x75: "…",
    
    0x79: "┌",
    0x7A: "─",
    0x7B: "┐",
    0x7C: "│",
    0x7D: "└",
    0x7E: "┘",
    
    0x74: "№",
    
    0x7F: " ",
    0x80: "A",
    0x81: "B",
    0x82: "C",
    0x83: "D",
    0x84: "E",
    0x85: "F",
    0x86: "G",
    0x87: "H",
    0x88: "I",
    0x89: "J",
    0x8A: "K",
    0x8B: "L",
    0x8C: "M",
    0x8D: "N",
    0x8E: "O",
    0x8F: "P",
    0x90: "Q",
    0x91: "R",
    0x92: "S",
    0x93: "T",
    0x94: "U",
    0x95: "V",
    0x96: "W",
    0x97: "X",
    0x98: "Y",
    0x99: "Z",
    0x9A: "(",
    0x9B: ")",
    0x9C: ":",
    0x9D: ";",
    0x9E: "[",
    0x9F: "]",
    0xA0: "a",
    0xA1: "b",
    0xA2: "c",
    0xA3: "d",
    0xA4: "e",
    0xA5: "f",
    0xA6: "g",
    0xA7: "h",
    0xA8: "i",
    0xA9: "j",
    0xAA: "k",
    0xAB: "l",
    0xAC: "m",
    0xAD: "n",
    0xAE: "o",
    0xAF: "p",
    0xB0: "q",
    0xB1: "r",
    0xB2: "s",
    0xB3: "t",
    0xB4: "u",
    0xB5: "v",
    0xB6: "w",
    0xB7: "x",
    0xB8: "y",
    0xB9: "z",
    0xC0: "Ä",
    0xC1: "Ö",
    0xC2: "Ü",
    0xC3: "ä",
    0xC4: "ö",
    0xC5: "ü",
    0xD0: "'d",
    0xD1: "'l",
    0xD2: "'m",
    0xD3: "'r",
    0xD4: "'s",
    0xD5: "'t",
    0xD6: "'v",
    0xE0: "'",
    0xE3: "-",
    0xE6: "?",
    0xE7: "!",
    0xE8: ".",
    0xE9: "&",
    0xEA: "é",
    0xEB: "→",
    0xEF: "♂",
    0xF0: "¥",
    0xF1: "×",
    0xF3: "/",
    0xF4: ",",
    0xF5: "♀",
    0xF6: "0",
    0xF7: "1",
    0xF8: "2",
    0xF9: "3",
    0xFA: "4",
    0xFB: "5",
    0xFC: "6",
    0xFD: "7",
    0xFE: "8",
    0xFF: "9",
}

#override whatever defaults for japanese symbols
jap_chars = copy(chars)
jap_chars.update({
    0x05: "ガ",
    0x06: "ギ",
    0x07: "グ",
    0x08: "ゲ",
    0x09: "ゴ",
    0x0A: "ザ",
    0x0B: "ジ",
    0x0C: "ズ",
    0x0D: "ゼ",
    0x0E: "ゾ",
    0x0F: "ダ",
    0x10: "ヂ",
    0x11: "ヅ",
    0x12: "デ",
    0x13: "ド",
    0x19: "バ",
    0x1A: "ビ",
    0x1B: "ブ",
    0x1C: "ボ",
    0x26: "が",
    0x27: "ぎ",
    0x28: "ぐ",
    0x29: "げ",
    0x2A: "ご",
    0x2B: "ざ",
    0x2C: "じ",
    0x2D: "ず",
    0x2E: "ぜ",
    0x2F: "ぞ",
    0x30: "だ",
    0x31: "ぢ",
    0x32: "づ",
    0x33: "で",
    0x34: "ど",
    0x3A: "ば",
    0x3B: "び",
    0x3C: "ぶ",
    0x3D: "べ",
    0x3E: "ぼ",
    0x40: "パ",
    0x41: "ピ",
    0x42: "プ",
    0x43: "ポ",
    0x44: "ぱ",
    0x45: "ぴ",
    0x46: "ぷ",
    0x47: "ぺ",
    0x48: "ぽ",
    0x80: "ア",
    0x81: "イ",
    0x82: "ウ",
    0x83: "エ",
    0x84: "ォ",
    0x85: "カ",
    0x86: "キ",
    0x87: "ク",
    0x88: "ケ",
    0x89: "コ",
    0x8A: "サ",
    0x8B: "シ",
    0x8C: "ス",
    0x8D: "セ",
    0x8E: "ソ",
    0x8F: "タ",
    0x90: "チ",
    0x91: "ツ",
    0x92: "テ",
    0x93: "ト",
    0x94: "ナ",
    0x95: "ニ",
    0x96: "ヌ",
    0x97: "ネ",
    0x98: "ノ",
    0x99: "ハ",
    0x9A: "ヒ",
    0x9B: "フ",
    0x9C: "ホ",
    0x9D: "マ",
    0x9E: "ミ",
    0x9F: "ム",
    0xA0: "メ",
    0xA1: "モ",
    0xA2: "ヤ",
    0xA3: "ユ",
    0xA4: "ヨ",
    0xA5: "ラ",
    0xA6: "ル",
    0xA7: "レ",
    0xA8: "ロ",
    0xA9: "ワ",
    0xAA: "ヲ",
    0xAB: "ン",
    0xAC: "ッ",
    0xAD: "ャ",
    0xAE: "ュ",
    0xAF: "ョ",
    0xB0: "ィ",
    0xB1: "あ",
    0xB2: "い",
    0xB3: "う",
    0xB4: "え",
    0xB5: "お",
    0xB6: "か",
    0xB7: "き",
    0xB8: "く",
    0xB9: "け",
    0xBA: "こ",
    0xBB: "さ",
    0xBC: "し",
    0xBD: "す",
    0xBE: "せ",
    0xBF: "そ",
    0xC0: "た",
    0xC1: "ち",
    0xC2: "つ",
    0xC3: "て",
    0xC4: "と",
    0xC5: "な",
    0xC6: "に",
    0xC7: "ぬ",
    0xC8: "ね",
    0xC9: "の",
    0xCA: "は",
    0xCB: "ひ",
    0xCC: "ふ",
    0xCD: "へ",
    0xCE: "ほ",
    0xCF: "ま",
    0xD0: "み",
    0xD1: "む",
    0xD2: "め",
    0xD3: "も",
    0xD4: "や",
    0xD5: "ゆ",
    0xD6: "よ",
    0xD7: "ら",
    0xD8: "り",
    0xD9: "る",
    0xDA: "れ",
    0xDB: "ろ",
    0xDC: "わ",
    0xDD: "を",
    0xDE: "ん",
    0xDF: "っ",
    0xE0: "ゃ",
    0xE1: "ゅ",
    0xE2: "ょ",
    0xE3: "ー",
})

#some of the japanese characters can probably fit into the english table
#without overriding any of the other mappings.
for key, value in jap_chars.items():
    if key not in chars.keys():
        chars[key] = value

class Size():
    """a simple way to track whether or not a size
    includes the first value or not, like for
    whether or not the size of a command in a script
    also includes the command byte or not"""
    def __init__(self, size, inclusive=False):
        self.inclusive = inclusive
        if inclusive: size = size-1
        self.size = size
    def inclusive(self):
        return self.size + 1
    def exclusive(self):
        return self.size

class IntervalMap(object):
    """
    This class maps a set of intervals to a set of values.

    >>> i = IntervalMap()
    >>> i[0:5] = "hello world"
    >>> i[6:10] = "hello cruel world"
    >>> print i[4]
    "hello world"
    """
    def __init__(self):
        """initializes an empty IntervalMap"""
        self._bounds = []
        self._items = []
        self._upperitem = None
    def __setitem__(self, _slice, _value):
        """sets an interval mapping"""
        assert isinstance(_slice, slice), 'The key must be a slice object'
    
        if _slice.start is None:
            start_point = -1
        else:
            start_point = bisect_left(self._bounds, _slice.start)
        
        if _slice.stop is None:
            end_point = -1
        else:
            end_point = bisect_left(self._bounds, _slice.stop)
        
        if start_point>=0:
            if start_point < len(self._bounds) and self._bounds[start_point]<_slice.start:
                start_point += 1 

            if end_point>=0:        
                self._bounds[start_point:end_point] = [_slice.start, _slice.stop]
                if start_point < len(self._items):
                    self._items[start_point:end_point] = [self._items[start_point], _value]
                else:
                    self._items[start_point:end_point] = [self._upperitem, _value]
            else:
                self._bounds[start_point:] = [_slice.start]
                if start_point < len(self._items):
                    self._items[start_point:] = [self._items[start_point], _value]
                else:
                    self._items[start_point:] = [self._upperitem]
                self._upperitem = _value
        else:
            if end_point>=0:
                self._bounds[:end_point] = [_slice.stop]
                self._items[:end_point] = [_value]
            else:
                self._bounds[:] = []
                self._items[:] = []
                self._upperitem = _value
    def __getitem__(self,_point):
        """gets a value from the mapping"""
        assert not isinstance(_point, slice), 'The key cannot be a slice object'  
            
        index = bisect_right(self._bounds, _point)
        if index < len(self._bounds):
            return self._items[index]
        else:
            return self._upperitem
    def items(self):
        """returns an iterator with each item being
        ((low_bound, high_bound), value)
        these items are returned in order"""
        previous_bound = None
        for (b, v) in izip(self._bounds, self._items):
            if v is not None:
                yield (previous_bound, b), v
            previous_bound = b
        if self._upperitem is not None:
            yield (previous_bound, None), self._upperitem
    def values(self):
        """returns an iterator with each item being a stored value
        the items are returned in order"""
        for v in self._items:
            if v is not None:
                yield v
        if self._upperitem is not None:
            yield self._upperitem
    def __repr__(self):
        s = []
        for b,v in self.items():
            if v is not None:
                s.append('[%r, %r] => %r'%(
                    b[0],
                    b[1],
                    v
                ))
        return '{'+', '.join(s)+'}'

#keys are intervals "500..555" of byte addresses for each script
#last byte is not inclusive
#this is how to make sure scripts are not recalculated
script_parse_table = IntervalMap()

def is_script_already_parsed_at(address):
    """looks up whether or not a script is parsed at a certain address"""
    if script_parse_table[address] == None: return False
    return True

def map_name_cleaner(input):
    """generate a valid asm label for a given map name"""
    return input.replace(":", "").\
                 replace("(", "").\
                 replace(")", "").\
                 replace("'", "").\
                 replace("/", "").\
                 replace(",", "").\
                 replace(".", "").\
                 replace("Pokémon Center", "PokeCenter").\
                 replace(" ", "")

class RomStr(str):
    """simple wrapper to prevent a giant rom from being shown on screen"""
    def length(self):
        """len(self)"""
        return len(self)
    def __repr__(self):
        return "RomStr(too long)"
rom = RomStr(None)
def direct_load_rom(filename="../baserom.gbc"):
    """loads bytes into memory"""
    global rom
    file_handler = open(filename, "r")
    rom = RomStr(file_handler.read())
    file_handler.close()
    return rom
def load_rom(filename="../baserom.gbc"):
    """checks that the loaded rom matches the path
    and then loads the rom if necessary."""
    global rom
    if rom != RomStr(None) and rom != None:
        return rom
    if not isinstance(rom, RomStr):
        return direct_load_rom(filename=filename)
    elif os.lstat(filename).st_size != len(rom):
        return direct_load_rom(filename)

class AsmList(list):
    """simple wrapper to prevent all asm lines from being shown on screen"""
    def length(self):
        """len(self)"""
        return len(self)
    def __repr__(self):
        return "AsmList(too long)"
def load_asm(filename="../main.asm"):
    """loads the asm source code into memory"""
    global asm
    asm = open(filename, "r").read().split("\n")
    asm = AsmList(asm)
    return asm

def grouper(some_list, count=2):
    """splits a list into sublists
    given: [1, 2, 3, 4]
    returns: [[1, 2], [3, 4]]"""
    return [some_list[i:i+count] for i in range(0, len(some_list), count)]

def is_valid_address(address):
    """is_valid_rom_address"""
    if address == None: return False
    if type(address) == str:
        address = int(address, 16)
    if 0 <= address <= 2097152: return True
    else: return False

def rom_interval(offset, length, strings=True, debug=True):
    """returns hex values for the rom starting at offset until offset+length"""
    global rom
    returnable = []
    for byte in rom[offset:offset+length]:
        if strings:
            returnable.append(hex(ord(byte)))
        else:
            returnable.append(ord(byte))
    return returnable

def rom_until(offset, byte, strings=True):
    """returns hex values from rom starting at offset until the given byte"""
    global rom
    return rom_interval(offset, rom.find(chr(byte), offset) - offset, strings=strings)

def how_many_until(byte, starting):
    index = rom.find(byte, starting)
    return index - starting

def load_map_group_offsets():
    """reads the map group table for the list of pointers"""
    global map_group_pointer_table, map_group_count, map_group_offsets
    global rom
    map_group_offsets = [] #otherwise this method can only be used once
    data = rom_interval(map_group_pointer_table, map_group_count*2, strings=False)
    data = grouper(data)
    for pointer_parts in data:
        pointer = pointer_parts[0] + (pointer_parts[1] << 8)
        offset = pointer - 0x4000 + map_group_pointer_table
        map_group_offsets.append(offset)
    return map_group_offsets

def calculate_bank(address):
    """you are too lazy to divide on your own?"""
    if type(address) == str:
        address = int(address, 16)
    if 0x4000 <= address <= 0x7FFF:
        raise Exception, "bank 1 does not exist"
    return int(address) / 0x4000
def calculate_pointer(short_pointer, bank=None):
    """calculates the full address given a 4-byte pointer and bank byte"""
    short_pointer = int(short_pointer)
    if 0x4000 <= short_pointer <= 0x7fff:
        short_pointer -= 0x4000
        bank = int(bank)
    else:
        bank = 0
    pointer = short_pointer + (bank * 0x4000)
    return pointer
def calculate_pointer_from_bytes_at(address, bank=False):
    """calculates a pointer from 2 bytes at a location
    or 3-byte pointer [bank][2-byte pointer] if bank=True"""
    if bank == True:
        bank = ord(rom[address])
        address += 1
    elif bank == False or bank == None:
        bank = calculate_bank(address)
    elif bank == "reverse" or bank == "reversed":
        bank = ord(rom[address+2])
    elif type(bank) == int:
        pass
    else:
        raise Exception, "bad bank given to calculate_pointer_from_bytes_at"
    byte1 = ord(rom[address])
    byte2 = ord(rom[address+1])
    temp  = byte1 + (byte2 << 8)
    if temp == 0:
        return None
    return calculate_pointer(temp, bank)

def clean_up_long_info(long_info):
    """cleans up some data from parse_script_engine_script_at formatting issues"""
    long_info = str(long_info)
    #get rid of the first newline
    if long_info[0] == "\n":
        long_info = long_info[1:]
    #get rid of the last newline and any leftover space
    if long_info.count("\n") > 0:
        if long_info[long_info.rindex("\n")+1:].isspace():
            long_info = long_info[:long_info.rindex("\n")]
        #remove spaces+hash from the front of each line
        new_lines = []
        for line in long_info.split("\n"):
            line = line.strip()
            if line[0] == "#":
                line = line[1:]
            new_lines.append(line)
        long_info = "\n".join(new_lines)
    return long_info

def command_debug_information(command_byte=None, map_group=None, map_id=None, address=0, info=None, long_info=None, pksv_name=None):
    "used to help debug in parse_script_engine_script_at"
    info1 = "parsing command byte " + hex(command_byte) + " for map " + \
          str(map_group) + "." + str(map_id) + " at " + hex(address)
    info1 += "    pksv: " + str(pksv_name)
    #info1 += "    info: " + str(info)
    #info1 += "    long_info: " + long_info
    return info1

class TextScript():
    "a text is a sequence of commands different from a script-engine script"
    def to_asm(self): raise NotImplementedError, bryan_message
    @staticmethod
    def find_addresses():
        """returns a list of text pointers
        useful for testing parse_text_engine_script_at
        
        Note that this list is not exhaustive. There are some texts that
        are only pointed to from some script that a current script just
        points to. So find_all_text_pointers_in_script_engine_script will
        have to recursively follow through each script to find those.
        .. it does this now :)
        """
        addresses = set()
        #for each map group
        for map_group in map_names:
            #for each map id
            for map_id in map_names[map_group]:
                #skip the offset key
                if map_id == "offset": continue
                #dump this into smap
                smap = map_names[map_group][map_id]
                #signposts
                signposts = smap["signposts"]
                #for each signpost
                for signpost in signposts:
                    if signpost["func"] in [0, 1, 2, 3, 4]:
                        #dump this into script
                        script = signpost["script"]
                    elif signpost["func"] in [05, 06]:
                        script = signpost["script"]
                    else: continue
                    #skip signposts with no bytes
                    if len(script) == 0: continue
                    #find all text pointers in script
                    texts = find_all_text_pointers_in_script_engine_script(script, smap["event_bank"])
                    #dump these addresses in
                    addresses.update(texts)
                #xy triggers
                xy_triggers = smap["xy_triggers"]
                #for each xy trigger
                for xy_trigger in xy_triggers:
                    #dump this into script
                    script = xy_trigger["script"]
                    #find all text pointers in script
                    texts = find_all_text_pointers_in_script_engine_script(script, smap["event_bank"])
                    #dump these addresses in
                    addresses.update(texts)
                #trigger scripts
                triggers = smap["trigger_scripts"]
                #for each trigger
                for (i, trigger) in triggers.items():
                    #dump this into script
                    script = trigger["script"]
                    #find all text pointers in script
                    texts = find_all_text_pointers_in_script_engine_script(script, calculate_bank(trigger["address"]))
                    #dump these addresses in
                    addresses.update(texts)
                #callback scripts
                callbacks = smap["callback_scripts"]
                #for each callback
                for (k, callback) in callbacks.items():
                    #dump this into script
                    script = callback["script"]
                    #find all text pointers in script
                    texts = find_all_text_pointers_in_script_engine_script(script, calculate_bank(callback["address"]))
                    #dump these addresses in
                    addresses.update(texts)
                #people-events
                events = smap["people_events"]
                #for each event
                for event in events:
                    if event["event_type"] == "script":
                        #dump this into script
                        script = event["script"]
                        #find all text pointers in script
                        texts = find_all_text_pointers_in_script_engine_script(script, smap["event_bank"])
                        #dump these addresses in
                        addresses.update(texts)
                    if event["event_type"] == "trainer":
                        trainer_data = event["trainer_data"]
                        addresses.update([trainer_data["text_when_seen_ptr"]])
                        addresses.update([trainer_data["text_when_trainer_beaten_ptr"]])
                        trainer_bank = calculate_bank(event["trainer_data_address"])
                        script1 = trainer_data["script_talk_again"]
                        texts1 = find_all_text_pointers_in_script_engine_script(script1, trainer_bank)
                        addresses.update(texts1)
                        script2 = trainer_data["script_when_lost"]
                        texts2 = find_all_text_pointers_in_script_engine_script(script2, trainer_bank)
                        addresses.update(texts2)
        return addresses
    @staticmethod
    def parse_text_at(address, map_group=None, map_id=None, debug=True, show=True):
        """parses a text-engine script ("in-text scripts")
        http://hax.iimarck.us/files/scriptingcodes_eng.htm#InText
    
        This is presently very broken.
    
        see parse_text_at2, parse_text_at, and process_00_subcommands
        """
        global rom, text_count, max_texts, texts
        if rom == None:
            direct_load_rom()
        if address == None:
            return "not a script"
        commands = {}
    
        total_text_commands = 0
        command_counter = 0
        original_address = address
        offset = address
        end = False
        while not end:
            address = offset
            command = {}
            command_byte = ord(rom[address])
            if debug:
                print "TextScript.parse_script_at has encountered a command byte " + hex(command_byte) + " at " + hex(address)
            end_address = address + 1
            if  command_byte == 0:
                #read until $57, $50 or $58
                jump57 = how_many_until(chr(0x57), offset)
                jump50 = how_many_until(chr(0x50), offset)
                jump58 = how_many_until(chr(0x58), offset)
         
                #whichever command comes first
                jump = min([jump57, jump50, jump58])
    
                end_address = offset + jump - 1 #we want the address before $57
    
                lines = process_00_subcommands(offset+1, end_address, debug=debug)
    
                if show and debug:
                    text = parse_text_at2(offset+1, end_address-offset+1, debug=debug)
                    print text
    
                command = {"type": command_byte,
                           "start_address": offset,
                           "end_address": end_address,
                           "size": jump,
                           "lines": lines,
                          }   
    
                offset += jump
            elif command_byte == 0x17:
                #TX_FAR [pointer][bank]
                pointer_byte1 = ord(rom[offset+1])
                pointer_byte2 = ord(rom[offset+2])
                pointer_bank = ord(rom[offset+3])
    
                pointer = (pointer_byte1 + (pointer_byte2 << 8))
                pointer = extract_maps.calculate_pointer(pointer, pointer_bank)
    
                command = {"type": command_byte,
                           "start_address": offset,
                           "end_address": offset + 3, #last byte belonging to this command
                           "pointer": pointer, #parameter
                          }
    
                offset += 3 + 1
            elif command_byte == 0x50 or command_byte == 0x57 or command_byte == 0x58: #end text
                command = {"type": command_byte,
                           "start_address": offset,
                           "end_address": offset,
                          }
    
                #this byte simply indicates to end the script
                end = True
    
                #this byte simply indicates to end the script
                if command_byte == 0x50 and ord(rom[offset+1]) == 0x50: #$50$50 means end completely
                    end = True
                    commands[command_counter+1] = command
    
                    #also save the next byte, before we quit
                    commands[command_counter+1]["start_address"] += 1
                    commands[command_counter+1]["end_address"] += 1
                    add_command_byte_to_totals(command_byte)
                elif command_byte == 0x50: #only end if we started with $0
                    if len(commands.keys()) > 0:
                        if commands[0]["type"] == 0x0: end = True
                elif command_byte == 0x57 or command_byte == 0x58: #end completely
                    end = True
                    offset += 1 #go past this 0x50
            elif command_byte == 0x1:
                #01 = text from RAM. [01][2-byte pointer]
                size = 3 #total size, including the command byte
                pointer_byte1 = ord(rom[offset+1])
                pointer_byte2 = ord(rom[offset+2])
    
                command = {"type": command_byte,
                           "start_address": offset+1,
                           "end_address": offset+2, #last byte belonging to this command
                           "pointer": [pointer_byte1, pointer_byte2], #RAM pointer
                          }
    
                #view near these bytes
                #subsection = rom[offset:offset+size+1] #peak ahead
                #for x in subsection:
                #    print hex(ord(x))
                #print "--"
    
                offset += 2 + 1 #go to the next byte
    
                #use this to look at the surrounding bytes
                if debug:
                    print "next command is: " + hex(ord(rom[offset])) + " ... we are at command number: " + str(command_counter) + " near " + hex(offset) + " on map_id=" + str(map_id)
            elif command_byte == 0x7:
                #07 = shift texts 1 row above (2nd line becomes 1st line); address for next text = 2nd line. [07]
                size = 1
                command = {"type": command_byte,
                           "start_address": offset,
                           "end_address": offset,
                          }
                offset += 1
            elif command_byte == 0x3:
                #03 = set new address in RAM for text. [03][2-byte RAM address]
                size = 3
                command = {"type": command_byte, "start_address": offset, "end_address": offset+2}
                offset += size
            elif command_byte == 0x4: #draw box
                #04 = draw box. [04][2-Byte pointer][height Y][width X]
                size = 5 #including the command
                command = {
                            "type": command_byte,
                            "start_address": offset,
                            "end_address": offset + size,
                            "pointer_bytes": [ord(rom[offset+1]), ord(rom[offset+2])],
                            "y": ord(rom[offset+3]),
                            "x": ord(rom[offset+4]),
                          }
                offset += size + 1
            elif command_byte == 0x5:
                #05 = write text starting at 2nd line of text-box. [05][text][ending command]
                #read until $57, $50 or $58
                jump57 = how_many_until(chr(0x57), offset)
                jump50 = how_many_until(chr(0x50), offset)
                jump58 = how_many_until(chr(0x58), offset)
    
                #whichever command comes first
                jump = min([jump57, jump50, jump58])
    
                end_address = offset + jump - 1 #we want the address before $57
                lines = process_00_subcommands(offset+1, end_address, debug=debug)
                
                if show and debug:
                    text = parse_text_at2(offset+1, end_address-offset+1, debug=debug)
                    print text
    
                command = {"type": command_byte,
                           "start_address": offset,
                           "end_address": end_address,
                           "size": jump,
                           "lines": lines,
                          }
                offset = end_address + 1
            elif command_byte == 0x6:
                #06 = wait for keypress A or B (put blinking arrow in textbox). [06]
                command = {"type": command_byte, "start_address": offset, "end_address": offset}
                offset += 1
            elif command_byte == 0x7:
                #07 = shift texts 1 row above (2nd line becomes 1st line); address for next text = 2nd line. [07]
                command = {"type": command_byte, "start_address": offset, "end_address": offset}
                offset += 1
            elif command_byte == 0x8:
                #08 = asm until whenever
                command = {"type": command_byte, "start_address": offset, "end_address": offset}
                offset += 1
                end = True
            elif command_byte == 0x9:
                #09 = write hex-to-dec number from RAM to textbox [09][2-byte RAM address][byte bbbbcccc]
                #  bbbb = how many bytes to read (read number is big-endian)
                #  cccc = how many digits display (decimal)
                #(note: max of decimal digits is 7,i.e. max number correctly displayable is 9999999)
                ram_address_byte1 = ord(rom[offset+1])
                ram_address_byte2 = ord(rom[offset+2])
                read_byte = ord(rom[offset+3])
    
                command = {
                            "type": command_byte,
                            "address": [ram_address_byte1, ram_address_byte2],
                            "read_byte": read_byte, #split this up when we make a macro for this
                          }
    
                offset += 4
            else:
                #if len(commands) > 0:
                #   print "Unknown text command " + hex(command_byte) + " at " + hex(offset) + ", script began with " + hex(commands[0]["type"])
                if debug:
                    print "Unknown text command at " + hex(offset) + " - command: " + hex(ord(rom[offset])) + " on map_id=" + str(map_id)
    
                #end at the first unknown command
                end = True
            commands[command_counter] = command
            command_counter += 1
        total_text_commands += len(commands)
        
        text_count += 1
        #if text_count >= max_texts:
        #    sys.exit()
        
        return commands
    @staticmethod
    def to_asm_at(address, label="SomeLabel"):
        #parse the text script
        commands = TextScript.parse_text_at(start_address)
        #apparently this isn't important anymore?
        needs_to_begin_with_0 = True
        #start with zero please
        byte_count = 0 
        #where we store all output
        output = ""
        had_text_end_byte = False
        had_text_end_byte_57_58 = False
        had_db_last = False
        #reset this pretty fast..
        first_line = True
        #for each command..
        for this_command in commands.keys():
            if not "lines" in commands[this_command].keys():
                command = commands[this_command]
                if not "type" in command.keys():
                    print "ERROR in command: " + str(command)
                    continue #dunno what to do here?
    
                if   command["type"] == 0x1: #TX_RAM
                    if first_line:
                        output = "\n"
                        output += label + ": ; " + hex(start_address)
                        first_line = False
                    p1 = command["pointer"][0]
                    p2 = command["pointer"][1]
    
                    #remember to account for big endian -> little endian
                    output += "\n" + spacing + "TX_RAM $%.2x%.2x" %(p2, p1)
                    byte_count += 3
                    had_db_last = False
                elif command["type"] == 0x17: #TX_FAR
                    if first_line:
                        output = "\n"
                        output += label + ": ; " + hex(start_address)
                        first_line = False
                    #p1 = command["pointer"][0]
                    #p2 = command["pointer"][1]
                    output += "\n" + spacing + "TX_FAR _" + label + " ; " + hex(command["pointer"])
                    byte_count += 4 #$17, bank, address word
                    had_db_last = False
                elif command["type"] == 0x9: #TX_RAM_HEX2DEC
                    if first_line:
                        output = "\n" + label + ": ; " + hex(start_address)
                        first_line = False
                    #address, read_byte
                    output += "\n" + spacing + "TX_NUM $%.2x%.2x, $%.2x" % (command["address"][1], command["address"][0], command["read_byte"])
                    had_db_last = False
                    byte_count += 4
                elif command["type"] == 0x50 and not had_text_end_byte:
                    #had_text_end_byte helps us avoid repeating $50s
                    if first_line:
                        output = "\n" + label + ": ; " + hex(start_address)
                        first_line = False
                    if had_db_last:
                        output += ", $50"
                    else:
                        output += "\n" + spacing + "db $50"
                    byte_count += 1
                    had_db_last = True
                elif command["type"] in [0x57, 0x58] and not had_text_end_byte_57_58:
                    if first_line: #shouldn't happen, really
                        output = "\n" + label + ": ; " + hex(start_address)
                        first_line = False
                    if had_db_last:
                        output += ", $%.2x" % (command["type"])
                    else:
                        output += "\n" + spacing + "db $%.2x" % (command["type"])
                    byte_count += 1
                    had_db_last = True
                elif command["type"] in [0x57, 0x58] and had_text_end_byte_57_58:
                    pass #this is ok
                elif command["type"] == 0x50 and had_text_end_byte:
                    pass #this is also ok
                elif command["type"] == 0x0b:
                    if first_line:
                        output = "\n" + label + ": ; " + hex(start_address)
                        first_line = False
                    if had_db_last:
                        output += ", $0b"
                    else:
                        output += "\n" + spacing + "db $0B"
                    byte_count += 1
                    had_db_last = True
                elif command["type"] == 0x11:
                    if first_line:
                        output = "\n" + label + ": ; " + hex(start_address)
                        first_line = False
                    if had_db_last:
                        output += ", $11"
                    else:
                        output += "\n" + spacing + "db $11"
                    byte_count += 1
                    had_db_last = True
                elif command["type"] == 0x6: #wait for keypress
                    if first_line:
                        output = "\n" + label + ": ; " + hex(start_address)
                        first_line = False
                    if had_db_last:
                        output += ", $6"
                    else:
                        output += "\n" + spacing + "db $6"
                    byte_count += 1
                    had_db_last = True
                else:
                    print "ERROR in command: " + hex(command["type"])
                    had_db_last = False
    
                #everything else is for $0s, really
                continue
            lines = commands[this_command]["lines"]
    
            #reset this in case we have non-$0s later
            had_db_last = False
    
            #add the ending byte to the last line- always seems $57
            #this should already be in there, but it's not because of a bug in the text parser
            lines[len(lines.keys())-1].append(commands[len(commands.keys())-1]["type"])
    
            if first_line:
                output  = "\n"
                output += label + ": ; " + hex(start_address) + "\n"
                first_line = False
            else:
                output += "\n"
    
            first = True #first byte
            for line_id in lines:
                line = lines[line_id]
                output += spacing + "db "
                if first and needs_to_begin_with_0:
                    output += "$0, "
                    first = False
                    byte_count += 1
    
                quotes_open = False
                first_byte = True
                was_byte = False
                for byte in line:
                    if byte == 0x50:
                        had_text_end_byte = True #don't repeat it
                    if byte in [0x58, 0x57]:
                        had_text_end_byte_57_58 = True
    
                    if byte in txt_bytes:
                        if not quotes_open and not first_byte: #start text
                            output += ", \""
                            quotes_open = True
                            first_byte = False
                        if not quotes_open and first_byte: #start text
                            output += "\""
                            quotes_open = True
                        output += txt_bytes[byte]
                    elif byte in constant_abbreviation_bytes:
                        if quotes_open:
                            output += "\""
                            quotes_open = False
                        if not first_byte:
                            output += ", "
                        output += constant_abbreviation_bytes[byte]
                    else:
                        if quotes_open:
                            output += "\""
                            quotes_open = False
    
                        #if you want the ending byte on the last line
                        #if not (byte == 0x57 or byte == 0x50 or byte == 0x58):
                        if not first_byte:
                            output += ", "
    
                        output += "$" + hex(byte)[2:]
                        was_byte = True
    
                        #add a comma unless it's the end of the line
                        #if byte_count+1 != len(line):
                        #    output += ", "
    
                    first_byte = False
                    byte_count += 1
                #close final quotes
                if quotes_open:
                    output += "\""
                    quotes_open = False
    
                output += "\n"
        include_newline = "\n"
        if len(output)!=0 and output[-1] == "\n":
            include_newline = ""
        output += include_newline + "; " + hex(start_address) + " + " + str(byte_count) + " bytes = " + hex(start_address + byte_count)
        print output
        return (output, byte_count)

def parse_text_engine_script_at(address, map_group=None, map_id=None, debug=True, show=True):
    """parses a text-engine script ("in-text scripts")
    http://hax.iimarck.us/files/scriptingcodes_eng.htm#InText
    see parse_text_at2, parse_text_at, and process_00_subcommands
    """
    return TextScript.parse_text_at(address, map_group=map_group, map_id=map_id, debug=debug, show=show)
def find_text_addresses():
    """returns a list of text pointers
    useful for testing parse_text_engine_script_at"""
    return TextScript.find_addresses()

class EncodedText():
    """a sequence of bytes that, when decoded, represent readable text
    based on the chars table from textpre.py and other places"""
    def to_asm(self): raise NotImplementedError, bryan_message
    @staticmethod
    def process_00_subcommands(start_address, end_address, debug=True):
        """split this text up into multiple lines
        based on subcommands ending each line"""
        if debug:
            print "process_00_subcommands(" + hex(start_address) + ", " + hex(end_address) + ")"
        lines = {}
        subsection = rom[start_address:end_address]
    
        line_count = 0
        current_line = []
        for pbyte in subsection:
            byte = ord(pbyte)
            current_line.append(byte)
            if  byte == 0x4f or byte == 0x51 or byte == 0x55:
                lines[line_count] = current_line
                current_line = []
                line_count += 1
    
        #don't forget the last line
        lines[line_count] = current_line
        line_count += 1
        return lines
    @staticmethod
    def from_bytes(bytes, debug=True):
        """assembles a string based on bytes looked up in the chars table"""
        line = ""
        for byte in bytes:
            if type(byte) != int:
                byte = ord(byte)
            if byte in chars.keys():
                line += chars[byte]
            elif debug:
                print "byte not known: " + hex(byte)
        return line
    @staticmethod
    def parse_text_at(address, count=10, debug=True):
        """returns a string of text from an address
        this does not handle text commands"""
        output = ""
        commands = process_00_subcommands(address, address+count, debug=debug)
        for (line_id, line) in commands.items():
            output += parse_text_from_bytes(line, debug=debug)
            output += "\n"
        texts.append([address, output])
        return output
def process_00_subcommands(start_address, end_address, debug=True):
    """split this text up into multiple lines
    based on subcommands ending each line"""
    return EncodedText.process_00_subcommands(start_address, end_address, debug=debug)
def parse_text_from_bytes(bytes, debug=True):
    """assembles a string based on bytes looked up in the chars table"""
    return EncodedText.from_bytes(bytes, debug=debug)
def parse_text_at(address, count=10, debug=True):
    """returns a list of bytes from an address
    see parse_text_at2 for pretty printing"""
    return parse_text_from_bytes(rom_interval(address, count, strings=False), debug=debug)
def parse_text_at2(address, count=10, debug=True):
    """returns a string of text from an address
    this does not handle text commands"""
    return EncodedText.parse_text_at(address, count, debug=debug)

def rom_text_at(address, count=10):
    """prints out raw text from the ROM
    like for 0x112110"""
    return "".join([chr(x) for x in rom_interval(address, count, strings=False)])

def get_map_constant_label(map_group=None, map_id=None):
    """returns PALLET_TOWN for some map group/id pair"""
    if map_group == None: raise Exception, "need map_group"
    if map_id == None: raise Exception, "need map_id"
    global map_internal_ids
    for (id, each) in map_internal_ids.items():
        if each["map_group"] == map_group and each["map_id"] == map_id:
            return each["label"]
    return None
def get_map_constant_label_by_id(global_id):
    """returns a map constant label for a particular map id"""
    global map_internal_ids
    return map_internal_ids[global_id]["label"]
def get_id_for_map_constant_label(label):
    """returns some global id for a given map constant label
    PALLET_TOWN = 1, for instance."""
    global map_internal_ids
    for (id, each) in map_internal_ids.items():
        if each["label"] == label: return id
    return None
def generate_map_constant_labels():
    """generates the global for this script
    mapping ids to map groups/ids/labels"""
    global map_internal_ids
    map_internal_ids = {}
    i = 0
    for map_group in map_names.keys():
        for map_id in map_names[map_group].keys():
            if map_id == "offset": continue
            cmap = map_names[map_group][map_id]
            name = cmap["name"]
            name = name.replace("Pokémon Center", "PokeCenter").\
                        replace(" ", "_")
            constant_label = map_name_cleaner(name).upper()
            map_internal_ids[i] = {"label": constant_label,
                                   "map_id": map_id,
                                   "map_group": map_group}
            i += 1
    return map_internal_ids
#see generate_map_constant_labels() later
def generate_map_constants():
    """generates content for constants.asm
    this will generate two macros: GROUP and MAP"""
    global map_internal_ids
    if map_internal_ids == None or map_internal_ids == {}:
        generate_map_constant_labels()
    globals, groups, maps = "", "", ""
    for (id, each) in map_internal_ids.items():
        groups += "GROUP_"+each["label"] + " EQU $%.2x" % (each["map_group"])
        groups += "\n"
        maps += "MAP_"+each["label"] + " EQU $%.2x" % (each["map_id"])
        maps += "\n"
        globals +=  each["label"] + " EQU $%.2x" % (id)
        globals += "\n"
        #for multi-byte constants:
        #print each["label"] + " EQUS \"$%.2x,$%.2x\"" % (each["map_group"], each["map_id"])
    print globals
    print groups
    print maps

pokemon_constants = {
1: "BULBASAUR",
2: "IVYSAUR",
3: "VENUSAUR",
4: "CHARMANDER",
5: "CHARMELEON",
6: "CHARIZARD",
7: "SQUIRTLE",
8: "WARTORTLE",
9: "BLASTOISE",
10: "CATERPIE",
11: "METAPOD",
12: "BUTTERFREE",
13: "WEEDLE",
14: "KAKUNA",
15: "BEEDRILL",
16: "PIDGEY",
17: "PIDGEOTTO",
18: "PIDGEOT",
19: "RATTATA",
20: "RATICATE",
21: "SPEAROW",
22: "FEAROW",
23: "EKANS",
24: "ARBOK",
25: "PIKACHU",
26: "RAICHU",
27: "SANDSHREW",
28: "SANDSLASH",
29: "NIDORAN_F",
30: "NIDORINA",
31: "NIDOQUEEN",
32: "NIDORAN_M",
33: "NIDORINO",
34: "NIDOKING",
35: "CLEFAIRY",
36: "CLEFABLE",
37: "VULPIX",
38: "NINETALES",
39: "JIGGLYPUFF",
40: "WIGGLYTUFF",
41: "ZUBAT",
42: "GOLBAT",
43: "ODDISH",
44: "GLOOM",
45: "VILEPLUME",
46: "PARAS",
47: "PARASECT",
48: "VENONAT",
49: "VENOMOTH",
50: "DIGLETT",
51: "DUGTRIO",
52: "MEOWTH",
53: "PERSIAN",
54: "PSYDUCK",
55: "GOLDUCK",
56: "MANKEY",
57: "PRIMEAPE",
58: "GROWLITHE",
59: "ARCANINE",
60: "POLIWAG",
61: "POLIWHIRL",
62: "POLIWRATH",
63: "ABRA",
64: "KADABRA",
65: "ALAKAZAM",
66: "MACHOP",
67: "MACHOKE",
68: "MACHAMP",
69: "BELLSPROUT",
70: "WEEPINBELL",
71: "VICTREEBEL",
72: "TENTACOOL",
73: "TENTACRUEL",
74: "GEODUDE",
75: "GRAVELER",
76: "GOLEM",
77: "PONYTA",
78: "RAPIDASH",
79: "SLOWPOKE",
80: "SLOWBRO",
81: "MAGNEMITE",
82: "MAGNETON",
83: "FARFETCH_D",
84: "DODUO",
85: "DODRIO",
86: "SEEL",
87: "DEWGONG",
88: "GRIMER",
89: "MUK",
90: "SHELLDER",
91: "CLOYSTER",
92: "GASTLY",
93: "HAUNTER",
94: "GENGAR",
95: "ONIX",
96: "DROWZEE",
97: "HYPNO",
98: "KRABBY",
99: "KINGLER",
100: "VOLTORB",
101: "ELECTRODE",
102: "EXEGGCUTE",
103: "EXEGGUTOR",
104: "CUBONE",
105: "MAROWAK",
106: "HITMONLEE",
107: "HITMONCHAN",
108: "LICKITUNG",
109: "KOFFING",
110: "WEEZING",
111: "RHYHORN",
112: "RHYDON",
113: "CHANSEY",
114: "TANGELA",
115: "KANGASKHAN",
116: "HORSEA",
117: "SEADRA",
118: "GOLDEEN",
119: "SEAKING",
120: "STARYU",
121: "STARMIE",
122: "MR__MIME",
123: "SCYTHER",
124: "JYNX",
125: "ELECTABUZZ",
126: "MAGMAR",
127: "PINSIR",
128: "TAUROS",
129: "MAGIKARP",
130: "GYARADOS",
131: "LAPRAS",
132: "DITTO",
133: "EEVEE",
134: "VAPOREON",
135: "JOLTEON",
136: "FLAREON",
137: "PORYGON",
138: "OMANYTE",
139: "OMASTAR",
140: "KABUTO",
141: "KABUTOPS",
142: "AERODACTYL",
143: "SNORLAX",
144: "ARTICUNO",
145: "ZAPDOS",
146: "MOLTRES",
147: "DRATINI",
148: "DRAGONAIR",
149: "DRAGONITE",
150: "MEWTWO",
151: "MEW",
152: "CHIKORITA",
153: "BAYLEEF",
154: "MEGANIUM",
155: "CYNDAQUIL",
156: "QUILAVA",
157: "TYPHLOSION",
158: "TOTODILE",
159: "CROCONAW",
160: "FERALIGATR",
161: "SENTRET",
162: "FURRET",
163: "HOOTHOOT",
164: "NOCTOWL",
165: "LEDYBA",
166: "LEDIAN",
167: "SPINARAK",
168: "ARIADOS",
169: "CROBAT",
170: "CHINCHOU",
171: "LANTURN",
172: "PICHU",
173: "CLEFFA",
174: "IGGLYBUFF",
175: "TOGEPI",
176: "TOGETIC",
177: "NATU",
178: "XATU",
179: "MAREEP",
180: "FLAAFFY",
181: "AMPHAROS",
182: "BELLOSSOM",
183: "MARILL",
184: "AZUMARILL",
185: "SUDOWOODO",
186: "POLITOED",
187: "HOPPIP",
188: "SKIPLOOM",
189: "JUMPLUFF",
190: "AIPOM",
191: "SUNKERN",
192: "SUNFLORA",
193: "YANMA",
194: "WOOPER",
195: "QUAGSIRE",
196: "ESPEON",
197: "UMBREON",
198: "MURKROW",
199: "SLOWKING",
200: "MISDREAVUS",
201: "UNOWN",
202: "WOBBUFFET",
203: "GIRAFARIG",
204: "PINECO",
205: "FORRETRESS",
206: "DUNSPARCE",
207: "GLIGAR",
208: "STEELIX",
209: "SNUBBULL",
210: "GRANBULL",
211: "QWILFISH",
212: "SCIZOR",
213: "SHUCKLE",
214: "HERACROSS",
215: "SNEASEL",
216: "TEDDIURSA",
217: "URSARING",
218: "SLUGMA",
219: "MAGCARGO",
220: "SWINUB",
221: "PILOSWINE",
222: "CORSOLA",
223: "REMORAID",
224: "OCTILLERY",
225: "DELIBIRD",
226: "MANTINE",
227: "SKARMORY",
228: "HOUNDOUR",
229: "HOUNDOOM",
230: "KINGDRA",
231: "PHANPY",
232: "DONPHAN",
233: "PORYGON2",
234: "STANTLER",
235: "SMEARGLE",
236: "TYROGUE",
237: "HITMONTOP",
238: "SMOOCHUM",
239: "ELEKID",
240: "MAGBY",
241: "MILTANK",
242: "BLISSEY",
243: "RAIKOU",
244: "ENTEI",
245: "SUICUNE",
246: "LARVITAR",
247: "PUPITAR",
248: "TYRANITAR",
249: "LUGIA",
250: "HO_OH",
251: "CELEBI",
}
def get_pokemon_constant_by_id(id):
    return pokemon_constants[id]

item_constants = {1: 'MASTER_BALL',
2: 'ULTRA_BALL',
3: 'BRIGHTPOWDER',
4: 'GREAT_BALL',
5: 'POKE_BALL',
7: 'BICYCLE',
8: 'MOON_STONE',
9: 'ANTIDOTE',
10: 'BURN_HEAL',
11: 'ICE_HEAL',
12: 'AWAKENING',
13: 'PARLYZ_HEAL',
14: 'FULL_RESTORE',
15: 'MAX_POTION',
16: 'HYPER_POTION',
17: 'SUPER_POTION',
18: 'POTION',
19: 'ESCAPE_ROPE',
20: 'REPEL',
21: 'MAX_ELIXER',
22: 'FIRE_STONE',
23: 'THUNDERSTONE',
24: 'WATER_STONE',
26: 'HP_UP',
27: 'PROTEIN',
28: 'IRON',
29: 'CARBOS',
30: 'LUCKY_PUNCH',
31: 'CALCIUM',
32: 'RARE_CANDY',
33: 'X_ACCURACY',
34: 'LEAF_STONE',
35: 'METAL_POWDER',
36: 'NUGGET',
37: 'POKE_DOLL',
38: 'FULL_HEAL',
39: 'REVIVE',
40: 'MAX_REVIVE',
41: 'GUARD_SPEC.',
42: 'SUPER_REPEL',
43: 'MAX_REPEL',
44: 'DIRE_HIT',
46: 'FRESH_WATER',
47: 'SODA_POP',
48: 'LEMONADE',
49: 'X_ATTACK',
51: 'X_DEFEND',
52: 'X_SPEED',
53: 'X_SPECIAL',
54: 'COIN_CASE',
55: 'ITEMFINDER',
57: 'EXP_SHARE',
58: 'OLD_ROD',
59: 'GOOD_ROD',
60: 'SILVER_LEAF',
61: 'SUPER_ROD',
62: 'PP_UP',
63: 'ETHER',
64: 'MAX_ETHER',
65: 'ELIXER',
66: 'RED_SCALE',
67: 'SECRETPOTION',
68: 'S.S.TICKET',
69: 'MYSTERY_EGG',
70: 'CLEAR_BELL',
71: 'SILVER_WING',
72: 'MOOMOO_MILK',
73: 'QUICK_CLAW',
74: 'PSNCUREBERRY',
75: 'GOLD_LEAF',
76: 'SOFT_SAND',
77: 'SHARP_BEAK',
78: 'PRZCUREBERRY',
79: 'BURNT_BERRY',
80: 'ICE_BERRY',
81: 'POISON_BARB',
82: "KING'S_ROCK",
83: 'BITTER_BERRY',
84: 'MINT_BERRY',
85: 'RED_APRICORN',
86: 'TINYMUSHROOM',
87: 'BIG_MUSHROOM',
88: 'SILVERPOWDER',
89: 'BLU_APRICORN',
91: 'AMULET_COIN',
92: 'YLW_APRICORN',
93: 'GRN_APRICORN',
94: 'CLEANSE_TAG',
95: 'MYSTIC_WATER',
96: 'TWISTEDSPOON',
97: 'WHT_APRICORN',
98: 'BLACKBELT',
99: 'BLK_APRICORN',
101: 'PNK_APRICORN',
102: 'BLACKGLASSES',
103: 'SLOWPOKETAIL',
104: 'PINK_BOW',
105: 'STICK',
106: 'SMOKE_BALL',
107: 'NEVERMELTICE',
108: 'MAGNET',
109: 'MIRACLEBERRY',
110: 'PEARL',
111: 'BIG_PEARL',
112: 'EVERSTONE',
113: 'SPELL_TAG',
114: 'RAGECANDYBAR',
115: 'GS_BALL',
116: 'BLUE_CARD',
117: 'MIRACLE_SEED',
118: 'THICK_CLUB',
119: 'FOCUS_BAND',
121: 'ENERGYPOWDER',
122: 'ENERGY_ROOT',
123: 'HEAL_POWDER',
124: 'REVIVAL_HERB',
125: 'HARD_STONE',
126: 'LUCKY_EGG',
127: 'CARD_KEY',
128: 'MACHINE_PART',
129: 'EGG_TICKET',
130: 'LOST_ITEM',
131: 'STARDUST',
132: 'STAR_PIECE',
133: 'BASEMENT_KEY',
134: 'PASS',
138: 'CHARCOAL',
139: 'BERRY_JUICE',
140: 'SCOPE_LENS',
143: 'METAL_COAT',
144: 'DRAGON_FANG',
146: 'LEFTOVERS',
150: 'MYSTERYBERRY',
151: 'DRAGON_SCALE',
152: 'BERSERK_GENE',
156: 'SACRED_ASH',
157: 'HEAVY_BALL',
158: 'FLOWER_MAIL',
159: 'LEVEL_BALL',
160: 'LURE_BALL',
161: 'FAST_BALL',
163: 'LIGHT_BALL',
164: 'FRIEND_BALL',
165: 'MOON_BALL',
166: 'LOVE_BALL',
167: 'NORMAL_BOX',
168: 'GORGEOUS_BOX',
169: 'SUN_STONE',
170: 'POLKADOT_BOW',
172: 'UP_GRADE',
173: 'BERRY',
174: 'GOLD_BERRY',
175: 'SQUIRTBOTTLE',
177: 'PARK_BALL',
178: 'RAINBOW_WING',
180: 'BRICK_PIECE',
181: 'SURF_MAIL',
182: 'LITEBLUEMAIL',
183: 'PORTRAITM_AIL',
184: 'LOVELY_MAIL',
185: 'EON_MAIL',
186: 'MORPH_MAIL',
187: 'BLUESKY_MAIL',
188: 'MUSIC_MAIL',
189: 'MIRAGE_MAIL',
191: 'TM_01',
192: 'TM_02',
193: 'TM_03',
194: 'TM_04',
196: 'TM_05',
197: 'TM_06',
198: 'TM_07',
199: 'TM_08',
200: 'TM_09',
201: 'TM_10',
202: 'TM_11',
203: 'TM_12',
204: 'TM_13',
205: 'TM_14',
206: 'TM_15',
207: 'TM_16',
208: 'TM_17',
209: 'TM_18',
210: 'TM_19',
211: 'TM_20',
212: 'TM_21',
213: 'TM_22',
214: 'TM_23',
215: 'TM_24',
216: 'TM_25',
217: 'TM_26',
218: 'TM_27',
219: 'TM_28',
221: 'TM_29',
222: 'TM_30',
223: 'TM_31',
224: 'TM_32',
225: 'TM_33',
226: 'TM_34',
227: 'TM_35',
228: 'TM_36',
229: 'TM_37',
230: 'TM_38',
231: 'TM_39',
232: 'TM_40',
233: 'TM_41',
234: 'TM_42',
235: 'TM_43',
236: 'TM_44',
237: 'TM_45',
238: 'TM_46',
239: 'TM_47',
240: 'TM_48',
241: 'TM_49',
242: 'TM_50',
243: 'HM_01',
244: 'HM_02',
245: 'HM_03',
246: 'HM_04',
247: 'HM_05',
248: 'HM_06',
249: 'HM_07'}
def find_item_label_by_id(id):
    if id in item_constants.keys():
        return item_constants[id]   
    else: return None
def generate_item_constants():
    """make a list of items to put in constants.asm"""
    output = ""
    for (id, item) in item_constants.items():
        val = ("$%.2x"%id).upper()
        while len(item)<13: item+= " "
        output += item + " EQU " + val
    return output

def find_all_text_pointers_in_script_engine_script(script, bank=None, debug=False):
    """returns a list of text pointers
    based on each script-engine script command"""
    #TODO: recursively follow any jumps in the script
    if script == None: return []
    addresses = set()
    for (k, command) in script.commands.items():
        if debug:
            print "command is: " + str(command)
        if   command["type"] == 0x4B:
            addresses.add(command["pointer"])
        elif command["type"] == 0x4C:
            addresses.add(command["pointer"])
        elif command["type"] == 0x51:
            addresses.add(command["pointer"])
        elif command["type"] == 0x53:
            addresses.add(command["pointer"])
        elif command["type"] == 0x64:
            addresses.add(command["won_pointer"])
            addresses.add(command["lost_pointer"])
    return addresses

def translate_command_byte(crystal=None, gold=None):
    """takes a command byte from either crystal or gold
    returns the command byte in the other (non-given) game

    The new commands are values 0x52 and 0x9F. This means:
        Crystal's 0x00–0x51 correspond to Gold's 0x00–0x51
        Crystal's 0x53–0x9E correspond to Gold's 0x52–0x9D
        Crystal's 0xA0–0xA5 correspond to Gold's 0x9E–0xA3

    see: http://www.pokecommunity.com/showpost.php?p=4347261
    """
    if crystal != None: #convert to gold
        if crystal <= 0x51: return crystal
        if crystal == 0x52: return None
        if 0x53 <= crystal <= 0x9E: return crystal-1
        if crystal == 0x9F: return None
        if 0xA0 <= crystal <= 0xA5: return crystal-2
        if crystal > 0xA5: raise Exception, "dunno yet if crystal has new insertions after crystal:0xA5 (gold:0xA3)"
    elif gold != None: #convert to crystal
        if gold <= 0x51: return gold
        if 0x52 <= gold <= 0x9D: return gold+1
        if 0x9E <= gold <= 0xA3: return gold+2
        if gold > 0xA3: raise Exception, "dunno yet if crystal has new insertions after gold:0xA3 (crystal:0xA5)"
    else: raise Exception, "translate_command_byte needs either a crystal or gold command"

pksv_gs = {
    0x00: "2call",
    0x01: "3call",
    0x02: "2ptcall",
    0x03: "2jump",
    0x04: "3jump",
    0x05: "2ptjump",
    0x06: "if equal",
    0x07: "if not equal",
    0x08: "if false",
    0x09: "if true",
    0x0A: "if less than",
    0x0B: "if greater than",
    0x0C: "jumpstd",
    0x0D: "callstd",
    0x0E: "3callasm",
    0x0F: "special",
    0x10: "2ptcallasm",
    0x11: "checkmaptriggers",
    0x12: "domaptrigger",
    0x13: "checktriggers",
    0x14: "dotrigger",
    0x15: "writebyte",
    0x16: "addvar",
    0x17: "random",
    0x19: "copybytetovar",
    0x1A: "copyvartobyte",
    0x1B: "loadvar",
    0x1C: "checkcode",
    0x1E: "writecode",
    0x1F: "giveitem",
    0x20: "takeitem",
    0x21: "checkitem",
    0x22: "givemoney",
    0x23: "takemoney",
    0x24: "checkmonkey",
    0x25: "givecoins",
    0x26: "takecoins",
    0x27: "checkcoins",
    0x2B: "checktime",
    0x2C: "checkpoke",
    0x2D: "givepoke",
    0x2E: "giveegg",
    0x2F: "givepokeitem",
    0x31: "checkbit1",
    0x32: "clearbit1",
    0x33: "setbit1",
    0x34: "checkbit2",
    0x35: "clearbit2",
    0x36: "setbit2",
    0x37: "wildoff",
    0x38: "wildon",
    0x39: "xycompare",
    0x3A: "warpmod",
    0x3B: "blackoutmod",
    0x3C: "warp",
    0x41: "itemtotext",
    0x43: "trainertotext",
    0x44: "stringtotext",
    0x45: "itemnotify",
    0x46: "pocketisfull",
    0x47: "loadfont",
    0x48: "refreshscreen",
    0x49: "loadmovesprites",
    0x4B: "3writetext",
    0x4C: "2writetext",
    0x4E: "yesorno",
    0x4F: "loadmenudata",
    0x50: "writebackup",
    0x51: "jumptextfaceplayer",
    0x52: "jumptext",
    0x53: "closetext",
    0x54: "keeptextopen",
    0x55: "pokepic",
    0x56: "pokepicyesorno",
    0x57: "interpretmenu",
    0x58: "interpretmenu2",
    0x5C: "loadpokedata",
    0x5D: "loadtrainer",
    0x5E: "startbattle",
    0x5F: "returnafterbattle",
    0x60: "catchtutorial",
    0x63: "winlosstext",
    0x65: "talkaftercancel",
    0x67: "setlasttalked",
    0x68: "applymovement",
    0x6A: "faceplayer",
    0x6B: "faceperson",
    0x6C: "variablesprite",
    0x6D: "disappear",
    0x6E: "appear",
    0x6F: "follow",
    0x70: "stopfollow",
    0x71: "moveperson",
    0x74: "showemote",
    0x75: "spriteface",
    0x76: "follownotexact",
    0x77: "earthquake",
    0x79: "changeblock",
    0x7A: "reloadmap",
    0x7B: "reloadmappart",
    0x7C: "writecmdqueue",
    0x7D: "delcmdqueue",
    0x7E: "playmusic",
    0x7F: "playrammusic",
    0x80: "musicfadeout",
    0x81: "playmapmusic",
    0x82: "reloadmapmusic",
    0x83: "cry",
    0x84: "playsound",
    0x85: "waitbutton",
    0x86: "warpsound",
    0x87: "specialsound",
    0x88: "passtoengine",
    0x89: "newloadmap",
    0x8A: "pause",
    0x8B: "deactivatefacing",
    0x8C: "priorityjump",
    0x8D: "warpcheck",
    0x8E: "ptpriorityjump",
    0x8F: "return",
    0x90: "end",
    0x91: "reloadandreturn",
    0x92: "resetfuncs",
    0x93: "pokemart",
    0x94: "elevator",
    0x95: "trade",
    0x96: "askforphonenumber",
    0x97: "phonecall",
    0x98: "hangup",
    0x99: "describedecoration",
    0x9A: "fruittree",
    0x9C: "checkphonecall",
    0x9D: "verbosegiveitem",
    0x9E: "loadwilddata",
    0x9F: "halloffame",
    0xA0: "credits",
    0xA1: "warpfacing",
    0xA2: "storetext",
    0xA3: "displaylocation",
}

#see http://www.pokecommunity.com/showpost.php?p=4347261
#NOTE: this has some updates that need to be back-ported to gold
pksv_crystal = {
    0x00: "2call",
    0x01: "3call",
    0x02: "2ptcall",
    0x03: "2jump",
    0x04: "3jump",
    0x05: "2ptjump",
    0x06: "if equal",
    0x07: "if not equal",
    0x08: "if false",
    0x09: "if true",
    0x0A: "if less than",
    0x0B: "if greater than",
    0x0C: "jumpstd",
    0x0D: "callstd",
    0x0E: "3callasm",
    0x0F: "special",
    0x10: "2ptcallasm",
    0x11: "checkmaptriggers",
    0x12: "domaptrigger",
    0x13: "checktriggers",
    0x14: "dotrigger",
    0x15: "writebyte",
    0x16: "addvar",
    0x17: "random",
    0x19: "copybytetovar",
    0x1A: "copyvartobyte",
    0x1B: "loadvar",
    0x1C: "checkcode",
    0x1E: "writecode",
    0x1F: "giveitem",
    0x20: "takeitem",
    0x21: "checkitem",
    0x22: "givemoney",
    0x23: "takemoney",
    0x24: "checkmonkey",
    0x25: "givecoins",
    0x26: "takecoins",
    0x27: "checkcoins",
    0x2B: "checktime",
    0x2C: "checkpoke",
    0x2D: "givepoke",
    0x2E: "giveegg",
    0x2F: "givepokeitem",
    0x31: "checkbit1",
    0x32: "clearbit1",
    0x33: "setbit1",
    0x34: "checkbit2",
    0x35: "clearbit2",
    0x36: "setbit2",
    0x37: "wildoff",
    0x38: "wildon",
    0x39: "xycompare",
    0x3A: "warpmod",
    0x3B: "blackoutmod",
    0x3C: "warp",
    0x41: "itemtotext",
    0x43: "trainertotext",
    0x44: "stringtotext",
    0x45: "itemnotify",
    0x46: "pocketisfull",
    0x47: "loadfont",
    0x48: "refreshscreen",
    0x49: "loadmovesprites",
    0x4B: "3writetext",
    0x4C: "2writetext",
    0x4E: "yesorno",
    0x4F: "loadmenudata",
    0x50: "writebackup",
    0x51: "jumptextfaceplayer",
    0x53: "jumptext",
    0x54: "closetext",
    0x55: "keeptextopen",
    0x56: "pokepic",
    0x57: "pokepicyesorno",
    0x58: "interpretmenu",
    0x59: "interpretmenu2",
    0x5D: "loadpokedata",
    0x5E: "loadtrainer",
    0x5F: "startbattle",
    0x60: "returnafterbattle",
    0x61: "catchtutorial",
    0x64: "winlosstext",
    0x66: "talkaftercancel",
    0x68: "setlasttalked",
    0x69: "applymovement",
    0x6B: "faceplayer",
    0x6C: "faceperson",
    0x6D: "variablesprite",
    0x6E: "disappear",
    0x6F: "appear",
    0x70: "follow",
    0x71: "stopfollow",
    0x72: "moveperson",
    0x75: "showemote",
    0x76: "spriteface",
    0x77: "follownotexact",
    0x78: "earthquake",
    0x7A: "changeblock",
    0x7B: "reloadmap",
    0x7C: "reloadmappart",
    0x7D: "writecmdqueue",
    0x7E: "delcmdqueue",
    0x7F: "playmusic",
    0x80: "playrammusic",
    0x81: "musicfadeout",
    0x82: "playmapmusic",
    0x83: "reloadmapmusic",
    0x84: "cry",
    0x85: "playsound",
    0x86: "waitbutton",
    0x87: "warpsound",
    0x88: "specialsound",
    0x89: "passtoengine",
    0x8A: "newloadmap",
    0x8B: "pause",
    0x8C: "deactivatefacing",
    0x8D: "priorityjump",
    0x8E: "warpcheck",
    0x8F: "ptpriorityjump",
    0x90: "return",
    0x91: "end",
    0x92: "reloadandreturn",
    0x93: "resetfuncs",
    0x94: "pokemart",
    0x95: "elevator",
    0x96: "trade",
    0x97: "askforphonenumber",
    0x98: "phonecall",
    0x99: "hangup",
    0x9A: "describedecoration",
    0x9B: "fruittree",
    0x9C: "specialphonecall",
    0x9D: "checkphonecall",
    0x9E: "verbosegiveitem",
    0xA0: "loadwilddata",
    0xA1: "halloffame",
    0xA2: "credits",
    0xA3: "warpfacing",
    0xA4: "storetext",
    0xA5: "displaylocation",
}

#these have no pksv names as of pksv 2.1.1
pksv_crystal_unknowns = [
    0x9F,
    0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF,
    0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8,
    0xCC, 0xCD,
    0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 
    0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF,
    0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8,
    0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF,
]

class SingleByteParam():
    """or SingleByte(CommandParam)"""
    size = 1
    should_be_decimal = False
    def __init__(self, *args, **kwargs):
        for (key, value) in kwargs.items():
            setattr(self, key, value)
        #check address
        if not hasattr(self, "address"):
            raise Exception, "an address is a requirement"
        elif self.address == None:
            raise Exception, "address must not be None"
        elif not is_valid_address(self.address):
            raise Exception, "address must be valid"
        #check size
        if not hasattr(self, "size") or self.size == None:
            raise Exception, "size is probably 1?"
        #parse bytes from ROM
        self.parse()
    def parse(self): self.byte = ord(rom[self.address])
    def to_asm(self):
        if not self.should_be_decimal: return hex(self.byte).replace("0x", "$")
        else: return str(self.byte)
class HexByte(SingleByteParam):
    def to_asm(self): return hex(self.byte)
class DollarSignByte(SingleByteParam):
    #def to_asm(self): return "$%.2x"%self.byte
    def to_asm(self): return hex(self.byte).replace("0x", "$")
class ItemLabelByte(DollarSignByte):
    def to_asm(self):
        label = find_item_label_by_id(self.byte)
        if label: return label
        elif not label: return DollarSignByte.to_asm(self)
class DecimalParam(SingleByteParam):
    should_be_decimal = True

class MultiByteParam():
    """or MultiByte(CommandParam)"""
    size = 2
    should_be_decimal = False
    def __init__(self, *args, **kwargs):
        self.prefix = "$" #default.. feel free to set 0x in kwargs
        for (key, value) in kwargs.items():
            setattr(self, key, value)
        #check address
        if not hasattr(self, "address") or self.address == None:
            raise Exception, "an address is a requirement"
        elif not is_valid_address(self.address):
            raise Exception, "address must be valid"
        #check size
        if not hasattr(self, "size") or self.size == None:
            raise Exception, "don't know how many bytes to read (size)"
        self.parse()
    def parse(self): self.bytes = rom_interval(self.address, self.size, strings=False)
    #you won't actually use this to_asm because it's too generic
    #def to_asm(self): return ", ".join([(self.prefix+"%.2x")%x for x in self.bytes])
    def to_asm(self):
        if not self.should_be_decimal:
            return self.prefix+"".join([("%.2x")%x for x in reversed(self.bytes)])
        elif self.should_be_decimal:
            decimal = int("0x"+"".join([("%.2x")%x for x in reversed(self.bytes)]), 16)
            return str(decimal)
class PointerLabelParam(MultiByteParam):
    #default size is 2 bytes
    default_size = 2
    size = 2
    #default is to not parse out a bank
    bank = False
    def __init__(self, *args, **kwargs):
        #bank can be overriden
        if "bank" in kwargs.keys():
            if kwargs["bank"] != False and kwargs["bank"] != None:
                #not +=1 because child classes set size=3 already
                self.size = self.default_size + 1
            if kwargs["bank"] not in [None, False, True, "reverse"]:
                raise Exception, "bank cannot be: " + str(bank)
        if self.size > 3:
            raise Exception, "param size is too large"
        #continue instantiation.. self.bank will be set down the road
        MultiByteParam.__init__(self, *args, **kwargs)
    def to_asm(self):
        bank = self.bank
        #we pass bank= for whether or not to include a bank byte when reading
        #.. it's not related to caddress
        caddress = calculate_pointer_from_bytes_at(self.address, bank=self.bank)
        label = get_label_for(caddress)
        pointer_part = label #use the label, if it is found
        #setup output bytes if the label was not found
        if not label:
            #pointer_part = (", ".join([(self.prefix+"%.2x")%x for x in reversed(self.bytes[1:])]))
            pointer_part = self.prefix+("%.2x"%self.bytes[1])+("%.2x"%self.bytes[0])
        #bank positioning matters!
        if bank == True or bank == "reverse": #bank, pointer
            #possibly use BANK(LABEL) if we know the bank
            if not label:
                bank_part = ((self.prefix+"%.2x")%bank)
            else:
                bank_part = "BANK("+label+")"
            #return the asm based on the order the bytes were specified to be in
            if bank == "reverse": #pointer, bank
                return pointer_part+", "+bank_part
            elif bank == True: #bank, pointer
                return bank_part+", "+pointer_part
            else: raise Exception, "this should never happen"
            raise Exception, "this should never happen"
        #this next one will either return the label or the raw bytes
        elif bank == False or bank == None: #pointer
            return pointer_part #this could be the same as label
        else:
            raise Exception, "this should never happen"
        raise Exception, "this should never happen"
class PointerLabelBeforeBank(PointerLabelParam):
    bank = True #bank appears first, see calculate_pointer_from_bytes_at
    size = 3
class PointerLabelAfterBank(PointerLabelParam):
    bank = "reverse" #bank appears last, see calculate_pointer_from_bytes_at
    size = 3
class ScriptPointerLabelParam(PointerLabelParam): pass
class ScriptPointerLabelBeforeBank(PointerLabelBeforeBank): pass
class ScriptPointerLabelAfterBank(PointerLabelAfterBank): pass
def _parse_script_pointer_bytes(self):
    PointerLabelParam.parse(self)
    address = calculate_pointer_from_bytes_at(self.address, bank=self.bank)
    self.script = parse_script_engine_script_at(address)
ScriptPointerLabelParam.parse = _parse_script_pointer_bytes
ScriptPointerLabelBeforeBank.parse = _parse_script_pointer_bytes
ScriptPointerLabelAfterBank.parse = _parse_script_pointer_bytes
class PointerLabelToScriptPointer(PointerLabelParam):
    def parse(self):
        PointerLabelParam.parse(self)
        address = calculate_pointer_from_bytes_at(self.address, bank=self.bank)
        address2 = calculate_pointer_from_bytes_at(address, bank="reverse") #maybe not "reverse"?
        self.script = parse_script_engine_script_at(address2, origin=False)
class AsmPointerParam(PointerLabelBeforeBank):
    def parse(self):
        PointerLabelBeforeBank.parse(self)
        address = calculate_pointer_from_bytes_at(self.address, bank=self.bank) #3-byte pointer
        self.asm = parse_script_asm_at(address) #might end in some specific way?
class PointerToAsmPointerParam(PointerLabelParam):
    def parse(self):
        PointerLabelParam.parse(self)
        address = calculate_pointer_from_bytes_at(self.address, bank=self.bank) #2-byte pointer
        address2 = calculate_pointer_from_bytes_at(address, bank="reverse") #maybe not "reverse"?
        self.asm = parse_script_asm_at(address) #might end in some specific way?
class RAMAddressParam(MultiByteParam):
    def to_asm(self):
        address = calculate_pointer_from_bytes_at(self.address, bank=False)
        label = get_ram_label(address)
        if label: return "["+label+"]"
        else: return "[$"+"".join(["%.2x"%x for x in self.bytes])+"]"
class MoneyByteParam(MultiByteParam):
    size = 3
    max_value = 0x0F423F
    should_be_decimal = True
class CoinByteParam(MultiByteParam):
    size = 2
    max_value = 0x270F
    should_be_decimal = True
class MapGroupParam(SingleByteParam):
    def to_asm(self):
        map_id = ord(rom[self.address+1])
        map_constant_label = get_map_constant_label(map_id=map_id, map_group=self.byte) #like PALLET_TOWN
        if map_constant_label == None: return str(self.byte)
        #else: return "GROUP("+map_constant_label+")"
        else: return "GROUP_"+map_constant_label
class MapIdParam(SingleByteParam):
    def parse(self):
        SingleByteParam.parse(self)
        self.map_group = ord(rom[self.address-1])
    def to_asm(self):
        map_group = ord(rom[self.address-1])
        map_constant_label = get_map_constant_label(map_id=self.byte, map_group=map_group)
        if map_constant_label == None: return str(self.byte)
        #else: return "MAP("+map_constant_label+")"
        else: return "MAP_"+map_constant_label
class MapGroupIdParam(MultiByteParam):
    def parse(self):
        MultiByteParam.parse(self)
        self.map_group = self.bytes[0]
        self.map_id = self.bytes[1]
    def to_asm(self):
        map_group = self.map_group
        map_id = self.map_id
        label = get_map_constant_label(map_group=map_group, map_id=map_id)
        return label
class PokemonParam(SingleByteParam):
    def to_asm(self):
        pokemon_constant = get_pokemon_constant_by_id(self.byte)
        if pokemon_constant: return pokemon_constant
        else: return str(self.byte)
class PointerParamToItemAndLetter(MultiByteParam):
    #[2F][2byte pointer to item no + 0x20 bytes letter text]
    #raise NotImplementedError, bryan_message
    pass
class TrainerIdParam(SingleByteParam):
    #raise NotImplementedError, bryan_message
    pass
class TrainerGroupParam(SingleByteParam):
    #raise NotImplementedError, bryan_message
    pass
class MenuDataPointerParam(PointerLabelParam):
    #read menu data at the target site
    #raise NotImplementedError, bryan_message
    pass
class RawTextPointerLabelParam(PointerLabelParam):
    #is this to raw text? or to a text script?
    #raise NotImplementedError, bryan_message
    pass
class TextPointerLabelParam(PointerLabelParam):
    #definitely points to a text script
    pass
class MovementPointerLabelParam(PointerLabelParam):
    pass
class MapDataPointerParam(PointerLabelParam):
    pass

#byte: [name, [param1 name, param1 type], [param2 name, param2 type], ...]
#0x9E: ["verbosegiveitem", ["item", ItemLabelByte], ["quantity", SingleByteParam]],
pksv_crystal_more = {
    0x00: ["2call", ["pointer", ScriptPointerLabelParam]],
    0x01: ["3call", ["pointer", ScriptPointerLabelBeforeBank]],
    0x02: ["2ptcall", ["pointer", PointerLabelToScriptPointer]],
    0x03: ["2jump", ["pointer", ScriptPointerLabelParam]],
    0x04: ["3jump", ["pointer", ScriptPointerLabelBeforeBank]],
    0x05: ["2ptjump", ["pointer", PointerLabelToScriptPointer]],
    0x06: ["if equal", ["byte", SingleByteParam], ["pointer", ScriptPointerLabelParam]],
    0x07: ["if not equal", ["byte", SingleByteParam], ["pointer", ScriptPointerLabelParam]],
    0x08: ["if false", ["pointer", ScriptPointerLabelParam]],
    0x09: ["if true", ["pointer", ScriptPointerLabelParam]],
    0x0A: ["if less than", ["byte", SingleByteParam], ["pointer", ScriptPointerLabelParam]],
    0x0B: ["if greater than", ["byte", SingleByteParam], ["pointer", ScriptPointerLabelParam]],
    0x0C: ["jumpstd", ["predefined_script", MultiByteParam]],
    0x0D: ["callstd", ["predefined_script", MultiByteParam]],
    0x0E: ["3callasm", ["asm", AsmPointerParam]],
    0x0F: ["special", ["predefined_script", MultiByteParam]],
    0x10: ["2ptcallasm", ["asm", PointerToAsmPointerParam]],
    #should map_group/map_id be dealt with in some special way in the asm?
    0x11: ["checkmaptriggers", ["map_group", SingleByteParam], ["map_id", SingleByteParam]],
    0x12: ["domaptrigger", ["map_group", MapGroupParam], ["map_id", MapIdParam], ["trigger_id", SingleByteParam]],
    0x13: ["checktriggers"],
    0x14: ["dotrigger", ["trigger_id", SingleByteParam]],
    0x15: ["writebyte", ["value", SingleByteParam]],
    0x16: ["addvar", ["value", SingleByteParam]],
    0x17: ["random", ["input", SingleByteParam]],
    0x19: ["copybytetovar", ["address", RAMAddressParam]],
    0x1A: ["copyvartobyte", ["address", RAMAddressParam]],
    0x1B: ["loadvar", ["address", RAMAddressParam], ["value", SingleByteParam]],
    0x1C: ["checkcode", ["variable_id", SingleByteParam]],
    0x1E: ["writecode", ["variable_id", SingleByteParam], ["value", SingleByteParam]],
    0x1F: ["giveitem", ["item", ItemLabelByte], ["quantity", SingleByteParam]],
    0x20: ["takeitem", ["item", ItemLabelByte], ["quantity", SingleByteParam]],
    0x21: ["checkitem", ["item", ItemLabelByte]],
    0x22: ["givemoney", ["account", SingleByteParam], ["money", MoneyByteParam]],
    0x23: ["takemoney", ["account", SingleByteParam], ["money", MoneyByteParam]],
    0x24: ["checkmonkey", ["account", SingleByteParam], ["money", MoneyByteParam]],
    0x25: ["givecoins", ["coins", CoinByteParam]],
    0x26: ["takecoins", ["coins", CoinByteParam]],
    0x27: ["checkcoins", ["coins", CoinByteParam]],
    #0x28-0x2A not from pksv
    0x28: ["addcellnum", ["person", SingleByteParam]],
    0x29: ["delcellnum", ["person", SingleByteParam]],
    0x2A: ["checkcellnum", ["person", SingleByteParam]],
    #back on track...
    0x2B: ["checktime", ["time", SingleByteParam]],
    0x2C: ["checkpoke", ["pkmn", PokemonParam]],
#0x2D: ["givepoke", ], .... see GivePoke class
    0x2E: ["giveegg", ["pkmn", PokemonParam], ["level", DecimalParam]],
    0x2F: ["givepokeitem", ["pointer", PointerParamToItemAndLetter]],
    0x30: ["checkpokeitem", ["pointer", PointerParamToItemAndLetter]], #not pksv
    0x31: ["checkbit1", ["bit_number", SingleByteParam]],
    0x32: ["clearbit1", ["bit_number", SingleByteParam]],
    0x33: ["setbit1", ["bit_number", SingleByteParam]],
    0x34: ["checkbit2", ["bit_number", SingleByteParam]],
    0x35: ["clearbit2", ["bit_number", SingleByteParam]],
    0x36: ["setbit2", ["bit_number", SingleByteParam]],
    0x37: ["wildoff"],
    0x38: ["wildon"],
    0x39: ["xycompare", ["pointer", MultiByteParam]],
    0x3A: ["warpmod", ["warp_id", SingleByteParam], ["map_group", MapGroupParam], ["map_id", MapIdParam]],
    0x3B: ["blackoutmod", ["map_group", MapGroupParam], ["map_id", MapIdParam]],
    0x3C: ["warp", ["map_group", MapGroupParam], ["map_id", MapIdParam], ["x", SingleByteParam], ["y", SingleByteParam]],
    0x3D: ["readmoney", ["account", SingleByteParam], ["memory", SingleByteParam]], #not pksv
    0x3E: ["readcoins", ["memory", SingleByteParam]], #not pksv
    0x3F: ["RAM2MEM", ["memory", SingleByteParam]], #not pksv
    0x40: ["pokenamemem", ["pokemon", PokemonParam], ["memory", SingleByteParam]], #not pksv
    0x41: ["itemtotext", ["item", ItemLabelByte], ["memory", SingleByteParam]],
    0x42: ["mapnametotext", ["memory", SingleByteParam]], #not pksv
    0x43: ["trainertotext", ["trainer_id", TrainerIdParam], ["trainer_group", TrainerGroupParam], ["memory", SingleByteParam]],
    0x44: ["stringtotext", ["text_pointer", RawTextPointerLabelParam], ["memory", SingleByteParam]],
    0x45: ["itemnotify"],
    0x46: ["pocketisfull"],
    0x47: ["loadfont"],
    0x48: ["refreshscreen", ["dummy", SingleByteParam]],
    0x49: ["loadmovesprites"],
    0x4A: ["loadbytec1ce", ["byte", SingleByteParam]], #not pksv
    0x4B: ["3writetext", ["text_pointer", PointerLabelBeforeBank]],
    0x4C: ["2writetext", ["text_pointer", RawTextPointerLabelParam]], #XXX - is this to a text script, or raw text?
    0x4D: ["repeattext", ["byte", SingleByteParam], ["byte", SingleByteParam]], #not pksv
    0x4E: ["yesorno"],
    0x4F: ["loadmenudata", ["data", MenuDataPointerParam]],
    0x50: ["writebackup"],
#XXX test123
    0x51: ["jumptextfaceplayer", ["text_pointer", RawTextPointerLabelParam]],
    0x53: ["jumptext", ["text_pointer", TextPointerLabelParam]],
    0x54: ["closetext"],
    0x55: ["keeptextopen"],
    0x56: ["pokepic", ["pokemon", PokemonParam]],
    0x57: ["pokepicyesorno"],
    0x58: ["interpretmenu"],
    0x59: ["interpretmenu2"],
#not pksv
    0x5A: ["loadpikachudata"],
    0x5B: ["battlecheck"],
    0x5C: ["loadtrainerdata"],
#back to pksv..
    0x5D: ["loadpokedata", ["pokemon", PokemonParam], ["level", DecimalParam]],
    0x5E: ["loadtrainer", ["trainer_group", TrainerGroupParam], ["trainer_id", TrainerIdParam]],
    0x5F: ["startbattle"],
    0x60: ["returnafterbattle"],
    0x61: ["catchtutorial", ["byte", SingleByteParam]],
#not pksv
    0x62: ["trainertext", ["which_text", SingleByteParam]],
    0x63: ["trainerstatus", ["action", SingleByteParam]],
#back to pksv..
    0x64: ["winlosstext", ["win_text_pointer", TextPointerLabelParam], ["loss_text_pointer", TextPointerLabelParam]],
    0x65: ["scripttalkafter"], #not pksv
    0x66: ["talkaftercancel"],
    0x67: ["istalkafterscriptexecutedafterbattle"], #not pksv
    0x68: ["setlasttalked", ["person", SingleByteParam]],
    0x69: ["applymovement", ["person", SingleByteParam], ["data", MovementPointerLabelParam]],
    0x6A: ["applymovement2", ["data", MovementPointerLabelParam]], #not pksv
    0x6B: ["faceplayer"],
    0x6C: ["faceperson", ["person1", SingleByteParam], ["person2", SingleByteParam]],
    0x6D: ["variablesprite", ["byte", SingleByteParam], ["sprite", SingleByteParam]],
    0x6E: ["disappear", ["person", SingleByteParam]], #hideperson
    0x6F: ["appear", ["person", SingleByteParam]], #showperson
    0x70: ["follow", ["person2", SingleByteParam], ["person1", SingleByteParam]], 
    0x71: ["stopfollow"],
    0x72: ["moveperson", ["person", SingleByteParam], ["x", SingleByteParam], ["y", SingleByteParam]],
    0x73: ["writepersonxy", ["person", SingleByteParam]], #not pksv
    0x74: ["loademote", ["bubble", SingleByteParam]],
    0x75: ["showemote", ["bubble", SingleByteParam], ["person", SingleByteParam], ["time", SingleByteParam]],
    0x76: ["spriteface", ["person", SingleByteParam], ["facing", SingleByteParam]],
    0x77: ["follownotexact", ["person2", SingleByteParam], ["person1", SingleByteParam]],
    0x78: ["earthquake", ["param", SingleByteParam]],
    0x79: ["changemap", ["map_data_pointer", MapDataPointerParam]],
    0x7A: ["changeblock", ["x", SingleByteParam], ["y", SingleByteParam], ["block", SingleByteParam]],
    0x7B: ["reloadmap"],
    0x7C: ["reloadmappart"],
    0x7D: ["writecmdqueue", ["queue_pointer", MultiByteParam]],
    0x7E: ["delcmdqueue", ["byte", SingleByteParam]],
    0x7F: ["playmusic", ["music_pointer", MultiByteParam]],
    0x80: ["playrammusic"],
    0x81: ["musicfadeout", ["music", MultiByteParam], ["fadetime", SingleByteParam]],
    0x82: ["playmapmusic"],
    0x83: ["reloadmapmusic"],
    0x84: ["cry", ["cry_id", SingleByteParam], ["wtf", SingleByteParam]], #XXX maybe it should use PokemonParam
    0x85: ["playsound", ["sound_pointer", MultiByteParam]],
    0x86: ["waitbutton"],
    0x87: ["warpsound"],
    0x88: ["specialsound"],
    0x89: ["passtoengine", ["data_pointer", PointerLabelBeforeBank]],
    0x8A: ["newloadmap", ["which_method", SingleByteParam]],
    0x8B: ["pause", ["length", SingleByteParam]],
    0x8C: ["deactivatefacing", ["time", SingleByteParam]],
    0x8D: ["priorityjump", ["pointer", ScriptPointerLabelParam]],
    0x8E: ["warpcheck"],
    0x8F: ["ptpriorityjump", ["pointer", ScriptPointerLabelParam]],
    0x90: ["return"],
    0x91: ["end"],
    0x92: ["reloadandreturn"],
    0x93: ["resetfuncs"],
    0x94: ["pokemart", ["dialog_id", SingleByteParam], ["mart_id", SingleByteParam]],
    0x95: ["elevator", ["floor_list_pointer", PointerLabelParam]],
    0x96: ["trade", ["trade_id", SingleByteParam]],
    0x97: ["askforphonenumber", ["number", SingleByteParam]],
    0x98: ["phonecall", ["caller_name", RawTextPointerLabelParam]],
    0x99: ["hangup"],
    0x9A: ["describedecoration", ["byte", SingleByteParam]],
    0x9B: ["fruittree", ["tree_id", SingleByteParam]],
    0x9C: ["specialphonecall", ["call_id", SingleByteParam], ["wtf", SingleByteParam]],
    0x9D: ["checkphonecall"],
    0x9E: ["verbosegiveitem", ["item", ItemLabelByte], ["quantity", DecimalParam]],
    0xA0: ["loadwilddata", ["map_group", MapGroupParam], ["map_id", MapIdParam]],
    0xA1: ["halloffame"],
    0xA2: ["credits"],
    0xA3: ["warpfacing", ["facing", SingleByteParam], ["map_group", MapGroupParam], ["map_id", MapIdParam], ["x", SingleByteParam], ["y", SingleByteParam]],
    0xA4: ["storetext", ["pointer", PointerLabelBeforeBank], ["memory", SingleByteParam]],
    0xA5: ["displaylocation", ["id", SingleByteParam]],
}

class Command():
    def __init__(self, address=None, *pargs, **kwargs):
        #raise Exception, "i don't think anything actually calls this?"
        self.params = {}
        if not is_valid_address(address):
            raise Exception, "address is invalid"
        self.address = address
        self.last_address = None
        self.params = {}
        self.parse()
    def to_asm(self):
        #start with the rgbasm macro name for this command
        output = self.macro_name
        #return if there are no params
        if len(self.param_types.keys()) == 0: return output
        #first one will have no prefixing comma
        first = True
        #start reading the bytes after the command byte
        current_address = self.address+1
        #add each param
        for (key, param) in self.params.items():
            name = param.name
            #the first param shouldn't have ", " prefixed
            if first:
                output += " "
                first = False
            #but all other params should
            else: output += ", "
            #now add the asm-compatible param string
            output += param.to_asm()
            current_address += param.size
        #for param_type in self.param_types:
        #    name = param_type["name"]
        #    klass = param_type["klass"]
        #    #create an instance of this type
        #    #tell it to begin parsing at this latest byte
        #    obj = klass(address=current_address)
        #    #the first param shouldn't have ", " prefixed
        #    if first: first = False
        #    #but all other params should
        #    else: output += ", "
        #    #now add the asm-compatible param string
        #    output += obj.to_asm()
        #    current_address += obj.size
        return output
    def parse(self):
        #id, size (inclusive), param_types
        #param_type = {"name": each[1], "class": each[0]}
        current_address = self.address+1
        byte = ord(rom[self.address])
        if not byte == self.id:
            raise Exception, "byte ("+hex(byte)+") != self.id ("+hex(self.id)+")"
        i = 0
        for (key, param_type) in self.param_types.items():
            name = param_type["name"]
            klass = param_type["class"]
            #make an instance of this class, like SingleByteParam()
            #or ItemLabelByte.. by making an instance, obj.parse() is called
            obj = klass(address=current_address, name=name)
            #save this for later
            self.params[i] = obj
            #increment our counters
            current_address += obj.size
            i += 1
        self.last_address = current_address
        return True
class GivePoke(Command):
    id = 0x2D
    size = 4 #minimum
    param_types = {
                  0: {"name": "pokemon", "class": PokemonParam},
                  1: {"name": "level", "class": SingleByteParam},
                  2: {"name": "item", "class": ItemLabelByte},
                  3: {"name": "trainer", "class": SingleByteParam},
                  4: {"name": "trainer_name_pointer", "class": MultiByteParam}, #should probably use TextLabelParam
                  5: {"name": "pkmn_nickname", "class": MultiByteParam}, #XXX TextLabelParam ?
                  }
    def parse(self):
        self.params = {}
        byte = int(rom[self.address])
        if not byte == self.id:
            raise Exception, "this should never happen"
        current_address = self.address+1
        i = 0
        for (key, param_type) in self.param_types.items():
            #stop executing after the 4th byte unless it == 0x1
            if i == 4 and self.params[-1].byte != 1: break
            name = param_type["name"]
            klass = param_type["class"]
            #make an instance of this class, like SingleByteParam()
            #or ItemLabelByte.. by making an instance, obj.parse() is called
            obj = klass(address=current_address, name=name)
            #save this for later
            self.params[i] = obj
            #increment our counters
            current_address += obj.size
            i += 1
        self.last_address = current_address
        return True

#these cause the script to end; used in create_command_classes
pksv_crystal_more_enders = [0x03, 0x04, 0x05, 0x0C, 0x51, 0x53,
                            0x8D, 0x8F, 0x90, 0x91, 0x92, 0x9B] 
def create_command_classes(debug=False):
    """creates some classes for each command byte"""
    klasses = []
    for (byte, cmd) in pksv_crystal_more.items():
        cmd_name = cmd[0]
        params = {"id": byte, "size": 1, "end": byte in pksv_crystal_more_enders, "macro_name": cmd_name}
        params["param_types"] = {}
        if len(cmd) > 1:
            param_types = cmd[1:]
            for (i, each) in enumerate(param_types):
                thing = {"name": each[0], "class": each[1]}
                params["param_types"][i] = thing
                if debug:
                    print "each is: " + str(each)
                    print "thing[class] is: " + str(thing["class"])
                params["size"] += thing["class"].size
        klass_name = cmd_name+"Command"
        klass = classobj(klass_name, (Command,), params)
        globals()[klass_name] = klass
        klasses.append(klass)
    #later an individual klass will be instantiated to handle something
    return klasses
command_classes = create_command_classes()

def parse_script_with_command_classes(start_address):
    """parses a script using the Command classes
    as an alternative to the old method using hard-coded commands"""
    global command_classes, rom
    load_rom()
    current_address = start_address
    commands = []
    end = False
    while not end:
        cur_byte = ord(rom[current_address])
        #find the right address
        right_kls = None
        for kls in command_classes:
            if kls.id == cur_byte:
                right_kls = kls
        if right_kls == None:
            print "xyz123 current_address is: " + hex(current_address)
            current_address += 1
            #continue
            asm_output = ""
            for command in commands:
                asm_output += command.to_asm() + "\n"
            raise Exception, "no command found? id: " + hex(cur_byte) + " at " + hex(current_address) + " asm is:\n" + asm_output
        cls = right_kls(address=current_address)
        print cls.to_asm()
        end = cls.end
        commands.append(cls)
        #current_address = cls.last_address + 1
        current_address += cls.size
    asm_output = "".join([command.to_asm()+"\n" for command in commands])
    print "--------------\n"+asm_output
    return commands

#use this to keep track of commands without pksv names
pksv_no_names = {}
def pretty_print_pksv_no_names():
    """just some nice debugging output
    use this to keep track of commands without pksv names
    pksv_no_names is created in parse_script_engine_script_at"""
    for (command_byte, addresses) in pksv_no_names.items():
        if command_byte in pksv_crystal_unknowns: continue
        print hex(command_byte) + " appearing in these scripts: "
        for address in addresses:
            print "    " + hex(address)

recursive_scripts = set([])
def rec_parse_script_engine_script_at(address, origin=None, debug=True):
    """this is called in parse_script_engine_script_at for recursion
    when this works it should be flipped back to using the regular
    parser."""
    recursive_scripts.add((address, origin))
    return parse_script_engine_script_at(address, origin=origin, debug=debug)
def find_broken_recursive_scripts(output=False, debug=True):
    """well.. these at least have a chance of maybe being broken?"""
    for r in list(recursive_scripts):
        script = {}
        length = "not counted here"
        if is_script_already_parsed_at(r[0]):
            script = script_parse_table[r[0]]
            length = str(len(script))
        if len(script) > 20 or script == {}:
            print "******************* begin"
            print "script at " + hex(r[0]) + " from main script " + hex(r[1]) + " with length: " + length
            if output:
                parse_script_engine_script_at(r[0], force=True, debug=True)
            print "==================== end"

stop_points = [0x1aafa2,
               0x9f58f, #battle tower
               0x9f62f, #battle tower
              ]
class Script():
    def __init__(self, *args, **kwargs):
        self.address = None
        self.commands = None
        if len(kwargs) == 0 and len(args) == 0:
            raise Exception, "Script.__init__ must be given some arguments"
        #first positional argument is address
        if len(args) == 1:
            address = args[0]
            if type(address) == str:
                address = int(address, 16)
            elif type(address) != int:
                raise Exception, "address must be an integer or string"
            self.address = address
        elif len(args) > 1:
            raise Exception, "don't know what to do with second (or later) positional arguments"
        #parse the script at the address
        self.parse(**kwargs)
    def pksv_list(self):
        """shows a list of pksv names for each command in the script"""
        items = []
        for (id, command) in self.commands.items():
            if command["type"] in pksv_crystal:
                items.append(pksv_crystal[command["type"]])
            else:
                items.append(hex(command["type"]))
        return items
    def to_pksv(self):
        """returns a string of pksv command names"""
        pksv = self.pksv_list()
        output = "script starting at: "+hex(self.address)+" .. "
        first = True
        for item in pksv:
            item = str(item)
            if first:
                output += item
                first = False
            else:
                output += ", "+item
        return output
    def show_pksv(self):
        """prints a list of pksv command names in this script"""
        print self.to_pksv()
    def parse(self, *args, **kwargs):
        """parses a script-engine script; force=True if you want to re-parse
        and get the debug information"""
        #can't handle more than one argument
        if len(args) > 1:
            raise Exception, "Script.parse_script doesn't know how to handle positional arguments"
        #use the first positional argument as the address
        elif len(args) == 1:
            self.address = args[0]
            if type(self.address) == str:
                self.address = int(self.address, 16)
            elif type(self.address) != int:
                raise Exception, "address param is the wrong type"
        #parse any keyword arguments, first make up the defaults
        kwargsorig = {"map_group": None, "map_id": None, "force": False, "debug": True, "origin": False}
        #let the caller override any defaults
        kwargsorig.update(kwargs)
        #copy these into kwargs
        kwargs = kwargsorig
        #set these defaults
        map_group = kwargs["map_group"]
        map_id = kwargs["map_id"]
        force = kwargs["force"]
        debug = kwargs["debug"]
        origin = kwargs["origin"]
        self.map_group = map_group
        self.map_id = map_id
    
        global rom
        if rom == None:
            direct_load_rom()
        
        #max number of commands in a 'recursive' script
        max_cmds = 150
    
        #set the address to be parsed
        address = self.address
        original_start_address = address
    
        #don't parse these crazy things (battle tower things, some rival things, etc.)
        if address in stop_points:
            print "got " + hex(address) + ".. map_group=" + str(map_group) + " map_id=" + str(map_id)
            return None
        #don't parse anything that looks crazy
        if address < 0x4000 and address not in [0x26ef, 0x114, 0x1108]:
            print "address is less than 0x4000.. address is: " + hex(address)
            sys.exit()
    
        #check if work is being repeated
        if is_script_already_parsed_at(address) and not force:
            raise Exception, "this script has already been parsed before, please use that instance"
            #use the commands from a previously-parsed Script object
            #self.commands = script_parse_table[address].commands
            #return True
            
            #return a previously-created Script object
            #return script_parse_table[address]
        
        #this next line stops the same script from being re-parsed multiple times
        #for instance.. maybe there's a script jump, then a jump back
        #the original script should only be parsed once
        script_parse_table[original_start_address:original_start_address+1] = "incomplete"
        
        #set up some variables
        self.commands = {}
        commands = self.commands
        offset = address
        end = False
    
        #main loop.. parse each command byte
        while not end:
            #reset variables so we don't contaminate this command
            info, long_info, size = None, None, 0
            #read the current command byte
            command_byte = ord(rom[offset])
            #setup the current command representation
            command = {"type": command_byte, "start_address": offset}
    
            #size is the total size including the command byte
            #last_byte_address is offset+size-1
            start_address = offset
    
            if (len(commands.keys()) > max_cmds) and origin != False:
                print "too many commands in this script? might not be a script (starting at: " +\
                      hex(original_start_address) + ").. called from a script at: " + hex(origin)
                sys.exit()
    
            #start checking against possible command bytes
            if   command_byte == 0x00: #Pointer code [2b+ret]
                pksv_name = "2call"
                info = "pointer code"
                long_info = """
                2byte pointer points to script; when pointed script ends --> return to old script
                [code][2 byte pointer]
                """
                size = 3
                start_address = offset
                last_byte_address = offset + size - 1
                pointer = calculate_pointer_from_bytes_at(start_address+1)
                if pointer == None:
                    raise Exception, "pointer is None (shouldn't be None pointer on 0x0 script command"
                command["pointer"] = pointer
                if debug:
                    print "in script starting at "+hex(original_start_address)+\
                          " about to parse script at "+hex(pointer)+\
                          " called by "+info+" byte="+hex(command_byte)
                script = rec_parse_script_engine_script_at(pointer, original_start_address, debug=debug)
                command["script"] = script
            elif command_byte == 0x01: #Pointer code [3b+ret]
                pksv_name = "3call"
                info = "pointer code"
                long_info = """
                3byte pointer points to script; when pointed script ends --> return to old script
                [Code][resp. pointer(2byte or 3byte)]
                """
                size = 4
                info = "pointer code"
                pointer = calculate_pointer_from_bytes_at(start_address+1, bank=True)
                if debug:
                    print "in script starting at "+hex(original_start_address)+\
                          " about to parse script at "+hex(pointer)+\
                          " called by "+info+" byte="+hex(command_byte)
                script = rec_parse_script_engine_script_at(pointer, original_start_address, debug)
                command["pointer"] = pointer
                command["script"] = script
            elif command_byte == 0x02: #Pointer code [2b+3b+ret]
                info = "pointer code"
                long_info = """
                2byte pointer points to 3byte pointer; when pointed script --> return to old script
                [Code][resp. pointer(2byte or 3byte)]
                """
                size = 3
                pointer = calculate_pointer_from_bytes_at(start_address+1)
                if debug:
                    print "in script starting at "+hex(original_start_address)+\
                          " about to parse script at "+hex(pointer)+\
                          " called by "+info+" byte="+hex(command_byte)
                script = rec_parse_script_engine_script_at(pointer, original_start_address, debug=debug)
                command["pointer"] = pointer
                command["script"] = script
            elif command_byte == 0x03: #Pointer code [2b]
                #XXX what does "new script is part of main script" mean?
                info = "pointer code"
                long_info = """
                2byte pointer points to script; new script is part of main script
                [Code][resp. pointer(2byte or 3byte)]
                """
                size = 3
                pointer = calculate_pointer_from_bytes_at(start_address+1)
                if debug:
                    print "in script starting at "+hex(original_start_address)+\
                          " about to parse script at "+hex(pointer)+\
                          " called by "+info+" byte="+hex(command_byte)
                script = rec_parse_script_engine_script_at(pointer, original_start_address, debug=debug)
                command["pointer"] = pointer
                command["script"] = script
                end = True #according to pksv
            elif command_byte == 0x04: #Pointer code [3b]
                info = "pointer code"
                long_info = """
                3byte pointer points to script; new script is part of main script
                [Code][resp. pointer(2byte or 3byte)]
                """
                size = 4
                pointer = calculate_pointer_from_bytes_at(start_address+1, bank=True)
                if debug:
                    print "in script starting at "+hex(original_start_address)+\
                      " about to parse script at "+hex(pointer)+\
                      " called by "+info+" byte="+hex(command_byte)
                script = rec_parse_script_engine_script_at(pointer, original_start_address, debug=debug)
                command["pointer"] = pointer
                command["script"] = script
                end = True #according to pksv
            elif command_byte == 0x05: #Pointer code [2b+3b]
                info = "pointer code"
                long_info = """
                2byte pointer points to 3byte pointer; new script is part of main script
                [Code][resp. pointer(2byte or 3byte)]
                """
                size = 3
                command["pointer"] = calculate_pointer_from_bytes_at(start_address+1)
                command["target_pointer"] = calculate_pointer_from_bytes_at(command["pointer"], bank=True)
                
                if debug:
                    print "in script starting at "+hex(original_start_address)+\
                      " about to parse script at "+hex(command["target_pointer"])+\
                      " called by "+info+" byte="+hex(command_byte)
                script = rec_parse_script_engine_script_at(command["target_pointer"], original_start_address, debug=debug)
                command["script"] = script
                end = True #according to pksv
            elif command_byte == 0x06: #RAM check [=byte]
                info = "RAM check [=byte]"
                long_info = """
                When the conditional is true...
                .. then go to pointed script, else resume interpreting after the pointer
                """
                size = 4
                command["byte"] = ord(rom[start_address+1])
                pointer = calculate_pointer_from_bytes_at(start_address+2)
                if debug:
                    print "in script starting at "+hex(original_start_address)+\
                      " about to parse script at "+hex(pointer)+\
                      " called by "+info+" byte="+hex(command_byte)
                script = rec_parse_script_engine_script_at(pointer, original_start_address, debug=debug)
                command["pointer"] = pointer
                command["script"] = script
            elif command_byte == 0x07: #RAM check [<>byte]
                info = "RAM check [<>byte]"
                long_info = """
                When the conditional is true...
                .. then go to pointed script, else resume interpreting after the pointer
                """
                size = 4
                command["byte"] = ord(rom[start_address+1])
                pointer = calculate_pointer_from_bytes_at(start_address+2)
                if debug:
                    print "in script starting at "+hex(original_start_address)+\
                      " about to parse script at "+hex(pointer)+\
                      " called by "+info+" byte="+hex(command_byte)
                script = rec_parse_script_engine_script_at(pointer, original_start_address, debug=debug)
                command["pointer"] = pointer
                command["script"] = script
            elif command_byte == 0x08: #RAM check [=0]
                info = "RAM check [=0]"
                long_info = """
                When the conditional is true...
                .. then go to pointed script, else resume interpreting after the pointer
                """
                size = 3
                pointer = calculate_pointer_from_bytes_at(start_address+1)
                if debug:
                    print "in script starting at "+hex(original_start_address)+\
                      " about to parse script at "+hex(pointer)+\
                      " called by "+info+" byte="+hex(command_byte)
                script = rec_parse_script_engine_script_at(pointer, original_start_address, debug=debug)
                command["pointer"] = pointer
                command["script"] = script
            elif command_byte == 0x09: #RAM check [<>0]
                info = "RAM check [<>0]"
                long_info = """
                When the conditional is true...
                .. then go to pointed script, else resume interpreting after the pointer
                """
                size = 3
                pointer = calculate_pointer_from_bytes_at(start_address+1)
                if debug:
                    print "in script starting at "+hex(original_start_address)+\
                      " about to parse script at "+hex(pointer)+\
                      " called by "+info+" byte="+hex(command_byte)
                script = rec_parse_script_engine_script_at(pointer, original_start_address, debug=debug)
                command["pointer"] = pointer
                command["script"] = script
            elif command_byte == 0x0A: #RAM check [<byte]
                info = "RAM check [<byte]"
                long_info = """
                When the conditional is true...
                .. then go to pointed script, else resume interpreting after the pointer
                """
                size = 4
                command["byte"] = ord(rom[start_address+1])
                pointer = calculate_pointer_from_bytes_at(start_address+2)
                if debug:
                    print "in script starting at "+hex(original_start_address)+\
                      " about to parse script at "+hex(pointer)+\
                      " called by "+info+" byte="+hex(command_byte)
                script = rec_parse_script_engine_script_at(pointer, original_start_address, debug=debug)
                command["pointer"] = pointer
                command["script"] = script
            elif command_byte == 0x0B: #RAM check [>byte]
                info = "RAM check [>byte]"
                long_info = """
                When the conditional is true...
                .. then go to pointed script, else resume interpreting after the pointer
                """
                size = 4
                command["byte"] = ord(rom[start_address+1])
                pointer = calculate_pointer_from_bytes_at(start_address+2)
                if debug:
                    print "in script starting at "+hex(original_start_address)+\
                      " about to parse script at "+hex(pointer)+\
                      " called by "+info+" byte="+hex(command_byte)
                script = rec_parse_script_engine_script_at(pointer, original_start_address, debug=debug)
                command["pointer"] = pointer
                command["script"] = script
            elif command_byte == 0x0C: #0C codes [xxyy]
                info = "call predefined script then end"
                long_info = """
                Calls predefined scripts. After this code the script ends.
                [0C][xxyy]
                """
                size = 3
                end = True
                byte1 = ord(rom[offset+1])
                byte2 = ord(rom[offset+2])
                number = byte1 + (byte2 << 8)
                #0000 to 000AD ... XXX how should these be handled?
                command["predefined_script_number"] = number
            elif command_byte == 0x0D: #0D codes [xxyy]
                info = "call some predefined script"
                long_info = """
                Calls predefined scripts. Exactly like $0C except the script does not end.
                [0D][xxyy]
                """
                size = 3
                byte1 = ord(rom[offset+1])
                byte2 = ord(rom[offset+2])
                number = byte1 + (byte2 << 8)
                #0000 to 000AD ... XXX how should these be handled?
                command["predefined_script_number"] = number
            elif command_byte == 0x0E: #ASM code1 [3b]
                info = "ASM code1 [3b]"
                long_info = """
                Calls a predefined routine by interpreting the ASM the pointer points to.
                [0E][3byte pointer]
                """
                size = 4
                command["pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=True)
                #XXX should we dissassemble the asm at the target location?
            elif command_byte == 0x0F: #0F codes [xxyy]
                info = "call some predefined script [0F][yyxx]"
                long_info = """
                Calls predefined scripts.
                [0F][yyxx]
                NOTE: For (some) dialogues the font needs to be loaded with the Text box&font code.
                """
                size = 3
                byte1 = ord(rom[offset+1])
                byte2 = ord(rom[offset+2])
                number = byte1 + (byte2 << 8)
                command["predefined_script_number"] = number
            elif command_byte == 0x10: #ASM code2 [2b]
                info = "ASM code2 [2b to 3b to asm]"
                long_info = """
                Call an ASM script via a 2byte pointer pointing to a 3byte pointer.
                [10][2byte pointer pointing to 3byte pointer pointing to ASM script]
                """
                size = 3
                command["pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
                #XXX should i include the 3-byte pointer at the target location?
                #XXX should we dissassemble the asm at the target location?
            elif command_byte == 0x11: #Trigger event check1 [xxyy]
                info = "Trigger event check1 [xx][yy]"
                long_info = """
                Check the current number of the trigger event on map (map group/map id).
                [11][map group][map number]
                """
                size = 3
                command["map_group"] = ord(rom[start_address+1])
                command["map_id"] = ord(rom[start_address+2])
            elif command_byte == 0x12: #Activate trigger event from afar [xxyyzz]
                info = "Activate trigger event from afar [xx][yy][zz]"
                long_info = """
                Changes trigger event number on map (map bank/map no) to xx.
                xx = trigger event number that should be activated
                [12][MapBank][MapNo][xx]
                """
                size = 4
                command["map_group"] = ord(rom[start_address+1])
                command["map_id"] = ord(rom[start_address+2])
                command["trigger_number"] = ord(rom[start_address+3])
            elif command_byte == 0x13: #Trigger event check
                info = "Trigger event check"
                long_info = """
                Checks the number of the trigger events on the current map.
                [13]
                """
                size = 1
            elif command_byte == 0x14: #De-/activate trigger event [xx]
                info = "De-/activate trigger event [xx]"
                long_info = """
                Changes trigger event number on current map to xx.
                xx = trigger event number that should be activated
                [14][xx]
                deactivate? Just activate a different trigger event number. There's a limit of 1 active trigger.
                """
                size = 2
                command["trigger_number"] = ord(rom[start_address+1])
            elif command_byte == 0x15: #Load variable into RAM [xx]
                info = "Load variable into RAM [xx]"
                long_info = "[15][xx]"
                size = 2
                command["variable"] = ord(rom[start_address+1])
            elif command_byte == 0x16: #Add variables [xx]
                info = "Add variables [xx]"
                long_info = """
                Adds xx and the variable in RAM.
                #[16][xx]
                """
                size = 2
                command["variable"] = ord(rom[start_address+1])
            elif command_byte == 0x17: #Random number [xx]
                info = "Random number [xx]"
                long_info = """
                #Reads xx and creates a random number between 00 and xx -1.
                #According to this xx can be all but 00. Random number = [00; xx)
                #The nearer the random number is to xx, the rarer it occurs.
                #Random number gets written to RAM.
                """
                size = 2
                command["rarest"] = ord(rom[start_address+1])
            elif command_byte == 0x18: #Version check
                info = "G/S version check"
                long_info = """
                #Check if version is gold or silver. Gives feedback.
                #00 = Gold
                #01 = Silver
                #[18]
                """
                size = 1
            elif command_byte == 0x19: #Copy variable code1 [xxyy]
                info = "Copy from RAM address to script RAM variable [xxyy]"
                long_info = """
                #Writes variable from ram address to RAM.
                #[19][2-byte RAM address]
                """
                size = 3
                #XXX maybe a pointer is a bad idea?
                command["pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
            elif command_byte == 0x1A: #Copy variable code2 [xxyy]
                info = "Write variable from script RAM variable to actual RAM address [xxyy]"
                long_info = """
                #Writes variable from RAM to actual RAM address.
                #[1A][2-byte RAM address]
                """
                size = 3
                command["pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
            elif command_byte == 0x1B: #Load variable [xxyyzz]
                info = "Load variable [xxyy][zz]"
                long_info = """
                #Writes zz to ram address.
                #[1B][2-byte RAM address][zz]
                """
                size = 4
                command["pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
                command["value"] = ord(rom[start_address+3])
            elif command_byte == 0x1C: #Check codes [xx]
                #XXX no idea what's going on in this one :(
                info = "Check pre-ID-mapped RAM location [xx]"
                long_info = """
                #Checks special game-technical values and writes then into RAM.
                #[1C][following part][Ram check (when <> 08/09 see „numbers“ in list of following parts)]
                #following part (and then hex values)
                #01 = PKMN count in party
                #     00 - 06
                #02 = ???
                #03 = Battle type of wild PKMN
                #04 = ???
                #05 = PokéDex caught
                #     00 - FA
                #06 = PokéDex seen
                #     00 - FA
                #07 = Badge count
                #     00 - 10
                #08 = Movement
                #     00 = walk
                #     01 = bike
                #     02 = slipping
                #     04 = surfer
                #     08 = surfing pikachu
                #09 = HIRO direction
                #     00 (d)
                #     01 (u)
                #     02 (l)
                #     03 (r)
                #0A = Time in hours
                #     00 - 18
                #0B = Day
                #     00 (Mo) - 06 (Su)
                #0C = Map bank of current map
                #0D = Map no of current map
                #0E = Num. of diff. unowns seen
                #     00 - 1A
                #0F = Action byte of map
                #10 = Amount of free spaces in pkmn box
                #     00 - 14
                #11 = Minutes until end bug contest
                #     00 - 14
                #12 = X position of HIRO
                #13 = Y position of HIRO
                #14 = phone call number
                """
                size = 2 #i think?
                command["following_part"] = ord(rom[start_address+1])
            elif command_byte == 0x1D: #Input code1 [xx]
                info = "Write to pre-ID-mapped RAM location [xx]"
                long_info = """
                #Writes variable from RAM to special game-technical value offsets.
                #[1D][following part]
                #where [following part] is the same as 0x1C
                """
                size = 2
                command["following_part"] = ord(rom[start_address+1])
            elif command_byte == 0x1E: #Input code2 [xxyy]
                info = "Write byte value to pre-ID-mapped RAM location [aa][xx]"
                long_info = """
                #Writes variable xx to special game-technical value offsets.
                #[1E][following part][xx]
                #where [following part] is the same as 0x1C
                """
                size = 3
                command["following_part"] = ord(rom[start_address+1])
                command["value"] = ord(rom[start_address+2])
            elif command_byte == 0x1F: #Give item code [xxyy]
                info = "Give item by id and quantity [xx][yy]"
                long_info = """
                #Gives item (item no) amount times.
                #feedback:
                #   00 = bag full
                #   01 = OK
                #[1F][item no][amount]
                """
                size = 3
                command["item_id"] = ord(rom[start_address+1])
                command["quantity"] = ord(rom[start_address+2])
            elif command_byte == 0x20: #Take item code [xxyy]
                info = "Take item by id and quantity [xx][yy]"
                long_info = """
                #Gives item (item no) amount times
                #feedback:
                #   00 = not enough items
                #[20][item no][amount]
                """
                size = 3
                command["item_id"] = ord(rom[start_address+1])
                command["quantity"] = ord(rom[start_address+2])
            elif command_byte == 0x21: #Check for item code [xx]
                info = "Check if player has item [xx]"
                long_info = """
                #Checks if item is possessed.
                #feedback:
                #   00 = does not have item
                #   01 = has item
                #[21][item no]
                """
                size = 2
                command["item_id"] = ord(rom[start_address+1])
            elif command_byte == 0x22: #Give money code [xxyyzzaa]
                info = "Give money to HIRO/account [xxyyzzaa]"
                long_info = """
                #Gives zzyyxx money to HIRO/account.
                #zzyyxx = amount of money (000000 - 0F423F)
                #[22][00-HIRO/01-account][xxyyzz]
                """
                size = 5
                bytes = rom_interval(start_address, size, strings=False)
                command["account"] = bytes[1]
                command["amount"] = bytes[2:]
                #raise NotImplementedError, "don't know if zzyyxx is a decimal or hex value"
            elif command_byte == 0x23: #Take money code [xxyyzzaa]
                info = "Take money from HIRO/account [xxyyzzaa]"
                long_info = """
                #Takes zzyyxx money from HIRO/account.
                #zzyyxx = amount of money (000000 - 0F423F)
                #[23][00-HIRO/01-account][xxyyzz]
                """
                size = 5
                bytes = rom_interval(start_address, size, strings=False)
                command["account"] = bytes[1]
                command["amount"] = bytes[2:]
                #raise NotImplementedError, "don't know if zzyyxx is a decimal or hex value"
            elif command_byte == 0x24: #Check for money code [xxyyzzaa]
                info = "Check if HIRO/account has enough money [xxyyzzaa]"
                long_info = """
                #Checks if HIRO/account has got zzyyxx money.
                #feedback:
                #   00 = enough money
                #   01 = exact amount
                #   02 = less money
                #zzyyxx = amount of money (000000 - 0F423F)
                #[24][00-HIRO/01-account][xxyyzz]
                """
                size = 5
                bytes = rom_interval(start_address, size, strings=False)
                command["account"] = bytes[1]
                command["quantity"] = bytes[2:]
                #XXX how is quantity formatted?
                #raise NotImplementedError, "don't know if zzyyxx is a decimal or hex value"
            elif command_byte == 0x25: #Give coins code [xxyy]
                info = "Give coins to HIRO [xxyy]"
                long_info = """
                #Gives coins to HIRO.
                #yyxx = amount of coins (0000 - 270F)
                #[25][xxyy]
                """
                size = 3
                bytes = rom_interval(start_address, size, strings=False)
                command["quantity"] = bytes[1] + (bytes[2] << 8)
            elif command_byte == 0x26: #Take coins code [xxyy]
                info = "Take coins from HIRO [xxyy]"
                long_info = """
                #Takes coins away from HIRO.
                #yyxx = amount of coins (0000 - 270F)
                #[26][xxyy]
                """
                size = 3
                bytes = rom_interval(start_address, size, strings=False)
                command["quantity"] = bytes[1] + (bytes[2] << 8)
            elif command_byte == 0x27: #Check for coins code [xxyy]
                info = "Check if HIRO has enough coins [xxyy]"
                long_info = """
                #Checks if HIRO has enough coins.
                #feedback:
                #   00 = has enough coins
                #   01 = has exact amount
                #   02 = does not have enough
                #yyxx = amount of coins necessary (0000 - 270F)
                #[27][xxyy]
                """
                size = 3
                bytes = rom_interval(start_address, size, strings=False)
                command["quantity"] = bytes[1] + (bytes[2] << 8)
            elif command_byte == 0x28: #Give cell phone number [xx]
                info = "Give cell phone number [xx]"
                long_info = """
                #Gives number to HIRO.
                #feedback:
                #   00 = number was added successfully
                #   01 = Number already added, or no memory
                #xx = number of person
                #[28][xx]
                #01 = mother
                #02 = bike store
                #03 = bll
                #04 = elm
                """
                size = 2
                command["number"] = ord(rom[start_address+1])
            elif command_byte == 0x29: #Take cell phone number [xx]
                info = "Delete cell phone number [xx]"
                long_info = """
                #Deletes a number from the list.
                #feedback:
                #   00 = number deleted successfully
                #   01 = number wasn't in list
                #xx = number of person
                #[29][xx]
                """
                size = 2
                command["number"] = ord(rom[start_address+1])
            elif command_byte == 0x2A: #Check for cell phone number [xx]
                info = "Check for cell phone number [xx]"
                long_info = """
                #Checks if a number is in the list.
                #feedback:
                #   00 = number is in list
                #   01 = number not in list
                #xx = number to look for
                #[2A][xx]
                """
                size = 2
                command["number"] = ord(rom[start_address+1])
            elif command_byte == 0x2B: #Check time of day [xx]
                info = "Check time of day [xx]"
                long_info = """
                #Checks the time of day.
                #feedback:
                #   00 = time of day is the same
                #   01 = time of day is not the same
                #[2B][time of day (01morn-04night)]
                """
                size = 2
                command["time_of_day"] = ord(rom[start_address+1])
            elif command_byte == 0x2C: #Check for PKMN [xx]
                info = "Check for pokemon [xx]"
                long_info = """
                #Checks if there is a certain PKMN in team.
                #feedback:
                #   00 = in team
                #   01 = not in team
                #xx = pkmn id
                #[2C][xx]
                """
                size = 2
                command["pokemon_id"] = ord(rom[start_address+1])
            elif command_byte == 0x2D: #Give PKMN [xxyyzzaa(+2b +2b)]
                info = "Give pokemon [pokemon][level][item][trainer2b][...]"
                long_info = """
                #Gives a PKMN if there's space
                #feedback:
                #   trainer id
                #[2D][PKMN][PKMNlvl][PKMNitem][TRAINER]
                #trainer:
                #   00 = HIRO
                #   01 = after the main code there are 4 bytes added
                #       [2byte pointer to trainer's name (max.0x0A figures + 0x50)][2byte pointer to nickname (max.0x0A figures + 0x50)]
                """
                size = 5
                bytes = rom_interval(start_address, size, strings=False)
                command["pokemon_id"] = bytes[1]
                command["pokemon_level"] = bytes[2]
                command["held_item_id"] = bytes[3]
                command["trainer"] = bytes[4]
                if command["trainer"] == 0x01:
                    size += 4
                    bytes = rom_interval(start_address, size, strings=False)
                    command["trainer_name_pointer"] = calculate_pointer_from_bytes_at(start_address+5, bank=False)
                    command["pokemon_nickname_pointer"] = calculate_pointer_from_bytes_at(start_address+7, bank=False)
            elif command_byte == 0x2E: #Give EGG [xxyy]
                info = "Give egg [xx][yy]"
                long_info = """
                #Gives egg if there's space.
                #feedback:
                #   00 = OK
                #   02 = transaction not complete
                #[2E][PKMN][PKMNlvl]
                """
                size = 3
                command["pokemon_id"] = ord(rom[start_address+1])
                command["pokemon_level"] = ord(rom[start_address+2])
            elif command_byte == 0x2F: #Attach item code [2B]
                info = "Attach item to last pokemon in list [xxyy]"
                long_info = """
                #Gives last PKMN in list an item and letter text if applicable. Replaces existing items.
                #[2F][2byte pointer to item no + 0x20 bytes letter text]
                """
                size = 3
                command["item_pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
                #XXX are those 20 bytes supposed to happen here? or at the pointer's destination?
            elif command_byte == 0x30: #Check letter code [2b]
                info = "Check letter against known letter [xxyy]"
                long_info = """
                #Opens a PKMN list. Selected PKMN must have the right letter + the right contents. If OK, then PKMN is taken away
                #feedback:
                #   00 = wrong letter
                #   01 = OK
                #   02 = Cancelled
                #   03 = Chosen PKMN has no letter
                #   04 = Chosen PKMN is the only one in the list.
                #[30][2byte pointer to letter item no + 0x20 bytes letter text]
                """
                size = 3
                command["item_pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
            elif command_byte == 0x31: #BitTable1 check [xxyy]
                info = "Check some bit on bit table 1 [xxyy]"
                long_info = """
                #Checks whether a bit of BitTable1 has the value 0 or 1.
                #feedback:
                #   00 = value 0 (off)
                #   01 = value 1 (on)
                #[31][2-byte bit number]
                """
                #XXX what format is the 2-byte number in?
                size = 3
                bytes = rom_interval(start_address+1, size-1, strings=False)
                command["bit_number_bytes"] = bytes
                #raise NotImplementedError, "what format is the 2-byte number in?"
            elif command_byte == 0x32: #BitTable1 reset [xxyy]
                info = "Reset (to 0) a bit on bit table 1 [xxyy]"
                long_info = """
                #Sets a bit of BitTable1 to value 0.
                #[32][Bit no (2byte)]
                """
                size = 3
                bytes = rom_interval(start_address+1, size-1, strings=False)
                command["bit_number_bytes"] = bytes
            elif command_byte == 0x33: #BitTable1 set [xxyy]
                info = "Set (to 1) a bit on bit table 1 [xxyy]"
                long_info = """
                #Sets a bit of BitTable1 to value 1.
                #[33][Bit-No (2byte)]
                """
                size = 3
                bytes = rom_interval(start_address+1, size-1, strings=False)
                command["bit_number_bytes"] = bytes
            elif command_byte == 0x34: #BitTable2 check [xxyy]
                info = "Check some bit on bit table 2 [xxyy]"
                long_info = """
                #Checks whether a bit of BitTable2 has the value 0 or 1.
                #feedback:
                #   00 = value 0 (off)
                #   01 = value 1 (on)
                #[34][Bit no (2byte)]
                """
                size = 3
                bytes = rom_interval(start_address+1, size-1, strings=False)
                command["bit_number_bytes"] = bytes
            elif command_byte == 0x35: #BitTable2 reset [xxyy]
                info = "Reset (to 0) a bit on bit table 2 [xxyy]"
                long_info = """
                #Sets a bit of BitTable2 to value 0.
                #[35][Bit no (2byte)]
                """
                size = 3
                bytes = rom_interval(start_address+1, size-1, strings=False)
                command["bit_number_bytes"] = bytes
            elif command_byte == 0x36: #BitTable2 set [xxyy]
                info = "Set (to 1) a bit on bit table 2 [xxyy]"
                long_info = """
                #Sets a bit of BitTable2 to value 1.
                #[36][Bit no (2byte)]
                """
                size = 3
                bytes = rom_interval(start_address+1, size-1, strings=False)
                command["bit_number_bytes"] = bytes
            elif command_byte == 0x37: #Deactivate PKMN battles
                info = "Turn off wild pokemon battles"
                long_info = """
                #This code turns all wild PKMN battles off.
                #[37]
                """
                size = 1
            elif command_byte == 0x38: #Activate PKMN battles
                info = "Turn no wild pokemon battles"
                long_info = "This code turns all wild PKMN battles on."
                size = 1
            elif command_byte == 0x39: #X/Y comparison [xxyy]
                info = "BUGGY x/y comparison [xxyy]"
                long_info = """
                #This code is buggy (Bug fix: 0x3021 --> C6) and can't used as
                #described without fix. This code compares the X and Y coordinates of
                #HIRO with the ones in a table (max. 20h XY pairs) on the current map.
                #It sets or resets the 4 bytes D17C to D17F accordingly to this table,
                #1 bit for every table entry. To be useful, this code can only be used
                #in a command queue, because with every regular move of HIRO the bits
                #are reset again. This code is an alternative to the trigger events and
                #can be used via the command queue code.
                #See Write command queue, Additional documentation: 3:4661 with c= index 
                #in table (start=00), hl=D171, b=01, d=00.
                """
                size = 3
                command["table_pointer"] = rom_interval(start_address+1, size-1, strings=False)
            elif command_byte == 0x3A: #Warp modifier [xxyyzz]
                info = "Set target for 0xFF warps [warp id][map group][map id]"
                long_info = """
                #Changes warp data for all warps of the current map that have a 0xFF for warp-to data.
                #[3A][Nee warp-to][New map bank][New map no]
                """
                size = 4
                bytes = rom_interval(start_address+1, size-1, strings=False)
                command["nee_warp_to"] = bytes[0]
                command["map_group"] = bytes[1]
                command["map_id"] = bytes[2]
            elif command_byte == 0x3B: #Blackout modifier [xxyy]
                info = "Blackout warp modifier [map group][map id]"
                long_info = """
                #Changes the map HIRO arrives at, after having a blackout.
                #There needs to be flying data for that map.
                #[3B][Map bank][Map no]
                """
                size = 3
                command["map_group"] = ord(rom[start_address+1])
                command["map_id"] = ord(rom[start_address+2])
            elif command_byte == 0x3C: #Warp code [xxyyzzaa]
                info = "Warp to [map group][map id][x][y]"
                long_info = """
                #Warps to another map.
                #If all data is 00s, then the current map is reloaded with
                #the current X and Y coordinates. Old script is not finished
                #without a [90].
                #[3C][Map bank][Map no][X][Y]
                """
                size = 5
                command["map_group"] = ord(rom[start_address+1])
                command["map_id"] = ord(rom[start_address+2])
                command["x"] = ord(rom[start_address+3])
                command["y"] = ord(rom[start_address+4])
            elif command_byte == 0x3D: #Account code [xxyy]
                info = "Read money amount [xx][yy]"
                long_info = """
                #Reads amount of money in accounts of HIRO and mother and writes
                #it to MEMORY1, 2 or 3 for later use in text.
                #[3D][00 = HIRO| <> 00 = Mother][00-02 MEMORY]
                #see http://hax.iimarck.us/files/scriptingcodes_eng.htm#InText01
                """
                size = 3
                command["account_id"] = ord(rom[start_address+1])
                command["memory_id"] = ord(rom[start_address+2])
            elif command_byte == 0x3E: #Coin case code [xx]
                info = "Read coins amount [xx]"
                long_info = """
                #Reads amount of coins in coin case and writes it to MEMORY 1, 2,
                #or 3 for later use in text.
                #[3E][00-02 MEMORY]
                """
                size = 2
                command["memory_id"] = ord(rom[start_address+1])
            elif command_byte == 0x3F: #Display RAM [xx]
                info = "Copy script RAM value into memX [xx]"
                long_info = """
                #Reads RAM value and writes it to MEMORY1, 2 or 3 for later use in text.
                #[3F][00-02 MEMORY]
                """
                size = 2
                command["memory_id"] = ord(rom[start_address+1])
            elif command_byte == 0x40: #Display pokémon name [xxyy]
                info = "Copy pokemon name (by id) to memX [id][xx]"
                long_info = """
                #Writes pokémon name to MEMORY1, 2 or 3 for later use in text.
                #[40][PKMN no][00-02 MEMORY]
                """
                size = 3
                command["map_id"] = ord(rom[start_address+1])
                command["memory_id"] = ord(rom[start_address+2])
            elif command_byte == 0x41: #Display item name [xxyy]
                info = "Copy item name (by id) to memX [id][xx]"
                long_info = """
                #Writes item name to MEMORY1, 2 or 3 for later use in text.
                #[41][Item no][00-02 MEMORY]
                """
                size = 3
                command["item_id"] = ord(rom[start_address+1])
                command["memory_id"] = ord(rom[start_address+2])
            elif command_byte == 0x42: #Display location name [xx]
                info = "Copy map name to memX [xx]"
                long_info = """
                #Writes current location's name to MEMORY1, 2 or 3 for later use in text.
                #[42][00-02 MEMORY]
                """
                size = 2
                command["memory_id"] = ord(rom[start_address+1])
            elif command_byte == 0x43: #Display trainer name [xxyyzz]
                info = "Copy trainer name (by id&group) to memZ [xx][yy][zz]"
                long_info = """
                #Writes trainer name to MEMORY1, 2 or 3 for later use in text.
                #[43][Trainer number][Trainer group][00-02 MEMORY]
                """
                size = 4
                command["trainer_id"] = ord(rom[start_address+1])
                command["trainer_group"] = ord(rom[start_address+2])
                command["memory_id"] = ord(rom[start_address+3])
            elif command_byte == 0x44: #Display strings [2b + xx]
                info = "Copy text (by pointer) to memX [aabb][xx]"
                long_info = """
                #Writes string to MEMORY1, 2 or 3 for later use in text.
                #[44][2byte pointer to string (max. 0x0C figures + 0x50)][00-02 MEMORY]
                #See 0C codes: 0C2900, 0C2A00, 0C1B00, 0C2200, Usage of variable strings in text.
                """
                size = 4
                command["pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
                command["memory_id"] = ord(rom[start_address+3])
                command["text"] = parse_text_engine_script_at(command["pointer"], map_group=map_group, map_id=map_id, debug=debug)
            elif command_byte == 0x45: #Stow away item code
                info = "Show HIRO put the ITEMNAME in the ITEMPOCKET text box"
                long_info = """
                #Text box: "HIRO put the ITEMNAME in the ITEMPOCKET."
                #The item number has to have been loaded beforehand
                #(e.g. by Give item code).
                """
                size = 1
            elif command_byte == 0x46: #Full item pocket code
                info = "Show ITEMPOCKET is full textbox"
                long_info = """
                #Text box: "ITEMPOCKET is full..." The item number has to have
                #been loaded beforehand (e.g. by Give item code).
                """
                size = 1
            elif command_byte == 0x47: #Text box&font code
                info = "Loads the font into the ram and opens a text box."
                size = 1
            elif command_byte == 0x48: #Refresh code [xx]
                info = "Screen refresh [xx]"
                long_info = """
                #Executes a complete screen refresh.
                #[48][xx]
                #xx is a dummy byte
                """
                size = 2
                command["dummy"] = ord(rom[start_address+1])
            elif command_byte == 0x49: #Load moving sprites
                info = "Load moving sprites into memory"
                long_info = "Loads moving sprites for person events into ram."
                size = 1
            elif command_byte == 0x4A: #Load byte to C1CE [xx]
                info = "Load specific byte to $C1CE [xx]"
                long_info = """
                #Loads a byte to C1CE. Seems to have no function in the game.
                #[4A][Byte]
                """
                size = 2
                command["byte"] = ord(rom[start_address+1])
            elif command_byte == 0x4B: #Display text [3b]
                info = "Display text by pointer [bb][xxyy]"
                long_info = """
                #Opens a text box and writes text. Doesn't load font.
                #[4B][Text bank][2byte text pointer]
                """
                size = 4
                command["text_group"] = ord(rom[start_address+1])
                command["pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=True)
                command["text"] = parse_text_engine_script_at(command["pointer"], map_group=map_group, map_id=map_id, debug=debug)
            elif command_byte == 0x4C: #Display text [2b]
                info = "Display text by pointer [xxyy]"
                long_info = """
                #Opens a text box and writes text. Doesn't load font.
                #[4C][2byte text pointer]
                """
                size = 3
                command["pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
                command["text"] = parse_text_engine_script_at(command["pointer"], map_group=map_group, map_id=map_id, debug=debug)
            elif command_byte == 0x4D: #Repeat text [xxyy]
                info = "Repeat text [FF][FF]"
                long_info = """
                #Opens a text box and writes the text written latest resp. whose address was put statically to D175-D177.
                #Doesn't load font.
                #[4D][FF][FF]
                #Without FF for both bytes, no operation occurs
                """
                size = 3
                command["bytes"] = rom_interval(start_address+1, 2, strings=False)
            elif command_byte == 0x4E: #YES/No box
                info = "YES/No box"
                long_info = """
                #Displays a YES/NO box at X0F/Y07
                #feedback:
                #   00 = no
                #   01 = yes
                """
                size = 1
            elif command_byte == 0x4F: #Menu data code [2b]
                info = "Load menu data by pointer [xxyy]"
                long_info = """
                #Loads data for menus
                #[4F][2byte pointer to menu data]
                #see http://hax.iimarck.us/files/scriptingcodes_eng.htm#ZusatzDatA4F
                """
                size = 3
                command["menu_pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
            elif command_byte == 0x50: #Write backup code
                info = "Write screen backup"
                long_info = "Writes backup of parts of the screen the box was overlapping."
                size = 1
            elif command_byte == 0x51: #Text1 code [2b]
                info = "Display text (by pointer), turn to HIRO, end [xxyy]"
                long_info = """
                #Displays a text and lets person turn to HIRO.
                #Afterwards there is no other script interpreted.
                #Corresponds to 6A + 47 + 4C + 53 + 49 + 90
                #[51][2byte textpointer]
                """
                size = 3
                end = True
                command["pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
                command["text"] = parse_text_engine_script_at(command["pointer"], map_group=map_id, map_id=map_id, debug=debug)
            elif command_byte == 0x53: #Text2 code [2b]
                info = "Display text (by pointer) and end [xxyy]"
                long_info = """
                #Displays a text. Afterwards there is no other script interpreted.
                #Corresponds to 47 + 4C + 53 + 49 + 90
                #[52][2byte textpointer]
                """
                size = 3
                end = True
                command["pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
                command["text"] = parse_text_engine_script_at(command["pointer"], map_group=map_id, map_id=map_id, debug=debug)
            elif command_byte == 0x54: #Close text box code
                info = "Close text box"
                long_info = "Closes a text box which was opened by 47 resp. 4B/4C/4D."
                size = 1
            elif command_byte == 0x55: #Keep text box open code
                info = "Keep text box open"
                long_info = "Keeps a text box open which was opened by 47 resp. 4B/4C/4D."
                size = 1
            elif command_byte == 0x56: #Pokémon picture code [xx]
                info = "Display a pokemon picture in a box by pokemon id [xx]"
                long_info = """
                #Opens a box and puts a Pokémon picture into it.
                #[55][xx]
                #xx:
                #    <>00 : Pokémon no
                #     =00 : Pokémon no gets read from RAM
                """
                size = 2
                command["byte"] = ord(rom[start_address+1])
            elif command_byte == 0x57: #Pokémon picture YES/NO code
                info = "?? Display a pokemon picture and a yes/no box"
                long_info = """
                #Displays a YES/NO box at X08/Y05.
                #feedback:
                #   00 = no chosen
                #   01 = yes chosen
                """
                size = 1
            elif command_byte == 0x58: #Menu interpreter 1
                info = "Menu interpreter 1 (see menu loader)"
                long_info = """
                #Interprets menu data loaded by 4F.
                #see also http://hax.iimarck.us/files/scriptingcodes_eng.htm#ZusatzDatA57
                """
                size = 1
            elif command_byte == 0x59: #Menu interpreter 2
                info = "Menu interpreter 2 (see menu loader)"
                long_info = """
                #Interprets menu data loaded by 4F.
                #see also http://hax.iimarck.us/files/scriptingcodes_eng.htm#Marke57
                #see also http://hax.iimarck.us/files/scriptingcodes_eng.htm#ZusatzDatA58
                """
                size = 1
            elif command_byte == 0x5A: #Load Pikachu data
                info = "Load pikachu data"
                long_info = "Loads 0x19 (Pikachu) to PokéRAM and level 5 to LevelRAM."
                size = 1
            elif command_byte == 0x5B: #Delete FightRAM/reset person check
                info = "? Disable fleeing from battle"
                long_info = """
                #Deletes the value in BattleRAM.
                #Turns off the check if the battle was started by entering
                #a trainer's area of view.
                """
                size = 1
            elif command_byte == 0x5C: #Load trainer data1
                info = "Load trainer from RAM"
                long_info = """
                #Loads trainer data when HIRO is in a trainer's range of sight.
                #Trainer group is read from CF2E and written to
                #TrRAM1, the trainer number is read from CF2F and written to
                #TrRAM2. 81 is written to BattleRAM.
                """
                size = 1
            elif command_byte == 0x5D: #Load Pokémon data [xxyy]
                info = "Loads pokemon by id and level for BattleRAM [xx][yy]"
                long_info = """
                #Loads Pokémon data. Writes 80 to BattleRAM.
                #[5C][Poke no][Level]
                """
                size = 3
                command["pokemon_id"] = ord(rom[start_address+1])
                command["pokemon_level"] = ord(rom[start_address+2])
            elif command_byte == 0x5E: #Load trainer data2 [xxyy]
                info = "Load trainer by group/id for BattleRAM [xx][yy]"
                long_info = """
                #Loads trainer data. Trainer group --> TrRAM1,
                #trainer number --> TrRAM2. Writes 81 to BattleRAM.
                #[5D][Trainer group][Trainer no]
                """
                size = 3
                command["trainer_group"] = ord(rom[start_address+1])
                command["trainer_id"] = ord(rom[start_address+2])
            elif command_byte == 0x5F: #Start battle
                info = "Start pre-configured battle"
                long_info = """
                #Starts trainer or Pokémon battle. BattleRAM: 80 = Poké battle; 81 = Trainer battle.
                #feedback:
                #   00 = win
                #   01 = lose
                """
                size = 1
            elif command_byte == 0x60: #Return to In game engine after battle
                info = "Return to in-game engine after battle"
                long_info = "Returns to ingame engine and evaluates battle. When lost then return to last Pokémon Center etc."
                size = 1
            elif command_byte == 0x61: #Learn how to catch PKMN [xx]
                info = "Pokemon catching tutorial [xx]"
                long_info = """
                #Starts a learn-how-to-catch battle with a Pokémon, whose data needs to be loaded beforehand
                #see http://hax.iimarck.us/files/scriptingcodes_eng.htm#Marke5C
                #Player has to have at least 1 Pokémon for it to work.
                #Items that are statically used: 1xPotion, 5xPoké ball.
                #[60][xx]
                #xx: Between 01 and 03. If <> 03 then HIRO sprite instead of dude sprite and kills
                #itself when using the item system.
                """
                size = 2
                command["byte"] = ord(rom[start_address+1])
            elif command_byte == 0x62: #Trainer text code
                info = "Set trainer text by id [xx]"
                long_info = """
                #Interprets the data of a in the event structure defined trainer.
                #[61][xx]
                #Xx decides which text to use.
                #xx: Between 00 and 03.
                #see http://hax.iimarck.us/files/scriptingcodes_eng.htm#Eventaufbau
                """
                size = 2
                command["byte"] = ord(rom[start_address+1])
            elif command_byte == 0x63: #Trainer status code [xx]
                info = "? Check trainer status [xx]"
                long_info = """
                #Checks/changes the status of a in the event structure defined trainer.
                #see http://hax.iimarck.us/files/scriptingcodes_eng.htm#Eventaufbau
                #[62][xx]
                #xx is:
                #   00 = deactivate
                #   01 = activate
                #   02 = check
                """
                size = 2
                command["byte"] = ord(rom[start_address+1])
            elif command_byte == 0x64: #Pointer Win/Lose [2b + 2b]
                info = "Set win/lose pointers for battle [xxyy][xxyy]"
                long_info = """
                #Writes the win/lose pointer of a battle into the ram.
                #[63][2byte pointer to text Win][2byte pointer to text Loss*]
                #* When pointer = 0000 then "Blackout" instead of return to gameplay.
                """
                size = 5
                command["won_pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
                command["lost_pointer"] = calculate_pointer_from_bytes_at(start_address+3, bank=False)
                command["text_won"] = parse_text_engine_script_at(command["won_pointer"], map_group=map_id, map_id=map_id, debug=debug)
                command["text_lost"] = parse_text_engine_script_at(command["lost_pointer"], map_group=map_id, map_id=map_id, debug=debug)
            elif command_byte == 0x65: #Script talk-after
                #XXX this is a really poor description of whatever this is
                info = "? Load the trainer talk-after script"
                long_info = """
                #Interprets which script is going to be run, when a in the event-structure-defined
                #trainer is talked to again.
                #see http://hax.iimarck.us/files/scriptingcodes_eng.htm#Eventaufbau
                #[64]
                """
                size = 1
            elif command_byte == 0x66: #Script talk-after-cancel
                info = "Disable/cancel trainer after-battle text"
                long_info = """
                #Cancels the talk-after script of the in the event-structure-defined
                #trainer when talk-after script is executed just after the battle.
                #[65]
                """
                size = 1
            elif command_byte == 0x67: #Script talk-after-check
                #XXX also bad explanation/name...
                info = "? Check if trainer talk-after script is executed just after battle or not"
                long_info = """
                #Checks if the talk-after script of the event structure defined trainer
                #is executed just after the battle or at a later point in time.
                #feedback:
                #   00 = no
                #   01 = yes
                #[66]
                """
                size = 1
            elif command_byte == 0x68: #Set talked-to person [xx]
                info = "Set last talked-to person [xx]"
                long_info = """
                #Sets the number of the last person talked to.
                #[67][person]
                """
                size = 2
                command["person_id"] = ord(rom[start_address+1])
            elif command_byte == 0x69: #Moving code [xx + 2b]
                info = "Move person (by id) with moving data (by pointer) [id][xxyy]"
                long_info = """
                #Moves the person using moving data.
                #[68][Person][2byte pointer to moving data]
                #see also http://hax.iimarck.us/files/scriptingcodes_eng.htm#ZusatzB68bis69
                """
                size = 4
                command["person_id"] = ord(rom[start_address+1])
                command["moving_data_pointer"] = calculate_pointer_from_bytes_at(start_address+2, bank=False)
            elif command_byte == 0x6A: #Moving code for talked-to person [2b]
                info = "Move talked-to person with moving data (by pointer) [xxyy]"
                long_info = """
                #Moves talked-to person using moving data.
                #[69][2byte pointer to moving data]
                """
                size = 3
                command["moving_data_pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
            elif command_byte == 0x6B: #Talk-to facing code
                info = "Move talked-to person's facing direction to HIRO"
                long_info = """
                #Turns the heads of the talked-to persons to HIRO.
                #[6A]
                """
                size = 1
            elif command_byte == 0x6C: #Facing of people code [xxyy]
                info = "Move facing direction of person1 to look at person2 [2][1]"
                long_info = """
                #Turns the head of person1 to another person2.
                #[6B][Person2][Person1]
                #Person2 = If number is greater than 0xFD, then use number of talked-to person.
                #Person1 = If number equals 0xFE, then take number of talked-to person.
                """
                size = 3
                command["person2_id"] = ord(rom[start_address+1])
                command["person1_id"] = ord(rom[start_address+2])
            elif command_byte == 0x6D: #Variable sprites [xxyy]
                info = "Store value in variable sprite RAM location x by id Y [xx][yy]"
                long_info = """
                #Writes a number to the variable sprite RAM from D555 to D564 (see Compendium on the sprite system).
                #[6C][xx][Sprite no]
                #xx: Number between 0x00 and 0x0F
                """
                size = 3
                command["number"] = ord(rom[start_address+1])
                command["sprite_id"] = ord(rom[start_address+2])
            elif command_byte == 0x6E: #Hide person [xx]
                info = "Hide person by id [xx]"
                long_info = """
                #Hides a person.
                #[6D][person id]
                """
                size = 2
                command["person_id"] = ord(rom[start_address+1])
            elif command_byte == 0x6F: #Show person [xx]
                info = "Show person by id [xx]"
                long_info = """
                #Shows a hidden person again.
                #[6E][person id]
                """
                size = 2
                command["person_id"] = ord(rom[start_address+1])
            elif command_byte == 0x70: #Following code1 [xxyy]
                info = "Following code1 [leader id][follower id]"
                long_info = """
                #A person1 follows another person2. The person1 that follows
                #just repeats the movement of person2, even if the persons are
                #not directly next to each other.
                #[6F][Leader Person2][Follower Person1]
                """
                size = 3
                command["leader_person_id"] = ord(rom[start_address+1])
                command["follower_person_id"] = ord(rom[start_address+2])
            elif command_byte == 0x71: #Stop following code
                info = "Stop all follow code"
                long_info = "Ends all current follow codes."
                size = 1
            elif command_byte == 0x72: #Move person [xxyyzz]
                info = "Move person by id to xy [id][xx][yy]"
                long_info = """
                #Sets the X/Y values of a person anew.
                #The person doesn't get shown immediately. Use hide&show.
                #[71][Person][X][Y]
                """
                size = 4
                command["person_id"] = ord(rom[start_address+1])
                command["x"] = ord(rom[start_address+2])
                command["y"] = ord(rom[start_address+3])
            elif command_byte == 0x73: #Write person location [xx] (lock person location?)
                info = "Lock person's location by id [id]"
                long_info = """
                #Writes the current X/Y values of a person into the ram.
                #The person is going to stand at its current location even when
                #it's out of HIRO's sight and is not going to return to its old
                #location until the next map load.
                #[72][person]
                """
                size = 2
                command["person_id"] = ord(rom[start_address+1])
            elif command_byte == 0x74: #Load emoticons [xx]
                info = "Load emoticon bubble [xx]"
                long_info = """
                #Loads the emoticon bubble depending on the given bubble number.
                #[73][bubble number]
                #xx: If xx = FF then take number from RAM.
                #  00 = Exclamation mark
                #  01 = Question mark
                #  02 = Happy
                #  03 = Sad
                #  04 = Heart
                #  05 = Flash
                #  06 = Snoring
                #  07 = Fish
                """
                size = 2
                command["bubble_number"] = ord(rom[start_address+1])
            elif command_byte == 0x75: #Display emoticon [xxyyzz]
                info = "Display emoticon by bubble id and person id and time [xx][yy][zz]"
                long_info = """
                #Displays the bubble above a persons head for the given time period.
                #Attention: Bubbles get loaded into ram!
                #[74][Bubble][Person][Time]
                #for bubble ids see 0x73
                """
                size = 4
                command["bubble_number"] = ord(rom[start_address+1])
                command["person_id"] = ord(rom[start_address+2])
                command["time"] = ord(rom[start_address+3])
            elif command_byte == 0x76: #Change facing [xxyy]
                info = "Set facing direction of person [person][facing]"
                long_info = """
                #Changes the facing direction of a person.
                #[75][person][facing]
                """
                size = 3
                command["person_id"] = ord(rom[start_address+1])
                command["facing"] = ord(rom[start_address+2])
            elif command_byte == 0x77: #Following code2 [xxyy]
                info = "Following code2 [leader id][follower id]"
                long_info = """
                #A person1 follows a person2. The following person1 automatically clings to person2.
                #Person1 just follows person2, but doesn't make the exact same movements at person2.
                #[76][Leader Person2][Follower Person1]
                """
                size = 3
                command["leader_person_id"] = ord(rom[start_address+1])
                command["follower_person_id"] = ord(rom[start_address+2])
            elif command_byte == 0x78: #Earth quake [xx]
                info = "Earthquake [xx]"
                long_info = """
                #The screen shakes. xx gives time as well as displacement of the screen.
                #[77][xx]
                """
                size = 2
                command["shake_byte"] = ord(rom[start_address+1])
            elif command_byte == 0x79: #Exchange map [3b]
                info = "Draw map data over current map [bank][pointer]"
                long_info = """
                #This code draws another whole map as wide and high as the
                #current map over the current map.
                #The 3byte pointer points to the new map.
                #[78][3byte pointer to new map data]
                """
                size = 4
                command["map_data_pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=True)
            elif command_byte == 0x7A: #Change block code [xxyyzz]
                info = "Change block to block id on map [xx][yy][id]"
                long_info = """
                #Changes a block on the current map by giving the new block
                #number and its X/Y values measured in half-blocks.
                #[79][X][Y][Block]
                """
                size = 4
                command["x"] = ord(rom[start_address+1])
                command["y"] = ord(rom[start_address+2])
                command["block"] = ord(rom[start_address+3])
            elif command_byte == 0x7B: #Reload map code
                info = "Reload/redisplay map"
                long_info = """
                #Reloads and re-displays the map completely.
                #Loads tileset and all map data anew. Screen gets light.
                #[7A]
                """
                size = 1
            elif command_byte == 0x7C: #Reload map part code
                info = "Reload/redisplay map portion occupied by HIRO"
                long_info = """
                #Reloads and re-displays the part of the map HIRO is on,
                #without reloading any other map data or the tileset.
                #[7B]
                """
                size = 1
            elif command_byte == 0x7D: #Write command queue
                info = "Write command queue [xxyy]"
                long_info = """
                #Writes a command queue to the next free slot in ram.
                #Max 4 command queues à 5 bytes. This code is buggy (bug fix: 25:7C74 --> 12).
                #[7C][2byte pointer to 5byte command queue]
                #see http://hax.iimarck.us/files/scriptingcodes_eng.htm#ZusatzDok25_7CC9
                """
                size = 3
                command["command_queue_pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
            elif command_byte == 0x7E: #Delete command queue
                info = "Delete command queue"
                long_info = """
                #Deletes a command queue and frees a slot in ram.
                #[7D][First command of the resp. queue]
                """
                #XXX wtf?
                size = 2
                command["first_command"] = ord(rom[start_address+1])
            elif command_byte == 0x7F: #Song code1 [xxyy]
                info = "Play music by number [xxyy]"
                long_info = """
                #Immediately plays the music.
                #[7E][Music no (2byte)]
                #Music no: See the music archive that should accompany
                #this document Thanks to Filb. He dumped all the songs
                #via gameboy player and gave them to me.
                """
                size = 3
                #XXX what is the format of this music data?
                command["music_number"] = rom_interval(start_address+1, size-1, strings=False)
            elif command_byte == 0x80: #Song code2
                info = "Song code2"
                long_info = """
                #Plays the music of the trainer group in TrRAM1.
                #Takes music numbers from list at 3A:5027.
                #[7F]
                """
                size = 1
            elif command_byte == 0x81: #Music fade-out code [xxyy][zz]
                info = "Music fade-out then play next [xxyy][time]"
                long_info = """
                #The current music is faded out and the new music is played afterwards.
                #[80][Music no (2byte)][Time to fade out (00-7F)]
                """
                size = 4
                command["music_number"] = rom_interval(start_address+1, 2, strings=False)
                command["fade_time"] = ord(rom[start_address+3])
            elif command_byte == 0x82: #Play map music code
                info = "Play map's music"
                long_info = """
                #Starts playing the original map music.
                #Includes special check for surfer and bug contest song.
                #[81]
                """
                size = 1
            elif command_byte == 0x83: #Map reload music code
                info = "Reload map music"
                long_info = """
                #After a map reload no music is played.
                #[82]
                """
                size = 1
            elif command_byte == 0x84: #Cry code [xx00]
                info = "Play cry by id or RAM [cry][00]"
                long_info = """
                #Plays the Pokémon's cry.
                #[83][Cry no][00]
                #If the cry no = 00 then the number is taken from RAM.
                """
                size = 3
                command["cry_number"] = ord(rom[start_address+1])
                command["other_byte"] = ord(rom[start_address+2])
            elif command_byte == 0x85: #Sound code [xxyy]
                info = "Play sound by sound number [xxyy]"
                long_info = """
                #Plays the sound.
                #[84][Sound no (2byte)]
                #Sound no: See the music archive that should accompany this document
                #Thanks to philb for this matter. He helped me to record a big
                #part of these sounds.
                """
                size = 3
                command["sound_number"] = rom_interval(start_address+1, 2, strings=False)
            elif command_byte == 0x86: #Key-down code
                info = "Wait for key-down"
                long_info = """
                #Waits for the Player to press a button.
                #[85]
                """
                size = 1
            elif command_byte == 0x87: #Warp sound
                info = "Warp sound"
                long_info = """
                #Evaluates which sound is played when HIRO enters a Warp field.
                #Usage via script ingame is rather not useful.
                #[86]
                """
                size = 1
            elif command_byte == 0x88: #Special sound
                info = "Special sound if TM was last checked"
                long_info = """
                #When last given/checked Item was a TM then it plays sound 0x9B. If not, then 0x01.
                #[87]
                """
                size = 1
            elif command_byte == 0x89: #Engine remote control [2b]
                info = "Engine remote control [bb][xxyy]"
                long_info = """
                #This code controls the engine via "data stream".
                #[88][3byte pointer to control structure]
                #see http://hax.iimarck.us/files/scriptingcodes_eng.htm#ZusatzDatA88
                """
                size = 4
                command["data_stream_pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=True)
            elif command_byte == 0x8A: #Load map anew [xx]
                info = "Load map with specific loading process [xx]"
                long_info = """
                #The number decides which map loading process is used.
                #The number must be 0xF0 + process number to work correctly.
                #[89][Number]
                #see map loading process:
                #   http://hax.iimarck.us/files/scriptingcodes_eng.htm#ZusatzDok5_5550
                """
                size = 2
                command["number"] = ord(rom[start_address+1])
            elif command_byte == 0x8B: #Waiting code [xx]
                info = "Wait code"
                long_info = """
                #This code lets the game wait for 2 * xx time intervals.
                #[8A][xx]
                #xx: Numbers from 0x01 to 0xFF.
                #If 0x00 is chosen then the time can be manipulated by previously loading a number to RAM2.
                """
                size = 2
                command["time"] = ord(rom[start_address+1])
            elif command_byte == 0x8C: #Deactivate static facing [xx]
                info = "Deactive static facing after time [xx]"
                long_info = """
                #Deactivates static facings on all persons on the screen after a time xx.
                #[8B][xx]
                """
                size = 2
                command["time"] = ord(rom[start_address+1])
            elif command_byte == 0x8D: #Priority jump1 [2b]
                info = "Priority jump to script by pointer [xxyy]"
                long_info = """
                #The pointer acts like code 00, but with this higher
                #functions like the bike etc. are not paid attention to,
                #while the script is running.
                #[8C][2byte pointer to script]
                """
                size = 3
                script_pointer = calculate_pointer_from_bytes_at(start_address+1, bank=False)
                if debug:
                    print "in script starting at "+hex(original_start_address)+\
                      " about to parse script at "+hex(script_pointer)+\
                      " called by "+info+" byte="+hex(command_byte)
                script = rec_parse_script_engine_script_at(script_pointer, original_start_address, debug=debug)
                command["script_pointer"] = script_pointer
                command["script"] = script
                end = True #according to pksv
            elif command_byte == 0x8E: #Warp check
                info = "Reactive all engine checks if player is warping"
                long_info = """
                #If HIRO is entering or leaving a warp then this code reactivates all the engine-checks.
                #[8D]
                """
                size = 1
            elif command_byte == 0x8F: #Priority jump2 [2b]
                info = "Priority jump to script by pointer (after 1st cycle) [xxyy]"
                long_info = """
                #The pointer acts like code 03, but with this code all
                #higher functions wait for a cycle before the script gets interpreted.
                #[8E][2byte pointer to script]
                """
                size = 3
                script_pointer = calculate_pointer_from_bytes_at(start_address+1, bank=False)
                if debug:
                    print "in script starting at "+hex(original_start_address)+\
                      " about to parse script at "+hex(script_pointer)+\
                      " called by "+info+" byte="+hex(command_byte)
                script = rec_parse_script_engine_script_at(script_pointer, original_start_address, debug=debug)
                command["script_pointer"] = script_pointer
                command["script"] = script
                end = True #according to pksv
            elif command_byte == 0x90: #Return code1
                info = "Return code 1"
                long_info = """
                #Ends the current script and loads the backup offset for "linked"
                #scripts if applicable. The sophisticated functions are not affected
                #and run like before the code. This code is mostly used for scripts
                #called by the 2nd part of the script header, because else malfunctions
                #occur.
                #[8F]
                """
                size = 1
                end = True
            elif command_byte == 0x91: #Return code2
                info = "Return code 2"
                long_info = """
                #Ends the current script and loads the backup offset for "linked"
                #scripts if applicable.  The sophisticated functions get reset if
                #no backup offset was loaded. This code is used to end most scripts.
                #[90]
                """
                size = 1
                end = True
            elif command_byte == 0x92: #Return code3
                info = "Return code 3"
                long_info = """
                #Reloads the map completely like the code 0x7A
                #and else acts completely like Return code2
                #[91]
                #see reload map code
                #   http://hax.iimarck.us/files/scriptingcodes_eng.htm#Marke7A
                #see 0x90
                """
                size = 1
                #XXX does this end the script?? "else acts like 0x90"
                #       else? what's the "if"?
                end = True
            elif command_byte == 0x93: #Reset sophisticated functions
                info = "Reset sophisticated functions"
                long_info = """
                #Resets all sophisticated functions to 0.
                #[92]
                """
                size = 1
            elif command_byte == 0x94: #Mart menu [xxyyzz]
                info = "Mart menu [dialog no][mart no 2b]"
                long_info = """
                #Displays a whole mart menu, however, doesn't load font to ram.
                #[93][Dialog no][Mart no (2byte)]
                #see http://hax.iimarck.us/files/scriptingcodes_eng.htm#AwBsp93
                #see http://hax.iimarck.us/files/scriptingcodes_eng.htm#ZusatzB93
                """
                size = 4
                command["dialog_number"] = ord(rom[start_address+1])
                command["mart_number"] = rom_interval(start_address+2, 2, strings=False)
            elif command_byte == 0x95: #Elevator menu [2b]
                info = "Display elevator menu by pointer [xxyy]"
                long_info = """
                #Displays a whole elevator menu, but it doesn't load font to ram.
                #Only works with warps with warp-to = 0xFF.
                #[94][2byte pointer to floor list]
                """
                size = 3
                command["floor_list_pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
            elif command_byte == 0x96: #Trade menu [xx]
                info = "Display trade menu by trade id [xx]"
                long_info = """
                #Displays a whole trade menu, but it doesn't load font to ram.
                #[95][trade no]
                #see http://hax.iimarck.us/files/scriptingcodes_eng.htm#ZusatzDokTausch
                """
                size = 2
                command["trade_number"] = ord(rom[start_address+1])
            elif command_byte == 0x97: #Give cell phone number with YES/NO [xx]
                info = "Give cell phone number by id with YES/NO [id]"
                long_info = """
                #Gives a telephone number but asks for decision beforehand.
                #feedback:
                #   00 = ok chosen
                #   01 = Cell phone number already registered/Memory full
                #   02 = no chosen
                #[96][Cell phone number]
                """
                size = 2
                #maybe this next param should be called "phone_number"
                command["number"] = ord(rom[start_address+1])
            elif command_byte == 0x98: #Call code [2b]
                info = "Call code pointing to name of caller [xxyy]"
                long_info = """
                #Displays the upper cell phone box and displays a freely selectable name.
                #[97][2byte pointer to name of caller]
                """
                size = 3
                command["caller_name_pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank=False)
            elif command_byte == 0x99: #Hang-up code
                info = "Hang-up phone"
                long_info = """
                #Simulates the hanging-up.
                #[98]
                """
                size = 1
            elif command_byte == 0x9A: #Decoration code [xx]
                info = "Set monologue decoration [xx]"
                long_info = """
                #Displays monologues according to the selected ornament.
                #[99][xx]
                #xx values:
                #  00 = Map/Poster
                #  01 = Ornament left
                #  02 = Ornament right
                #  03 = Huge doll
                #  04 = Console
                """
                size = 2
                command["ornament"] = ord(rom[start_address+1])
            elif command_byte == 0x9B: #Berry tree code [xx]
                info = "Berry tree by tree id [xx]"
                long_info = """
                #Creates a typical berry tree monologue.
                #There is a maximum of 32 berry trees in the game.
                #After this code the script ends.
                #[9A][Fruit tree number]
                #Fruit tree number + 11:4091 is the offset where the item no of the berry is defined.
                """
                size = 2
                end = True
                command["tree_id"] = ord(rom[start_address+1])
            elif command_byte == 0x9C: #Cell phone call code [xx00]
                #XXX confirm this?
                info = "Cell phone call [2-byte call id]" #was originally: [call id][00]
                long_info = """
                #Initiates with the next step on a outer world map (permission byte) a phone call.
                #[9B][Call no] and maybe [00] ???
                #call no:
                #  01 = PokéRus
                #  02 = Pokémon stolen
                #  03 = Egg examined/ Assistant in Viola City
                #  04 = Team Rocket on the radio
                #  05 = PROF. ELM has got something for HIRO
                #  06 = Bike shop gives bike away
                #  07 = Mother is unhappy that HIRO didn't talk to her before leaving
                #  08 = PROF. ELM has got something for HIRO a second time
                """
                size = 3
                command["call_id"] = ord(rom[start_address+1])
                command["id"] = rom_interval(start_address+2, 2, strings=False)
            elif command_byte == 0x9D: #Check cell phone call code
                info = "Check if/which a phone call is active"
                long_info = """
                #Checks if a phone call is "in the line".
                #feedback:
                #   00 = no
                # <>00 = call number
                #[9C]
                """
                size = 1
            elif command_byte == 0x9E: #Commented give item code [xxyy]
                info = "Give item by id and quantity with 'put in pocket' text [id][qty]"
                long_info = """
                #The same as 0x1F but this code comments where
                #HIRO puts what item in a short monologue.
                #[9D][Item][Amount]
                """
                size = 3
                command["item_id"] = ord(rom[start_address+1])
                command["quantity"] = ord(rom[start_address+2])
            elif command_byte == 0x9F: #Commented ive item code?
                info = "Give item by id and quantity with 'put in pocket' text [id][qty]"
                long_info = """
                #The same as 0x1F but this code comments where
                #HIRO puts what item in a short monologue.
                #[9D][Item][Amount]
                """
                size = 3
                command["item_id"] = ord(rom[start_address+1])
                command["quantity"] = ord(rom[start_address+2])
            elif command_byte == 0xA0: #Load special wild PKMN data [xxyy]
                info = "Load wild pokemon data for a remote map [map group][map id]"
                long_info = """
                #Activates the checks in the special tables for the wild pokémon data.
                #[9E][map group][map id]
                #see also http://hax.iimarck.us/files/scriptingcodes_eng.htm#ZusatzDok3E_66ED
                """
                size = 3
                command["map_group"] = ord(rom[start_address+1])
                command["map_id"] = ord(rom[start_address+2])
            elif command_byte == 0xA1: #Hall of Fame code
                info = "Hall of Fame"
                long_info = """
                #Saves and enters HIRO's complete Team in the Hall of Fame.
                #Shows the credits and restarts the game with HIRO located in New Bark Town.
                #[9F]
                """
                size = 1
            elif command_byte == 0xA2: #Credits code
                info = "Credits"
                long_info = """
                #Shows the credits and HIRO is located on the Silver mountain plateau.
                #[A0]
                """
                size = 1
            elif command_byte == 0xA3: #Facing warp
                info = "Warp-to and set facing direction [Facing (00-03)][Map bank][Map no][X][Y]"
                long_info = """
                #Acts like code 0x3C but defines the desired facing of HIRO.
                #[A1][Facing (00-03)][Map bank][Map no][X][Y]
                """
                size = 6
                command["facing"] = ord(rom[start_address+1])
                command["map_group"] = ord(rom[start_address+2])
                command["map_id"] = ord(rom[start_address+3])
                command["x"] = ord(rom[start_address+4])
                command["y"] = ord(rom[start_address+5])
            elif command_byte == 0xA4: #MEMORY code [2b + Bank + xx]
                info = "Set memX to a string by a pointer [aabb][bank][xx]"
                long_info = """
                #MEMORY1, 2 or 3 can directly be filled with a string from
                #a different rom bank.
                #[A2][2byte pointer][Bank][00-02 MEMORY]
                """
                size = 5
                command["string_pointer"] = calculate_pointer_from_bytes_at(start_address+1, bank="reversed")
                command["string_pointer_bank"] = ord(rom[start_address+3])
                command["memory_id"] = ord(rom[start_address+4])
            elif command_byte == 0xA5: #Display any location name [xx]
                info = "Copy the name of a location (by id) to TEMPMEMORY1"
                long_info = """
                #By the location number the name of that location is written to TEMPMEMORY1.
                #[A3][Location no]
                """
                size = 2
                command["location_number"] = ord(rom[start_address+1])
            else:
                size = 1
                #end = True
                #raise NotImplementedError, "command byte is " + hex(command_byte) + " at " + hex(offset) + " on map " + str(map_group) + "." + str(map_id)
                print "dunno what this command is: " + hex(command_byte)
            long_info = clean_up_long_info(long_info)
            
            if command_byte in pksv_crystal.keys():
                pksv_name = pksv_crystal[command_byte]
            else:
                pksv_name = None
                if command_byte in pksv_no_names.keys():
                    pksv_no_names[command_byte].append(address)
                else:
                    pksv_no_names[command_byte] = [address]
    
            if debug:
                print command_debug_information(command_byte=command_byte, map_group=map_group, map_id=map_id, address=offset, info=info, long_info=long_info, pksv_name=pksv_name)
            
            #store the size of the command
            command["size"] = size
            #the end address is just offset + size - 1 (because size includes command byte)
            offset += size - 1
            #the end address is the last byte belonging to this command
            command["last_byte_address"] = offset
            #we also add the size of the command byte to get to the next command
            offset += 1
            #add the command into the command list please
            commands[len(commands.keys())] = command
    
        self.commands = commands
        script_parse_table[original_start_address : offset-1] = self
        return True
def parse_script_engine_script_at(address, map_group=None, map_id=None, force=False, debug=True, origin=True):
    if is_script_already_parsed_at(address) and not force:
        return script_parse_table[address]
    return Script(address, map_group=map_group, map_id=map_id, force=force, debug=debug, origin=origin)

def parse_warp_bytes(some_bytes, debug=True):
    """parse some number of warps from the data"""
    assert len(some_bytes) % warp_byte_size == 0, "wrong number of bytes"
    warps = []
    for bytes in grouper(some_bytes, count=warp_byte_size):
        y = int(bytes[0], 16)
        x = int(bytes[1], 16)
        warp_to = int(bytes[2], 16)
        map_group = int(bytes[3], 16)
        map_id = int(bytes[4], 16)
        warps.append({
            "y": y,
            "x": x,
            "warp_to": warp_to,
            "map_group": map_group,
            "map_id": map_id,
        })
    return warps
def parse_xy_trigger_bytes(some_bytes, bank=None, map_group=None, map_id=None, debug=True):
    """parse some number of triggers from the data"""
    assert len(some_bytes) % trigger_byte_size == 0, "wrong number of bytes"
    triggers = []
    for bytes in grouper(some_bytes, count=trigger_byte_size):
        trigger_number = int(bytes[0], 16)
        y = int(bytes[1], 16)
        x = int(bytes[2], 16)
        unknown1 = int(bytes[3], 16) #XXX probably 00?
        script_ptr_byte1 = int(bytes[4], 16)
        script_ptr_byte2 = int(bytes[5], 16)
        script_ptr = script_ptr_byte1 + (script_ptr_byte2 << 8)
        script_address = None
        script = None
        if bank:
            script_address = calculate_pointer(script_ptr, bank)
            print "******* parsing xy trigger byte scripts... x=" + str(x) + " y=" + str(y)
            script = parse_script_engine_script_at(script_address, map_group=map_group, map_id=map_id)
        
        triggers.append({
            "trigger_number": trigger_number,
            "y": y,
            "x": x,
            "unknown1": unknown1, #probably 00
            "script_ptr": script_ptr,
            "script_pointer": {"1": script_ptr_byte1, "2": script_ptr_byte2},
            "script_address": script_address,
            "script": script,
        })
    return triggers
def parse_signpost_bytes(some_bytes, bank=None, map_group=None, map_id=None, debug=True):
    """parse some number of signposts from the data

    [Y position][X position][Function][Script pointer (2byte)]

    functions:
        00      Sign can be read from all directions
                script pointer to: script
        01      Sign can only be read from below
                script pointer to: script
        02      Sign can only be read from above
                script pointer to: script
        03      Sign can only be read from right
                script pointer to: script
        04      Sign can only be read from left
                script pointer to: script
        05      If bit of BitTable1 is set then pointer is interpreted
                script pointer to: [Bit-Nr. (2byte)][2byte pointer to script]
        06      If bit of BitTable1 is not set then pointer is interpreted
                script pointer to: [Bit-Nr. (2byte)][2byte pointer to script]
        07      If bit of BitTable1 is set then item is given
                script pointer to: [Bit-Nr. (2byte)][Item no.]
        08      No Action
                script pointer to: [Bit-Nr. (2byte)][??]
    """
    assert len(some_bytes) % signpost_byte_size == 0, "wrong number of bytes"
    signposts = []
    for bytes in grouper(some_bytes, count=signpost_byte_size):
        y = int(bytes[0], 16)
        x = int(bytes[1], 16)
        func = int(bytes[2], 16)

        additional = {}
        if func in [0, 1, 2, 3, 4]:
            print "******* parsing signpost script.. signpost is at: x=" + str(x) + " y=" + str(y)
            script_ptr_byte1 = int(bytes[3], 16)
            script_ptr_byte2 = int(bytes[4], 16)
            script_pointer = script_ptr_byte1 + (script_ptr_byte2 << 8)
        
            script_address = None
            script = None
        
            script_address = calculate_pointer(script_pointer, bank)
            script = parse_script_engine_script_at(script_address, map_group=map_group, map_id=map_id)

            additional = {
            "script_ptr": script_pointer,
            "script_pointer": {"1": script_ptr_byte1, "2": script_ptr_byte2},
            "script_address": script_address,
            "script": script,
            }
        elif func in [5, 6]:
            print "******* parsing signpost script.. signpost is at: x=" + str(x) + " y=" + str(y)
            ptr_byte1 = int(bytes[3], 16)
            ptr_byte2 = int(bytes[4], 16)
            pointer = ptr_byte1 + (ptr_byte2 << 8)
            address = calculate_pointer(pointer, bank)
            bit_table_byte1 = ord(rom[address])
            bit_table_byte2 = ord(rom[address+1])
            script_ptr_byte1 = ord(rom[address+2])
            script_ptr_byte2 = ord(rom[address+3])
            script_address = calculate_pointer_from_bytes_at(address+2, bank=bank)
            script = parse_script_engine_script_at(script_address, map_group=map_group, map_id=map_id)
            
            additional = {
            "bit_table_bytes": {"1": bit_table_byte1, "2": bit_table_byte2},
            "script_ptr": script_ptr_byte1 + (script_ptr_byte2 << 8),
            "script_pointer": {"1": script_ptr_byte1, "2": script_ptr_byte2},
            "script_address": script_address,
            "script": script,
            }
        else:
            print ".. type 7 or 8 signpost not parsed yet."
        
        spost = {
            "y": y,
            "x": x,
            "func": func,
        }
        spost.update(additional)
        signposts.append(spost)
    return signposts
def parse_trainer_header_at(address, map_group=None, map_id=None, debug=True):
    """
    [Bit no. (2byte)][Trainer group][Trainer]
    [2byte pointer to Text when seen]
    [2byte pointer to text when trainer beaten]
    [2byte pointer to script when lost (0000=Blackout)]
    [2byte pointer to script if won/talked to again]
     
    The bit number tell the game later on if the trainer has been
    beaten already (bit = 1) or not (bit = 0). All Bit number of BitTable1.
     
    03 = Nothing
    04 = Nothing
    05 = Nothing
    06 = Nothing
    """
    bank = calculate_bank(address)
    bytes = rom_interval(address, 12, strings=False)
    bit_number = bytes[0] + (bytes[1] << 8)
    trainer_group = bytes[2]
    trainer_id = bytes[3]
    text_when_seen_ptr = calculate_pointer_from_bytes_at(address+4, bank=bank)
    text_when_seen = parse_text_engine_script_at(text_when_seen_ptr, map_group=map_group, map_id=map_id, debug=debug)
    text_when_trainer_beaten_ptr = calculate_pointer_from_bytes_at(address+6, bank=bank)
    text_when_trainer_beaten = parse_text_engine_script_at(text_when_trainer_beaten_ptr, map_group=map_group, map_id=map_id, debug=debug)

    if [ord(rom[address+8]), ord(rom[address+9])] == [0, 0]:
        script_when_lost_ptr = 0
        script_when_lost = None
    else:
        print "parsing script-when-lost"
        script_when_lost_ptr = calculate_pointer_from_bytes_at(address+8, bank=bank)
        script_when_lost = None
        silver_avoids = [0xfa53]
        if script_when_lost_ptr > 0x4000 and not script_when_lost_ptr in silver_avoids:
            script_when_lost = parse_script_engine_script_at(script_when_lost_ptr, map_group=map_group, map_id=map_id, debug=debug)
    
    print "parsing script-talk-again" #or is this a text?
    script_talk_again_ptr = calculate_pointer_from_bytes_at(address+10, bank=bank)
    script_talk_again = None
    if script_talk_again_ptr > 0x4000:
        script_talk_again = parse_script_engine_script_at(script_talk_again_ptr, map_group=map_group, map_id=map_id, debug=debug)
    
    return {
        "bit_number": bit_number,
        "trainer_group": trainer_group,
        "trainer_id": trainer_id,
        "text_when_seen_ptr": text_when_seen_ptr,
        "text_when_seen": text_when_seen,
        "text_when_trainer_beaten_ptr": text_when_trainer_beaten_ptr,
        "text_when_trainer_beaten": text_when_trainer_beaten,
        "script_when_lost_ptr": script_when_lost_ptr,
        "script_when_lost": script_when_lost,
        "script_talk_again_ptr": script_talk_again_ptr,
        "script_talk_again": script_talk_again,
    }
    
def parse_people_event_bytes(some_bytes, address=None, map_group=None, map_id=None, debug=True): #max of 14 people per map?
    """parse some number of people-events from the data
    see http://hax.iimarck.us/files/scriptingcodes_eng.htm#Scripthdr

    For example, map 1.1 (group 1 map 1) has four person-events.
    
        37 05 07 06 00 FF FF 00 00 02 40 FF FF
        3B 08 0C 05 01 FF FF 00 00 05 40 FF FF
        3A 07 06 06 00 FF FF A0 00 08 40 FF FF
        29 05 0B 06 00 FF FF 00 00 0B 40 FF FF
    """
    assert len(some_bytes) % people_event_byte_size == 0, "wrong number of bytes"

    #address is not actually required for this function to work...
    bank = None
    if address:
        bank = calculate_bank(address)

    people_events = []
    for bytes in grouper(some_bytes, count=people_event_byte_size):
        pict = int(bytes[0], 16)
        y = int(bytes[1], 16)    #y from top + 4
        x = int(bytes[2], 16)    #x from left + 4
        face = int(bytes[3], 16) #0-4 for regular, 6-9 for static facing
        move = int(bytes[4], 16)
        clock_time_byte1 = int(bytes[5], 16)
        clock_time_byte2 = int(bytes[6], 16)
        color_function_byte = int(bytes[7], 16) #Color|Function
        trainer_sight_range = int(bytes[8], 16)
        
        lower_bits = color_function_byte & 0xF
        #lower_bits_high = lower_bits >> 2
        #lower_bits_low = lower_bits & 3
        higher_bits = color_function_byte >> 4
        #higher_bits_high = higher_bits >> 2
        #higher_bits_low = higher_bits & 3

        is_regular_script = lower_bits == 00
        #pointer points to script
        is_give_item = lower_bits == 01
        #pointer points to [Item no.][Amount]
        is_trainer = lower_bits == 02
        #pointer points to trainer header

        #goldmap called these next two bytes "text_block" and "text_bank"?
        script_pointer_byte1 = int(bytes[9], 16)
        script_pointer_byte2 = int(bytes[10], 16)
        script_pointer = script_pointer_byte1 + (script_pointer_byte2 << 8)
        #calculate the full address by assuming it's in the current bank
        #but what if it's not in the same bank?
        extra_portion = {}
        if bank:
            ptr_address = calculate_pointer(script_pointer, bank)
            if is_regular_script:
                print "parsing a person-script at x=" + str(x-4) + " y=" + str(y-4) + " address="+hex(ptr_address)
                script = parse_script_engine_script_at(ptr_address, map_group=map_group, map_id=map_id)
                extra_portion = {
                    "script_address": ptr_address,
                    "script": script,
                    "event_type": "script",
                }
            if is_give_item:
                print "... not parsing give item event... [item id][quantity]"
                extra_portion = {
                    "event_type": "give_item",
                    "give_item_data_address": ptr_address,
                    "item_id": ord(rom[ptr_address]),
                    "item_qty": ord(rom[ptr_address+1]),
                }
            if is_trainer:
                print "parsing a trainer (person-event) at x=" + str(x) + " y=" + str(y)
                parsed_trainer = parse_trainer_header_at(ptr_address, map_group=map_group, map_id=map_id)
                extra_portion = {
                    "event_type": "trainer",
                    "trainer_data_address": ptr_address,
                    "trainer_data": parsed_trainer,
                }
        
        #XXX not sure what's going on here
        #bit no. of bit table 1 (hidden if set)
        #note: FFFF for none
        when_byte = int(bytes[11], 16)
        hide = int(bytes[12], 16)

        bit_number_of_bit_table1_byte2 = int(bytes[11], 16)
        bit_number_of_bit_table1_byte1 = int(bytes[12], 16)
        bit_number_of_bit_table1 = bit_number_of_bit_table1_byte1 + (bit_number_of_bit_table1_byte2 << 8)

        people_event = {
            "pict": pict,
            "y": y,                      #y from top + 4
            "x": x,                      #x from left + 4
            "face": face,                #0-4 for regular, 6-9 for static facing
            "move": move,
            "clock_time": {"1": clock_time_byte1,
                           "2": clock_time_byte2},       #clock/time setting byte 1
            "color_function_byte": color_function_byte,  #Color|Function
            "trainer_sight_range": trainer_sight_range,  #trainer range of sight
            "script_pointer": {"1": script_pointer_byte1,
                               "2": script_pointer_byte2},

            #"text_block": text_block,   #script pointer byte 1
            #"text_bank": text_bank,     #script pointer byte 2
            "when_byte": when_byte,      #bit no. of bit table 1 (hidden if set)
            "hide": hide,                #note: FFFF for none

            "is_trainer": is_trainer,
            "is_regular_script": is_regular_script,
            "is_give_item": is_give_item,
        }
        people_event.update(extra_portion)
        people_events.append(people_event)
    return people_events

class MapEventElement():
    def __init__(self, *args, **kwargs):
        if len(args) == 1:
            if isinstance(args[0], list):
                if len(args[0]) != self.__class__.standard_size:
                    raise "input has the wrong size"
                #convert all of the list elements to integers
                ints = []
                for byte in args[0]:
                    ints.append(int(byte, 16))
                #parse using the class default method
                events = self.__class__.parse_func(ints)
                for key, value in events[0]:
                    setattr(self, key, value)
            else:
                raise "dunno how to handle this positional input"
        elif len(kwargs.keys()) != 0:
            for key, value in kwargs.items():
                setattr(self, key, value)
        else:
            raise "dunno how to handle given input"
class Warp(MapEventElement):
    standard_size = warp_byte_size
    parse_func    = parse_warp_bytes
class Trigger(MapEventElement):
    standard_size = trigger_byte_size
    parse_func    = parse_xy_trigger_bytes
class Signpost(MapEventElement):
    standard_size = signpost_byte_size
    parse_func    = parse_signpost_bytes
class PeopleEvent(MapEventElement):
    standard_size = people_event_byte_size
    parse_func    = parse_people_event_bytes

def parse_map_header_at(address, map_group=None, map_id=None, debug=True):
    """parses an arbitrary map header at some address"""
    print "parsing a map header at: " + hex(address)
    bytes = rom_interval(address, map_header_byte_size, strings=False, debug=debug)
    bank = bytes[0]
    tileset = bytes[1]
    permission = bytes[2]
    second_map_header_address = calculate_pointer(bytes[3] + (bytes[4] << 8), 0x25)
    location_on_world_map = bytes[5] #pokégear world map location
    music = bytes[6]
    time_of_day = bytes[7]
    fishing_group = bytes[8]

    map_header = {
        "bank": bank,
        "tileset": tileset,
        "permission": permission, #map type?
        "second_map_header_pointer": {"1": bytes[3], "2": bytes[4]},
        "second_map_header_address": second_map_header_address,
        "location_on_world_map": location_on_world_map, #area
        "music": music,
        "time_of_day": time_of_day,
        "fishing": fishing_group,
    }
    print "second map header address is: " + hex(second_map_header_address)
    map_header.update(parse_second_map_header_at(second_map_header_address, debug=debug))
    map_header.update(parse_map_event_header_at(map_header["event_address"], map_group=map_group, map_id=map_id, debug=debug))
    #maybe this next one should be under the "scripts" key?
    map_header.update(parse_map_script_header_at(map_header["script_address"], map_group=map_group, map_id=map_id, debug=debug))
    return map_header

def parse_second_map_header_at(address, map_group=None, map_id=None, debug=True):
    """each map has a second map header"""
    bytes = rom_interval(address, second_map_header_byte_size, strings=False)
    border_block = bytes[0]
    height = bytes[1]
    width = bytes[2]
    blockdata_bank = bytes[3]
    blockdata_pointer = bytes[4] + (bytes[5] << 8)
    blockdata_address = calculate_pointer(blockdata_pointer, blockdata_bank)
    script_bank = bytes[6]
    script_pointer = bytes[7] + (bytes[8] << 8)
    script_address = calculate_pointer(script_pointer, script_bank)
    event_bank = script_bank
    event_pointer = bytes[9] + (bytes[10] << 8)
    event_address = calculate_pointer(event_pointer, event_bank)
    connections = bytes[11]
    return {
        "border_block": border_block,
        "height": height,
        "width": width,
        "blockdata_bank": blockdata_bank,
        "blockdata_pointer": {"1": bytes[4], "2": bytes[5]},
        "blockdata_address": blockdata_address,
        "script_bank": script_bank,
        "script_pointer": {"1": bytes[7], "2": bytes[8]},
        "script_address": script_address,
        "event_bank": event_bank,
        "event_pointer": {"1": bytes[9], "2": bytes[10]},
        "event_address": event_address,
        "connections": connections,
    }

def parse_map_event_header_at(address, map_group=None, map_id=None, debug=True):
    """parse crystal map event header byte structure thing"""
    returnable = {}

    bank = calculate_bank(address)

    print "event header address is: " + hex(address)
    filler1 = ord(rom[address])
    filler2 = ord(rom[address+1])
    returnable.update({"1": filler1, "2": filler2})
    
    #warps
    warp_count = ord(rom[address+2])
    warp_byte_count = warp_byte_size * warp_count
    warps = rom_interval(address+3, warp_byte_count)
    after_warps = address + 3 + warp_byte_count
    returnable.update({"warp_count": warp_count, "warps": parse_warp_bytes(warps)})
    
    #triggers (based on xy location)
    trigger_count = ord(rom[after_warps])
    trigger_byte_count = trigger_byte_size * trigger_count
    triggers = rom_interval(after_warps+1, trigger_byte_count)
    after_triggers = after_warps + 1 + trigger_byte_count
    returnable.update({"xy_trigger_count": trigger_count, "xy_triggers": parse_xy_trigger_bytes(triggers, bank=bank, map_group=map_group, map_id=map_id)})
    
    #signposts
    signpost_count = ord(rom[after_triggers])
    signpost_byte_count = signpost_byte_size * signpost_count
    signposts = rom_interval(after_triggers+1, signpost_byte_count)
    after_signposts = after_triggers + 1 + signpost_byte_count
    returnable.update({"signpost_count": signpost_count, "signposts": parse_signpost_bytes(signposts, bank=bank, map_group=map_group, map_id=map_id)})
  
    #people events
    people_event_count = ord(rom[after_signposts])
    people_event_byte_count = people_event_byte_size * people_event_count
    people_events_bytes = rom_interval(after_signposts+1, people_event_byte_count)
    people_events = parse_people_event_bytes(people_events_bytes, address=after_signposts+1, map_group=map_group, map_id=map_id)
    returnable.update({"people_event_count": people_event_count, "people_events": people_events})

    return returnable

def parse_map_script_header_at(address, map_group=None, map_id=None, debug=True):
    """parses a script header
    
    This structure allows the game to have e.g. one-time only events on a map
    or first enter events or permanent changes to the map or permanent script
    calls.

    This header a combination of a trigger script section and a callback script
    section. I don't know if these 'trigger scripts' are the same as the others
    referenced in the map event header, so this might need to be renamed very
    soon.

    trigger scripts: 
    [[Number1 of pointers] Number1 * [2byte pointer to script][00][00]]

    callback scripts:
    [[Number2 of pointers] Number2 * [hook number][2byte pointer to script]]

    hook byte choices:
        01 - map data has already been loaded to ram, tileset and sprites still missing
            map change (3rd step)
            loading (2nd step)
            map connection (3rd step)
            after battle (1st step)
        02 - map data, tileset and sprites are all loaded
            map change (5th step)
        03 - neither map data not tilesets nor sprites are loaded
            map change (2nd step)
            loading (1st step)
            map connection (2nd step)
        04 - map data and tileset loaded, sprites still missing
            map change (4th step)
            loading (3rd step)
            sprite reload (1st step)
            map connection (4th step)
            after battle (2nd step)
        05 - neither map data not tilesets nor sprites are loaded
            map change (1st step)
            map connection (1st step)

    When certain events occur, the call backs will be called in this order (same info as above):
        map change:
            05, 03, 01, 04, 02
        loading:
            03, 01, 04
        sprite reload:
            04
        map connection:
            05, 03, 01, 04 note that #2 is not called (unlike "map change")
        after battle:
            01, 04
    """
    print "starting to parse the map's script header.."
    #[[Number1 of pointers] Number1 * [2byte pointer to script][00][00]]
    ptr_line_size = 4 #[2byte pointer to script][00][00]
    trigger_ptr_cnt = ord(rom[address])
    trigger_pointers = grouper(rom_interval(address+1, trigger_ptr_cnt * ptr_line_size, strings=False), count=ptr_line_size)
    triggers = {}
    for index, trigger_pointer in enumerate(trigger_pointers):
        print "parsing a trigger header..."
        byte1 = trigger_pointer[0]
        byte2 = trigger_pointer[1]
        ptr   = byte1 + (byte2 << 8)
        trigger_address = calculate_pointer(ptr, calculate_bank(address))
        trigger_script  = parse_script_engine_script_at(trigger_address, map_group=map_group, map_id=map_id)
        triggers[index] = {
            "script": trigger_script,
            "address": trigger_address,
            "pointer": {"1": byte1, "2": byte2},
        }
    
    #bump ahead in the byte stream
    address += trigger_ptr_cnt * ptr_line_size + 1
    
    #[[Number2 of pointers] Number2 * [hook number][2byte pointer to script]]
    callback_ptr_line_size = 3
    callback_ptr_cnt = ord(rom[address])
    callback_ptrs = grouper(rom_interval(address+1, callback_ptr_cnt * callback_ptr_line_size, strings=False), count=callback_ptr_line_size)
    callback_pointers = {}
    callbacks = {}
    for index, callback_line in enumerate(callback_ptrs):
        print "parsing a callback header..."
        hook_byte = callback_line[0] #1, 2, 3, 4, 5
        callback_byte1 = callback_line[1]
        callback_byte2 = callback_line[2]
        callback_ptr = callback_byte1 + (callback_byte2 << 8)
        callback_address = calculate_pointer(callback_ptr, calculate_bank(address))
        callback_script = parse_script_engine_script_at(callback_address)
        callback_pointers[len(callback_pointers.keys())] = [hook_byte, callback_ptr]
        callbacks[index] = {
            "script": callback_script,
            "address": callback_address,
            "pointer": {"1": callback_byte1, "2": callback_byte2},
        }
    
    #XXX do these triggers/callbacks call asm or script engine scripts?
    return {
        #"trigger_ptr_cnt": trigger_ptr_cnt,
        "trigger_pointers": trigger_pointers,
        #"callback_ptr_cnt": callback_ptr_cnt,
        #"callback_ptr_scripts": callback_ptrs,
        "callback_pointers": callback_pointers,
        "trigger_scripts": triggers,
        "callback_scripts": callbacks,
    }

def parse_map_header_by_id(*args, **kwargs):
    """convenience function to parse a specific map"""
    map_group, map_id = None, None
    if "map_group" in kwargs.keys():
        map_group = kwargs["map_group"]
    if "map_id" in kwargs.keys():
        map_id = kwargs["map_id"]
    if (map_group == None and map_id != None) or \
       (map_group != None and map_id == None):
        raise Exception, "map_group and map_id must both be provided"
    elif map_group == None and map_id == None and len(args) == 0:
        raise Exception, "must be given an argument"
    elif len(args) == 1 and type(args[0]) == str:
        map_group = int(args[0].split(".")[0])
        map_id = int(args[0].split(".")[1])
    else:
        raise Exception, "dunno what to do with input"
    offset = map_names[map_group]["offset"]
    map_header_offset = offset + ((map_id - 1) * map_header_byte_size)
    return parse_map_header_at(map_header_offset, map_group=map_group, map_id=map_id)

def parse_all_map_headers(debug=True):
    """calls parse_map_header_at for each map in each map group"""
    global map_names
    if not map_names[1].has_key("offset"):
        raise Exception, "dunno what to do - map_names should have groups with pre-calculated offsets by now"
    for group_id, group_data in map_names.items():
        offset = group_data["offset"]
        #we only care about the maps
        #del group_data["offset"]
        for map_id, map_data in group_data.items():
            if map_id == "offset": continue #skip the "offset" address for this map group
            if debug: print "map_group is: " + str(group_id) + "  map_id is: " + str(map_id)
            map_header_offset = offset + ((map_id - 1) * map_header_byte_size)
            parsed_map = parse_map_header_at(map_header_offset, map_group=group_id, map_id=map_id, debug=debug)
            map_names[group_id][map_id].update(parsed_map)
            map_names[group_id][map_id]["header_offset"] = map_header_offset

#map names with no labels will be generated at the end of the structure 
map_names = {
    1: {
        0x1: {"name": "Olivine Pokémon Center 1F",
              "label": "OlivinePokeCenter1F"},
        0x2: {"name": "Olivine Gym"},
        0x3: {"name": "Olivine Voltorb House"},
        0x4: {"name": "Olivine House Beta"},
        0x5: {"name": "Olivine Punishment Speech House"},
        0x6: {"name": "Olivine Good Rod House"},
        0x7: {"name": "Olivine Cafe"},
        0x8: {"name": "Olivine Mart"},
        0x9: {"name": "Route 38 Ecruteak Gate"},
        0xA: {"name": "Route 39 Barn"},
        0xB: {"name": "Route 39 Farmhouse"},
        0xC: {"name": "Route 38"},
        0xD: {"name": "Route 39"},
        0xE: {"name": "Olivine City"},
       },
    2: {
        0x1: {"name": "Mahogany Red Gyarados Speech House"},
        0x2: {"name": "Mahogany Gym"},
        0x3: {"name": "Mahogany Pokémon Center 1F",
              "label": "MahoganyPokeCenter1F"},
        0x4: {"name": "Route 42 Ecruteak Gate"},
        0x5: {"name": "Route 42"},
        0x6: {"name": "Route 44"},
        0x7: {"name": "Mahogany Town"},
    },
    3: {
        0x1: {"name": "Sprout Tower 1F"},
        0x2: {"name": "Sprout Tower 2F"},
        0x3: {"name": "Sprout Tower 3F"},
        0x4: {"name": "Tin Tower 1F"},
        0x5: {"name": "Tin Tower 2F"},
        0x6: {"name": "Tin Tower 3F"},
        0x7: {"name": "Tin Tower 4F"},
        0x8: {"name": "Tin Tower 5F"},
        0x9: {"name": "Tin Tower 6F"},
        0xA: {"name": "Tin Tower 7F"},
        0xB: {"name": "Tin Tower 8F"},
        0xC: {"name": "Tin Tower 9F"},
        0xD: {"name": "Burned Tower 1F"},
        0xE: {"name": "Burned Tower B1F"},
        0xF: {"name": "National Park"},
        0x10: {"name": "National Park Bug Contest"},
        0x11: {"name": "Radio Tower 1F"},
        0x12: {"name": "Radio Tower 2F"},
        0x13: {"name": "Radio Tower 3F"},
        0x14: {"name": "Radio Tower 4F"},
        0x15: {"name": "Radio Tower 5F"},
        0x16: {"name": "Ruins of Alph Outside"},
        0x17: {"name": "Ruins of Alph Ho-oh Chamber"},
        0x18: {"name": "Ruins of Alph Kabuto Chamber"},
        0x19: {"name": "Ruins of Alph Omanyte Chamber"},
        0x1A: {"name": "Ruins of Alph Aerodactyl Chamber"},
        0x1B: {"name": "Ruins of Alph Inner Chamber"},
        0x1C: {"name": "Ruins of Alph Research Center"},
        0x1D: {"name": "Ruins of Alph Ho-oh Item Room"},
        0x1E: {"name": "Ruins of Alph Kabuto Item Room"},
        0x1F: {"name": "Ruins of Alph Omanyte Item Room"},
        0x20: {"name": "Ruins of Alph Aerodactyl Item Room"},
        0x21: {"name": "Ruins of Alph Ho-Oh Word Room"},
        0x22: {"name": "Ruins of Alph Kabuto Word Room"},
        0x23: {"name": "Ruins of Alph Omanyte Word Room"},
        0x24: {"name": "Ruins of Alph Aerodactyl Word Room"},
        0x25: {"name": "Union Cave 1F"},
        0x26: {"name": "Union Cave B1F"},
        0x27: {"name": "Union Cave B2F"},
        0x28: {"name": "Slowpoke Well B1F"},
        0x29: {"name": "Slowpoke Well B2F"},
        0x2A: {"name": "Olivine Lighthouse 1F"},
        0x2B: {"name": "Olivine Lighthouse 2F"},
        0x2C: {"name": "Olivine Lighthouse 3F"},
        0x2D: {"name": "Olivine Lighthouse 4F"},
        0x2E: {"name": "Olivine Lighthouse 5F"},
        0x2F: {"name": "Olivine Lighthouse 6F"},
        0x30: {"name": "Mahogany Mart 1F"},
        0x31: {"name": "Team Rocket Base B1F"},
        0x32: {"name": "Team Rocket Base B2F"},
        0x33: {"name": "Team Rocket Base B3F"},
        0x34: {"name": "Ilex Forest"},
        0x35: {"name": "Warehouse Entrance"},
        0x36: {"name": "Underground Path Switch Room Entrances"},
        0x37: {"name": "Goldenrod Dept Store B1F"},
        0x38: {"name": "Underground Warehouse"},
        0x39: {"name": "Mount Mortar 1F Outside"},
        0x3A: {"name": "Mount Mortar 1F Inside"},
        0x3B: {"name": "Mount Mortar 2F Inside"},
        0x3C: {"name": "Mount Mortar B1F"},
        0x3D: {"name": "Ice Path 1F"},
        0x3E: {"name": "Ice Path B1F"},
        0x3F: {"name": "Ice Path B2F Mahogany Side"},
        0x40: {"name": "Ice Path B2F Blackthorn Side"},
        0x41: {"name": "Ice Path B3F"},
        0x42: {"name": "Whirl Island NW"},
        0x43: {"name": "Whirl Island NE"},
        0x44: {"name": "Whirl Island SW"},
        0x45: {"name": "Whirl Island Cave"},
        0x46: {"name": "Whirl Island SE"},
        0x47: {"name": "Whirl Island B1F"},
        0x48: {"name": "Whirl Island B2F"},
        0x49: {"name": "Whirl Island Lugia Chamber"},
        0x4A: {"name": "Silver Cave Room 1"},
        0x4B: {"name": "Silver Cave Room 2"},
        0x4C: {"name": "Silver Cave Room 3"},
        0x4D: {"name": "Silver Cave Item Rooms"},
        0x4E: {"name": "Dark Cave Violet Entrance"},
        0x4F: {"name": "Dark Cave Blackthorn Entrance"},
        0x50: {"name": "Dragon's Den 1F"},
        0x51: {"name": "Dragon's Den B1F"},
        0x52: {"name": "Dragon Shrine"},
        0x53: {"name": "Tohjo Falls"},
        0x54: {"name": "Diglett's Cave"},
        0x55: {"name": "Mount Moon"},
        0x56: {"name": "Underground"},
        0x57: {"name": "Rock Tunnel 1F"},
        0x58: {"name": "Rock Tunnel B1F"},
        0x59: {"name": "Safari Zone Fuchsia Gate Beta"},
        0x5A: {"name": "Safari Zone Beta"},
        0x5B: {"name": "Victory Road"},
    },
    4: {
        0x1: {"name": "Ecruteak House"}, #passage to Tin Tower
        0x2: {"name": "Wise Trio's Room"},
        0x3: {"name": "Ecruteak Pokémon Center 1F",
              "label": "EcruteakPokeCenter1F"},
        0x4: {"name": "Ecruteak Lugia Speech House"},
        0x5: {"name": "Dance Theatre"},
        0x6: {"name": "Ecruteak Mart"},
        0x7: {"name": "Ecruteak Gym"},
        0x8: {"name": "Ecruteak Itemfinder House"},
        0x9: {"name": "Ecruteak City"},
    },
    5: {
        0x1: {"name": "Blackthorn Gym 1F"},
        0x2: {"name": "Blackthorn Gym 2F"},
        0x3: {"name": "Blackthorn Dragon Speech House"},
        0x4: {"name": "Blackthorn Dodrio Trade House"},
        0x5: {"name": "Blackthorn Mart"},
        0x6: {"name": "Blackthorn Pokémon Center 1F",
              "label": "BlackthornPokeCenter1F"},
        0x7: {"name": "Move Deleter's House"},
        0x8: {"name": "Route 45"},
        0x9: {"name": "Route 46"},
        0xA: {"name": "Blackthorn City"},
    },
    6: {
        0x1: {"name": "Cinnabar Pokémon Center 1F",
              "label": "CinnabarPokeCenter1F"},
        0x2: {"name": "Cinnabar Pokémon Center 2F Beta",
              "label": "CinnabarPokeCenter2FBeta"},
        0x3: {"name": "Route 19 - Fuchsia Gate"},
        0x4: {"name": "Seafoam Gym"},
        0x5: {"name": "Route 19"},
        0x6: {"name": "Route 20"},
        0x7: {"name": "Route 21"},
        0x8: {"name": "Cinnabar Island"},
    },
    7: {
        0x1: {"name": "Cerulean Gym Badge Speech House"},
        0x2: {"name": "Cerulean Police Station"},
        0x3: {"name": "Cerulean Trade Speech House"},
        0x4: {"name": "Cerulean Pokémon Center 1F",
              "label": "CeruleanPokeCenter1F"},
        0x5: {"name": "Cerulean Pokémon Center 2F Beta",
              "label": "CeruleanPokeCenter2FBeta"},
        0x6: {"name": "Cerulean Gym"},
        0x7: {"name": "Cerulean Mart"},
        0x8: {"name": "Route 10 Pokémon Center 1F",
              "label": "Route10PokeCenter1F"},
        0x9: {"name": "Route 10 Pokémon Center 2F Beta",
              "label": "Route10PokeCenter2FBeta"},
        0xA: {"name": "Power Plant"},
        0xB: {"name": "Bill's House"},
        0xC: {"name": "Route 4"},
        0xD: {"name": "Route 9"},
        0xE: {"name": "Route 10"},
        0xF: {"name": "Route 24"},
        0x10: {"name": "Route 25"},
        0x11: {"name": "Cerulean City"},
    },
    8: {
        0x1: {"name": "Azalea Pokémon Center 1F",
              "label": "AzaleaPokeCenter1F"},
        0x2: {"name": "Charcoal Kiln"},
        0x3: {"name": "Azalea Mart"},
        0x4: {"name": "Kurt's House"},
        0x5: {"name": "Azalea Gym"},
        0x6: {"name": "Route 33"},
        0x7: {"name": "Azalea Town"},
    },
    9: {
        0x1: {"name": "Lake of Rage Hidden Power House"},
        0x2: {"name": "Lake of Rage Magikarp House"},
        0x3: {"name": "Route 43 Mahogany Gate"},
        0x4: {"name": "Route 43 Gate"},
        0x5: {"name": "Route 43"},
        0x6: {"name": "Lake of Rage"},
    },
    10: {
        0x1: {"name": "Route 32"},
        0x2: {"name": "Route 35"},
        0x3: {"name": "Route 36"},
        0x4: {"name": "Route 37"},
        0x5: {"name": "Violet City"},
        0x6: {"name": "Violet Mart"},
        0x7: {"name": "Violet Gym"},
        0x8: {"name": "Earl's Pokémon Academy",
              "label": "EarlsPokemonAcademy"},
        0x9: {"name": "Violet Nickname Speech House"},
        0xA: {"name": "Violet Pokémon Center 1F",
              "label": "VioletPokeCenter1F"},
        0xB: {"name": "Violet Onix Trade House"},
        0xC: {"name": "Route 32 Ruins of Alph Gate"},
        0xD: {"name": "Route 32 Pokémon Center 1F",
              "label": "Route32PokeCenter1F"},
        0xE: {"name": "Route 35 Goldenrod gate"},
        0xF: {"name": "Route 35 National Park gate"},
        0x10: {"name": "Route 36 Ruins of Alph gate"},
        0x11: {"name": "Route 36 National Park gate"},
    },
    11: {
        0x1: {"name": "Route 34"},
        0x2: {"name": "Goldenrod City"},
        0x3: {"name": "Goldenrod Gym"},
        0x4: {"name": "Goldenrod Bike Shop"},
        0x5: {"name": "Goldenrod Happiness Rater"},
        0x6: {"name": "Goldenrod Bill's House"},
        0x7: {"name": "Goldenrod Magnet Train Station"},
        0x8: {"name": "Goldenrod Flower Shop"},
        0x9: {"name": "Goldenrod PP Speech House"},
        0xA: {"name": "Goldenrod Name Rater's House"},
        0xB: {"name": "Goldenrod Dept Store 1F"},
        0xC: {"name": "Goldenrod Dept Store 2F"},
        0xD: {"name": "Goldenrod Dept Store 3F"},
        0xE: {"name": "Goldenrod Dept Store 4F"},
        0xF: {"name": "Goldenrod Dept Store 5F"},
        0x10: {"name": "Goldenrod Dept Store 6F"},
        0x11: {"name": "Goldenrod Dept Store Elevator"},
        0x12: {"name": "Goldenrod Dept Store Roof"},
        0x13: {"name": "Goldenrod Game Corner"},
        0x14: {"name": "Goldenrod Pokémon Center 1F",
               "label": "GoldenrodPokeCenter1F"},
        0x15: {"name": "Goldenrod PokéCom Center 2F Mobile",
               "label": "GoldenrodPokeComCenter2FMobile"},
        0x16: {"name": "Ilex Forest Azalea Gate"},
        0x17: {"name": "Route 34 Ilex Forest Gate"},
        0x18: {"name": "Day Care"},
    },
    12: {
        0x1: {"name": "Route 6"},
        0x2: {"name": "Route 11"},
        0x3: {"name": "Vermilion City"},
        0x4: {"name": "Vermilion House Fishing Speech House"},
        0x5: {"name": "Vermilion Pokémon Center 1F",
              "label": "VermilionPokeCenter1F"},
        0x6: {"name": "Vermilion Pokémon Center 2F Beta",
              "label": "VermilionPokeCenter2FBeta"},
        0x7: {"name": "Pokémon Fan Club"},
        0x8: {"name": "Vermilion Magnet Train Speech House"},
        0x9: {"name": "Vermilion Mart"},
        0xA: {"name": "Vermilion House Diglett's Cave Speech House"},
        0xB: {"name": "Vermilion Gym"},
        0xC: {"name": "Route 6 Saffron Gate"},
        0xD: {"name": "Route 6 Underground Entrance"},
    },
    13: {
        0x1: {"name": "Route 1"},
        0x2: {"name": "Pallet Town"},
        0x3: {"name": "Red's House 1F"},
        0x4: {"name": "Red's House 2F"},
        0x5: {"name": "Blue's House"},
        0x6: {"name": "Oak's Lab"},
    },
    14: {
        0x1: {"name": "Route 3"},
        0x2: {"name": "Pewter City"},
        0x3: {"name": "Pewter Nidoran Speech House"},
        0x4: {"name": "Pewter Gym"},
        0x5: {"name": "Pewter Mart"},
        0x6: {"name": "Pewter Pokémon Center 1F",
              "label": "PewterPokeCenter1F"},
        0x7: {"name": "Pewter Pokémon Center 2F Beta",
              "label": "PewterPokeCEnter2FBeta"},
        0x8: {"name": "Pewter Snooze Speech House"},
    },
    15: {
        0x1: {"name": "Olivine Port"},
        0x2: {"name": "Vermilion Port"},
        0x3: {"name": "Fast Ship 1F"},
        0x4: {"name": "Fast Ship Cabins NNW, NNE, NE",
              "label": "FastShipCabins_NNW_NNE_NE"},
        0x5: {"name": "Fast Ship Cabins SW, SSW, NW",
              "label": "FastShipCabins_SW_SSW_NW"},
        0x6: {"name": "Fast Ship Cabins SE, SSE, Captain's Cabin",
              "label": "FastShipCabins_SE_SSE_CaptainsCabin"},
        0x7: {"name": "Fast Ship B1F"},
        0x8: {"name": "Olivine Port Passage"},
        0x9: {"name": "Vermilion Port Passage"},
        0xA: {"name": "Mount Moon Square"},
        0xB: {"name": "Mount Moon Gift Shop"},
        0xC: {"name": "Tin Tower Roof"},
    },
    16: {
        0x1: {"name": "Route 23"},
        0x2: {"name": "Indigo Plateau Pokémon Center 1F",
              "label": "IndigoPlateauPokeCenter1F"},
        0x3: {"name": "Will's Room"},
        0x4: {"name": "Koga's Room"},
        0x5: {"name": "Bruno's Room"},
        0x6: {"name": "Karen's Room"},
        0x7: {"name": "Lance's Room"},
        0x8: {"name": "Hall of Fame",
              "label": "HallOfFame"},
    },
    17: {
        0x1: {"name": "Route 13"},
        0x2: {"name": "Route 14"},
        0x3: {"name": "Route 15"},
        0x4: {"name": "Route 18"},
        0x5: {"name": "Fuchsia City"},
        0x6: {"name": "Fuchsia Mart"},
        0x7: {"name": "Safari Zone Main Office"},
        0x8: {"name": "Fuchsia Gym"},
        0x9: {"name": "Fuchsia Bill Speech House"},
        0xA: {"name": "Fuchsia Pokémon Center 1F",
              "label": "FuchsiaPokeCenter1F"},
        0xB: {"name": "Fuchsia Pokémon Center 2F Beta",
              "label": "FuchsiaPokeCenter2FBeta"},
        0xC: {"name": "Safari Zone Warden's Home"},
        0xD: {"name": "Route 15 Fuchsia Gate"},
    },
    18: {
        0x1: {"name": "Route 8"},
        0x2: {"name": "Route 12"},
        0x3: {"name": "Route 10"},
        0x4: {"name": "Lavender Town"},
        0x5: {"name": "Lavender Pokémon Center 1F",
              "label": "LavenderPokeCenter1F"},
        0x6: {"name": "Lavender Pokémon Center 2F Beta",
              "label": "LavenderPokeCenter2FBeta"},
        0x7: {"name": "Mr. Fuji's House"},
        0x8: {"name": "Lavender Town Speech House"},
        0x9: {"name": "Lavender Name Rater"},
        0xA: {"name": "Lavender Mart"},
        0xB: {"name": "Soul House"},
        0xC: {"name": "Lav Radio Tower 1F"},
        0xD: {"name": "Route 8 Saffron Gate"},
        0xE: {"name": "Route 12 Super Rod House"},
    },
    19: {
        0x1: {"name": "Route 28"},
        0x2: {"name": "Silver Cave Outside"},
        0x3: {"name": "Silver Cave Pokémon Center 1F",
              "label": "SilverCavePokeCenter1F"},
        0x4: {"name": "Route 28 Famous Speech House"},
    },
    20: {
        0x1: {"name": "Pokémon Center 2F",
              "label": "PokeCenter2F"},
        0x2: {"name": "Trade Center"},
        0x3: {"name": "Colosseum"},
        0x4: {"name": "Time Capsule"},
        0x5: {"name": "Mobile Trade Room Mobile"},
        0x6: {"name": "Mobile Battle Room"},
    },
    21: {
        0x1: {"name": "Route 7"},
        0x2: {"name": "Route 16"},
        0x3: {"name": "Route 17"},
        0x4: {"name": "Celadon City"},
        0x5: {"name": "Celadon Dept Store 1F"},
        0x6: {"name": "Celadon Dept Store 2F"},
        0x7: {"name": "Celadon Dept Store 3F"},
        0x8: {"name": "Celadon Dept Store 4F"},
        0x9: {"name": "Celadon Dept Store 5F"},
        0xA: {"name": "Celadon Dept Store 6F"},
        0xB: {"name": "Celadon Dept Store Elevator"},
        0xC: {"name": "Celadon Mansion 1F"},
        0xD: {"name": "Celadon Mansion 2F"},
        0xE: {"name": "Celadon Mansion 3F"},
        0xF: {"name": "Celadon Mansion Roof"},
        0x10: {"name": "Celadon Mansion Roof House"},
        0x11: {"name": "Celadon Pokémon Center 1F",
               "label": "CeladonPokeCenter1F"},
        0x12: {"name": "Celadon Pokémon Center 2F Beta",
               "label": "CeladonPokeCenter2FBeta"},
        0x13: {"name": "Celadon Game Corner"},
        0x14: {"name": "Celadon Game Corner Prize Room"},
        0x15: {"name": "Celadon Gym"},
        0x16: {"name": "Celadon Cafe"},
        0x17: {"name": "Route 16 Fuchsia Speech House"},
        0x18: {"name": "Route 16 Gate"},
        0x19: {"name": "Route 7 Saffron Gate"},
        0x1A: {"name": "Route 17 18 Gate"},
    },
    22: {
        0x1: {"name": "Route 40"},
        0x2: {"name": "Route 41"},
        0x3: {"name": "Cianwood City"},
        0x4: {"name": "Mania's House"},
        0x5: {"name": "Cianwood Gym"},
        0x6: {"name": "Cianwood Pokémon Center 1F",
              "label": "CianwoodPokeCenter1F"},
        0x7: {"name": "Cianwood Pharmacy"},
        0x8: {"name": "Cianwood City Photo Studio"},
        0x9: {"name": "Cianwood Lugia Speech House"},
        0xA: {"name": "Poke Seer's House"},
        0xB: {"name": "Battle Tower 1F"},
        0xC: {"name": "Battle Tower Battle Room"},
        0xD: {"name": "Battle Tower Elevator"},
        0xE: {"name": "Battle Tower Hallway"},
        0xF: {"name": "Route 40 Battle Tower Gate"},
        0x10: {"name": "Battle Tower Outside"},
    },
    23: {
        0x1: {"name": "Route 2"},
        0x2: {"name": "Route 22"},
        0x3: {"name": "Viridian City"},
        0x4: {"name": "Viridian Gym"},
        0x5: {"name": "Viridian Nickname Speech House"},
        0x6: {"name": "Trainer House 1F"},
        0x7: {"name": "Trainer House B1F"},
        0x8: {"name": "Viridian Mart"},
        0x9: {"name": "Viridian Pokémon Center 1F",
              "label": "ViridianPokeCenter1F"},
        0xA: {"name": "Viridian Pokémon Center 2F Beta",
              "label": "ViridianPokeCenter2FBeta"},
        0xB: {"name": "Route 2 Nugget Speech House"},
        0xC: {"name": "Route 2 Gate"},
        0xD: {"name": "Victory Road Gate"},
    },
    24: {
        0x1: {"name": "Route 26"},
        0x2: {"name": "Route 27"},
        0x3: {"name": "Route 29"},
        0x4: {"name": "New Bark Town"},
        0x5: {"name": "Elm's Lab"},
        0x6: {"name": "Kris's House 1F"},
        0x7: {"name": "Kris's House 2F"},
        0x8: {"name": "Kris's Neighbor's House"},
        0x9: {"name": "Elm's House"},
        0xA: {"name": "Route 26 Heal Speech House"},
        0xB: {"name": "Route 26 Day of Week Siblings House"},
        0xC: {"name": "Route 27 Sandstorm House"},
        0xD: {"name": "Route 29 46 Gate"},
    },
    25: {
        0x1: {"name": "Route 5"},
        0x2: {"name": "Saffron City"},
        0x3: {"name": "Fighting Dojo"},
        0x4: {"name": "Saffron Gym"},
        0x5: {"name": "Saffron Mart"},
        0x6: {"name": "Saffron Pokémon Center 1F",
              "label": "SaffronPokeCenter1F"},
        0x7: {"name": "Saffron Pokémon Center 2F Beta",
              "label": "SaffronPokeCenter2FBeta"},
        0x8: {"name": "Mr. Psychic's House"},
        0x9: {"name": "Saffron Train Station"},
        0xA: {"name": "Silph Co. 1F"},
        0xB: {"name": "Copycat's House 1F"},
        0xC: {"name": "Copycat's House 2F"},
        0xD: {"name": "Route 5 Underground Entrance"},
        0xE: {"name": "Route 5 Saffron City Gate"},
        0xF: {"name": "Route 5 Cleanse Tag Speech House"},
    },
    26: {
        0x1: {"name": "Route 30"},
        0x2: {"name": "Route 31"},
        0x3: {"name": "Cherrygrove City"},
        0x4: {"name": "Cherrygrove Mart"},
        0x5: {"name": "Cherrygrove Pokémon Center 1F",
              "label": "CherrygrovePokeCenter1F"},
        0x6: {"name": "Cherrygrove Gym Speech House"},
        0x7: {"name": "Guide Gent's House"},
        0x8: {"name": "Cherrygrove Evolution Speech House"},
        0x9: {"name": "Route 30 Berry Speech House"},
        0xA: {"name": "Mr. Pokémon's House"},
        0xB: {"name": "Route 31 Violet Gate"},
    },
}
#generate labels for each map name
for map_group_id in map_names.keys():
    map_group = map_names[map_group_id]
    for map_id in map_group.keys():
        #skip if we maybe already have the 'offset' label set in this map group
        if map_id == "offset": continue
        #skip if we provided a pre-set value for the map's label
        if map_group[map_id].has_key("label"): continue
        #convience alias
        map_data = map_group[map_id]
        #clean up the map name to be an asm label
        cleaned_name = map_name_cleaner(map_data["name"])
        #set the value in the original dictionary
        map_names[map_group_id][map_id]["label"] = cleaned_name
#generate map constants (like 1=PALLET_TOWN)
generate_map_constant_labels()

#### pretty printing ###
#texts: TextScript.to_asm_at
#scripts: Script.to_asm_at

#### asm utilities ####
#these are pulled in from pokered/extras/analyze_incbins.py

#store each line of source code here
asm = None

#store each incbin line separately
incbin_lines = []

#storage for processed incbin lines
processed_incbins = {}

def isolate_incbins():
    "find each incbin line"
    global incbin_lines, asm
    incbin_lines = []
    for line in asm:
        if line == "": continue
        if line.count(" ") == len(line): continue

        #clean up whitespace at beginning of line
        while line[0] == " ":
            line = line[1:]

        if line[0:6] == "INCBIN" and "baserom.gbc" in line:
            incbin_lines.append(line)
    return incbin_lines

def process_incbins():
    "parse incbin lines into memory"
    global asm, incbin_lines, processed_incbins
    #load asm if it isn't ready yet
    if asm == [] or asm == None:
        load_asm()
    #get a list of incbins if that hasn't happened yet
    if incbin_lines == [] or incbin_lines == None:
        isolate_incbins()
    #reset the global that this function creates
    processed_incbins = {}
    #for each incbin..
    for incbin in incbin_lines:
        #reset this entry
        processed_incbin = {}
        #get the line number from the global asm line list
        line_number = asm.index(incbin)
        #forget about all the leading characters
        partial_start = incbin[21:]
        start = partial_start.split(",")[0].replace("$", "0x")
        start = eval(start)
        start_hex = hex(start).replace("0x", "$")

        partial_interval = incbin[21:].split(",")[1]
        partial_interval = partial_interval.replace(";", "#")
        partial_interval = partial_interval.replace("$", "0x").replace("0xx", "0x")
        interval = eval(partial_interval)
        interval_hex = hex(interval).replace("0x", "$").replace("x", "")

        end = start + interval
        end_hex = hex(end).replace("0x", "$")

        processed_incbin = {"line_number": line_number,
                            "line": incbin,
                            "start": start,
                            "interval": interval,
                            "end": end, }
        #don't add this incbin if the interval is 0
        if interval != 0:
            processed_incbins[line_number] = processed_incbin
    return processed_incbins

def reset_incbins():
    "reset asm before inserting another diff"
    global asm, incbin_lines, processed_incbins
    asm = None
    incbin_lines = []
    processed_incbins = {}
    load_asm()
    isolate_incbins()
    process_incbins()

def find_incbin_to_replace_for(address, debug=False, rom_file="../baserom.gbc"):
    """returns a line number for which incbin to edit
    if you were to insert bytes into main.asm"""
    if type(address) == str: address = int(address, 16)
    if not (0 <= address <= os.lstat(rom_file).st_size):
        raise IndexError, "address is out of bounds"
    for incbin_key in processed_incbins.keys():
        incbin = processed_incbins[incbin_key]
        start = incbin["start"]
        end = incbin["end"]
        if debug:
            print "start is: " + str(start)
            print "end is: " + str(end)
            print "address is: " + str(type(address))
            print "checking.... " + hex(start) + " <= " + hex(address) + " <= " + hex(end)
        if start <= address <= end:
            return incbin_key
    return None

def split_incbin_line_into_three(line, start_address, byte_count, rom_file="../baserom.gbc"):
    """
    splits an incbin line into three pieces.
    you can replace the middle one with the new content of length bytecount
    
    start_address: where you want to start inserting bytes
    byte_count: how many bytes you will be inserting
    """
    if type(start_address) == str: start_address = int(start_address, 16)
    if not (0 <= start_address <= os.lstat(rom_file).st_size):
        raise IndexError, "start_address is out of bounds"
    if len(processed_incbins) == 0:
        raise Exception, "processed_incbins must be populated"

    original_incbin = processed_incbins[line]
    start = original_incbin["start"]
    end = original_incbin["end"]

    #start, end1, end2 (to be printed as start, end1 - end2)
    if start_address - start > 0:
        first = (start, start_address, start)
    else:
        first = (None) #skip this one because we're not including anything

    #this is the one you will replace with whatever content
    second = (start_address, byte_count)

    third = (start_address + byte_count, end - (start_address + byte_count))

    output = ""

    if first:
        output += "INCBIN \"baserom.gbc\",$" + hex(first[0])[2:] + ",$" + hex(first[1])[2:] + " - $" + hex(first[2])[2:] + "\n"
    output += "INCBIN \"baserom.gbc\",$" + hex(second[0])[2:] + "," + str(byte_count) + "\n"
    output += "INCBIN \"baserom.gbc\",$" + hex(third[0])[2:] + ",$" + hex(third[1])[2:] #no newline
    return output

def generate_diff_insert(line_number, newline, debug=False):
    """generates a diff between the old main.asm and the new main.asm
    note: requires python2.7 i think? b/c of subprocess.check_output"""
    global asm
    original = "\n".join(line for line in asm)
    newfile = deepcopy(asm)
    newfile[line_number] = newline #possibly inserting multiple lines
    newfile = "\n".join(line for line in newfile)

    #make sure there's a newline at the end of the file
    if newfile[-1] != "\n":
        newfile += "\n"

    original_filename = "ejroqjfoad.temp"
    newfile_filename = "fjiqefo.temp"

    original_fh = open(original_filename, "w")
    original_fh.write(original)
    original_fh.close()

    newfile_fh = open(newfile_filename, "w")
    newfile_fh.write(newfile)
    newfile_fh.close()

    try:
        diffcontent = subprocess.check_output("diff -u ../main.asm " + newfile_filename, shell=True)
    except AttributeError, exc:
        p = subprocess.Popen(["diff", "-u", "../main.asm", newfile_filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = p.communicate()
        diffcontent = out
    except Exception, exc:
        raise exc

    os.system("rm " + original_filename)
    os.system("rm " + newfile_filename)

    if debug: print diffcontent
    return diffcontent

def apply_diff(diff, try_fixing=True, do_compile=True):
    print "... Applying diff."

    #write the diff to a file
    fh = open("temp.patch", "w")
    fh.write(diff)
    fh.close()

    #apply the patch
    os.system("cp ../main.asm ../main1.asm")
    os.system("patch ../main.asm temp.patch")

    #remove the patch
    os.system("rm temp.patch")

    #confirm it's working
    if do_compile:
        try:
            subprocess.check_call("cd ../; make clean; make", shell=True)
            return True
        except Exception, exc:
            if try_fixing:
                os.system("mv ../main1.asm ../main.asm")
            return False

def index(seq, f):
    """return the index of the first item in seq
    where f(item) == True."""
    return next((i for i in xrange(len(seq)) if f(seq[i])), None)

def analyze_intervals():
    """find the largest baserom.gbc intervals"""
    global asm, processed_incbins
    if asm == None:
        load_asm()
    if processed_incbins == {}:
        isolate_incbins()
        process_incbins()
    results = []
    ordered_keys = sorted(processed_incbins, key=lambda entry: processed_incbins[entry]["interval"])
    ordered_keys.reverse()
    for key in ordered_keys:
        results.append(processed_incbins[key])
    return results

def write_all_labels(all_labels, filename="labels.json"):
    fh = open(filename, "w")
    fh.write(json.dumps(all_labels))
    fh.close()
    return True

#TODO: implement get_ram_label
def get_ram_label(address):
    """not implemented yet.. supposed to get a label for a particular RAM location
    like W_PARTYPOKE1HP"""
    return None

def get_label_for(address):
    """returns a label assigned to a particular address"""
    global all_labels
    if type(address) != int:
        raise Exception, "get_label_for requires an integer address"
    for thing in all_labels:
        if thing["address"] == address:
            return thing["label"]
    return None

def remove_quoted_text(line):
    """get rid of content inside quotes
    and also removes the quotes from the input string"""
    while line.count("\"") % 2 == 0 and line.count("\"") > 0:
        first = line.find("\"")
        second = line.find("\"", first+1)
        line = line[0:first] + line[second+1:]
    while line.count("\'") % 2 == 0 and line.count("'") > 0:
        first = line.find("\'")
        second = line.find("\'", first+1)
        line = line[0:first] + line[second+1:]
    return line

class Label:
    def __init__(self, name=None, address=None, line_number=None):
        assert name!=None, "need a name"
        assert address!=None, "need an address"
        assert line_number!=None, "need a line number"
        self.name, self.address, self.line_number = str(name), int(address), int(line_number)

def line_has_comment_address(line, returnable={}, bank=None):
    """checks that a given line has a comment
    with a valid address, and returns the address in the object.
    Note: bank is required if you have a 4-letter-or-less address,
    because otherwise there is no way to figure out which bank
    is curretly being scanned."""
    #first set the bank/offset to nada
    returnable["bank"] = None
    returnable["offset"] = None
    returnable["address"] = None
    #only valid characters are 0-9A-F
    valid = [str(x) for x in range(0,10)] + [chr(x) for x in range(97, 102+1)]
    #check if there is a comment in this line
    if ";" not in line:
        return False
    #first throw away anything in quotes
    if (line.count("\"") % 2 == 0 and line.count("\"")!=0) \
       or (line.count("\'") % 2 == 0 and line.count("\'")!=0):
        line = remove_quoted_text(line)
    #check if there is still a comment in this line after quotes removed
    if ";" not in line:
        return False
    #but even if there's a semicolon there must be later text
    if line[-1] == ";":
        return False
    #and just a space doesn't count
    if line[-2:] == "; ":
        return False
    #and multiple whitespace doesn't count either
    line = line.rstrip(" ").lstrip(" ")
    if line[-1] == ";":
        return False
    #there must be more content after the semicolon
    if len(line)-1 == line.find(";"):
        return False
    #split it up into the main comment part
    comment = line[line.find(";")+1:]
    #don't want no leading whitespace
    comment = comment.lstrip(" ").rstrip(" ")
    #split up multi-token comments into single tokens
    token = comment
    if " " in comment:
        #use the first token in the comment
        token = comment.split(" ")[0]
    if token in ["0x", "$", "x", ":"]:
        return False
    offset = None
    #process a token with a A:B format
    if ":" in token: #3:3F0A, $3:$3F0A, 0x3:0x3F0A, 3:3F0A
        #split up the token
        bank_piece = token.split(":")[0].lower()
        offset_piece = token.split(":")[1].lower()
        #filter out blanks/duds
        if bank_piece in ["$", "0x", "x"] \
        or offset_piece in ["$", "0x", "x"]:
            return False
        #they can't have both "$" and "x"
        if "$" in bank_piece and "x" in bank_piece:
            return False
        if "$" in offset_piece and "x" in offset_piece:
            return False
        #process the bank piece
        if "$" in bank_piece:
            bank_piece = bank_piece.replace("$", "0x")
        #check characters for validity?
        for c in bank_piece.replace("x", ""):
            if c not in valid:
                return False
        bank = int(bank_piece, 16)
        #process the offset piece
        if "$" in offset_piece:
            offset_piece = offset_piece.replace("$", "0x")
        #check characters for validity?
        for c in offset_piece.replace("x", ""):
            if c not in valid:
                return False
        offset = int(offset_piece, 16)
    #filter out blanks/duds
    elif token in ["$", "0x", "x"]:
        return False
    #can't have both "$" and "x" in the number
    elif "$" in token and "x" in token:
        return False
    elif "x" in token and not "0x" in token: #it should be 0x
        return False
    elif "$" in token and not "x" in token:
        token = token.replace("$", "0x")
        offset = int(token, 16)
    elif "0x" in token and not "$" in token:
        offset = int(token, 16)
    else: #might just be "1" at this point
        token = token.lower()
        #check if there are bad characters
        for c in token:
            if c not in valid:
                return False
        offset = int(token, 16)
    if offset == None and bank == None:
        return False
    if bank == None:
        bank = calculate_bank(offset)
    returnable["bank"] = bank
    returnable["offset"] = offset
    returnable["address"] = calculate_pointer(offset, bank=bank)
    return True
def line_has_label(line):
    """returns True if the line has an asm label"""
    if not isinstance(line, str):
        raise Exception, "can't check this type of object"
    line = line.rstrip(" ").lstrip(" ")
    line = remove_quoted_text(line)
    if ";" in line:
        line = line.split(";")[0]
    if 0 <= len(line) <= 1:
        return False
    if ":" not in line:
        return False
    if line[0] == ";":
        return False
    if line[0] == "\"":
        return False
    if "::" in line:
        return False
    return True
def get_label_from_line(line):
    """returns the label from the line"""
    #check if the line has a label
    if not line_has_label(line):
        return None
    #split up the line
    label = line.split(":")[0]
    return label
def find_labels_without_addresses():
    """scans the asm source and finds labels that are unmarked"""
    without_addresses = []
    for (line_number, line) in enumerate(asm):
        if line_has_label(line):
            label = get_label_from_line(line)
            if not line_has_comment_address(line):
                without_addresses.append({"line_number": line_number, "line": line, "label": label})
    return without_addresses

label_errors = ""
def get_labels_between(start_line_id, end_line_id, bank):
    labels = []
    #label = {
    #   "line_number": 15,
    #   "bank": 32,
    #   "label": "PalletTownText1",
    #   "offset": 0x5315,
    #   "address": 0x75315,
    #}
    if asm == None:
        load_asm()
    sublines = asm[start_line_id : end_line_id + 1]
    for (current_line_offset, line) in enumerate(sublines):
        #skip lines without labels
        if not line_has_label(line): continue
        #reset some variables
        line_id = start_line_id + current_line_offset
        line_label = get_label_from_line(line)
        address = None
        offset = None
        #setup a place to store return values from line_has_comment_address
        returnable = {}
        #get the address from the comment
        has_comment = line_has_comment_address(line, returnable=returnable, bank=bank)
        #skip this line if it has no address in the comment
        if not has_comment: continue
        #parse data from line_has_comment_address
        address = returnable["address"]
        bank = returnable["bank"]
        offset = returnable["offset"]
        #dump all this info into a single structure
        label = {
            "line_number": line_id,
            "bank": bank,
            "label": line_label,
            "offset": offset,
            "address": address,
        }
        #store this structure
        labels.append(label)
    return labels

def scan_for_predefined_labels(debug=False):
    """looks through the asm file for labels at specific addresses,
    this relies on the label having its address after. ex:

    ViridianCity_h: ; 0x18357 to 0x18384 (45 bytes) (bank=6) (id=1)
    PalletTownText1: ; 4F96 0x18f96
    ViridianCityText1: ; 0x19102

    It would be more productive to use rgbasm to spit out all label
    addresses, but faster to write this script. rgbasm would be able
    to grab all label addresses better than this script..
    """
    global all_labels
    all_labels = []
    bank_intervals = {}

    #figure out line numbers for each bank
    for bank_id in range(0x7F+1):
        abbreviation = ("%.x" % (bank_id)).upper()
        abbreviation_next = ("%.x" % (bank_id+1)).upper()
        if bank_id == 0:
            abbreviation = "0"
            abbreviation_next = "1"

        #calculate the start/stop line numbers for this bank
        start_line_id = index(asm, lambda line: "\"bank" + abbreviation + "\"" in line)
        if bank_id != 0x7F:
            end_line_id = index(asm, lambda line: "\"bank" + abbreviation_next + "\"" in line)
            end_line_id += 1
        else:
            end_line_id = len(asm) - 1

        if debug:
            output = "bank" + abbreviation + " starts at "
            output += str(start_line_id)
            output += " to "
            output += str(end_line_id)
            print output
        
        #store the start/stop line number for this bank
        bank_intervals[bank_id] = {"start": start_line_id,
                                   "end": end_line_id,}
    #for each bank..
    for bank_id in bank_intervals.keys():
        #get the start/stop line number
        bank_data = bank_intervals[bank_id]
        start_line_id = bank_data["start"]
        end_line_id   = bank_data["end"]
        #get all labels between these two lines
        labels = get_labels_between(start_line_id, end_line_id, bank_id)
        #bank_intervals[bank_id]["labels"] = labels
        all_labels.extend(labels)
    write_all_labels(all_labels)
    return all_labels

#### generic testing ####

class TestCram(unittest.TestCase):
    "this is where i cram all of my unit tests together"
    @classmethod
    def setUpClass(cls):
        global rom
        cls.rom = direct_load_rom()
        rom = cls.rom
    @classmethod
    def tearDownClass(cls):
        del cls.rom
    def test_generic_useless(self):
        "do i know how to write a test?"
        self.assertEqual(1, 1)
    def test_map_name_cleaner(self):
        name = "hello world"
        cleaned_name = map_name_cleaner(name)
        self.assertNotEqual(name, cleaned_name)
        self.failUnless(" " not in cleaned_name)
        name = "Some Random Pokémon Center"
        cleaned_name = map_name_cleaner(name)
        self.assertNotEqual(name, cleaned_name)
        self.failIf(" " in cleaned_name)
        self.failIf("é" in cleaned_name)
    def test_grouper(self):
        data = range(0, 10)
        groups = grouper(data, count=2)
        self.assertEquals(len(groups), 5)
        data = range(0, 20)
        groups = grouper(data, count=2)
        self.assertEquals(len(groups), 10)
        self.assertNotEqual(data, groups)
        self.assertNotEqual(len(data), len(groups))
    def test_direct_load_rom(self):
        rom = self.rom
        self.assertEqual(len(rom), 2097152)
        self.failUnless(isinstance(rom, RomStr))
    def test_load_rom(self):
        global rom
        rom = None
        load_rom()
        self.failIf(rom == None)
        rom = RomStr(None)
        load_rom()
        self.failIf(rom == RomStr(None))
    def test_load_asm(self):
        asm = load_asm()
        joined_lines = "\n".join(asm)
        self.failUnless("SECTION" in joined_lines)
        self.failUnless("bank" in joined_lines)
        self.failUnless(isinstance(asm, AsmList))
    def test_rom_file_existence(self):
        "ROM file must exist"
        self.failUnless("baserom.gbc" in os.listdir("../"))
    def test_rom_md5(self):
        "ROM file must have the correct md5 sum"
        rom = self.rom
        correct = "9f2922b235a5eeb78d65594e82ef5dde"
        md5sum = md5.md5(rom).hexdigest()
        self.assertEqual(md5sum, correct)
    def test_bizarre_http_presence(self):
        rom_segment = self.rom[0x112116:0x112116+8]
        self.assertEqual(rom_segment, "HTTP/1.0")
    def test_rom_interval(self):
        address = 0x100
        interval = 10
        correct_strings = ['0x0', '0xc3', '0x6e', '0x1', '0xce',
                           '0xed', '0x66', '0x66', '0xcc', '0xd']
        byte_strings = rom_interval(address, interval, strings=True)
        self.assertEqual(byte_strings, correct_strings)
        correct_ints = [0, 195, 110, 1, 206, 237, 102, 102, 204, 13]
        ints = rom_interval(address, interval, strings=False)
        self.assertEqual(ints, correct_ints)
    def test_rom_until(self):
        address = 0x1337
        byte = 0x13
        bytes = rom_until(address, byte, strings=True)
        self.failUnless(len(bytes) == 3)
        self.failUnless(bytes[0] == '0xd5')
        bytes = rom_until(address, byte, strings=False)
        self.failUnless(len(bytes) == 3)
        self.failUnless(bytes[0] == 0xd5)
    def test_how_many_until(self):
        how_many = how_many_until(chr(0x13), 0x1337)
        self.assertEqual(how_many, 3)
    def test_calculate_bank(self):
        self.failUnless(calculate_bank(0x8000) == 2)
        self.failUnless(calculate_bank("0x9000") == 2)
        self.failUnless(calculate_bank(0) == 0)
        for address in [0x4000, 0x5000, 0x6000, 0x7000]:
            self.assertRaises(Exception, calculate_bank, address)
    def test_calculate_pointer(self):
        #for offset <= 0x4000
        self.assertEqual(calculate_pointer(0x0000), 0x0000)
        self.assertEqual(calculate_pointer(0x3FFF), 0x3FFF)
        #for 0x4000 <= offset <= 0x7FFFF
        self.assertEqual(calculate_pointer(0x430F, bank=5), 0x1430F)
        #for offset >= 0x7FFF
        self.assertEqual(calculate_pointer(0x8FFF, bank=6), calculate_pointer(0x8FFF, bank=7))
    def test_calculate_pointer_from_bytes_at(self):
        addr1 = calculate_pointer_from_bytes_at(0x100, bank=False)
        self.assertEqual(addr1, 0xc300)
        addr2 = calculate_pointer_from_bytes_at(0x100, bank=True)
        self.assertEqual(addr2, 0x2ec3)
    def test_rom_text_at(self):
        self.assertEquals(rom_text_at(0x112116, 8), "HTTP/1.0")
    def test_translate_command_byte(self):
        self.failUnless(translate_command_byte(crystal=0x0) == 0x0)
        self.failUnless(translate_command_byte(crystal=0x10) == 0x10)
        self.failUnless(translate_command_byte(crystal=0x40) == 0x40)
        self.failUnless(translate_command_byte(gold=0x0) == 0x0)
        self.failUnless(translate_command_byte(gold=0x10) == 0x10)
        self.failUnless(translate_command_byte(gold=0x40) == 0x40)
        self.assertEqual(translate_command_byte(gold=0x0), translate_command_byte(crystal=0x0))
        self.failUnless(translate_command_byte(gold=0x52) == 0x53)
        self.failUnless(translate_command_byte(gold=0x53) == 0x54)
        self.failUnless(translate_command_byte(crystal=0x53) == 0x52)
        self.failUnless(translate_command_byte(crystal=0x52) == None)
        self.assertRaises(Exception, translate_command_byte, None, gold=0xA4)
    def test_pksv_integrity(self):
        "does pksv_gs look okay?"
        self.assertEqual(pksv_gs[0x00], "2call")
        self.assertEqual(pksv_gs[0x2D], "givepoke")
        self.assertEqual(pksv_gs[0x85], "waitbutton")
        self.assertEqual(pksv_crystal[0x00], "2call")
        self.assertEqual(pksv_crystal[0x86], "waitbutton")
        self.assertEqual(pksv_crystal[0xA2], "credits")
    def test_chars_integrity(self):
        self.assertEqual(chars[0x80], "A")
        self.assertEqual(chars[0xA0], "a")
        self.assertEqual(chars[0xF0], "¥")
        self.assertEqual(jap_chars[0x44], "ぱ")
    def test_map_names_integrity(self):
        def map_name(map_group, map_id): return map_names[map_group][map_id]["name"]
        self.assertEqual(map_name(2, 7), "Mahogany Town")
        self.assertEqual(map_name(3, 0x34), "Ilex Forest")
        self.assertEqual(map_name(7, 0x11), "Cerulean City")
    def test_load_map_group_offsets(self):
        addresses = load_map_group_offsets()
        self.assertEqual(len(addresses), 26, msg="there should be 26 map groups")
        addresses = load_map_group_offsets()
        self.assertEqual(len(addresses), 26, msg="there should still be 26 map groups")
        self.assertIn(0x94034, addresses)
        for address in addresses:
            self.assertGreaterEqual(address, 0x4000)
            self.failIf(0x4000 <= address <= 0x7FFF)
            self.failIf(address <= 0x4000)
    def test_index(self):
        self.assertTrue(index([1,2,3,4], lambda f: True) == 0)
        self.assertTrue(index([1,2,3,4], lambda f: f==3) == 2)
    def test_get_pokemon_constant_by_id(self):
        x = get_pokemon_constant_by_id
        self.assertEqual(x(1), "BULBASAUR")
        self.assertEqual(x(151), "MEW")
        self.assertEqual(x(250), "HO_OH")
    def test_find_item_label_by_id(self):
        x = find_item_label_by_id
        self.assertEqual(x(249), "HM_07")
        self.assertEqual(x(173), "BERRY")
        self.assertEqual(x(45), None)
    def test_generate_item_constants(self):
        x = generate_item_constants
        r = x()
        self.failUnless("HM_07" in r)
        self.failUnless("EQU" in r)
    def test_get_label_for(self):
        global all_labels
        temp = copy(all_labels)
        #this is basd on the format defined in get_labels_between
        all_labels = [{"label": "poop", "address": 0x5,
                       "offset": 0x5, "bank": 0,
                       "line_number": 2
                     }]
        self.assertEqual(get_label_for(5), "poop")
        all_labels = temp
    def test_generate_map_constant_labels(self):
        ids = generate_map_constant_labels()
        self.assertEqual(ids[0]["label"], "OLIVINE_POKECENTER_1F")
        self.assertEqual(ids[1]["label"], "OLIVINE_GYM")
    def test_get_id_for_map_constant_label(self):
        global map_internal_ids
        map_internal_ids = generate_map_constant_labels()
        self.assertEqual(get_id_for_map_constant_label("OLIVINE_GYM"), 1)
        self.assertEqual(get_id_for_map_constant_label("OLIVINE_POKECENTER_1F"), 0)
    def test_get_map_constant_label_by_id(self):
        global map_internal_ids
        map_internal_ids = generate_map_constant_labels()
        self.assertEqual(get_map_constant_label_by_id(0), "OLIVINE_POKECENTER_1F")
        self.assertEqual(get_map_constant_label_by_id(1), "OLIVINE_GYM")
    def test_is_valid_address(self):
        self.assertTrue(is_valid_address(0))
        self.assertTrue(is_valid_address(1))
        self.assertTrue(is_valid_address(10))
        self.assertTrue(is_valid_address(100))
        self.assertTrue(is_valid_address(1000))
        self.assertTrue(is_valid_address(10000))
        self.assertFalse(is_valid_address(2097153))
        self.assertFalse(is_valid_address(2098000))
        addresses = [random.randrange(0,2097153) for i in range(0, 9+1)]
        for address in addresses:
            self.assertTrue(is_valid_address(address))
class TestIntervalMap(unittest.TestCase):
    def test_intervals(self):
        i = IntervalMap()
        first = "hello world"
        second = "testing 123"
        i[0:5] = first
        i[5:10] = second
        self.assertEqual(i[0], first)
        self.assertEqual(i[1], first)
        self.assertNotEqual(i[5], first)
        self.assertEqual(i[6], second)
        i[3:10] = second
        self.assertEqual(i[3], second)
        self.assertNotEqual(i[4], first)
    def test_items(self):
        i = IntervalMap()
        first = "hello world"
        second = "testing 123"
        i[0:5] = first
        i[5:10] = second
        results = list(i.items())
        self.failUnless(len(results) == 2)
        self.assertEqual(results[0], ((0, 5), "hello world"))
        self.assertEqual(results[1], ((5, 10), "testing 123"))
class TestRomStr(unittest.TestCase):
    """RomStr is a class that should act exactly like str()
    except that it never shows the contents of it string
    unless explicitly forced"""
    sample_text = "hello world!"
    sample = None
    def setUp(self):
        if self.sample == None:
            self.__class__.sample = RomStr(self.sample_text)
    def test_equals(self):
        "check if RomStr() == str()"
        self.assertEquals(self.sample_text, self.sample)
    def test_not_equal(self):
        "check if RomStr('a') != RomStr('b')"
        self.assertNotEqual(RomStr('a'), RomStr('b'))
    def test_appending(self):
        "check if RomStr()+'a'==str()+'a'"
        self.assertEquals(self.sample_text+'a', self.sample+'a')
    def test_conversion(self):
        "check if RomStr() -> str() works"
        self.assertEquals(str(self.sample), self.sample_text)
    def test_inheritance(self):
        self.failUnless(issubclass(RomStr, str))
    def test_length(self):
        self.assertEquals(len(self.sample_text), len(self.sample))
        self.assertEquals(len(self.sample_text), self.sample.length())
        self.assertEquals(len(self.sample), self.sample.length())
class TestAsmList(unittest.TestCase):
    """AsmList is a class that should act exactly like list()
    except that it never shows the contents of its list
    unless explicitly forced"""
    def test_equals(self):
        base = [1,2,3]
        asm = AsmList(base)
        self.assertEquals(base, asm)
        self.assertEquals(asm, base)
        self.assertEquals(base, list(asm))
    def test_inheritance(self):
        self.failUnless(issubclass(AsmList, list))
    def test_length(self):
        base = range(0, 10)
        asm = AsmList(base)
        self.assertEquals(len(base), len(asm))
        self.assertEquals(len(base), asm.length())
        self.assertEquals(len(base), len(list(asm)))
        self.assertEquals(len(asm), asm.length())
    def test_remove_quoted_text(self):
        x = remove_quoted_text
        self.assertEqual(x("hello world"), "hello world")
        self.assertEqual(x("hello \"world\""), "hello ")
        input = 'hello world "testing 123"'
        self.assertNotEqual(x(input), input)
        input = "hello world 'testing 123'"
        self.assertNotEqual(x(input), input)
        self.failIf("testing" in x(input))
    def test_line_has_comment_address(self):
        x = line_has_comment_address
        self.assertFalse(x(""))
        self.assertFalse(x(";"))
        self.assertFalse(x(";;;"))
        self.assertFalse(x(":;"))
        self.assertFalse(x(":;:"))
        self.assertFalse(x(";:"))
        self.assertFalse(x(" "))
        self.assertFalse(x("".join(" " * 5)))
        self.assertFalse(x("".join(" " * 10)))
        self.assertFalse(x("hello world"))
        self.assertFalse(x("hello_world"))
        self.assertFalse(x("hello_world:"))
        self.assertFalse(x("hello_world:;"))
        self.assertFalse(x("hello_world: ;"))
        self.assertFalse(x("hello_world: ; "))
        self.assertFalse(x("hello_world: ;" + "".join(" " * 5)))
        self.assertFalse(x("hello_world: ;" + "".join(" " * 10)))
        self.assertTrue(x(";1"))
        self.assertTrue(x(";F"))
        self.assertTrue(x(";$00FF"))
        self.assertTrue(x(";0x00FF"))
        self.assertTrue(x("; 0x00FF"))
        self.assertTrue(x(";$3:$300"))
        self.assertTrue(x(";0x3:$300"))
        self.assertTrue(x(";$3:0x300"))
        self.assertTrue(x(";3:300"))
        self.assertTrue(x(";3:FFAA"))
        self.assertFalse(x('hello world "how are you today;0x1"'))
        self.assertTrue(x('hello world "how are you today:0x1";1'))
        returnable = {}
        self.assertTrue(x("hello_world: ; 0x4050", returnable=returnable, bank=5))
        self.assertTrue(returnable["address"] == 0x14050)
    def test_line_has_label(self):
        x = line_has_label
        self.assertTrue(x("hi:"))
        self.assertTrue(x("Hello: "))
        self.assertTrue(x("MyLabel: ; test xyz"))
        self.assertFalse(x(":"))
        self.assertFalse(x(";HelloWorld:"))
        self.assertFalse(x("::::"))
        self.assertFalse(x(":;:;:;:::"))
    def test_get_label_from_line(self):
        x = get_label_from_line
        self.assertEqual(x("HelloWorld: "), "HelloWorld")
        self.assertEqual(x("HiWorld:"), "HiWorld")
        self.assertEqual(x("HiWorld"), None)
    def test_find_labels_without_addresses(self):
        global asm
        asm = ["hello_world: ; 0x1", "hello_world2: ;"]
        labels = find_labels_without_addresses()
        self.failUnless(labels[0]["label"] == "hello_world2")
        asm = ["hello world: ;1", "hello_world: ;2"]
        labels = find_labels_without_addresses()
        self.failUnless(len(labels) == 0)
        asm = None
    def test_get_labels_between(self):
        global asm
        x = get_labels_between#(start_line_id, end_line_id, bank)
        asm = ["HelloWorld: ;1",
               "hi:",
               "no label on this line",
              ]
        labels = x(0, 2, 0x12)
        self.assertEqual(len(labels), 1)
        self.assertEqual(labels[0]["label"], "HelloWorld")
        del asm
    def test_scan_for_predefined_labels(self):
        #label keys: line_number, bank, label, offset, address
        load_asm()
        all_labels = scan_for_predefined_labels()
        label_names = [x["label"] for x in all_labels]
        self.assertIn("GetFarByte", label_names)
        self.assertIn("AddNTimes", label_names)
        self.assertIn("CheckShininess", label_names)
    def test_write_all_labels(self):
        """dumping json into a file"""
        filename = "test_labels.json"
        #remove the current file
        if os.path.exists(filename):
            os.system("rm " + filename)
        #make up some labels
        labels = []
        #fake label 1
        label = {"line_number": 5, "bank": 0, "label": "SomeLabel", "address": 0x10}
        labels.append(label)
        #fake label 2
        label = {"line_number": 15, "bank": 2, "label": "SomeOtherLabel", "address": 0x9F0A}
        labels.append(label)
        #dump to file
        write_all_labels(labels, filename=filename)
        #open the file and read the contents
        file_handler = open(filename, "r")
        contents = file_handler.read()
        file_handler.close()
        #parse into json
        obj = json.read(contents)
        #begin testing
        self.assertEqual(len(obj), len(labels))
        self.assertEqual(len(obj), 2)
        self.assertEqual(obj, labels)
    def test_isolate_incbins(self):
        global asm
        asm = ["123", "456", "789", "abc", "def", "ghi",
               'INCBIN "baserom.gbc",$12DA,$12F8 - $12DA',
               "jkl",
               'INCBIN "baserom.gbc",$137A,$13D0 - $137A']
        lines = isolate_incbins()
        self.assertIn(asm[6], lines)
        self.assertIn(asm[8], lines)
        for line in lines:
            self.assertIn("baserom", line)
    def test_process_incbins(self):
        global incbin_lines, processed_incbins, asm
        incbin_lines = ['INCBIN "baserom.gbc",$12DA,$12F8 - $12DA',
                        'INCBIN "baserom.gbc",$137A,$13D0 - $137A']
        asm = copy(incbin_lines)
        asm.insert(1, "some other random line")
        processed_incbins = process_incbins()
        self.assertEqual(len(processed_incbins), len(incbin_lines))
        self.assertEqual(processed_incbins[0]["line"], incbin_lines[0])
        self.assertEqual(processed_incbins[2]["line"], incbin_lines[1])
    def test_reset_incbins(self):
        global asm, incbin_lines, processed_incbins
        #temporarily override the functions
        global load_asm, isolate_incbins, process_incbins
        temp1, temp2, temp3 = load_asm, isolate_incbins, process_incbins
        def load_asm(): pass
        def isolate_incbins(): pass
        def process_incbins(): pass
        #call reset
        reset_incbins()
        #check the results
        self.assertTrue(asm == [] or asm == None)
        self.assertTrue(incbin_lines == [])
        self.assertTrue(processed_incbins == {})
        #reset the original functions
        load_asm, isolate_incbins, process_incbins = temp1, temp2, temp3
    def test_find_incbin_to_replace_for(self):
        global asm, incbin_lines, processed_incbins
        asm = ['first line', 'second line', 'third line',
               'INCBIN "baserom.gbc",$90,$200 - $90',
               'fifth line', 'last line']
        isolate_incbins()
        process_incbins()
        line_num = find_incbin_to_replace_for(0x100)
        #must be the 4th line (the INBIN line)
        self.assertEqual(line_num, 3)
    def test_split_incbin_line_into_three(self):
        global asm, incbin_lines, processed_incbins
        asm = ['first line', 'second line', 'third line',
               'INCBIN "baserom.gbc",$90,$200 - $90',
               'fifth line', 'last line']
        isolate_incbins()
        process_incbins()
        content = split_incbin_line_into_three(3, 0x100, 10)
        #must end up with three INCBINs in output
        self.failUnless(content.count("INCBIN") == 3)
    def test_analyze_intervals(self):
        global asm, incbin_lines, processed_incbins
        asm, incbin_lines, processed_incbins = None, [], {}
        asm = ['first line', 'second line', 'third line',
               'INCBIN "baserom.gbc",$90,$200 - $90',
               'fifth line', 'last line',
               'INCBIN "baserom.gbc",$33F,$4000 - $33F']
        isolate_incbins()
        process_incbins()
        largest = analyze_intervals()
        self.assertEqual(largest[0]["line_number"], 6)
        self.assertEqual(largest[0]["line"], asm[6])
        self.assertEqual(largest[1]["line_number"], 3)
        self.assertEqual(largest[1]["line"], asm[3])
    def test_generate_diff_insert(self):
        global asm
        asm = ['first line', 'second line', 'third line',
               'INCBIN "baserom.gbc",$90,$200 - $90',
               'fifth line', 'last line',
               'INCBIN "baserom.gbc",$33F,$4000 - $33F']
        diff = generate_diff_insert(0, "the real first line", debug=False)
        self.assertIn("the real first line", diff)
        self.assertIn("INCBIN", diff)
        self.assertNotIn("No newline at end of file", diff)
        self.assertIn("+"+asm[1], diff)
class TestMapParsing(unittest.TestCase):
    #def test_parse_warp_bytes(self):
    #    pass #or raise NotImplementedError, bryan_message
    #def test_parse_xy_trigger_bytes(self):
    #    pass #or raise NotImplementedError, bryan_message
    #def test_parse_signpost_bytes(self):
    #    pass #or raise NotImplementedError, bryan_message
    #def test_parse_people_event_bytes(self):
    #    pass #or raise NotImplementedError, bryan_message
    #def test_parse_trainer_header_at(self):
    #    pass #or raise NotImplementedError, bryan_message
    #def test_parse_map_header_at(self):
    #    pass #or raise NotImplementedError, bryan_message
    #def test_parse_second_map_header_at(self):
    #    pass #or raise NotImplementedError, bryan_message
    #def test_parse_map_event_header_at(self):
    #    pass #or raise NotImplementedError, bryan_message
    #def test_parse_map_script_header_at(self):
    #    pass #or raise NotImplementedError, bryan_message
    #def test_parse_map_header_by_id(self):
    #    pass #or raise NotImplementedError, bryan_message
    def test_parse_all_map_headers(self):
        global parse_map_header_at, counter
        counter = 0
        for k in map_names.keys():
            if "offset" not in map_names[k].keys():
                map_names[k]["offset"] = 0
        temp = parse_map_header_at
        def parse_map_header_at(address, map_group=None, map_id=None, debug=False):
            global counter
            counter += 1
            return {}
        parse_all_map_headers(debug=False)
        self.assertEqual(counter, 388)
        parse_map_header_at = temp
class TestTextScript(unittest.TestCase):
    """for testing 'in-script' commands, etc."""
    #def test_to_asm(self):
    #    pass #or raise NotImplementedError, bryan_message
    #def test_find_addresses(self):
    #    pass #or raise NotImplementedError, bryan_message
    #def test_parse_text_at(self):
    #    pass #or raise NotImplementedError, bryan_message
    #def test_to_asm_at(self):
    #    pass #or raise NotImplementedError, bryan_message
class TestEncodedText(unittest.TestCase):
    """for testing chars-table encoded text chunks"""
    def test_process_00_subcommands(self):
        g = process_00_subcommands(0x197186, 0x197186+601, debug=False)
        self.assertEqual(len(g), 42)
        self.assertEqual(len(g[0]), 13)
        self.assertEqual(g[1], [184, 174, 180, 211, 164, 127, 20, 231, 81])
    def test_parse_text_at2(self):
        oakspeech = parse_text_at2(0x197186, 601, debug=False)
        self.assertIn("encyclopedia", oakspeech)
        self.assertIn("researcher", oakspeech)
        self.assertIn("dependable", oakspeech)
    def test_parse_text_engine_script_at(self):
        p = parse_text_engine_script_at(0x197185, debug=False)
        self.assertEqual(len(p), 2)
        self.assertEqual(len(p[0]["lines"]), 41)
    #don't really care about these other two
    def test_parse_text_from_bytes(self): pass
    def test_parse_text_at(self): pass
class TestScript(unittest.TestCase):
    """for testing parse_script_engine_script_at and script parsing in
    general. Script should be a class."""
    #def test_parse_script_engine_script_at(self):
    #    pass #or raise NotImplementedError, bryan_message
    def test_find_all_text_pointers_in_script_engine_script(self):
        address = 0x197637 #0x197634
        script = parse_script_engine_script_at(address, debug=False)
        bank = calculate_bank(address)
        r = find_all_text_pointers_in_script_engine_script(script, bank=bank, debug=False)
        results = list(r)
        self.assertIn(0x197661, results)
class TestLabel(unittest.TestCase):
    def test_label_making(self):
        line_number = 2
        address = 0xf0c0
        label_name = "poop"
        l = Label(name=label_name, address=address, line_number=line_number)
        self.failUnless(hasattr(l, "name"))
        self.failUnless(hasattr(l, "address"))
        self.failUnless(hasattr(l, "line_number"))
        self.failIf(isinstance(l.address, str))
        self.failIf(isinstance(l.line_number, str))
        self.failUnless(isinstance(l.name, str))
        self.assertEqual(l.line_number, line_number)
        self.assertEqual(l.name, label_name)
        self.assertEqual(l.address, address)
class TestByteParams(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        load_rom()
        cls.address = 10
        cls.sbp = SingleByteParam(address=cls.address)
    @classmethod
    def tearDownClass(cls):
        del cls.sbp
    def test__init__(self):
        self.assertEqual(self.sbp.size, 1)
        self.assertEqual(self.sbp.address, self.address)
    def test_parse(self):
        self.sbp.parse()
        self.assertEqual(str(self.sbp.byte), str(45))
    def test_to_asm(self):
        self.assertEqual(self.sbp.to_asm(), "$2d")
        self.sbp.should_be_decimal = True
        self.assertEqual(self.sbp.to_asm(), str(45))
    def test_HexByte_to_asm(self):
        h = HexByte(address=10)
        a = h.to_asm()
        self.assertEqual(a, "0x2d")
    def test_DollarSignByte_to_asm(self):
        d = DollarSignByte(address=10)
        a = d.to_asm()
        self.assertEqual(a, "$2d")
    def test_ItemLabelByte_to_asm(self):
        i = ItemLabelByte(address=433)
        self.assertEqual(i.byte, 54)
        self.assertEqual(i.to_asm(), "COIN_CASE")
        self.assertEqual(ItemLabelByte(address=10).to_asm(), "$2d")
    def test_DecimalParam_to_asm(self):
        d = DecimalParam(address=10)
        x = d.to_asm()
        self.assertEqual(x, str(0x2d))
class TestMultiByteParam(unittest.TestCase):
    def setup_for(self, somecls, byte_size=2, address=443, **kwargs):
        self.cls = somecls(address=address, size=byte_size, **kwargs)
        self.assertEqual(self.cls.address, address)
        self.assertEqual(self.cls.bytes, rom_interval(address, byte_size, strings=False))
        self.assertEqual(self.cls.size, byte_size)
    def test_two_byte_param(self):
        self.setup_for(MultiByteParam, byte_size=2)
        self.assertEqual(self.cls.to_asm(), "$f0c0")
    def test_three_byte_param(self):
        self.setup_for(MultiByteParam, byte_size=3)
    def test_PointerLabelParam_no_bank(self):
        self.setup_for(PointerLabelParam, bank=None)
        #assuming no label at this location..
        self.assertEqual(self.cls.to_asm(), "$f0c0")
        global all_labels
        #hm.. maybe all_labels should be using a class?
        all_labels = [{"label": "poop", "address": 0xf0c0,
                       "offset": 0xf0c0, "bank": 0,
                       "line_number": 2
                     }]
        self.assertEqual(self.cls.to_asm(), "poop")
class TestPostParsing: #(unittest.TestCase):
    """tests that must be run after parsing all maps"""
    @classmethod
    def setUpClass(cls):
        run_main()
    def test_signpost_counts(self):
        self.assertEqual(len(map_names[1][1]["signposts"]), 0)
        self.assertEqual(len(map_names[1][2]["signposts"]), 2)
        self.assertEqual(len(map_names[10][5]["signposts"]), 7)
    def test_warp_counts(self):
        self.assertEqual(map_names[10][5]["warp_count"], 9)
        self.assertEqual(map_names[18][5]["warp_count"], 3)
        self.assertEqual(map_names[15][1]["warp_count"], 2)
    def test_map_sizes(self):
        self.assertEqual(map_names[15][1]["height"], 18)
        self.assertEqual(map_names[15][1]["width"], 10)
        self.assertEqual(map_names[7][1]["height"], 4)
        self.assertEqual(map_names[7][1]["width"], 4)
    def test_map_connection_counts(self):
        self.assertEqual(map_names[7][1]["connections"], 0)
        self.assertEqual(map_names[10][1]["connections"], 12)
        self.assertEqual(map_names[10][2]["connections"], 12)
        self.assertEqual(map_names[11][1]["connections"], 9) #or 13?
    def test_second_map_header_address(self):
        self.assertEqual(map_names[11][1]["second_map_header_address"], 0x9509c)
        self.assertEqual(map_names[1][5]["second_map_header_address"], 0x95bd0)
    def test_event_address(self):
        self.assertEqual(map_names[17][5]["event_address"], 0x194d67)
        self.assertEqual(map_names[23][3]["event_address"], 0x1a9ec9)
    def test_people_event_counts(self):
        self.assertEqual(len(map_names[23][3]["people_events"]), 4)
        self.assertEqual(len(map_names[10][3]["people_events"]), 9)
class TestMetaTesting(unittest.TestCase):
    """test whether or not i am finding at least
    some of the tests in this file"""
    tests = None
    def setUp(self):
        if self.tests == None:
            self.__class__.tests = assemble_test_cases()
    def test_assemble_test_cases_count(self):
        "does assemble_test_cases find some tests?"
        self.failUnless(len(self.tests) > 0)
    def test_assemble_test_cases_inclusion(self):
        "is this class found by assemble_test_cases?"
        #i guess it would have to be for this to be running?
        self.failUnless(self.__class__ in self.tests)
    def test_assemble_test_cases_others(self):
        "test other inclusions for assemble_test_cases"
        self.failUnless(TestRomStr in self.tests)
        self.failUnless(TestCram in self.tests)
    def test_check_has_test(self):
        self.failUnless(check_has_test("beaver", ["test_beaver"]))
        self.failUnless(check_has_test("beaver", ["test_beaver_2"]))
        self.failIf(check_has_test("beaver_1", ["test_beaver"]))
    def test_find_untested_methods(self):
        untested = find_untested_methods()
        #the return type must be an iterable
        self.failUnless(hasattr(untested, "__iter__"))
        #.. basically, a list
        self.failUnless(isinstance(untested, list))
    def test_find_untested_methods_method(self):
        """create a function and see if it is found"""
        #setup a function in the global namespace
        global some_random_test_method
        #define the method
        def some_random_test_method(): pass
        #first make sure it is in the global scope
        members = inspect.getmembers(sys.modules[__name__], inspect.isfunction)
        func_names = [functuple[0] for functuple in members]
        self.assertIn("some_random_test_method", func_names)
        #test whether or not it is found by find_untested_methods
        untested = find_untested_methods()
        self.assertIn("some_random_test_method", untested)
        #remove the test method from the global namespace
        del some_random_test_method
    def test_load_tests(self):
        loader = unittest.TestLoader()
        suite = load_tests(loader, None, None)
        suite._tests[0]._testMethodName
        membership_test = lambda member: \
            inspect.isclass(member) and issubclass(member, unittest.TestCase)
        tests = inspect.getmembers(sys.modules[__name__], membership_test)
        classes = [x[1] for x in tests]
        for test in suite._tests:
            self.assertIn(test.__class__, classes)
    def test_report_untested(self):
        untested = find_untested_methods()
        output = report_untested()
        if len(untested) > 0:
            self.assertIn("NOT TESTED", output)
            for name in untested:
                self.assertIn(name, output)
        elif len(untested) == 0:
            self.assertNotIn("NOT TESTED", output)
def assemble_test_cases():
    """finds classes that inherit from unittest.TestCase
    because i am too lazy to remember to add them to a 
    global list of tests for the suite runner"""
    classes = []
    clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)
    for (name, some_class) in clsmembers:
        if issubclass(some_class, unittest.TestCase):
            classes.append(some_class)
    return classes
def load_tests(loader, tests, pattern):
    suite = unittest.TestSuite()
    for test_class in assemble_test_cases():
        tests = loader.loadTestsFromTestCase(test_class)
        suite.addTests(tests)
    return suite
def check_has_test(func_name, tested_names):
    """checks if there is a test dedicated to this function"""
    if "test_"+func_name in tested_names:
        return True
    for name in tested_names:
        if "test_"+func_name in name:
            return True
    return False
def find_untested_methods():
    """finds all untested functions in this module
    by searching for method names in test case
    method names."""
    untested = []
    avoid_funcs = ["main", "run_tests", "run_main", "copy", "deepcopy"]
    test_funcs = []
    #get a list of all classes in this module
    classes = inspect.getmembers(sys.modules[__name__], inspect.isclass)
    #for each class..
    for (name, klass) in classes:
        #only look at those that have tests
        if issubclass(klass, unittest.TestCase):
            #look at this class' methods
            funcs = inspect.getmembers(klass, inspect.ismethod)
            #for each method..
            for (name2, func) in funcs:
                #store the ones that begin with test_
                if "test_" in name2 and name2[0:5] == "test_":
                    test_funcs.append([name2, func])
    #assemble a list of all test method names (test_x, test_y, ..)
    tested_names = [funcz[0] for funcz in test_funcs]
    #now get a list of all functions in this module
    funcs = inspect.getmembers(sys.modules[__name__], inspect.isfunction)
    #for each function..
    for (name, func) in funcs:
        #we don't care about some of these
        if name in avoid_funcs: continue
        #skip functions beginning with _
        if name[0] == "_": continue 
        #check if this function has a test named after it
        has_test = check_has_test(name, tested_names)
        if not has_test:
            untested.append(name)
    return untested
def report_untested():
    untested = find_untested_methods()
    output = "NOT TESTED: ["
    first = True
    for name in untested:
        if first:
            output += name
            first = False
        else: output += ", "+name
    output += "]\n"
    output += "total untested: " + str(len(untested))
    return output

#### ways to run this file ####

def run_tests(): #rather than unittest.main()
    loader = unittest.TestLoader()
    suite = load_tests(loader, None, None)
    unittest.TextTestRunner(verbosity=2).run(suite)
    print report_untested()
def run_main():
    #read the rom and figure out the offsets for maps
    direct_load_rom()
    load_map_group_offsets()
    #add the offsets into our map structure, why not (johto maps only)
    [map_names[map_group_id+1].update({"offset": offset}) for map_group_id, offset in enumerate(map_group_offsets)]
    #parse map header bytes for each map
    parse_all_map_headers()
#just a helpful alias
main=run_main
#when you run the file.. do unit tests
if __name__ == "__main__":
    run_tests()
#when you load the module.. parse everything
elif __name__ == "crystal": pass
    #run_main()