File: bincopy.py

package info (click to toggle)
python-bincopy 20.1.1%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 184 kB
  • sloc: python: 1,418; makefile: 16
file content (2281 lines) | stat: -rwxr-xr-x 74,796 bytes parent folder | download
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
"""Mangling of various file formats that conveys binary information
(Motorola S-Record, Intel HEX, TI-TXT and binary files).

"""

import re
import copy
import binascii
import string
import sys
import argparse
from collections import namedtuple
from io import StringIO
from io import BytesIO

from humanfriendly import format_size
from argparse_addons import Integer
from elftools.elf.elffile import ELFFile
from elftools.elf.constants import SH_FLAGS


__author__ = 'Erik Moqvist'
__version__ = '20.1.1'


DEFAULT_WORD_SIZE_BITS = 8

# Intel hex types.
IHEX_DATA = 0
IHEX_END_OF_FILE = 1
IHEX_EXTENDED_SEGMENT_ADDRESS = 2
IHEX_START_SEGMENT_ADDRESS = 3
IHEX_EXTENDED_LINEAR_ADDRESS = 4
IHEX_START_LINEAR_ADDRESS = 5

# TI-TXT defines
TI_TXT_BYTES_PER_LINE = 16


class Error(Exception):
    """Bincopy base exception.

    """

    pass


class UnsupportedFileFormatError(Error):

    def __str__(self):
        return 'Unsupported file format.'


class AddDataError(Error):
    pass


def crc_srec(hexstr):
    """Calculate the CRC for given Motorola S-Record hexstring.

    """

    crc = sum(binascii.unhexlify(hexstr))
    crc &= 0xff
    crc ^= 0xff

    return crc


def crc_ihex(hexstr):
    """Calculate the CRC for given Intel HEX hexstring.

    """

    crc = sum(binascii.unhexlify(hexstr))
    crc &= 0xff
    crc = ((~crc + 1) & 0xff)

    return crc


def pack_srec(type_, address, size, data):
    """Create a Motorola S-Record record of given data.

    """

    if type_ in '0159':
        line = f'{size + 2 + 1:02X}{address:04X}'
    elif type_ in '268':
        line = f'{size + 3 + 1:02X}{address:06X}'
    elif type_ in '37':
        line = f'{size + 4 + 1:02X}{address:08X}'
    else:
        raise Error(f"expected record type 0..3 or 5..9, but got '{type_}'")

    if data:
        line += binascii.hexlify(data).decode('ascii').upper()

    return f'S{type_}{line}{crc_srec(line):02X}'


def unpack_srec(record):
    """Unpack given Motorola S-Record record into variables.

    """

    # Minimum STSSCC, where T is type, SS is size and CC is crc.
    if len(record) < 6:
        raise Error(f"record '{record}' too short")

    if record[0] != 'S':
        raise Error(f"record '{record}' not starting with an 'S'")

    value = bytearray.fromhex(record[2:])
    size = value[0]

    if size != len(value) - 1:
        raise Error(f"record '{record}' has wrong size")

    type_ = record[1]

    if type_ in '0159':
        width = 2
    elif type_ in '268':
        width = 3
    elif type_ in '37':
        width = 4
    else:
        raise Error(f"expected record type 0..3 or 5..9, but got '{type_}'")

    data_offset = (1 + width)
    address = int.from_bytes(value[1:data_offset], byteorder='big')
    data = value[data_offset:-1]
    actual_crc = value[-1]
    expected_crc = crc_srec(record[2:-2])

    if actual_crc != expected_crc:
        raise Error(
            f"expected crc '{expected_crc:02X}' in record {record}, but got "
            f"'{actual_crc:02X}'")

    return (type_, address, len(data), data)


def pack_ihex(type_, address, size, data):
    """Create a Intel HEX record of given data.

    """

    line = f'{size:02X}{address:04X}{type_:02X}'

    if data:
        line += binascii.hexlify(data).decode('ascii').upper()

    return f':{line}{crc_ihex(line):02X}'


def unpack_ihex(record):
    """Unpack given Intel HEX record into variables.

    """

    # Minimum :SSAAAATTCC, where SS is size, AAAA is address, TT is
    # type and CC is crc.
    if len(record) < 11:
        raise Error(f"record '{record}' too short")

    if record[0] != ':':
        raise Error(f"record '{record}' not starting with a ':'")

    value = bytearray.fromhex(record[1:])
    size = value[0]

    if size != len(value) - 5:
        raise Error(f"record '{record}' has wrong size")

    address = int.from_bytes(value[1:3], byteorder='big')
    type_ = value[3]
    data = value[4:-1]
    actual_crc = value[-1]
    expected_crc = crc_ihex(record[1:-2])

    if actual_crc != expected_crc:
        raise Error(
            f"expected crc '{expected_crc:02X}' in record {record}, but got "
            f"'{actual_crc:02X}'")

    return (type_, address, size, data)


def pretty_srec(record):
    """Make given Motorola S-Record pretty by adding colors to it.

    """

    type_ = record[1:2]

    if type_ == '0':
        width = 4
        type_color = '\033[0;92m'
        type_text = ' (header)'
    elif type_ in '1':
        width = 4
        type_color = '\033[0;32m'
        type_text = ' (data)'
    elif type_ in '2':
        width = 6
        type_color = '\033[0;32m'
        type_text = ' (data)'
    elif type_ in '3':
        width = 8
        type_color = '\033[0;32m'
        type_text = ' (data)'
    elif type_ in '5':
        width = 4
        type_color = '\033[0;93m'
        type_text = ' (count)'
    elif type_ in '6':
        width = 6
        type_color = '\033[0;93m'
        type_text = ' (count)'
    elif type_ in '7':
        width = 8
        type_color = '\033[0;96m'
        type_text = ' (start address)'
    elif type_ in '8':
        width = 6
        type_color = '\033[0;96m'
        type_text = ' (start address)'
    elif type_ in '9':
        width = 4
        type_color = '\033[0;96m'
        type_text = ' (start address)'
    else:
        raise Error(f"expected record type 0..3 or 5..9, but got '{type_}'")

    return (type_color + record[:2]
            + '\033[0;95m' + record[2:4]
            + '\033[0;33m' + record[4:4 + width]
            + '\033[0m' + record[4 + width:-2]
            + '\033[0;36m' + record[-2:]
            + '\033[0m' + type_text)


def pretty_ihex(record):
    """Make given Intel HEX record pretty by adding colors to it.

    """

    type_ = int(record[7:9], 16)

    if type_ == IHEX_DATA:
        type_color = '\033[0;32m'
        type_text = ' (data)'
    elif type_ == IHEX_END_OF_FILE:
        type_color = '\033[0;96m'
        type_text = ' (end of file)'
    elif type_ == IHEX_EXTENDED_SEGMENT_ADDRESS:
        type_color = '\033[0;34m'
        type_text = ' (extended segment address)'
    elif type_ == IHEX_EXTENDED_LINEAR_ADDRESS:
        type_color = '\033[0;96m'
        type_text = ' (extended linear address)'
    elif type_ == IHEX_START_SEGMENT_ADDRESS:
        type_color = '\033[0;92m'
        type_text = ' (start segment address)'
    elif type_ == IHEX_START_LINEAR_ADDRESS:
        type_color = '\033[0;92m'
        type_text = ' (start linear address)'
    else:
        raise Error(f"expected type 1..5 in record {record}, but got {type_}")

    return ('\033[0;31m' + record[:1]
            + '\033[0;95m' + record[1:3]
            + '\033[0;33m' + record[3:7]
            + type_color + record[7:9]
            + '\033[0m' + record[9:-2]
            + '\033[0;36m' + record[-2:]
            + '\033[0m' + type_text)


def pretty_ti_txt(line):
    """Make given TI TXT line pretty by adding colors to it.

    """

    if line.startswith('@'):
        line = '\033[0;33m' + line + '\033[0m (segment address)'
    elif line == 'q':
        line = '\033[0;35m' + line + '\033[0m (end of file)'
    else:
        line += ' (data)'

    return line


def comment_remover(text):
    def replacer(match):
        s = match.group(0)

        if s.startswith('/'):
            return " " # note: a space and not an empty string
        else:
            return s

    pattern = re.compile(
        r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
        re.DOTALL | re.MULTILINE)

    return re.sub(pattern, replacer, text)


def is_srec(records):
    try:
        unpack_srec(records.partition('\n')[0].rstrip())
    except Error:
        return False
    else:
        return True


def is_ihex(records):
    try:
        unpack_ihex(records.partition('\n')[0].rstrip())
    except Error:
        return False
    else:
        return True


def is_ti_txt(data):
    try:
        BinFile().add_ti_txt(data)
    except Exception:
        return False
    else:
        return True


def is_verilog_vmem(data):
    try:
        BinFile().add_verilog_vmem(data)
    except Exception:
        return False
    else:
        return True


class Segment:
    """A segment is a chunk data with given minimum and maximum address.

    """

    def __init__(self, minimum_address, maximum_address, data, word_size_bytes):
        self.minimum_address = minimum_address
        self.maximum_address = maximum_address
        self.data = bytearray(data)
        self.word_size_bytes = word_size_bytes

    @property
    def address(self):
        return self.minimum_address // self.word_size_bytes

    def chunks(self, size=32, alignment=1, padding=b''):
        """Yield data chunks of `size` words, aligned as given by `alignment`.

        Each chunk is itself a Segment.

        `size` and `alignment` are in words. `size` must be a multiple of
        `alignment`. If set, `padding` must be a word value.

        If `padding` is set, the first and final chunks are padded so that:
            1. The first chunk is aligned even if the segment itself is not.
            2. The final chunk's size is a multiple of `alignment`.

        """

        if (size % alignment) != 0:
            raise Error(f'size {size} is not a multiple of alignment {alignment}')

        if padding and len(padding) != self.word_size_bytes:
            raise Error(f'padding must be a word value (size {self.word_size_bytes}),'
                        f' got {padding}')

        size *= self.word_size_bytes
        alignment *= self.word_size_bytes
        address = self.minimum_address
        data = self.data

        # Apply padding to first and final chunk, if padding is non-empty.
        align_offset = address % alignment
        address -= align_offset * bool(padding)
        data = align_offset // self.word_size_bytes * padding + data
        data += (alignment - len(data)) % alignment // self.word_size_bytes * padding

        # First chunk may be non-aligned and shorter than `size` if padding is empty.
        chunk_offset = (address % alignment)

        if chunk_offset != 0:
            first_chunk_size = (alignment - chunk_offset)
            yield Segment(address,
                          address + size,
                          data[:first_chunk_size],
                          self.word_size_bytes)
            address += first_chunk_size
            data = data[first_chunk_size:]
        else:
            first_chunk_size = 0

        for offset in range(0, len(data), size):
            yield Segment(address + offset,
                          address + offset + size,
                          data[offset:offset + size],
                          self.word_size_bytes)

    def add_data(self, minimum_address, maximum_address, data, overwrite):
        """Add given data to this segment. The added data must be adjacent to
        the current segment data, otherwise an exception is thrown.

        """

        if minimum_address == self.maximum_address:
            self.maximum_address = maximum_address
            self.data += data
        elif maximum_address == self.minimum_address:
            self.minimum_address = minimum_address
            self.data = data + self.data
        elif (overwrite
              and minimum_address < self.maximum_address
              and maximum_address > self.minimum_address):
            self_data_offset = minimum_address - self.minimum_address

            # Prepend data.
            if self_data_offset < 0:
                self_data_offset *= -1
                self.data = data[:self_data_offset] + self.data
                del data[:self_data_offset]
                self.minimum_address = minimum_address

            # Overwrite overlapping part.
            self_data_left = len(self.data) - self_data_offset

            if len(data) <= self_data_left:
                self.data[self_data_offset:self_data_offset + len(data)] = data
                data = bytearray()
            else:
                self.data[self_data_offset:] = data[:self_data_left]
                data = data[self_data_left:]

            # Append data.
            if len(data) > 0:
                self.data += data
                self.maximum_address = maximum_address
        else:
            raise AddDataError(
                'data added to a segment must be adjacent to or overlapping '
                'with the original segment data')

    def remove_data(self, minimum_address, maximum_address):
        """Remove given data range from this segment. Returns the second
        segment if the removed data splits this segment in two.

        """

        if ((minimum_address >= self.maximum_address)
            or (maximum_address <= self.minimum_address)):
            return

        if minimum_address < self.minimum_address:
            minimum_address = self.minimum_address

        if maximum_address > self.maximum_address:
            maximum_address = self.maximum_address

        remove_size = maximum_address - minimum_address
        part1_size = minimum_address - self.minimum_address
        part1_data = self.data[0:part1_size]
        part2_data = self.data[part1_size + remove_size:]

        if len(part1_data) and len(part2_data):
            # Update this segment and return the second segment.
            self.maximum_address = self.minimum_address + part1_size
            self.data = part1_data

            return Segment(maximum_address,
                           maximum_address + len(part2_data),
                           part2_data,
                           self.word_size_bytes)
        else:
            # Update this segment.
            if len(part1_data) > 0:
                self.maximum_address = minimum_address
                self.data = part1_data
            elif len(part2_data) > 0:
                self.minimum_address = maximum_address
                self.data = part2_data
            else:
                self.maximum_address = self.minimum_address
                self.data = bytearray()

    def __eq__(self, other):
        if isinstance(other, tuple):
            return self.address, self.data == other
        elif isinstance(other, Segment):
            return ((self.minimum_address == other.minimum_address)
                    and (self.maximum_address == other.maximum_address)
                    and (self.data == other.data)
                    and (self.word_size_bytes == other.word_size_bytes))
        else:
            return False

    def __iter__(self):
        # Allows unpacking as ``address, data = segment``.
        yield self.address
        yield self.data

    def __repr__(self):
        return f'Segment(address={self.address}, data={self.data})'

    def __len__(self):
        return len(self.data) // self.word_size_bytes


_Segment = Segment


class Segments:
    """A list of segments.

    """

    def __init__(self, word_size_bytes):
        self.word_size_bytes = word_size_bytes
        self._current_segment = None
        self._current_segment_index = None
        self._list = []

    def __str__(self):
        return '\n'.join([str(s) for s in self._list])

    def __iter__(self):
        """Iterate over all segments.

        """

        for segment in self._list:
            yield segment

    def __getitem__(self, index):
        try:
            return self._list[index]
        except IndexError:
            raise Error('segment does not exist')

    @property
    def minimum_address(self):
        """The minimum address of the data, or ``None`` if no data is
        available.

        """

        if not self._list:
            return None

        return self._list[0].minimum_address

    @property
    def maximum_address(self):
        """The maximum address of the data, or ``None`` if no data is
        available.

        """

        if not self._list:
            return None

        return self._list[-1].maximum_address

    def add(self, segment, overwrite=False):
        """Add segments by ascending address.

        """

        if self._list:
            if segment.minimum_address == self._current_segment.maximum_address:
                # Fast insertion for adjacent segments.
                self._current_segment.add_data(segment.minimum_address,
                                               segment.maximum_address,
                                               segment.data,
                                               overwrite)
            else:
                # Linear insert.
                for i, s in enumerate(self._list):
                    if segment.minimum_address <= s.maximum_address:
                        break

                if segment.minimum_address > s.maximum_address:
                    # Non-overlapping, non-adjacent after.
                    self._list.append(segment)
                elif segment.maximum_address < s.minimum_address:
                    # Non-overlapping, non-adjacent before.
                    self._list.insert(i, segment)
                else:
                    # Adjacent or overlapping.
                    s.add_data(segment.minimum_address,
                               segment.maximum_address,
                               segment.data,
                               overwrite)
                    segment = s

                self._current_segment = segment
                self._current_segment_index = i

            # Remove overwritten and merge adjacent segments.
            while self._current_segment is not self._list[-1]:
                s = self._list[self._current_segment_index + 1]

                if self._current_segment.maximum_address >= s.maximum_address:
                    # The whole segment is overwritten.
                    del self._list[self._current_segment_index + 1]
                elif self._current_segment.maximum_address >= s.minimum_address:
                    # Adjacent or beginning of the segment overwritten.
                    self._current_segment.add_data(
                        self._current_segment.maximum_address,
                        s.maximum_address,
                        s.data[self._current_segment.maximum_address - s.minimum_address:],
                        overwrite=False)
                    del self._list[self._current_segment_index+1]
                    break
                else:
                    # Segments are not overlapping, nor adjacent.
                    break
        else:
            self._list.append(segment)
            self._current_segment = segment
            self._current_segment_index = 0

    def remove(self, minimum_address, maximum_address):
        new_list = []

        for segment in self._list:
            split = segment.remove_data(minimum_address, maximum_address)

            if segment.minimum_address < segment.maximum_address:
                new_list.append(segment)

            if split:
                new_list.append(split)

        self._list = new_list

    def chunks(self, size=32, alignment=1, padding=b''):
        """Iterate over all segments and yield chunks of the data.
        
        The chunks are `size` words long, aligned as given by `alignment`.

        Each chunk is itself a Segment.

        `size` and `alignment` are in words. `size` must be a multiple of
        `alignment`. If set, `padding` must be a word value.

        If `padding` is set, the first and final chunks of each segment are
        padded so that:
            1. The first chunk is aligned even if the segment itself is not.
            2. The final chunk's size is a multiple of `alignment`.

        """

        if (size % alignment) != 0:
            raise Error(f'size {size} is not a multiple of alignment {alignment}')

        if padding and len(padding) != self.word_size_bytes:
            raise Error(f'padding must be a word value (size {self.word_size_bytes}),'
                        f' got {padding}')

        previous = Segment(-1, -1, b'', 1)

        for segment in self:
            for chunk in segment.chunks(size, alignment, padding):
                # When chunks are padded to alignment, the final chunk of the previous
                # segment and the first chunk of the current segment may overlap by
                # one alignment block. To avoid overwriting data from the lower
                # segment, the chunks must be merged.
                if chunk.address < previous.address + len(previous):
                    low = previous.data[-alignment * self.word_size_bytes:]
                    high = chunk.data[:alignment * self.word_size_bytes]
                    merged = int.to_bytes(int.from_bytes(low, 'big') ^
                                          int.from_bytes(high, 'big') ^
                                          int.from_bytes(alignment * padding, 'big'),
                                          alignment * self.word_size_bytes, 'big')
                    chunk.data = merged + chunk.data[alignment * self.word_size_bytes:]

                yield chunk

            previous = chunk

    def __len__(self):
        """Get the number of segments.

        """

        return len(self._list)


_Segments = Segments
    

class BinFile:
    """A binary file.

    `filenames` may be a single file or a list of files. Each file is
    opened and its data added, given that the format is Motorola
    S-Records, Intel HEX or TI-TXT.

    Set `overwrite` to ``True`` to allow already added data to be
    overwritten.

    `word_size_bits` is the number of bits per word.

    `header_encoding` is the encoding used to encode and decode the
    file header (if any). Give as ``None`` to disable encoding,
    leaving the header as an untouched bytes object.

    """

    def __init__(self,
                 filenames=None,
                 overwrite=False,
                 word_size_bits=DEFAULT_WORD_SIZE_BITS,
                 header_encoding='utf-8'):
        if (word_size_bits % 8) != 0:
            raise Error(
                f'word size must be a multiple of 8 bits, but got {word_size_bits} '
                f'bits')

        self.word_size_bits = word_size_bits
        self.word_size_bytes = (word_size_bits // 8)
        self._header_encoding = header_encoding
        self._header = None
        self._execution_start_address = None
        self._segments = Segments(self.word_size_bytes)

        if filenames is not None:
            if isinstance(filenames, str):
                filenames = [filenames]

            for filename in filenames:
                self.add_file(filename, overwrite=overwrite)

    def __setitem__(self, key, data):
        """Write data to given absolute address or address range.

        """

        if isinstance(key, slice):
            if key.start is None:
                address = self.minimum_address
            else:
                address = key.start
        else:
            address = key
            data = hex((0x80 << (8 * self.word_size_bytes)) | data)
            data = binascii.unhexlify(data[4:])

        self.add_binary(data, address, overwrite=True)

    def __getitem__(self, key):
        """Read data from given absolute address or address range.

        """

        if isinstance(key, slice):
            if key.start is None:
                minimum_address = self.minimum_address
            else:
                minimum_address = key.start

            if key.stop is None:
                maximum_address = self.maximum_address
            else:
                maximum_address = key.stop

            return self.as_binary(minimum_address, maximum_address)
        else:
            if key < self.minimum_address or key >= self.maximum_address:
                raise IndexError(f'binary file index {key} out of range')

            return int(binascii.hexlify(self.as_binary(key, key + 1)), 16)


    def __len__(self):
        """Number of words in the file.

        """

        length = sum([len(segment.data) for segment in self.segments])
        length //= self.word_size_bytes

        return length

    def __iadd__(self, other):
        self.add_srec(other.as_srec())

        return self

    def __str__(self):
        return str(self._segments)

    @property
    def execution_start_address(self):
        """The execution start address, or ``None`` if missing.

        """

        return self._execution_start_address

    @execution_start_address.setter
    def execution_start_address(self, address):
        self._execution_start_address = address

    @property
    def minimum_address(self):
        """The minimum address of the data, or ``None`` if the file is empty.

        """

        minimum_address = self._segments.minimum_address

        if minimum_address is not None:
            minimum_address //= self.word_size_bytes

        return minimum_address

    @property
    def maximum_address(self):
        """The maximum address of the data plus one, or ``None`` if the file
        is empty.

        """

        maximum_address = self._segments.maximum_address

        if maximum_address is not None:
            maximum_address //= self.word_size_bytes

        return maximum_address

    @property
    def header(self):
        """The binary file header, or ``None`` if missing. See
        :class:`BinFile's<.BinFile>` `header_encoding` argument for
        encoding options.

        """

        if self._header_encoding is None:
            return self._header
        else:
            return self._header.decode(self._header_encoding)

    @header.setter
    def header(self, header):
        if self._header_encoding is None:
            if not isinstance(header, bytes):
                raise TypeError(f'expected a bytes object, but got {type(header)}')

            self._header = header
        else:
            self._header = header.encode(self._header_encoding)

    @property
    def segments(self):
        """The segments object. Can be used to iterate over all segments in
        the binary.

        Below is an example iterating over all segments, two in this
        case, and printing them.

        >>> for segment in binfile.segments:
        ...     print(segment)
        ...
        Segment(address=0, data=bytearray(b'\\x00\\x01\\x02'))
        Segment(address=10, data=bytearray(b'\\x03\\x04\\x05'))

        All segments can be split into smaller pieces using the
        `chunks(size=32, alignment=1)` method.

        >>> for chunk in binfile.segments.chunks(2):
        ...     print(chunk)
        ...
        Segment(address=0, data=bytearray(b'\\x00\\x01'))
        Segment(address=2, data=bytearray(b'\\x02'))
        Segment(address=10, data=bytearray(b'\\x03\\x04'))
        Segment(address=12, data=bytearray(b'\\x05'))

        Each segment can be split into smaller pieces using the
        `chunks(size=32, alignment=1)` method on a single segment.

        >>> for segment in binfile.segments:
        ...     print(segment)
        ...     for chunk in segment.chunks(2):
        ...         print(chunk)
        ...
        Segment(address=0, data=bytearray(b'\\x00\\x01\\x02'))
        Segment(address=0, data=bytearray(b'\\x00\\x01'))
        Segment(address=2, data=bytearray(b'\\x02'))
        Segment(address=10, data=bytearray(b'\\x03\\x04\\x05'))
        Segment(address=10, data=bytearray(b'\\x03\\x04'))
        Segment(address=12, data=bytearray(b'\\x05'))

        """

        return self._segments

    def add(self, data, overwrite=False):
        """Add given data string by guessing its format. The format must be
        Motorola S-Records, Intel HEX or TI-TXT. Set `overwrite` to
        ``True`` to allow already added data to be overwritten.

        """

        if is_srec(data):
            self.add_srec(data, overwrite)
        elif is_ihex(data):
            self.add_ihex(data, overwrite)
        elif is_ti_txt(data):
            self.add_ti_txt(data, overwrite)
        elif is_verilog_vmem(data):
            self.add_verilog_vmem(data, overwrite)
        else:
            raise UnsupportedFileFormatError()

    def add_srec(self, records, overwrite=False):
        """Add given Motorola S-Records string. Set `overwrite` to ``True`` to
        allow already added data to be overwritten.

        """

        for record in StringIO(records):
            record = record.strip()

            # Ignore blank lines.
            if not record:
                continue

            type_, address, size, data = unpack_srec(record)

            if type_ == '0':
                self._header = data
            elif type_ in '123':
                address *= self.word_size_bytes
                self._segments.add(Segment(address,
                                           address + size,
                                           data,
                                           self.word_size_bytes),
                                   overwrite)
            elif type_ in '789':
                self.execution_start_address = address

    def add_ihex(self, records, overwrite=False):
        """Add given Intel HEX records string. Set `overwrite` to ``True`` to
        allow already added data to be overwritten.

        """

        extended_segment_address = 0
        extended_linear_address = 0

        for record in StringIO(records):
            record = record.strip()

            # Ignore blank lines.
            if not record:
                continue

            type_, address, size, data = unpack_ihex(record)

            if type_ == IHEX_DATA:
                address = (address
                           + extended_segment_address
                           + extended_linear_address)
                address *= self.word_size_bytes
                self._segments.add(Segment(address,
                                           address + size,
                                           data,
                                           self.word_size_bytes),
                                   overwrite)
            elif type_ == IHEX_END_OF_FILE:
                pass
            elif type_ == IHEX_EXTENDED_SEGMENT_ADDRESS:
                extended_segment_address = int(binascii.hexlify(data), 16)
                extended_segment_address *= 16
            elif type_ == IHEX_EXTENDED_LINEAR_ADDRESS:
                extended_linear_address = int(binascii.hexlify(data), 16)
                extended_linear_address <<= 16
            elif type_ in [IHEX_START_SEGMENT_ADDRESS, IHEX_START_LINEAR_ADDRESS]:
                self.execution_start_address = int(binascii.hexlify(data), 16)
            else:
                raise Error(f"expected type 1..5 in record {record}, but got {type_}")

    def add_ti_txt(self, lines, overwrite=False):
        """Add given TI-TXT string `lines`. Set `overwrite` to ``True`` to
        allow already added data to be overwritten.

        """

        address = None
        eof_found = False

        for line in StringIO(lines):
            # Abort if data is found after end of file.
            if eof_found:
                raise Error("bad file terminator")

            line = line.strip()

            if len(line) < 1:
                raise Error("bad line length")

            if line[0] == 'q':
                eof_found = True
            elif line[0] == '@':
                try:
                    address = int(line[1:], 16)
                except ValueError:
                    raise Error("bad section address")
            else:
                # Try to decode the data.
                try:
                    data = bytearray(binascii.unhexlify(line.replace(' ', '')))
                except (TypeError, binascii.Error):
                    raise Error("bad data")

                size = len(data)

                # Check that there are correct number of bytes per
                # line. There should TI_TXT_BYTES_PER_LINE. Only
                # exception is last line of section which may be
                # shorter.
                if size > TI_TXT_BYTES_PER_LINE:
                    raise Error("bad line length")

                if address is None:
                    raise Error("missing section address")

                self._segments.add(Segment(address,
                                           address + size,
                                           data,
                                           self.word_size_bytes),
                                   overwrite)

                if size == TI_TXT_BYTES_PER_LINE:
                    address += size
                else:
                    address = None

        if not eof_found:
            raise Error("missing file terminator")

    def add_verilog_vmem(self, data, overwrite=False):
        address = None
        chunk = b''
        words = re.split(r'\s+', comment_remover(data).strip())
        word_size_bytes = None

        for word in words:
            if not word.startswith('@'):
                length = len(word)

                if (length % 2) != 0:
                    raise Error('Invalid word length.')

                length //= 2

                if word_size_bytes is None:
                    word_size_bytes = length
                elif length != word_size_bytes:
                    raise Error(
                        f'Mixed word lengths {length} and {word_size_bytes}.')

        for word in words:
            if word.startswith('@'):
                if address is not None:
                    self._segments.add(Segment(address,
                                               address + len(chunk),
                                               chunk,
                                               self.word_size_bytes))

                address = int(word[1:], 16) * word_size_bytes
                chunk = b''
            else:
                chunk += bytes.fromhex(word)

        if address is not None and chunk:
            self._segments.add(Segment(address,
                                       address + len(chunk),
                                       chunk,
                                       self.word_size_bytes))

    def add_binary(self, data, address=0, overwrite=False):
        """Add given data at given address. Set `overwrite` to ``True`` to
        allow already added data to be overwritten.

        """

        address *= self.word_size_bytes
        self._segments.add(Segment(address,
                                   address + len(data),
                                   bytearray(data),
                                   self.word_size_bytes),
                           overwrite)

    def add_elf(self, data, overwrite=True):
        """Add given ELF data.

        """

        elffile = ELFFile(BytesIO(data))

        self.execution_start_address = elffile.header['e_entry']

        for segment in elffile.iter_segments():
            if segment['p_type'] != 'PT_LOAD':
                 continue

            segment_address = segment['p_paddr']
            segment_offset = segment['p_offset']
            segment_size = segment['p_filesz']

            for section in elffile.iter_sections():
                offset = section['sh_offset']
                size = section['sh_size']
                address = segment_address + offset - segment_offset

                if size == 0:
                    continue

                if segment_offset <= offset < segment_offset + segment_size:
                    if section['sh_type'] == 'SHT_NOBITS':
                        continue

                    if (section['sh_flags'] & SH_FLAGS.SHF_ALLOC) == 0:
                        continue

                    self._segments.add(Segment(address,
                                               address + size,
                                               data[offset:offset + size],
                                               self.word_size_bytes),
                                       overwrite)

    def add_microchip_hex(self, records, overwrite=False):
        """Add given Microchip HEX data.

        Microchip's HEX format is identical to Intel's except an address in
        the HEX file is twice the actual machine address. For example:

        :02000E00E4C943

            :       Start code
            02      Record contains two data bytes
            000E    Address 0x000E; Machine address is 0x000E // 2 == 0x0007
            00      Record type is data
            E4      Low byte at address 0x0007 is 0xE4
            C9      High byte at address 0x0007 is 0xC9

        Microchip HEX records therefore need to be parsed as if the word size
        is one byte, but the parsed data must be handled as if the word size
        is two bytes. This is true for both 8-bit PICs such as PIC18 and
        16-bit PICs such as PIC24.

        """

        self.word_size_bytes = 1
        self.add_ihex(records, overwrite)
        self.word_size_bytes = 2
        self.segments.word_size_bytes = 2

        for segment in self.segments:
            segment.word_size_bytes = 2

    def add_file(self, filename, overwrite=False):
        """Open given file and add its data by guessing its format. The format
        must be Motorola S-Records, Intel HEX, TI-TXT. Set `overwrite`
        to ``True`` to allow already added data to be overwritten.

        """

        with open(filename, 'r') as fin:
            try:
                data = fin.read()
            except UnicodeDecodeError:
                raise UnsupportedFileFormatError()

        self.add(data, overwrite)

    def add_srec_file(self, filename, overwrite=False):
        """Open given Motorola S-Records file and add its records. Set
        `overwrite` to ``True`` to allow already added data to be
        overwritten.

        """

        with open(filename, 'r') as fin:
            self.add_srec(fin.read(), overwrite)

    def add_ihex_file(self, filename, overwrite=False):
        """Open given Intel HEX file and add its records. Set `overwrite` to
        ``True`` to allow already added data to be overwritten.

        """

        with open(filename, 'r') as fin:
            self.add_ihex(fin.read(), overwrite)

    def add_ti_txt_file(self, filename, overwrite=False):
        """Open given TI-TXT file and add its contents. Set `overwrite` to
        ``True`` to allow already added data to be overwritten.

        """

        with open(filename, 'r') as fin:
            self.add_ti_txt(fin.read(), overwrite)

    def add_verilog_vmem_file(self, filename, overwrite=False):
        """Open given Verilog VMEM file and add its contents. Set `overwrite` to
        ``True`` to allow already added data to be overwritten.

        """

        with open(filename, 'r') as fin:
            self.add_verilog_vmem(fin.read(), overwrite)

    def add_binary_file(self, filename, address=0, overwrite=False):
        """Open given binary file and add its contents. Set `overwrite` to
        ``True`` to allow already added data to be overwritten.

        """

        with open(filename, 'rb') as fin:
            self.add_binary(fin.read(), address, overwrite)

    def add_elf_file(self, filename, overwrite=False):
        """Open given ELF file and add its contents. Set `overwrite` to
        ``True`` to allow already added data to be overwritten.

        """

        with open(filename, 'rb') as fin:
            self.add_elf(fin.read(), overwrite)

    def add_microchip_hex_file(self, filename, overwrite=False):
        """Open given Microchip HEX file and add its contents. Set `overwrite`
        to ``True`` to allow already added data to be overwritten.

        """

        with open(filename, 'r') as fin:
            self.add_microchip_hex(fin.read(), overwrite)

    def as_srec(self, number_of_data_bytes=32, address_length_bits=32):
        """Format the binary file as Motorola S-Records records and return
        them as a string.

        `number_of_data_bytes` is the number of data bytes in each
        record.

        `address_length_bits` is the number of address bits in each
        record.

        >>> print(binfile.as_srec())
        S32500000100214601360121470136007EFE09D219012146017E17C20001FF5F16002148011973
        S32500000120194E79234623965778239EDA3F01B2CA3F0156702B5E712B722B73214601342199
        S5030002FA

        """

        header = []

        if self._header is not None:
            record = pack_srec('0', 0, len(self._header), self._header)
            header.append(record)

        type_ = str((address_length_bits // 8) - 1)

        if type_ not in '123':
            raise Error(f"expected data record type 1..3, but got {type_}")

        data = [pack_srec(type_, address, len(data), data)
                for address, data in self._segments.chunks(
                        number_of_data_bytes // self.word_size_bytes)]
        number_of_records = len(data)

        if number_of_records <= 0xffff:
            footer = [pack_srec('5', number_of_records, 0, None)]
        elif number_of_records <= 0xffffff:
            footer = [pack_srec('6', number_of_records, 0, None)]
        else:
            raise Error(f'too many records {number_of_records}')

        # Add the execution start address.
        if self.execution_start_address is not None:
            if type_ == '1':
                record = pack_srec('9', self.execution_start_address, 0, None)
            elif type_ == '2':
                record = pack_srec('8', self.execution_start_address, 0, None)
            else:
                record = pack_srec('7', self.execution_start_address, 0, None)

            footer.append(record)

        return '\n'.join(header + data + footer) + '\n'

    def as_ihex(self, number_of_data_bytes=32, address_length_bits=32):
        """Format the binary file as Intel HEX records and return them as a
        string.

        `number_of_data_bytes` is the number of data bytes in each
        record.

        `address_length_bits` is the number of address bits in each
        record.

        >>> print(binfile.as_ihex())
        :20010000214601360121470136007EFE09D219012146017E17C20001FF5F16002148011979
        :20012000194E79234623965778239EDA3F01B2CA3F0156702B5E712B722B7321460134219F
        :00000001FF

        """

        def i32hex(address, extended_linear_address, data_address):
            if address > 0xffffffff:
                raise Error(
                    'cannot address more than 4 GB in I32HEX files (32 '
                    'bits addresses)')

            address_upper_16_bits = (address >> 16)
            address &= 0xffff

            # All segments are sorted by address. Update the
            # extended linear address when required.
            if address_upper_16_bits > extended_linear_address:
                extended_linear_address = address_upper_16_bits
                packed = pack_ihex(
                    IHEX_EXTENDED_LINEAR_ADDRESS,
                    0,
                    2,
                    binascii.unhexlify(f'{extended_linear_address:04X}'))
                data_address.append(packed)

            return address, extended_linear_address

        def i16hex(address, extended_segment_address, data_address):
            if address > 16 * 0xffff + 0xffff:
                raise Error(
                    'cannot address more than 1 MB in I16HEX files (20 '
                    'bits addresses)')

            address_lower = (address - 16 * extended_segment_address)

            # All segments are sorted by address. Update the
            # extended segment address when required.
            if address_lower > 0xffff:
                extended_segment_address = (4096 * (address >> 16))

                if extended_segment_address > 0xffff:
                    extended_segment_address = 0xffff

                address_lower = (address - 16 * extended_segment_address)
                packed = pack_ihex(
                    IHEX_EXTENDED_SEGMENT_ADDRESS,
                    0,
                    2,
                    binascii.unhexlify(f'{extended_segment_address:04X}'))
                data_address.append(packed)

            return address_lower, extended_segment_address

        def i8hex(address):
            if address > 0xffff:
                raise Error(
                    'cannot address more than 64 kB in I8HEX files (16 '
                    'bits addresses)')

        data_address = []
        extended_segment_address = 0
        extended_linear_address = 0
        number_of_data_words = number_of_data_bytes // self.word_size_bytes

        for address, data in self._segments.chunks(number_of_data_words):
            if address_length_bits == 32:
                address, extended_linear_address = i32hex(address,
                                                          extended_linear_address,
                                                          data_address)
            elif address_length_bits == 24:
                address, extended_segment_address = i16hex(address,
                                                           extended_segment_address,
                                                           data_address)
            elif address_length_bits == 16:
                i8hex(address)
            else:
                raise Error(f'expected address length 16, 24 or 32, but got '
                            f'{address_length_bits}')

            data_address.append(pack_ihex(IHEX_DATA,
                                          address,
                                          len(data),
                                          data))

        footer = []

        if self.execution_start_address is not None:
            if address_length_bits == 24:
                address = binascii.unhexlify(f'{self.execution_start_address:08X}')
                footer.append(pack_ihex(IHEX_START_SEGMENT_ADDRESS,
                                        0,
                                        4,
                                        address))
            elif address_length_bits == 32:
                address = binascii.unhexlify(f'{self.execution_start_address:08X}')
                footer.append(pack_ihex(IHEX_START_LINEAR_ADDRESS,
                                        0,
                                        4,
                                        address))

        footer.append(pack_ihex(IHEX_END_OF_FILE, 0, 0, None))

        return '\n'.join(data_address + footer) + '\n'

    def as_microchip_hex(self, number_of_data_bytes=32, address_length_bits=32):
        """Format the binary file as Microchip HEX records and return them as a
        string.

        `number_of_data_bytes` is the number of data bytes in each
        record.

        `address_length_bits` is the number of address bits in each
        record.

        >>> print(binfile.as_microchip_hex())
        :20010000214601360121470136007EFE09D219012146017E17C20001FF5F16002148011979
        :20012000194E79234623965778239EDA3F01B2CA3F0156702B5E712B722B7321460134219F
        :00000001FF

        """

        self.word_size_bytes = 1
        self.segments.word_size_bytes = 1

        for segment in self.segments:
            segment.word_size_bytes = 1

        records = self.as_ihex(number_of_data_bytes, address_length_bits)

        self.word_size_bytes = 2
        self.segments.word_size_bytes = 2

        for segment in self.segments:
            segment.word_size_bytes = 2

        return records

    def as_ti_txt(self):
        """Format the binary file as a TI-TXT file and return it as a string.

        >>> print(binfile.as_ti_txt())
        @0100
        21 46 01 36 01 21 47 01 36 00 7E FE 09 D2 19 01
        21 46 01 7E 17 C2 00 01 FF 5F 16 00 21 48 01 19
        19 4E 79 23 46 23 96 57 78 23 9E DA 3F 01 B2 CA
        3F 01 56 70 2B 5E 71 2B 72 2B 73 21 46 01 34 21
        q

        """

        lines = []
        number_of_data_words = TI_TXT_BYTES_PER_LINE // self.word_size_bytes

        for segment in self._segments:
            lines.append(f'@{segment.address:04X}')

            for _, data in segment.chunks(number_of_data_words):
                lines.append(' '.join(f'{byte:02X}' for byte in data))

        lines.append('q')

        return '\n'.join(lines) + '\n'

    def as_verilog_vmem(self):
        """Format the binary file as a Verilog VMEM file and return it as a string.

        >>> print(binfile.as_verilog_vmem())

        """

        lines = []

        if self._header is not None:
            lines.append(f'/* {self.header} */')

        for segment in self._segments:
            for address, data in segment.chunks(32 // self.word_size_bytes):
                words = []

                for i in range(0, len(data), self.word_size_bytes):
                    word = ''

                    for byte in data[i:i + self.word_size_bytes]:
                        word += f'{byte:02X}'

                    words.append(word)

                data_hex = ' '.join(words)
                lines.append(f'@{address:08X} {data_hex}')

        return '\n'.join(lines) + '\n'

    def as_binary(self,
                  minimum_address=None,
                  maximum_address=None,
                  padding=None):
        """Return a byte string of all data within given address range.

        `minimum_address` is the absolute minimum address of the
        resulting binary data (including). By default this is the
        minimum address in the binary.

        `maximum_address` is the absolute maximum address of the
        resulting binary data (excluding). By default this is the
        maximum address in the binary plus one.

        `padding` is the word value of the padding between
        non-adjacent segments. Give as a bytes object of length 1 when
        the word size is 8 bits, length 2 when the word size is 16
        bits, and so on. By default the padding is ``b'\\xff' *
        word_size_bytes``.

        >>> binfile.as_binary()
        bytearray(b'!F\\x016\\x01!G\\x016\\x00~\\xfe\\t\\xd2\\x19\\x01!F\\x01~\\x17\\xc2\\x00\\x01
        \\xff_\\x16\\x00!H\\x01\\x19\\x19Ny#F#\\x96Wx#\\x9e\\xda?\\x01\\xb2\\xca?\\x01Vp+^q+r+s!
        F\\x014!')

        """

        if len(self._segments) == 0:
            return b''

        if minimum_address is None:
            current_maximum_address = self.minimum_address
        else:
            current_maximum_address = minimum_address

        if maximum_address is None:
            maximum_address = self.maximum_address

        if current_maximum_address >= maximum_address:
            return b''

        if padding is None:
            padding = b'\xff' * self.word_size_bytes

        binary = bytearray()

        for address, data in self._segments:
            length = len(data) // self.word_size_bytes

            # Discard data below the minimum address.
            if address < current_maximum_address:
                if address + length <= current_maximum_address:
                    continue

                offset = (current_maximum_address - address) * self.word_size_bytes
                data = data[offset:]
                length = len(data) // self.word_size_bytes
                address = current_maximum_address

            # Discard data above the maximum address.
            if address + length > maximum_address:
                if address < maximum_address:
                    size = (maximum_address - address) * self.word_size_bytes
                    data = data[:size]
                    length = len(data) // self.word_size_bytes
                elif maximum_address >= current_maximum_address:
                    binary += padding * (maximum_address - current_maximum_address)
                    break

            binary += padding * (address - current_maximum_address)
            binary += data
            current_maximum_address = address + length

        return binary

    def as_array(self, minimum_address=None, padding=None, separator=', '):
        """Format the binary file as a string values separated by given
        separator `separator`. This function can be used to generate
        array initialization code for C and other languages.

        `minimum_address` is the absolute minimum address of the
        resulting binary data. By default this is the minimum address
        in the binary.

        `padding` is the word value of the padding between
        non-adjacent segments. Give as a bytes object of length 1 when
        the word size is 8 bits, length 2 when the word size is 16
        bits, and so on. By default the padding is ``b'\\xff' *
        word_size_bytes``.

        >>> binfile.as_array()
        '0x21, 0x46, 0x01, 0x36, 0x01, 0x21, 0x47, 0x01, 0x36, 0x00, 0x7e,
         0xfe, 0x09, 0xd2, 0x19, 0x01, 0x21, 0x46, 0x01, 0x7e, 0x17, 0xc2,
         0x00, 0x01, 0xff, 0x5f, 0x16, 0x00, 0x21, 0x48, 0x01, 0x19, 0x19,
         0x4e, 0x79, 0x23, 0x46, 0x23, 0x96, 0x57, 0x78, 0x23, 0x9e, 0xda,
         0x3f, 0x01, 0xb2, 0xca, 0x3f, 0x01, 0x56, 0x70, 0x2b, 0x5e, 0x71,
         0x2b, 0x72, 0x2b, 0x73, 0x21, 0x46, 0x01, 0x34, 0x21'

        """

        binary_data = self.as_binary(minimum_address,
                                     padding=padding)
        words = []

        for offset in range(0, len(binary_data), self.word_size_bytes):
            word = 0

            for byte in binary_data[offset:offset + self.word_size_bytes]:
                word <<= 8
                word += byte

            words.append(f'0x{word:02x}')

        return separator.join(words)

    def as_hexdump(self):
        """Format the binary file as a hexdump and return it as a string.

        >>> print(binfile.as_hexdump())
        00000100  21 46 01 36 01 21 47 01  36 00 7e fe 09 d2 19 01  |!F.6.!G.6.~.....|
        00000110  21 46 01 7e 17 c2 00 01  ff 5f 16 00 21 48 01 19  |!F.~....._..!H..|
        00000120  19 4e 79 23 46 23 96 57  78 23 9e da 3f 01 b2 ca  |.Ny#F#.Wx#..?...|
        00000130  3f 01 56 70 2b 5e 71 2b  72 2b 73 21 46 01 34 21  |?.Vp+^q+r+s!F.4!|

        """

        # Empty file?
        if len(self) == 0:
            return '\n'

        non_dot_characters = set(string.printable)
        non_dot_characters -= set(string.whitespace)
        non_dot_characters |= set(' ')

        def align_to_line(address):
            return address - (address % (16 // self.word_size_bytes))

        def padding(length):
            return [None] * length

        def format_line(address, data):
            """`data` is a list of integers and None for unused elements.

            """

            data += padding(16 - len(data))
            hexdata = []

            for byte in data:
                if byte is not None:
                    elem = f'{byte:02x}'
                else:
                    elem = '  '

                hexdata.append(elem)

            first_half = ' '.join(hexdata[0:8])
            second_half = ' '.join(hexdata[8:16])
            text = ''

            for byte in data:
                if byte is None:
                    text += ' '
                elif chr(byte) in non_dot_characters:
                    text += chr(byte)
                else:
                    text += '.'

            return (f'{address:08x}  {first_half:23s}  {second_half:23s}  |'
                    f'{text:16s}|')

        # Format one line at a time.
        lines = []
        line_address = align_to_line(self.minimum_address)
        line_data = []

        for chunk in self._segments.chunks(16 // self.word_size_bytes,
                                           16 // self.word_size_bytes):
            aligned_chunk_address = align_to_line(chunk.address)

            if aligned_chunk_address > line_address:
                lines.append(format_line(line_address, line_data))

                if aligned_chunk_address > line_address + 16:
                    lines.append('...')

                line_address = aligned_chunk_address
                line_data = []

            line_data += padding((chunk.address - line_address) * self.word_size_bytes
                                 - len(line_data))
            line_data += [byte for byte in chunk.data]

        lines.append(format_line(line_address, line_data))

        return '\n'.join(lines) + '\n'

    def fill(self, value=None, max_words=None):
        """Fill empty space between segments.

        `value` is the value which is used to fill the empty space. By
        default the value is ``b'\\xff' * word_size_bytes``.

        `max_words` is the maximum number of words to fill between the
        segments. Empty space which larger than this is not
        touched. If ``None``, all empty space is filled.

        """

        if value is None:
            value = b'\xff' * self.word_size_bytes

        previous_segment_maximum_address = None
        fill_segments = []

        for address, data in self._segments:
            address *= self.word_size_bytes
            maximum_address = address + len(data)

            if previous_segment_maximum_address is not None:
                fill_size = address - previous_segment_maximum_address
                fill_size_words = fill_size // self.word_size_bytes

                if max_words is None or fill_size_words <= max_words:
                    fill_segments.append(Segment(
                        previous_segment_maximum_address,
                        previous_segment_maximum_address + fill_size,
                        value * fill_size_words,
                        self.word_size_bytes))

            previous_segment_maximum_address = maximum_address

        for segment in fill_segments:
            self._segments.add(segment)

    def exclude(self, minimum_address, maximum_address):
        """Exclude given range and keep the rest.

        `minimum_address` is the first word address to exclude
        (including).

        `maximum_address` is the last word address to exclude
        (excluding).

        """

        if maximum_address < minimum_address:
            raise Error('bad address range')

        minimum_address *= self.word_size_bytes
        maximum_address *= self.word_size_bytes
        self._segments.remove(minimum_address, maximum_address)

    def crop(self, minimum_address, maximum_address):
        """Keep given range and discard the rest.

        `minimum_address` is the first word address to keep
        (including).

        `maximum_address` is the last word address to keep
        (excluding).

        """

        minimum_address *= self.word_size_bytes
        maximum_address *= self.word_size_bytes
        maximum_address_address = self._segments.maximum_address
        self._segments.remove(0, minimum_address)
        self._segments.remove(maximum_address, maximum_address_address)

    def info(self):
        """Return a string of human readable information about the binary
        file.

        .. code-block:: python

           >>> print(binfile.info())
           Data ranges:

               0x00000100 - 0x00000140 (64 bytes)

        """

        info = ''

        if self._header is not None:
            if self._header_encoding is None:
                header = ''

                for b in self.header:
                    if chr(b) in string.printable:
                        header += chr(b)
                    else:
                        header += f'\\x{b:02x}'
            else:
                header = self.header

            info += f'Header:                  "{header}"\n'

        if self.execution_start_address is not None:
            info += (f'Execution start address: '
                     f'0x{self.execution_start_address:08x}\n')

        info += 'Data ranges:\n\n'

        for address, data in self._segments:
            minimum_address = address
            size = len(data)
            maximum_address = (minimum_address + size // self.word_size_bytes)
            info += 4 * ' '
            info += (f'0x{minimum_address:08x} - 0x{maximum_address:08x} '
                     f'({format_size(size, binary=True)})\n')

        return info

    def layout(self):
        """Return the memory layout as a string.

        .. code-block:: python

           >>> print(binfile.layout())
           0x100                                                      0x140
           ================================================================

        """

        size = self.maximum_address - self.minimum_address
        width = min(80, size)
        chunk_address = self.minimum_address
        chunk_size = size // width
        minimum_address = hex(self.minimum_address)
        maximum_address = hex(self.maximum_address)
        padding = ' ' * max(width - len(minimum_address) - len(maximum_address), 0)
        output = f'{minimum_address}{padding}{maximum_address}\n'

        for i in range(width):
            chunk = copy.deepcopy(self)

            if i < (width - 1):
                maximum_address = chunk_address + chunk_size
            else:
                maximum_address = chunk.maximum_address

            chunk.crop(chunk_address, maximum_address)

            if len(chunk) == 0:
                output += ' '
            elif len(chunk) != (maximum_address - chunk_address):
                output += '-'
            else:
                output += '='

            chunk_address += chunk_size

        return output + '\n'


def _do_info(args):
    for binfile in args.binfile:
        bf = BinFile(header_encoding=args.header_encoding,
                     word_size_bits=args.word_size_bits)
        bf.add_file(binfile)
        print('File:                   ', binfile)
        print(bf.info())
        size = (bf.maximum_address - bf.minimum_address)
        print(f'Data ratio:              {round(100 * len(bf) / size, 2)} %')
        print('Layout:')
        print()
        print('\n'.join(['    ' + line for line in bf.layout().splitlines()]))
        print()


def _convert_input_format_type(value):
    items = value.split(',')
    fmt = items[0]
    args = tuple()

    if fmt == 'binary':
        address = 0

        if len(items) >= 2:
            try:
                address = int(items[1], 0)
            except ValueError:
                raise argparse.ArgumentTypeError(
                    f"invalid binary address '{items[1]}'")

        args = (address, )
    elif fmt in ['ihex', 'srec', 'auto', 'ti_txt', 'verilog_vmem', 'elf']:
        pass
    else:
        raise argparse.ArgumentTypeError(f"invalid input format '{fmt}'")

    return fmt, args


def _convert_output_format_type(value):
    items = value.split(',')
    fmt = items[0]
    args = tuple()

    if fmt in ['srec', 'ihex', 'ti_txt']:
        number_of_data_bytes = 32
        address_length_bits = 32

        if len(items) >= 2:
            try:
                number_of_data_bytes = int(items[1], 0)
            except ValueError:
                raise argparse.ArgumentTypeError(
                    f"invalid {fmt} number of data bytes '{items[1]}'")

        if len(items) >= 3:
            try:
                address_length_bits = int(items[2], 0)
            except ValueError:
                raise argparse.ArgumentTypeError(
                    f"invalid {fmt} address length of '{items[2]}' bits")

        args = (number_of_data_bytes, address_length_bits)
    elif fmt == 'elf':
        raise argparse.ArgumentTypeError(f"invalid output format '{fmt}'")
    elif fmt == 'binary':
        minimum_address = None
        maximum_address = None

        if len(items) >= 2:
            try:
                minimum_address = int(items[1], 0)
            except ValueError:
                raise argparse.ArgumentTypeError(
                    f"invalid binary minimum address '{items[1]}'")

        if len(items) >= 3:
            try:
                maximum_address = int(items[2], 0)
            except ValueError:
                raise argparse.ArgumentTypeError(
                    f"invalid binary maximum address '{items[2]}'")

        args = (minimum_address, maximum_address)
    elif fmt == 'hexdump':
        pass
    elif fmt == 'verilog_vmem':
        pass
    else:
        raise argparse.ArgumentTypeError(f"invalid output format '{fmt}'")

    return fmt, args


def _do_convert_add_file(bf, input_format, infile, overwrite):
    fmt, args = input_format

    try:
        if fmt == 'auto':
            try:
                bf.add_file(infile, *args, overwrite=overwrite)
            except UnsupportedFileFormatError:
                try:
                    bf.add_elf_file(infile, *args, overwrite=overwrite)
                except:
                    bf.add_binary_file(infile, *args, overwrite=overwrite)
        elif fmt == 'srec':
            bf.add_srec_file(infile, *args, overwrite=overwrite)
        elif fmt == 'ihex':
            bf.add_ihex_file(infile, *args, overwrite=overwrite)
        elif fmt == 'binary':
            bf.add_binary_file(infile, *args, overwrite=overwrite)
        elif fmt == 'ti_txt':
            bf.add_ti_txt_file(infile, *args, overwrite=overwrite)
        elif fmt == 'verilog_vmem':
            bf.add_verilog_vmem_file(infile, *args, overwrite=overwrite)
        elif fmt == 'elf':
            bf.add_elf_file(infile, *args, overwrite=overwrite)
    except AddDataError:
        sys.exit('overlapping segments detected, give --overwrite to overwrite '
                 'overlapping segments')


def _do_convert_as(bf, output_format):
    fmt, args = output_format

    if fmt == 'srec':
        converted = bf.as_srec(*args)
    elif fmt == 'ihex':
        converted = bf.as_ihex(*args)
    elif fmt == 'binary':
        converted = bf.as_binary(*args)
    elif fmt == 'hexdump':
        converted = bf.as_hexdump()
    elif fmt == 'ti_txt':
        converted = bf.as_ti_txt()
    elif fmt == 'verilog_vmem':
        converted = bf.as_verilog_vmem()

    return converted


def _do_convert(args):
    input_formats_missing = len(args.infiles) - len(args.input_format)

    if input_formats_missing < 0:
        sys.exit("found more input formats than input files")

    args.input_format += input_formats_missing * [('auto', tuple())]
    binfile = BinFile(word_size_bits=args.word_size_bits)

    for input_format, infile in zip(args.input_format, args.infiles):
        _do_convert_add_file(binfile, input_format, infile, args.overwrite)

    converted = _do_convert_as(binfile, args.output_format)

    if args.outfile == '-':
        if isinstance(converted, str):
            print(converted, end='')
        else:
            sys.stdout.buffer.write(converted)
    else:
        if isinstance(converted, str):
            with open(args.outfile, 'w') as fout:
                fout.write(converted)
        else:
            with open(args.outfile, 'wb') as fout:
                fout.write(converted)


def _do_pretty(args):
    if args.binfile is None:
        data = sys.stdin.read()
    else:
        with open(args.binfile, 'r') as fin:
            data = fin.read()

    if is_srec(data):
        print('\n'.join([pretty_srec(line) for line in data.splitlines()]))
    elif is_ihex(data):
        print('\n'.join([pretty_ihex(line) for line in data.splitlines()]))
    elif is_ti_txt(data):
        print('\n'.join([pretty_ti_txt(line) for line in data.splitlines()]))
    else:
        raise UnsupportedFileFormatError()


def _do_as_srec(args):
    for binfile in args.binfile:
        bf = BinFile()
        bf.add_file(binfile)
        print(bf.as_srec(), end='')


def _do_as_ihex(args):
    for binfile in args.binfile:
        bf = BinFile()
        bf.add_file(binfile)
        print(bf.as_ihex(), end='')


def _do_as_hexdump(args):
    for binfile in args.binfile:
        bf = BinFile()
        bf.add_file(binfile)
        print(bf.as_hexdump(), end='')


def _do_as_ti_txt(args):
    for binfile in args.binfile:
        bf = BinFile()
        bf.add_file(binfile)
        print(bf.as_ti_txt(), end='')


def _do_as_verilog_vmem(args):
    for binfile in args.binfile:
        bf = BinFile()
        bf.add_file(binfile)
        print(bf.as_verilog_vmem(), end='')


def _do_fill(args):
    with open(args.infile, 'r') as fin:
        data = fin.read()

    bf = BinFile()
    bf.add(data)
    bf.fill(args.value.to_bytes(1, 'big'), args.max_words)

    if is_srec(data):
        data = bf.as_srec()
    elif is_ihex(data):
        data = bf.as_ihex()
    elif is_ti_txt(data):
        data = bf.as_ti_txt()
    else:
        raise UnsupportedFileFormatError()

    if args.outfile == '-':
        sys.stdout.write(data)
    else:
        if args.outfile is None:
            outfile = args.infile
        else:
            outfile = args.outfile

        with open(outfile, 'w') as fout:
            fout.write(data)


def _main():
    parser = argparse.ArgumentParser(
        description='Various binary file format utilities.')

    parser.add_argument('-d', '--debug', action='store_true')
    parser.add_argument('--version',
                        action='version',
                        version=__version__,
                        help='Print version information and exit.')

    # Workaround to make the subparser required in Python 3.
    subparsers = parser.add_subparsers(title='subcommands',
                                       dest='subcommand')
    subparsers.required = True

    # The 'info' subparser.
    subparser = subparsers.add_parser(
        'info',
        description='Print general information about given file(s).')
    subparser.add_argument('-e', '--header-encoding',
                           help=('File header encoding. Common encodings '
                                 'include utf-8 and ascii.'))
    subparser.add_argument(
        '-s', '--word-size-bits',
        default=8,
        type=int,
        help='Word size in number of bits (default: %(default)s).')
    subparser.add_argument('binfile',
                           nargs='+',
                           help='One or more binary format files.')
    subparser.set_defaults(func=_do_info)

    # The 'convert' subparser.
    subparser = subparsers.add_parser(
        'convert',
        description='Convert given file(s) to a single file.')
    subparser.add_argument(
        '-i', '--input-format',
        action='append',
        default=[],
        type=_convert_input_format_type,
        help=('Input format auto, srec, ihex, ti_txt, verilog_vmem, elf, or '
              'binary[,<address>] (default: auto). This argument may be repeated, '
              'selecting the input format for each input file.'))
    subparser.add_argument(
        '-o', '--output-format',
        default='hexdump',
        type=_convert_output_format_type,
        help=('Output format srec, ihex, ti_txt, verilog_vmem, binary or hexdump '
              '(default: %(default)s).'))
    subparser.add_argument(
        '-s', '--word-size-bits',
        default=8,
        type=int,
        help='Word size in number of bits (default: %(default)s).')
    subparser.add_argument('-w', '--overwrite',
                           action='store_true',
                           help='Overwrite overlapping data segments.')
    subparser.add_argument('infiles',
                           nargs='+',
                           help='One or more binary format files.')
    subparser.add_argument('outfile',
                           help='Output file, or - to print to standard output.')
    subparser.set_defaults(func=_do_convert)

    # The 'pretty' subparser.
    subparser = subparsers.add_parser(
        'pretty',
        description='Make given binary format file pretty by colorizing it.')
    subparser.add_argument(
        'binfile',
        nargs='?',
        help='A binary format file, or omitted to read from stdin.')
    subparser.set_defaults(func=_do_pretty)

    # The 'as_srec' subparser.
    subparser = subparsers.add_parser(
        'as_srec',
        description='Print given file(s) as Motorola S-records.')
    subparser.add_argument('binfile',
                           nargs='+',
                           help='One or more binary format files.')
    subparser.set_defaults(func=_do_as_srec)

    # The 'as_ihex' subparser.
    subparser = subparsers.add_parser(
        'as_ihex',
        description='Print given file(s) as Intel HEX.')
    subparser.add_argument('binfile',
                           nargs='+',
                           help='One or more binary format files.')
    subparser.set_defaults(func=_do_as_ihex)

    # The 'as_hexdump' subparser.
    subparser = subparsers.add_parser(
        'as_hexdump',
        description='Print given file(s) as hexdumps.')
    subparser.add_argument('binfile',
                           nargs='+',
                           help='One or more binary format files.')
    subparser.set_defaults(func=_do_as_hexdump)

    # The 'as_ti_txt' subparser.
    subparser = subparsers.add_parser(
        'as_ti_txt',
        description='Print given file(s) as TI-TXT.')
    subparser.add_argument('binfile',
                           nargs='+',
                           help='One or more binary format files.')
    subparser.set_defaults(func=_do_as_ti_txt)

    # The 'as_verilog_vmem' subparser.
    subparser = subparsers.add_parser(
        'as_verilog_vmem',
        description='Print given file(s) as Verilog VMEM.')
    subparser.add_argument('binfile',
                           nargs='+',
                           help='One or more binary format files.')
    subparser.set_defaults(func=_do_as_verilog_vmem)

    # The 'fill' subparser.
    subparser = subparsers.add_parser(
        'fill',
        description='Fill empty space between segments.')
    subparser.add_argument(
        '-v', '--value',
        type=Integer(0, 255),
        default=255,
        help=('The value which is used to fill the empty space. Must be in '
              'the range 0..255 (default: %(default)s).'))
    subparser.add_argument(
        '-m', '--max-words',
        type=Integer(0, None),
        help=('The maximum number of words to fill between the segments. Empty '
              'space which larger than this is not touched.'))
    subparser.add_argument('infile',
                           help='Binary format file to fill.')
    subparser.add_argument(
        'outfile',
        nargs='?',
        help=('Output file, or - to print to standard output. Modifies the '
              'input file if omitted.'))
    subparser.set_defaults(func=_do_fill)

    args = parser.parse_args()

    if args.debug:
        args.func(args)
    else:
        try:
            args.func(args)
        except BaseException as e:
            sys.exit('error: ' + str(e))


if __name__ == '__main__':
    _main()