File: HexBox.cs

package info (click to toggle)
hexbox 1.5.0-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 2,440 kB
  • ctags: 1,210
  • sloc: cs: 6,784; makefile: 21; sh: 1
file content (3923 lines) | stat: -rw-r--r-- 107,697 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
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
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Security.Permissions;
using System.Windows.Forms.VisualStyles;
using System.Text;
using System.Collections.Generic;

namespace Be.Windows.Forms
{
	/// <summary>
	/// Represents a hex box control.
	/// </summary>
	[ToolboxBitmap(typeof(HexBox), "HexBox.bmp")]
	public class HexBox : Control
	{
		#region IKeyInterpreter interface
		/// <summary>
		/// Defines a user input handler such as for mouse and keyboard input
		/// </summary>
		interface IKeyInterpreter
		{
			/// <summary>
			/// Activates mouse events
			/// </summary>
			void Activate();
			/// <summary>
			/// Deactivate mouse events
			/// </summary>
			void Deactivate();
			/// <summary>
			/// Preprocesses WM_KEYUP window message.
			/// </summary>
			/// <param name="m">the Message object to process.</param>
			/// <returns>True, if the message was processed.</returns>
			bool PreProcessWmKeyUp(ref Message m);
			/// <summary>
			/// Preprocesses WM_CHAR window message.
			/// </summary>
			/// <param name="m">the Message object to process.</param>
			/// <returns>True, if the message was processed.</returns>
			bool PreProcessWmChar(ref Message m);
			/// <summary>
			/// Preprocesses WM_KEYDOWN window message.
			/// </summary>
			/// <param name="m">the Message object to process.</param>
			/// <returns>True, if the message was processed.</returns>
			bool PreProcessWmKeyDown(ref Message m);
			/// <summary>
			/// Gives some information about where to place the caret.
			/// </summary>
			/// <param name="byteIndex">the index of the byte</param>
			/// <returns>the position where the caret is to place.</returns>
			PointF GetCaretPointF(long byteIndex);
		}
		#endregion

		#region EmptyKeyInterpreter class
		/// <summary>
		/// Represents an empty input handler without any functionality. 
		/// If is set ByteProvider to null, then this interpreter is used.
		/// </summary>
		class EmptyKeyInterpreter : IKeyInterpreter
		{
			HexBox _hexBox;

			public EmptyKeyInterpreter(HexBox hexBox)
			{
				_hexBox = hexBox;
			}

			#region IKeyInterpreter Members
			public void Activate() { }
			public void Deactivate() { }

			public bool PreProcessWmKeyUp(ref Message m)
			{ return _hexBox.BasePreProcessMessage(ref m); }

			public bool PreProcessWmChar(ref Message m)
			{ return _hexBox.BasePreProcessMessage(ref m); }

			public bool PreProcessWmKeyDown(ref Message m)
			{ return _hexBox.BasePreProcessMessage(ref m); }

			public PointF GetCaretPointF(long byteIndex)
			{ return new PointF(); }

			#endregion
		}
		#endregion

		#region KeyInterpreter class
		/// <summary>
		/// Handles user input such as mouse and keyboard input during hex view edit
		/// </summary>
		class KeyInterpreter : IKeyInterpreter
		{
			/// <summary>
			/// Delegate for key-down processing.
			/// </summary>
			/// <param name="m">the message object contains key data information</param>
			/// <returns>True, if the message was processed</returns>
			delegate bool MessageDelegate(ref Message m);

			#region Fields
			/// <summary>
			/// Contains the parent HexBox control
			/// </summary>
			protected HexBox _hexBox;

			/// <summary>
			/// Contains True, if shift key is down
			/// </summary>
			protected bool _shiftDown;
			/// <summary>
			/// Contains True, if mouse is down
			/// </summary>
			bool _mouseDown;
			/// <summary>
			/// Contains the selection start position info
			/// </summary>
			BytePositionInfo _bpiStart;
			/// <summary>
			/// Contains the current mouse selection position info
			/// </summary>
			BytePositionInfo _bpi;
			/// <summary>
			/// Contains all message handlers of key interpreter key down message
			/// </summary>
			Dictionary<Keys, MessageDelegate> _messageHandlers;
			#endregion

			#region Ctors
			public KeyInterpreter(HexBox hexBox)
			{
				_hexBox = hexBox;
			}
			#endregion

			#region Activate, Deactive methods
			public virtual void Activate()
			{
				_hexBox.MouseDown += new MouseEventHandler(BeginMouseSelection);
				_hexBox.MouseMove += new MouseEventHandler(UpdateMouseSelection);
				_hexBox.MouseUp += new MouseEventHandler(EndMouseSelection);
			}

			public virtual void Deactivate()
			{
				_hexBox.MouseDown -= new MouseEventHandler(BeginMouseSelection);
				_hexBox.MouseMove -= new MouseEventHandler(UpdateMouseSelection);
				_hexBox.MouseUp -= new MouseEventHandler(EndMouseSelection);
			}
			#endregion

			#region Mouse selection methods
			void BeginMouseSelection(object sender, MouseEventArgs e)
			{
				System.Diagnostics.Debug.WriteLine("BeginMouseSelection()", "KeyInterpreter");

				if (e.Button != MouseButtons.Left)
					return;

				_mouseDown = true;

				if (!_shiftDown)
				{
					_bpiStart = new BytePositionInfo(_hexBox._bytePos, _hexBox._byteCharacterPos);
					_hexBox.ReleaseSelection();
				}
				else
				{
					UpdateMouseSelection(this, e);
				}
			}

			void UpdateMouseSelection(object sender, MouseEventArgs e)
			{
				if (!_mouseDown)
					return;

				_bpi = GetBytePositionInfo(new Point(e.X, e.Y));
				long selEnd = _bpi.Index;
				long realselStart;
				long realselLength;

				if (selEnd < _bpiStart.Index)
				{
					realselStart = selEnd;
					realselLength = _bpiStart.Index - selEnd;
				}
				else if (selEnd > _bpiStart.Index)
				{
					realselStart = _bpiStart.Index;
					realselLength = selEnd - realselStart;
				}
				else
				{
					realselStart = _hexBox._bytePos;
					realselLength = 0;
				}

				if (realselStart != _hexBox._bytePos || realselLength != _hexBox._selectionLength)
				{
					_hexBox.InternalSelect(realselStart, realselLength);
					_hexBox.ScrollByteIntoView(_bpi.Index);
				}
			}

			void EndMouseSelection(object sender, MouseEventArgs e)
			{
				_mouseDown = false;
			}
			#endregion

			#region PrePrcessWmKeyDown methods
			public virtual bool PreProcessWmKeyDown(ref Message m)
			{
				System.Diagnostics.Debug.WriteLine("PreProcessWmKeyDown(ref Message m)", "KeyInterpreter");

				Keys vc = (Keys)m.WParam.ToInt32();

				Keys keyData = vc | Control.ModifierKeys;

				// detect whether key down event should be raised
				var hasMessageHandler = this.MessageHandlers.ContainsKey(keyData);
				if (hasMessageHandler && RaiseKeyDown(keyData))
					return true;

				MessageDelegate messageHandler = hasMessageHandler
					? this.MessageHandlers[keyData]
					: messageHandler = new MessageDelegate(PreProcessWmKeyDown_Default);

				return messageHandler(ref m);
			}

			protected bool PreProcessWmKeyDown_Default(ref Message m)
			{
				_hexBox.ScrollByteIntoView();
				return _hexBox.BasePreProcessMessage(ref m);
			}

			protected bool RaiseKeyDown(Keys keyData)
			{
				KeyEventArgs e = new KeyEventArgs(keyData);
				_hexBox.OnKeyDown(e);
				return e.Handled;
			}

			protected virtual bool PreProcessWmKeyDown_Left(ref Message m)
			{
				return PerformPosMoveLeft();
			}

			protected virtual bool PreProcessWmKeyDown_Up(ref Message m)
			{
				long pos = _hexBox._bytePos;
				int cp = _hexBox._byteCharacterPos;

				if (!(pos == 0 && cp == 0))
				{
					pos = Math.Max(-1, pos - _hexBox._iHexMaxHBytes);
					if (pos == -1)
						return true;

					_hexBox.SetPosition(pos);

					if (pos < _hexBox._startByte)
					{
						_hexBox.PerformScrollLineUp();
					}

					_hexBox.UpdateCaret();
					_hexBox.Invalidate();
				}

				_hexBox.ScrollByteIntoView();
				_hexBox.ReleaseSelection();

				return true;
			}

			protected virtual bool PreProcessWmKeyDown_Right(ref Message m)
			{
				return PerformPosMoveRight();
			}

			protected virtual bool PreProcessWmKeyDown_Down(ref Message m)
			{
				long pos = _hexBox._bytePos;
				int cp = _hexBox._byteCharacterPos;

				if (pos == _hexBox._byteProvider.Length && cp == 0)
					return true;

				pos = Math.Min(_hexBox._byteProvider.Length, pos + _hexBox._iHexMaxHBytes);

				if (pos == _hexBox._byteProvider.Length)
					cp = 0;

				_hexBox.SetPosition(pos, cp);

				if (pos > _hexBox._endByte - 1)
				{
					_hexBox.PerformScrollLineDown();
				}

				_hexBox.UpdateCaret();
				_hexBox.ScrollByteIntoView();
				_hexBox.ReleaseSelection();
				_hexBox.Invalidate();

				return true;
			}

			protected virtual bool PreProcessWmKeyDown_PageUp(ref Message m)
			{
				long pos = _hexBox._bytePos;
				int cp = _hexBox._byteCharacterPos;

				if (pos == 0 && cp == 0)
					return true;

				pos = Math.Max(0, pos - _hexBox._iHexMaxBytes);
				if (pos == 0)
					return true;

				_hexBox.SetPosition(pos);

				if (pos < _hexBox._startByte)
				{
					_hexBox.PerformScrollPageUp();
				}

				_hexBox.ReleaseSelection();
				_hexBox.UpdateCaret();
				_hexBox.Invalidate();
				return true;
			}

			protected virtual bool PreProcessWmKeyDown_PageDown(ref Message m)
			{
				long pos = _hexBox._bytePos;
				int cp = _hexBox._byteCharacterPos;

				if (pos == _hexBox._byteProvider.Length && cp == 0)
					return true;

				pos = Math.Min(_hexBox._byteProvider.Length, pos + _hexBox._iHexMaxBytes);

				if (pos == _hexBox._byteProvider.Length)
					cp = 0;

				_hexBox.SetPosition(pos, cp);

				if (pos > _hexBox._endByte - 1)
				{
					_hexBox.PerformScrollPageDown();
				}

				_hexBox.ReleaseSelection();
				_hexBox.UpdateCaret();
				_hexBox.Invalidate();

				return true;
			}

			protected virtual bool PreProcessWmKeyDown_ShiftLeft(ref Message m)
			{
				long pos = _hexBox._bytePos;
				long sel = _hexBox._selectionLength;

				if (pos + sel < 1)
					return true;

				if (pos + sel <= _bpiStart.Index)
				{
					if (pos == 0)
						return true;

					pos--;
					sel++;
				}
				else
				{
					sel = Math.Max(0, sel - 1);
				}

				_hexBox.ScrollByteIntoView();
				_hexBox.InternalSelect(pos, sel);

				return true;
			}

			protected virtual bool PreProcessWmKeyDown_ShiftUp(ref Message m)
			{
				long pos = _hexBox._bytePos;
				long sel = _hexBox._selectionLength;

				if (pos - _hexBox._iHexMaxHBytes < 0 && pos <= _bpiStart.Index)
					return true;

				if (_bpiStart.Index >= pos + sel)
				{
					pos = pos - _hexBox._iHexMaxHBytes;
					sel += _hexBox._iHexMaxHBytes;
					_hexBox.InternalSelect(pos, sel);
					_hexBox.ScrollByteIntoView();
				}
				else
				{
					sel -= _hexBox._iHexMaxHBytes;
					if (sel < 0)
					{
						pos = _bpiStart.Index + sel;
						sel = -sel;
						_hexBox.InternalSelect(pos, sel);
						_hexBox.ScrollByteIntoView();
					}
					else
					{
						sel -= _hexBox._iHexMaxHBytes;
						_hexBox.InternalSelect(pos, sel);
						_hexBox.ScrollByteIntoView(pos + sel);
					}
				}

				return true;
			}

			protected virtual bool PreProcessWmKeyDown_ShiftRight(ref Message m)
			{
				long pos = _hexBox._bytePos;
				long sel = _hexBox._selectionLength;

				if (pos + sel >= _hexBox._byteProvider.Length)
					return true;

				if (_bpiStart.Index <= pos)
				{
					sel++;
					_hexBox.InternalSelect(pos, sel);
					_hexBox.ScrollByteIntoView(pos + sel);
				}
				else
				{
					pos++;
					sel = Math.Max(0, sel - 1);
					_hexBox.InternalSelect(pos, sel);
					_hexBox.ScrollByteIntoView();
				}

				return true;
			}

			protected virtual bool PreProcessWmKeyDown_ShiftDown(ref Message m)
			{
				long pos = _hexBox._bytePos;
				long sel = _hexBox._selectionLength;

				long max = _hexBox._byteProvider.Length;

				if (pos + sel + _hexBox._iHexMaxHBytes > max)
					return true;

				if (_bpiStart.Index <= pos)
				{
					sel += _hexBox._iHexMaxHBytes;
					_hexBox.InternalSelect(pos, sel);
					_hexBox.ScrollByteIntoView(pos + sel);
				}
				else
				{
					sel -= _hexBox._iHexMaxHBytes;
					if (sel < 0)
					{
						pos = _bpiStart.Index;
						sel = -sel;
					}
					else
					{
						pos += _hexBox._iHexMaxHBytes;
						//sel -= _hexBox._iHexMaxHBytes;
					}

					_hexBox.InternalSelect(pos, sel);
					_hexBox.ScrollByteIntoView();
				}

				return true;
			}

			protected virtual bool PreProcessWmKeyDown_Tab(ref Message m)
			{
				if (_hexBox._stringViewVisible && _hexBox._keyInterpreter.GetType() == typeof(KeyInterpreter))
				{
					_hexBox.ActivateStringKeyInterpreter();
					_hexBox.ScrollByteIntoView();
					_hexBox.ReleaseSelection();
					_hexBox.UpdateCaret();
					_hexBox.Invalidate();
					return true;
				}

				if (_hexBox.Parent == null) return true;
				_hexBox.Parent.SelectNextControl(_hexBox, true, true, true, true);
				return true;
			}

			protected virtual bool PreProcessWmKeyDown_ShiftTab(ref Message m)
			{
				if (_hexBox._keyInterpreter is StringKeyInterpreter)
				{
					_shiftDown = false;
					_hexBox.ActivateKeyInterpreter();
					_hexBox.ScrollByteIntoView();
					_hexBox.ReleaseSelection();
					_hexBox.UpdateCaret();
					_hexBox.Invalidate();
					return true;
				}

				if (_hexBox.Parent == null) return true;
				_hexBox.Parent.SelectNextControl(_hexBox, false, true, true, true);
				return true;
			}

			protected virtual bool PreProcessWmKeyDown_Back(ref Message m)
			{
				if (!_hexBox._byteProvider.SupportsDeleteBytes())
					return true;

				if (_hexBox.ReadOnly)
					return true;

				long pos = _hexBox._bytePos;
				long sel = _hexBox._selectionLength;
				int cp = _hexBox._byteCharacterPos;

				long startDelete = (cp == 0 && sel == 0) ? pos - 1 : pos;
				if (startDelete < 0 && sel < 1)
					return true;

				long bytesToDelete = (sel > 0) ? sel : 1;
				_hexBox._byteProvider.DeleteBytes(Math.Max(0, startDelete), bytesToDelete);
				_hexBox.UpdateScrollSize();

				if (sel == 0)
					PerformPosMoveLeftByte();

				_hexBox.ReleaseSelection();
				_hexBox.Invalidate();

				return true;
			}

			protected virtual bool PreProcessWmKeyDown_Delete(ref Message m)
			{
				if (!_hexBox._byteProvider.SupportsDeleteBytes())
					return true;

				if (_hexBox.ReadOnly)
					return true;

				long pos = _hexBox._bytePos;
				long sel = _hexBox._selectionLength;

				if (pos >= _hexBox._byteProvider.Length)
					return true;

				long bytesToDelete = (sel > 0) ? sel : 1;
				_hexBox._byteProvider.DeleteBytes(pos, bytesToDelete);

				_hexBox.UpdateScrollSize();
				_hexBox.ReleaseSelection();
				_hexBox.Invalidate();

				return true;
			}

			protected virtual bool PreProcessWmKeyDown_Home(ref Message m)
			{
				long pos = _hexBox._bytePos;
				int cp = _hexBox._byteCharacterPos;

				if (pos < 1)
					return true;

				pos = 0;
				cp = 0;
				_hexBox.SetPosition(pos, cp);

				_hexBox.ScrollByteIntoView();
				_hexBox.UpdateCaret();
				_hexBox.ReleaseSelection();

				return true;
			}

			protected virtual bool PreProcessWmKeyDown_End(ref Message m)
			{
				long pos = _hexBox._bytePos;
				int cp = _hexBox._byteCharacterPos;

				if (pos >= _hexBox._byteProvider.Length - 1)
					return true;

				pos = _hexBox._byteProvider.Length;
				cp = 0;
				_hexBox.SetPosition(pos, cp);

				_hexBox.ScrollByteIntoView();
				_hexBox.UpdateCaret();
				_hexBox.ReleaseSelection();

				return true;
			}

			protected virtual bool PreProcessWmKeyDown_ShiftShiftKey(ref Message m)
			{
				if (_mouseDown)
					return true;
				if (_shiftDown)
					return true;

				_shiftDown = true;

				if (_hexBox._selectionLength > 0)
					return true;

				_bpiStart = new BytePositionInfo(_hexBox._bytePos, _hexBox._byteCharacterPos);

				return true;
			}

			protected virtual bool PreProcessWmKeyDown_ControlC(ref Message m)
			{
				_hexBox.Copy();
				return true;
			}

			protected virtual bool PreProcessWmKeyDown_ControlX(ref Message m)
			{
				_hexBox.Cut();
				return true;
			}

			protected virtual bool PreProcessWmKeyDown_ControlV(ref Message m)
			{
				_hexBox.Paste();
				return true;
			}

			#endregion

			#region PreProcessWmChar methods
			public virtual bool PreProcessWmChar(ref Message m)
			{
				if (Control.ModifierKeys == Keys.Control)
				{
					return _hexBox.BasePreProcessMessage(ref m);
				}

				bool sw = _hexBox._byteProvider.SupportsWriteByte();
				bool si = _hexBox._byteProvider.SupportsInsertBytes();
				bool sd = _hexBox._byteProvider.SupportsDeleteBytes();

				long pos = _hexBox._bytePos;
				long sel = _hexBox._selectionLength;
				int cp = _hexBox._byteCharacterPos;

				if (
					(!sw && pos != _hexBox._byteProvider.Length) ||
					(!si && pos == _hexBox._byteProvider.Length))
				{
					return _hexBox.BasePreProcessMessage(ref m);
				}

				char c = (char)m.WParam.ToInt32();

				if (Uri.IsHexDigit(c))
				{
					if (RaiseKeyPress(c))
						return true;

					if (_hexBox.ReadOnly)
						return true;

					bool isInsertMode = (pos == _hexBox._byteProvider.Length);

					// do insert when insertActive = true
					if (!isInsertMode && si && _hexBox.InsertActive && cp == 0)
						isInsertMode = true;

					if (sd && si && sel > 0)
					{
						_hexBox._byteProvider.DeleteBytes(pos, sel);
						isInsertMode = true;
						cp = 0;
						_hexBox.SetPosition(pos, cp);
					}

					_hexBox.ReleaseSelection();

					byte currentByte;
					if (isInsertMode)
						currentByte = 0;
					else
						currentByte = _hexBox._byteProvider.ReadByte(pos);

					string sCb = currentByte.ToString("X", System.Threading.Thread.CurrentThread.CurrentCulture);
					if (sCb.Length == 1)
						sCb = "0" + sCb;

					string sNewCb = c.ToString();
					if (cp == 0)
						sNewCb += sCb.Substring(1, 1);
					else
						sNewCb = sCb.Substring(0, 1) + sNewCb;
					byte newcb = byte.Parse(sNewCb, System.Globalization.NumberStyles.AllowHexSpecifier, System.Threading.Thread.CurrentThread.CurrentCulture);

					if (isInsertMode)
						_hexBox._byteProvider.InsertBytes(pos, new byte[] { newcb });
					else
						_hexBox._byteProvider.WriteByte(pos, newcb);

					PerformPosMoveRight();

					_hexBox.Invalidate();
					return true;
				}
				else
				{
					return _hexBox.BasePreProcessMessage(ref m);
				}
			}

			protected bool RaiseKeyPress(char keyChar)
			{
				KeyPressEventArgs e = new KeyPressEventArgs(keyChar);
				_hexBox.OnKeyPress(e);
				return e.Handled;
			}
			#endregion

			#region PreProcessWmKeyUp methods
			public virtual bool PreProcessWmKeyUp(ref Message m)
			{
				System.Diagnostics.Debug.WriteLine("PreProcessWmKeyUp(ref Message m)", "KeyInterpreter");

				Keys vc = (Keys)m.WParam.ToInt32();

				Keys keyData = vc | Control.ModifierKeys;

				switch (keyData)
				{
					case Keys.ShiftKey:
					case Keys.Insert:
						if (RaiseKeyUp(keyData))
							return true;
						break;
				}

				switch (keyData)
				{
					case Keys.ShiftKey:
						_shiftDown = false;
						return true;
					case Keys.Insert:
						return PreProcessWmKeyUp_Insert(ref m);
					default:
						return _hexBox.BasePreProcessMessage(ref m);
				}
			}

			protected virtual bool PreProcessWmKeyUp_Insert(ref Message m)
			{
				_hexBox.InsertActive = !_hexBox.InsertActive;
				return true;
			}

			protected bool RaiseKeyUp(Keys keyData)
			{
				KeyEventArgs e = new KeyEventArgs(keyData);
				_hexBox.OnKeyUp(e);
				return e.Handled;
			}
			#endregion

			#region Misc
			Dictionary<Keys, MessageDelegate> MessageHandlers
			{
				get
				{
					if (_messageHandlers == null)
					{
						_messageHandlers = new Dictionary<Keys, MessageDelegate>();
						_messageHandlers.Add(Keys.Left, new MessageDelegate(PreProcessWmKeyDown_Left)); // move left
						_messageHandlers.Add(Keys.Up, new MessageDelegate(PreProcessWmKeyDown_Up)); // move up
						_messageHandlers.Add(Keys.Right, new MessageDelegate(PreProcessWmKeyDown_Right)); // move right
						_messageHandlers.Add(Keys.Down, new MessageDelegate(PreProcessWmKeyDown_Down)); // move down
						_messageHandlers.Add(Keys.PageUp, new MessageDelegate(PreProcessWmKeyDown_PageUp)); // move pageup
						_messageHandlers.Add(Keys.PageDown, new MessageDelegate(PreProcessWmKeyDown_PageDown)); // move page down
						_messageHandlers.Add(Keys.Left | Keys.Shift, new MessageDelegate(PreProcessWmKeyDown_ShiftLeft)); // move left with selection
						_messageHandlers.Add(Keys.Up | Keys.Shift, new MessageDelegate(PreProcessWmKeyDown_ShiftUp)); // move up with selection
						_messageHandlers.Add(Keys.Right | Keys.Shift, new MessageDelegate(PreProcessWmKeyDown_ShiftRight)); // move right with selection
						_messageHandlers.Add(Keys.Down | Keys.Shift, new MessageDelegate(PreProcessWmKeyDown_ShiftDown)); // move down with selection
						_messageHandlers.Add(Keys.Tab, new MessageDelegate(PreProcessWmKeyDown_Tab)); // switch to string view
						_messageHandlers.Add(Keys.Back, new MessageDelegate(PreProcessWmKeyDown_Back)); // back
						_messageHandlers.Add(Keys.Delete, new MessageDelegate(PreProcessWmKeyDown_Delete)); // delete
						_messageHandlers.Add(Keys.Home, new MessageDelegate(PreProcessWmKeyDown_Home)); // move to home
						_messageHandlers.Add(Keys.End, new MessageDelegate(PreProcessWmKeyDown_End)); // move to end
						_messageHandlers.Add(Keys.ShiftKey | Keys.Shift, new MessageDelegate(PreProcessWmKeyDown_ShiftShiftKey)); // begin selection process
						_messageHandlers.Add(Keys.C | Keys.Control, new MessageDelegate(PreProcessWmKeyDown_ControlC)); // copy 
						_messageHandlers.Add(Keys.X | Keys.Control, new MessageDelegate(PreProcessWmKeyDown_ControlX)); // cut
						_messageHandlers.Add(Keys.V | Keys.Control, new MessageDelegate(PreProcessWmKeyDown_ControlV)); // paste
					}
					return _messageHandlers;
				}
			}

			protected virtual bool PerformPosMoveLeft()
			{
				long pos = _hexBox._bytePos;
				long sel = _hexBox._selectionLength;
				int cp = _hexBox._byteCharacterPos;

				if (sel != 0)
				{
					cp = 0;
					_hexBox.SetPosition(pos, cp);
					_hexBox.ReleaseSelection();
				}
				else
				{
					if (pos == 0 && cp == 0)
						return true;

					if (cp > 0)
					{
						cp--;
					}
					else
					{
						pos = Math.Max(0, pos - 1);
						cp++;
					}

					_hexBox.SetPosition(pos, cp);

					if (pos < _hexBox._startByte)
					{
						_hexBox.PerformScrollLineUp();
					}
					_hexBox.UpdateCaret();
					_hexBox.Invalidate();
				}

				_hexBox.ScrollByteIntoView();
				return true;
			}
			protected virtual bool PerformPosMoveRight()
			{
				long pos = _hexBox._bytePos;
				int cp = _hexBox._byteCharacterPos;
				long sel = _hexBox._selectionLength;

				if (sel != 0)
				{
					pos += sel;
					cp = 0;
					_hexBox.SetPosition(pos, cp);
					_hexBox.ReleaseSelection();
				}
				else
				{
					if (!(pos == _hexBox._byteProvider.Length && cp == 0))
					{

						if (cp > 0)
						{
							pos = Math.Min(_hexBox._byteProvider.Length, pos + 1);
							cp = 0;
						}
						else
						{
							cp++;
						}

						_hexBox.SetPosition(pos, cp);

						if (pos > _hexBox._endByte - 1)
						{
							_hexBox.PerformScrollLineDown();
						}
						_hexBox.UpdateCaret();
						_hexBox.Invalidate();
					}
				}

				_hexBox.ScrollByteIntoView();
				return true;
			}
			protected virtual bool PerformPosMoveLeftByte()
			{
				long pos = _hexBox._bytePos;
				int cp = _hexBox._byteCharacterPos;

				if (pos == 0)
					return true;

				pos = Math.Max(0, pos - 1);
				cp = 0;

				_hexBox.SetPosition(pos, cp);

				if (pos < _hexBox._startByte)
				{
					_hexBox.PerformScrollLineUp();
				}
				_hexBox.UpdateCaret();
				_hexBox.ScrollByteIntoView();
				_hexBox.Invalidate();

				return true;
			}

			protected virtual bool PerformPosMoveRightByte()
			{
				long pos = _hexBox._bytePos;
				int cp = _hexBox._byteCharacterPos;

				if (pos == _hexBox._byteProvider.Length)
					return true;

				pos = Math.Min(_hexBox._byteProvider.Length, pos + 1);
				cp = 0;

				_hexBox.SetPosition(pos, cp);

				if (pos > _hexBox._endByte - 1)
				{
					_hexBox.PerformScrollLineDown();
				}
				_hexBox.UpdateCaret();
				_hexBox.ScrollByteIntoView();
				_hexBox.Invalidate();

				return true;
			}


			public virtual PointF GetCaretPointF(long byteIndex)
			{
				System.Diagnostics.Debug.WriteLine("GetCaretPointF()", "KeyInterpreter");

				return _hexBox.GetBytePointF(byteIndex);
			}

			protected virtual BytePositionInfo GetBytePositionInfo(Point p)
			{
				return _hexBox.GetHexBytePositionInfo(p);
			}
			#endregion
		}
		#endregion

		#region StringKeyInterpreter class
		/// <summary>
		/// Handles user input such as mouse and keyboard input during string view edit
		/// </summary>
		class StringKeyInterpreter : KeyInterpreter
		{
			#region Ctors
			public StringKeyInterpreter(HexBox hexBox)
				: base(hexBox)
			{
				_hexBox._byteCharacterPos = 0;
			}
			#endregion

			#region PreProcessWmKeyDown methods
			public override bool PreProcessWmKeyDown(ref Message m)
			{
				Keys vc = (Keys)m.WParam.ToInt32();

				Keys keyData = vc | Control.ModifierKeys;

				switch (keyData)
				{
					case Keys.Tab | Keys.Shift:
					case Keys.Tab:
						if (RaiseKeyDown(keyData))
							return true;
						break;
				}

				switch (keyData)
				{
					case Keys.Tab | Keys.Shift:
						return PreProcessWmKeyDown_ShiftTab(ref m);
					case Keys.Tab:
						return PreProcessWmKeyDown_Tab(ref m);
					default:
						return base.PreProcessWmKeyDown(ref m);
				}
			}

			protected override bool PreProcessWmKeyDown_Left(ref Message m)
			{
				return PerformPosMoveLeftByte();
			}

			protected override bool PreProcessWmKeyDown_Right(ref Message m)
			{
				return PerformPosMoveRightByte();
			}

			#endregion

			#region PreProcessWmChar methods
			public override bool PreProcessWmChar(ref Message m)
			{
				if (Control.ModifierKeys == Keys.Control)
				{
					return _hexBox.BasePreProcessMessage(ref m);
				}

				bool sw = _hexBox._byteProvider.SupportsWriteByte();
				bool si = _hexBox._byteProvider.SupportsInsertBytes();
				bool sd = _hexBox._byteProvider.SupportsDeleteBytes();

				long pos = _hexBox._bytePos;
				long sel = _hexBox._selectionLength;
				int cp = _hexBox._byteCharacterPos;

				if (
					(!sw && pos != _hexBox._byteProvider.Length) ||
					(!si && pos == _hexBox._byteProvider.Length))
				{
					return _hexBox.BasePreProcessMessage(ref m);
				}

				char c = (char)m.WParam.ToInt32();

				if (RaiseKeyPress(c))
					return true;

				if (_hexBox.ReadOnly)
					return true;

				bool isInsertMode = (pos == _hexBox._byteProvider.Length);

				// do insert when insertActive = true
				if (!isInsertMode && si && _hexBox.InsertActive)
					isInsertMode = true;

				if (sd && si && sel > 0)
				{
					_hexBox._byteProvider.DeleteBytes(pos, sel);
					isInsertMode = true;
					cp = 0;
					_hexBox.SetPosition(pos, cp);
				}

				_hexBox.ReleaseSelection();

				byte b = _hexBox.ByteCharConverter.ToByte(c);
				if (isInsertMode)
					_hexBox._byteProvider.InsertBytes(pos, new byte[] { b });
				else
					_hexBox._byteProvider.WriteByte(pos, b);

				PerformPosMoveRightByte();
				_hexBox.Invalidate();

				return true;
			}
			#endregion

			#region Misc
			public override PointF GetCaretPointF(long byteIndex)
			{
				System.Diagnostics.Debug.WriteLine("GetCaretPointF()", "StringKeyInterpreter");

				Point gp = _hexBox.GetGridBytePoint(byteIndex);
				return _hexBox.GetByteStringPointF(gp);
			}

			protected override BytePositionInfo GetBytePositionInfo(Point p)
			{
				return _hexBox.GetStringBytePositionInfo(p);
			}
			#endregion
		}
		#endregion

		#region Fields
		/// <summary>
		/// Contains the hole content bounds of all text
		/// </summary>
		Rectangle _recContent;
		/// <summary>
		/// Contains the line info bounds
		/// </summary>
		Rectangle _recLineInfo;
		/// <summary>
		/// Contains the column info header rectangle bounds
		/// </summary>
		Rectangle _recColumnInfo;
		/// <summary>
		/// Contains the hex data bounds
		/// </summary>
		Rectangle _recHex;
		/// <summary>
		/// Contains the string view bounds
		/// </summary>
		Rectangle _recStringView;

		/// <summary>
		/// Contains string format information for text drawing
		/// </summary>
		StringFormat _stringFormat;
		/// <summary>
		/// Contains the width and height of a single char
		/// </summary>
		SizeF _charSize;

		/// <summary>
		/// Contains the maximum of visible horizontal bytes
		/// </summary>
		int _iHexMaxHBytes;
		/// <summary>
		/// Contains the maximum of visible vertical bytes
		/// </summary>
		int _iHexMaxVBytes;
		/// <summary>
		/// Contains the maximum of visible bytes.
		/// </summary>
		int _iHexMaxBytes;

		/// <summary>
		/// Contains the scroll bars minimum value
		/// </summary>
		long _scrollVmin;
		/// <summary>
		/// Contains the scroll bars maximum value
		/// </summary>
		long _scrollVmax;
		/// <summary>
		/// Contains the scroll bars current position
		/// </summary>
		long _scrollVpos;
		/// <summary>
		/// Contains a vertical scroll
		/// </summary>
		VScrollBar _vScrollBar;
		/// <summary>
		/// Contains a timer for thumbtrack scrolling
		/// </summary>
		Timer _thumbTrackTimer = new Timer();
		/// <summary>
		/// Contains the thumbtrack scrolling position
		/// </summary>
		long _thumbTrackPosition;
		/// <summary>
		/// Contains the thumptrack delay for scrolling in milliseconds.
		/// </summary>
		const int THUMPTRACKDELAY = 50;
		/// <summary>
		/// Contains the Enviroment.TickCount of the last refresh
		/// </summary>
		int _lastThumbtrack;
		/// <summary>
		/// Contains the border�s left shift
		/// </summary>
		int _recBorderLeft = SystemInformation.Border3DSize.Width;
		/// <summary>
		/// Contains the border�s right shift
		/// </summary>
		int _recBorderRight = SystemInformation.Border3DSize.Width;
		/// <summary>
		/// Contains the border�s top shift
		/// </summary>
		int _recBorderTop = SystemInformation.Border3DSize.Height;
		/// <summary>
		/// Contains the border bottom shift
		/// </summary>
		int _recBorderBottom = SystemInformation.Border3DSize.Height;

		/// <summary>
		/// Contains the index of the first visible byte
		/// </summary>
		long _startByte;
		/// <summary>
		/// Contains the index of the last visible byte
		/// </summary>
		long _endByte;

		/// <summary>
		/// Contains the current byte position
		/// </summary>
		long _bytePos = -1;
		/// <summary>
		/// Contains the current char position in one byte
		/// </summary>
		/// <example>
		/// "1A"
		/// "1" = char position of 0
		/// "A" = char position of 1
		/// </example>
		int _byteCharacterPos;

		/// <summary>
		/// Contains string format information for hex values
		/// </summary>
		string _hexStringFormat = "X";


		/// <summary>
		/// Contains the current key interpreter
		/// </summary>
		IKeyInterpreter _keyInterpreter;
		/// <summary>
		/// Contains an empty key interpreter without functionality
		/// </summary>
		EmptyKeyInterpreter _eki;
		/// <summary>
		/// Contains the default key interpreter
		/// </summary>
		KeyInterpreter _ki;
		/// <summary>
		/// Contains the string key interpreter
		/// </summary>
		StringKeyInterpreter _ski;

		/// <summary>
		/// Contains True if caret is visible
		/// </summary>
		bool _caretVisible;

		/// <summary>
		/// Contains true, if the find (Find method) should be aborted.
		/// </summary>
		bool _abortFind;
		/// <summary>
		/// Contains a value of the current finding position.
		/// </summary>
		long _findingPos;

		/// <summary>
		/// Contains a state value about Insert or Write mode. When this value is true and the ByteProvider SupportsInsert is true bytes are inserted instead of overridden.
		/// </summary>
		bool _insertActive;
		#endregion

		#region Events
		/// <summary>
		/// Occurs, when the value of InsertActive property has changed.
		/// </summary>
		[Description("Occurs, when the value of InsertActive property has changed.")]
		public event EventHandler InsertActiveChanged;
		/// <summary>
		/// Occurs, when the value of ReadOnly property has changed.
		/// </summary>
		[Description("Occurs, when the value of ReadOnly property has changed.")]
		public event EventHandler ReadOnlyChanged;
		/// <summary>
		/// Occurs, when the value of ByteProvider property has changed.
		/// </summary>
		[Description("Occurs, when the value of ByteProvider property has changed.")]
		public event EventHandler ByteProviderChanged;
		/// <summary>
		/// Occurs, when the value of SelectionStart property has changed.
		/// </summary>
		[Description("Occurs, when the value of SelectionStart property has changed.")]
		public event EventHandler SelectionStartChanged;
		/// <summary>
		/// Occurs, when the value of SelectionLength property has changed.
		/// </summary>
		[Description("Occurs, when the value of SelectionLength property has changed.")]
		public event EventHandler SelectionLengthChanged;
		/// <summary>
		/// Occurs, when the value of LineInfoVisible property has changed.
		/// </summary>
		[Description("Occurs, when the value of LineInfoVisible property has changed.")]
		public event EventHandler LineInfoVisibleChanged;
		/// <summary>
		/// Occurs, when the value of ColumnInfoVisibleChanged property has changed.
		/// </summary>
		[Description("Occurs, when the value of ColumnInfoVisibleChanged property has changed.")]
		public event EventHandler ColumnInfoVisibleChanged;
		/// <summary>
		/// Occurs, when the value of GroupSeparatorVisibleChanged property has changed.
		/// </summary>
		[Description("Occurs, when the value of GroupSeparatorVisibleChanged property has changed.")]
		public event EventHandler GroupSeparatorVisibleChanged;
		/// <summary>
		/// Occurs, when the value of StringViewVisible property has changed.
		/// </summary>
		[Description("Occurs, when the value of StringViewVisible property has changed.")]
		public event EventHandler StringViewVisibleChanged;
		/// <summary>
		/// Occurs, when the value of BorderStyle property has changed.
		/// </summary>
		[Description("Occurs, when the value of BorderStyle property has changed.")]
		public event EventHandler BorderStyleChanged;
		/// <summary>
		/// Occurs, when the value of ColumnWidth property has changed.
		/// </summary>
		[Description("Occurs, when the value of GroupSize property has changed.")]
		public event EventHandler GroupSizeChanged;
		/// <summary>
		/// Occurs, when the value of BytesPerLine property has changed.
		/// </summary>
		[Description("Occurs, when the value of BytesPerLine property has changed.")]
		public event EventHandler BytesPerLineChanged;
		/// <summary>
		/// Occurs, when the value of UseFixedBytesPerLine property has changed.
		/// </summary>
		[Description("Occurs, when the value of UseFixedBytesPerLine property has changed.")]
		public event EventHandler UseFixedBytesPerLineChanged;
		/// <summary>
		/// Occurs, when the value of VScrollBarVisible property has changed.
		/// </summary>
		[Description("Occurs, when the value of VScrollBarVisible property has changed.")]
		public event EventHandler VScrollBarVisibleChanged;
		/// <summary>
		/// Occurs, when the value of HexCasing property has changed.
		/// </summary>
		[Description("Occurs, when the value of HexCasing property has changed.")]
		public event EventHandler HexCasingChanged;
		/// <summary>
		/// Occurs, when the value of HorizontalByteCount property has changed.
		/// </summary>
		[Description("Occurs, when the value of HorizontalByteCount property has changed.")]
		public event EventHandler HorizontalByteCountChanged;
		/// <summary>
		/// Occurs, when the value of VerticalByteCount property has changed.
		/// </summary>
		[Description("Occurs, when the value of VerticalByteCount property has changed.")]
		public event EventHandler VerticalByteCountChanged;
		/// <summary>
		/// Occurs, when the value of CurrentLine property has changed.
		/// </summary>
		[Description("Occurs, when the value of CurrentLine property has changed.")]
		public event EventHandler CurrentLineChanged;
		/// <summary>
		/// Occurs, when the value of CurrentPositionInLine property has changed.
		/// </summary>
		[Description("Occurs, when the value of CurrentPositionInLine property has changed.")]
		public event EventHandler CurrentPositionInLineChanged;
		/// <summary>
		/// Occurs, when Copy method was invoked and ClipBoardData changed.
		/// </summary>
		[Description("Occurs, when Copy method was invoked and ClipBoardData changed.")]
		public event EventHandler Copied;
		/// <summary>
		/// Occurs, when CopyHex method was invoked and ClipBoardData changed.
		/// </summary>
		[Description("Occurs, when CopyHex method was invoked and ClipBoardData changed.")]
		public event EventHandler CopiedHex;
		#endregion

		#region Ctors

		/// <summary>
		/// Initializes a new instance of a HexBox class.
		/// </summary>
		public HexBox()
		{
			this._vScrollBar = new VScrollBar();
			this._vScrollBar.Scroll += new ScrollEventHandler(_vScrollBar_Scroll);

			this._builtInContextMenu = new BuiltInContextMenu(this);

			BackColor = Color.White;
			Font = new Font("Courier New", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
			_stringFormat = new StringFormat(StringFormat.GenericTypographic);
			_stringFormat.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;

			ActivateEmptyKeyInterpreter();

			SetStyle(ControlStyles.UserPaint, true);
			SetStyle(ControlStyles.DoubleBuffer, true);
			SetStyle(ControlStyles.AllPaintingInWmPaint, true);
			SetStyle(ControlStyles.ResizeRedraw, true);

			_thumbTrackTimer.Interval = 50;
			_thumbTrackTimer.Tick += new EventHandler(PerformScrollThumbTrack);
		}

		#endregion

		#region Scroll methods
		void _vScrollBar_Scroll(object sender, ScrollEventArgs e)
		{
			switch (e.Type)
			{
				case ScrollEventType.Last:
					break;
				case ScrollEventType.EndScroll:
					break;
				case ScrollEventType.SmallIncrement:
					PerformScrollLineDown();
					break;
				case ScrollEventType.SmallDecrement:
					PerformScrollLineUp();
					break;
				case ScrollEventType.LargeIncrement:
					PerformScrollPageDown();
					break;
				case ScrollEventType.LargeDecrement:
					PerformScrollPageUp();
					break;
				case ScrollEventType.ThumbPosition:
					long lPos = FromScrollPos(e.NewValue);
					PerformScrollThumpPosition(lPos);
					break;
				case ScrollEventType.ThumbTrack:
					// to avoid performance problems use a refresh delay implemented with a timer
					if (_thumbTrackTimer.Enabled) // stop old timer
						_thumbTrackTimer.Enabled = false;

					// perform scroll immediately only if last refresh is very old
					int currentThumbTrack = System.Environment.TickCount;
					if (currentThumbTrack - _lastThumbtrack > THUMPTRACKDELAY)
					{
						PerformScrollThumbTrack(null, null);
						_lastThumbtrack = currentThumbTrack;
						break;
					}

					// start thumbtrack timer 
					_thumbTrackPosition = FromScrollPos(e.NewValue);
					_thumbTrackTimer.Enabled = true;
					break;
				case ScrollEventType.First:
					break;
				default:
					break;
			}

			e.NewValue = ToScrollPos(_scrollVpos);
		}

		/// <summary>
		/// Performs the thumbtrack scrolling after an delay.
		/// </summary>
		void PerformScrollThumbTrack(object sender, EventArgs e)
		{
			_thumbTrackTimer.Enabled = false;
			PerformScrollThumpPosition(_thumbTrackPosition);
			_lastThumbtrack = Environment.TickCount;
		}

		void UpdateScrollSize()
		{
			System.Diagnostics.Debug.WriteLine("UpdateScrollSize()", "HexBox");

			// calc scroll bar info
			if (VScrollBarVisible && _byteProvider != null && _byteProvider.Length > 0 && _iHexMaxHBytes != 0)
			{
				long scrollmax = (long)Math.Ceiling((double)(_byteProvider.Length + 1) / (double)_iHexMaxHBytes - (double)_iHexMaxVBytes);
				scrollmax = Math.Max(0, scrollmax);

				long scrollpos = _startByte / _iHexMaxHBytes;

				if (scrollmax < _scrollVmax)
				{
					/* Data size has been decreased. */
					if (_scrollVpos == _scrollVmax)
						/* Scroll one line up if we at bottom. */
						PerformScrollLineUp();
				}

				if (scrollmax == _scrollVmax && scrollpos == _scrollVpos)
					return;

				_scrollVmin = 0;
				_scrollVmax = scrollmax;
				_scrollVpos = Math.Min(scrollpos, scrollmax);
				UpdateVScroll();
			}
			else if (VScrollBarVisible)
			{
				// disable scroll bar
				_scrollVmin = 0;
				_scrollVmax = 0;
				_scrollVpos = 0;
				UpdateVScroll();
			}
		}

		void UpdateVScroll()
		{
			System.Diagnostics.Debug.WriteLine("UpdateVScroll()", "HexBox");

			int max = ToScrollMax(_scrollVmax);

			if (max > 0)
			{
				_vScrollBar.Minimum = 0;
				_vScrollBar.Maximum = max;
				_vScrollBar.Value = ToScrollPos(_scrollVpos);
				_vScrollBar.Visible = true;
			}
			else
			{
				_vScrollBar.Visible = false;
			}
		}

		int ToScrollPos(long value)
		{
			int max = 65535;

			if (_scrollVmax < max)
				return (int)value;
			else
			{
				double valperc = (double)value / (double)_scrollVmax * (double)100;
				int res = (int)Math.Floor((double)max / (double)100 * valperc);
				res = (int)Math.Max(_scrollVmin, res);
				res = (int)Math.Min(_scrollVmax, res);
				return res;
			}
		}

		long FromScrollPos(int value)
		{
			int max = 65535;
			if (_scrollVmax < max)
			{
				return (long)value;
			}
			else
			{
				double valperc = (double)value / (double)max * (double)100;
				long res = (int)Math.Floor((double)_scrollVmax / (double)100 * valperc);
				return res;
			}
		}

		int ToScrollMax(long value)
		{
			long max = 65535;
			if (value > max)
				return (int)max;
			else
				return (int)value;
		}

		void PerformScrollToLine(long pos)
		{
			if (pos < _scrollVmin || pos > _scrollVmax || pos == _scrollVpos)
				return;

			_scrollVpos = pos;

			UpdateVScroll();
			UpdateVisibilityBytes();
			UpdateCaret();
			Invalidate();
		}

		void PerformScrollLines(int lines)
		{
			long pos;
			if (lines > 0)
			{
				pos = Math.Min(_scrollVmax, _scrollVpos + lines);
			}
			else if (lines < 0)
			{
				pos = Math.Max(_scrollVmin, _scrollVpos + lines);
			}
			else
			{
				return;
			}

			PerformScrollToLine(pos);
		}

		void PerformScrollLineDown()
		{
			this.PerformScrollLines(1);
		}

		void PerformScrollLineUp()
		{
			this.PerformScrollLines(-1);
		}

		void PerformScrollPageDown()
		{
			this.PerformScrollLines(_iHexMaxVBytes);
		}

		void PerformScrollPageUp()
		{
			this.PerformScrollLines(-_iHexMaxVBytes);
		}

		void PerformScrollThumpPosition(long pos)
		{
			// Bug fix: Scroll to end, do not scroll to end
			int difference = (_scrollVmax > 65535) ? 10 : 9;

			if (ToScrollPos(pos) == ToScrollMax(_scrollVmax) - difference)
				pos = _scrollVmax;
			// End Bug fix


			PerformScrollToLine(pos);
		}

		/// <summary>
		/// Scrolls the selection start byte into view
		/// </summary>
		public void ScrollByteIntoView()
		{
			System.Diagnostics.Debug.WriteLine("ScrollByteIntoView()", "HexBox");

			ScrollByteIntoView(_bytePos);
		}

		/// <summary>
		/// Scrolls the specific byte into view
		/// </summary>
		/// <param name="index">the index of the byte</param>
		public void ScrollByteIntoView(long index)
		{
			System.Diagnostics.Debug.WriteLine("ScrollByteIntoView(long index)", "HexBox");

			if (_byteProvider == null || _keyInterpreter == null)
				return;

			if (index < _startByte)
			{
				long line = (long)Math.Floor((double)index / (double)_iHexMaxHBytes);
				PerformScrollThumpPosition(line);
			}
			else if (index > _endByte)
			{
				long line = (long)Math.Floor((double)index / (double)_iHexMaxHBytes);
				line -= _iHexMaxVBytes - 1;
				PerformScrollThumpPosition(line);
			}
		}
		#endregion

		#region Selection methods
		void ReleaseSelection()
		{
			System.Diagnostics.Debug.WriteLine("ReleaseSelection()", "HexBox");

			if (_selectionLength == 0)
				return;
			_selectionLength = 0;
			OnSelectionLengthChanged(EventArgs.Empty);

			if (!_caretVisible)
				CreateCaret();
			else
				UpdateCaret();

			Invalidate();
		}

		/// <summary>
		/// Returns true if Select method could be invoked.
		/// </summary>
		public bool CanSelectAll()
		{
			if (!this.Enabled)
				return false;
			if (_byteProvider == null)
				return false;

			return true;
		}

		/// <summary>
		/// Selects all bytes.
		/// </summary>
		public void SelectAll()
		{
			if (this.ByteProvider == null)
				return;
			this.Select(0, this.ByteProvider.Length);
		}

		/// <summary>
		/// Selects the hex box.
		/// </summary>
		/// <param name="start">the start index of the selection</param>
		/// <param name="length">the length of the selection</param>
		public void Select(long start, long length)
		{
			if (this.ByteProvider == null)
				return;
			if (!this.Enabled)
				return;

			InternalSelect(start, length);
			ScrollByteIntoView();
		}

		void InternalSelect(long start, long length)
		{
			long pos = start;
			long sel = length;
			int cp = 0;

			if (sel > 0 && _caretVisible)
				DestroyCaret();
			else if (sel == 0 && !_caretVisible)
				CreateCaret();

			SetPosition(pos, cp);
			SetSelectionLength(sel);

			UpdateCaret();
			Invalidate();
		}
		#endregion

		#region Key interpreter methods
		void ActivateEmptyKeyInterpreter()
		{
			if (_eki == null)
				_eki = new EmptyKeyInterpreter(this);

			if (_eki == _keyInterpreter)
				return;

			if (_keyInterpreter != null)
				_keyInterpreter.Deactivate();

			_keyInterpreter = _eki;
			_keyInterpreter.Activate();
		}

		void ActivateKeyInterpreter()
		{
			if (_ki == null)
				_ki = new KeyInterpreter(this);

			if (_ki == _keyInterpreter)
				return;

			if (_keyInterpreter != null)
				_keyInterpreter.Deactivate();

			_keyInterpreter = _ki;
			_keyInterpreter.Activate();
		}

		void ActivateStringKeyInterpreter()
		{
			if (_ski == null)
				_ski = new StringKeyInterpreter(this);

			if (_ski == _keyInterpreter)
				return;

			if (_keyInterpreter != null)
				_keyInterpreter.Deactivate();

			_keyInterpreter = _ski;
			_keyInterpreter.Activate();
		}
		#endregion

		#region Caret methods
		void CreateCaret()
		{
			if (_byteProvider == null || _keyInterpreter == null || _caretVisible || !this.Focused)
				return;

			System.Diagnostics.Debug.WriteLine("CreateCaret()", "HexBox");

			// define the caret width depending on InsertActive mode
			int caretWidth = (this.InsertActive) ? 1 : (int)_charSize.Width;
			int caretHeight = (int)_charSize.Height;
            Caret.Create(Handle, IntPtr.Zero, caretWidth, caretHeight);

			UpdateCaret();

			Caret.Show(Handle);

			_caretVisible = true;
		}

		void UpdateCaret()
		{
			if (_byteProvider == null || _keyInterpreter == null)
				return;

			System.Diagnostics.Debug.WriteLine("UpdateCaret()", "HexBox");

			long byteIndex = _bytePos - _startByte;
			PointF p = _keyInterpreter.GetCaretPointF(byteIndex);
			p.X += _byteCharacterPos * _charSize.Width;
			Caret.SetPos((int)p.X, (int)p.Y);
		}

		void DestroyCaret()
		{
			if (!_caretVisible)
				return;

			System.Diagnostics.Debug.WriteLine("DestroyCaret()", "HexBox");

			Caret.Destroy();
			_caretVisible = false;
		}

		void SetCaretPosition(Point p)
		{
			System.Diagnostics.Debug.WriteLine("SetCaretPosition()", "HexBox");

			if (_byteProvider == null || _keyInterpreter == null)
				return;

			long pos = _bytePos;
			int cp = _byteCharacterPos;

			if (_recHex.Contains(p))
			{
				BytePositionInfo bpi = GetHexBytePositionInfo(p);
				pos = bpi.Index;
				cp = bpi.CharacterPosition;

				SetPosition(pos, cp);

				ActivateKeyInterpreter();
				UpdateCaret();
				Invalidate();
			}
			else if (_recStringView.Contains(p))
			{
				BytePositionInfo bpi = GetStringBytePositionInfo(p);
				pos = bpi.Index;
				cp = bpi.CharacterPosition;

				SetPosition(pos, cp);

				ActivateStringKeyInterpreter();
				UpdateCaret();
				Invalidate();
			}
		}

		BytePositionInfo GetHexBytePositionInfo(Point p)
		{
			System.Diagnostics.Debug.WriteLine("GetHexBytePositionInfo()", "HexBox");

			long bytePos;
			int byteCharaterPos;

			float x = ((float)(p.X - _recHex.X) / _charSize.Width);
			float y = ((float)(p.Y - _recHex.Y) / _charSize.Height);
			int iX = (int)x;
			int iY = (int)y;

			int hPos = (iX / 3 + 1);

			bytePos = Math.Min(_byteProvider.Length,
				_startByte + (_iHexMaxHBytes * (iY + 1) - _iHexMaxHBytes) + hPos - 1);
			byteCharaterPos = (iX % 3);
			if (byteCharaterPos > 1)
				byteCharaterPos = 1;

			if (bytePos == _byteProvider.Length)
				byteCharaterPos = 0;

			if (bytePos < 0)
				return new BytePositionInfo(0, 0);
			return new BytePositionInfo(bytePos, byteCharaterPos);
		}

		BytePositionInfo GetStringBytePositionInfo(Point p)
		{
			System.Diagnostics.Debug.WriteLine("GetStringBytePositionInfo()", "HexBox");

			long bytePos;
			int byteCharacterPos;

			float x = ((float)(p.X - _recStringView.X) / _charSize.Width);
			float y = ((float)(p.Y - _recStringView.Y) / _charSize.Height);
			int iX = (int)x;
			int iY = (int)y;

			int hPos = iX + 1;

			bytePos = Math.Min(_byteProvider.Length,
				_startByte + (_iHexMaxHBytes * (iY + 1) - _iHexMaxHBytes) + hPos - 1);
			byteCharacterPos = 0;

			if (bytePos < 0)
				return new BytePositionInfo(0, 0);
			return new BytePositionInfo(bytePos, byteCharacterPos);
		}
		#endregion

		#region PreProcessMessage methods
		/// <summary>
		/// Preprocesses windows messages.
		/// </summary>
		/// <param name="m">the message to process.</param>
		/// <returns>true, if the message was processed</returns>
		[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true), SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
		public override bool PreProcessMessage(ref Message m)
		{
			switch (m.Msg)
			{
				case NativeMethods.WM_KEYDOWN:
					return _keyInterpreter.PreProcessWmKeyDown(ref m);
				case NativeMethods.WM_CHAR:
					return _keyInterpreter.PreProcessWmChar(ref m);
				case NativeMethods.WM_KEYUP:
					return _keyInterpreter.PreProcessWmKeyUp(ref m);
				default:
					return base.PreProcessMessage(ref m);
			}
		}

		bool BasePreProcessMessage(ref Message m)
		{
			return base.PreProcessMessage(ref m);
		}
		#endregion

		#region Find methods
		/// <summary>
		/// Searches the current ByteProvider
		/// </summary>
		/// <param name="options">contains all find options</param>
		/// <returns>the SelectionStart property value if find was successfull or
		/// -1 if there is no match
		/// -2 if Find was aborted.</returns>
		public long Find(FindOptions options)
		{
			var startIndex = this.SelectionStart + this.SelectionLength;
			int match = 0;

			byte[] buffer1 = null;
			byte[] buffer2 = null;
			if (options.Type == FindType.Text && options.MatchCase)
			{
				if(options.FindBuffer == null || options.FindBuffer.Length == 0)
					throw new ArgumentException("FindBuffer can not be null when Type: Text and MatchCase: false");
				buffer1 = options.FindBuffer;
			}
			else if (options.Type == FindType.Text && !options.MatchCase)
			{
				if(options.FindBufferLowerCase == null || options.FindBufferLowerCase.Length == 0)
					throw new ArgumentException("FindBufferLowerCase can not be null when Type is Text and MatchCase is true");
				if(options.FindBufferUpperCase == null || options.FindBufferUpperCase.Length == 0)
					throw new ArgumentException("FindBufferUpperCase can not be null when Type is Text and MatchCase is true");
				if(options.FindBufferLowerCase.Length != options.FindBufferUpperCase.Length)
					throw new ArgumentException("FindBufferUpperCase and FindBufferUpperCase must have the same size when Type is Text and MatchCase is true");
				buffer1 = options.FindBufferLowerCase;
				buffer2 = options.FindBufferUpperCase;
				
			}
			else if (options.Type == FindType.Hex)
			{
				if(options.Hex == null || options.Hex.Length == 0)
					throw new ArgumentException("Hex can not be null when Type is Hex");
				buffer1 = options.Hex;
			}

			int buffer1Length = buffer1.Length;

			_abortFind = false;

			for (long pos = startIndex; pos < _byteProvider.Length; pos++)
			{
				if (_abortFind)
					return -2;

				if (pos % 1000 == 0) // for performance reasons: DoEvents only 1 times per 1000 loops
					Application.DoEvents();

				byte compareByte = _byteProvider.ReadByte(pos);
				bool buffer1Match = compareByte == buffer1[match];
				bool hasBuffer2 = buffer2 != null;
				bool buffer2Match = hasBuffer2 ? compareByte == buffer2[match] : false;
				bool isMatch = buffer1Match || buffer2Match;
				if (!isMatch)
				{
					pos -= match;
					match = 0;
					_findingPos = pos;
					continue;
				}

				match++;

				if (match == buffer1Length)
				{
					long bytePos = pos - buffer1Length + 1;
					Select(bytePos, buffer1Length);
					ScrollByteIntoView(_bytePos + _selectionLength);
					ScrollByteIntoView(_bytePos);

					return bytePos;
				}
			}

			return -1;
		}

		/// <summary>
		/// Aborts a working Find method.
		/// </summary>
		public void AbortFind()
		{
			_abortFind = true;
		}

		/// <summary>
		/// Gets a value that indicates the current position during Find method execution.
		/// </summary>
		[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public long CurrentFindingPosition
		{
			get
			{
				return _findingPos;
			}
		}
		#endregion

		#region Copy, Cut and Paste methods
		byte[] GetCopyData()
		{
			if (!CanCopy()) return new byte[0];

			// put bytes into buffer
			byte[] buffer = new byte[_selectionLength];
			int id = -1;
			for (long i = _bytePos; i < _bytePos + _selectionLength; i++)
			{
				id++;

				buffer[id] = _byteProvider.ReadByte(i);
			}
			return buffer;
		}
		/// <summary>
		/// Copies the current selection in the hex box to the Clipboard.
		/// </summary>
		public void Copy()
		{
			if (!CanCopy()) return;

			// put bytes into buffer
			byte[] buffer = GetCopyData();

			DataObject da = new DataObject();

			// set string buffer clipbard data
			string sBuffer = System.Text.Encoding.ASCII.GetString(buffer, 0, buffer.Length);
			da.SetData(typeof(string), sBuffer);

			//set memorystream (BinaryData) clipboard data
			System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer, 0, buffer.Length, false, true);
			da.SetData("BinaryData", ms);

			Clipboard.SetDataObject(da, true);
			UpdateCaret();
			ScrollByteIntoView();
			Invalidate();

			OnCopied(EventArgs.Empty);
		}

		/// <summary>
		/// Return true if Copy method could be invoked.
		/// </summary>
		public bool CanCopy()
		{
			if (_selectionLength < 1 || _byteProvider == null)
				return false;

			return true;
		}

		/// <summary>
		/// Moves the current selection in the hex box to the Clipboard.
		/// </summary>
		public void Cut()
		{
			if (!CanCut()) return;

			Copy();

			_byteProvider.DeleteBytes(_bytePos, _selectionLength);
			_byteCharacterPos = 0;
			UpdateCaret();
			ScrollByteIntoView();
			ReleaseSelection();
			Invalidate();
			Refresh();
		}

		/// <summary>
		/// Return true if Cut method could be invoked.
		/// </summary>
		public bool CanCut()
		{
			if (ReadOnly || !this.Enabled)
				return false;
			if (_byteProvider == null)
				return false;
			if (_selectionLength < 1 || !_byteProvider.SupportsDeleteBytes())
				return false;

			return true;
		}

		/// <summary>
		/// Replaces the current selection in the hex box with the contents of the Clipboard.
		/// </summary>
		public void Paste()
		{
			if (!CanPaste()) return;

			if (_selectionLength > 0)
				_byteProvider.DeleteBytes(_bytePos, _selectionLength);

			byte[] buffer = null;
			IDataObject da = Clipboard.GetDataObject();
			if (da.GetDataPresent("BinaryData"))
			{
				System.IO.MemoryStream ms = (System.IO.MemoryStream)da.GetData("BinaryData");
				buffer = new byte[ms.Length];
				ms.Read(buffer, 0, buffer.Length);
			}
			else if (da.GetDataPresent(typeof(string)))
			{
				string sBuffer = (string)da.GetData(typeof(string));
				buffer = System.Text.Encoding.ASCII.GetBytes(sBuffer);
			}
			else
			{
				return;
			}

			_byteProvider.InsertBytes(_bytePos, buffer);

			SetPosition(_bytePos + buffer.Length, 0);

			ReleaseSelection();
			ScrollByteIntoView();
			UpdateCaret();
			Invalidate();
		}

		/// <summary>
		/// Return true if Paste method could be invoked.
		/// </summary>
		public bool CanPaste()
		{
			if (ReadOnly || !this.Enabled) return false;

			if (_byteProvider == null || !_byteProvider.SupportsInsertBytes())
				return false;

			if (!_byteProvider.SupportsDeleteBytes() && _selectionLength > 0)
				return false;

			IDataObject da = Clipboard.GetDataObject();
			if (da.GetDataPresent("BinaryData"))
				return true;
			else if (da.GetDataPresent(typeof(string)))
				return true;
			else
				return false;
		}
		/// <summary>
		/// Return true if PasteHex method could be invoked.
		/// </summary>
		public bool CanPasteHex()
		{
			if (!CanPaste()) return false;

			byte[] buffer = null;
			IDataObject da = Clipboard.GetDataObject();
			if (da.GetDataPresent(typeof(string)))
			{
				string hexString = (string)da.GetData(typeof(string));
				buffer = ConvertHexToBytes(hexString);
				return (buffer != null);
			}
			return false;
		}

		/// <summary>
		/// Replaces the current selection in the hex box with the hex string data of the Clipboard.
		/// </summary>
		public void PasteHex()
		{
			if (!CanPaste()) return;

			byte[] buffer = null;
			IDataObject da = Clipboard.GetDataObject();
			if (da.GetDataPresent(typeof(string)))
			{
				string hexString = (string)da.GetData(typeof(string));
				buffer = ConvertHexToBytes(hexString);
				if (buffer == null)
					return;
			}
			else
			{
				return;
			}

			if (_selectionLength > 0)
				_byteProvider.DeleteBytes(_bytePos, _selectionLength);

			_byteProvider.InsertBytes(_bytePos, buffer);

			SetPosition(_bytePos + buffer.Length, 0);

			ReleaseSelection();
			ScrollByteIntoView();
			UpdateCaret();
			Invalidate();
		}

		/// <summary>
		/// Copies the current selection in the hex box to the Clipboard in hex format.
		/// </summary>
		public void CopyHex()
		{
			if (!CanCopy()) return;

			// put bytes into buffer
			byte[] buffer = GetCopyData();

			DataObject da = new DataObject();

			// set string buffer clipbard data
			string hexString = ConvertBytesToHex(buffer); ;
			da.SetData(typeof(string), hexString);

			//set memorystream (BinaryData) clipboard data
			System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer, 0, buffer.Length, false, true);
			da.SetData("BinaryData", ms);

			Clipboard.SetDataObject(da, true);
			UpdateCaret();
			ScrollByteIntoView();
			Invalidate();

			OnCopiedHex(EventArgs.Empty);
		}


		#endregion

		#region Paint methods
		/// <summary>
		/// Paints the background.
		/// </summary>
		/// <param name="e">A PaintEventArgs that contains the event data.</param>
		protected override void OnPaintBackground(PaintEventArgs e)
		{
			switch (_borderStyle)
			{
				case BorderStyle.Fixed3D:
					{
						if (TextBoxRenderer.IsSupported)
						{
							VisualStyleElement state = VisualStyleElement.TextBox.TextEdit.Normal;
							Color backColor = this.BackColor;

							if (this.Enabled)
							{
								if (this.ReadOnly)
									state = VisualStyleElement.TextBox.TextEdit.ReadOnly;
								else if (this.Focused)
									state = VisualStyleElement.TextBox.TextEdit.Focused;
							}
							else
							{
								state = VisualStyleElement.TextBox.TextEdit.Disabled;
								backColor = this.BackColorDisabled;
							}

							VisualStyleRenderer vsr = new VisualStyleRenderer(state);
							vsr.DrawBackground(e.Graphics, this.ClientRectangle);

							Rectangle rectContent = vsr.GetBackgroundContentRectangle(e.Graphics, this.ClientRectangle);
							e.Graphics.FillRectangle(new SolidBrush(backColor), rectContent);
						}
						else
						{
							// draw background
							e.Graphics.FillRectangle(new SolidBrush(BackColor), ClientRectangle);

							// draw default border
							ControlPaint.DrawBorder3D(e.Graphics, ClientRectangle, Border3DStyle.Sunken);
						}

						break;
					}
				case BorderStyle.FixedSingle:
					{
						// draw background
						e.Graphics.FillRectangle(new SolidBrush(BackColor), ClientRectangle);

						// draw fixed single border
						ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Color.Black, ButtonBorderStyle.Solid);
						break;
					}
				default:
					{
						// draw background
						e.Graphics.FillRectangle(new SolidBrush(BackColor), ClientRectangle);
						break;
					}
			}
		}


		/// <summary>
		/// Paints the hex box.
		/// </summary>
		/// <param name="e">A PaintEventArgs that contains the event data.</param>
		protected override void OnPaint(PaintEventArgs e)
		{
			base.OnPaint(e);

			if (_byteProvider == null)
				return;

			System.Diagnostics.Debug.WriteLine("OnPaint " + DateTime.Now.ToString(), "HexBox");

			// draw only in the content rectangle, so exclude the border and the scrollbar.
			Region r = new Region(ClientRectangle);
			r.Exclude(_recContent);
			e.Graphics.ExcludeClip(r);

			UpdateVisibilityBytes();


			if (_lineInfoVisible)
				PaintLineInfo(e.Graphics, _startByte, _endByte);

			if (!_stringViewVisible)
			{
				PaintHex(e.Graphics, _startByte, _endByte);
			}
			else
			{
				PaintHexAndStringView(e.Graphics, _startByte, _endByte);
				if (_shadowSelectionVisible)
					PaintCurrentBytesSign(e.Graphics);
			}
			if (_columnInfoVisible)
				PaintHeaderRow(e.Graphics);
			if (_groupSeparatorVisible)
				PaintColumnSeparator(e.Graphics);
		}


		void PaintLineInfo(Graphics g, long startByte, long endByte)
		{
			// Ensure endByte isn't > length of array.
			endByte = Math.Min(_byteProvider.Length - 1, endByte);

			Color lineInfoColor = (this.InfoForeColor != Color.Empty) ? this.InfoForeColor : this.ForeColor;
			Brush brush = new SolidBrush(lineInfoColor);

			int maxLine = GetGridBytePoint(endByte - startByte).Y + 1;

			for (int i = 0; i < maxLine; i++)
			{
				long firstLineByte = (startByte + (_iHexMaxHBytes) * i) + _lineInfoOffset;

				PointF bytePointF = GetBytePointF(new Point(0, 0 + i));
				string info = firstLineByte.ToString(_hexStringFormat, System.Threading.Thread.CurrentThread.CurrentCulture);
				int nulls = 8 - info.Length;
				string formattedInfo;
				if (nulls > -1)
				{
					formattedInfo = new string('0', 8 - info.Length) + info;
				}
				else
				{
					formattedInfo = new string('~', 8);
				}

				g.DrawString(formattedInfo, Font, brush, new PointF(_recLineInfo.X, bytePointF.Y), _stringFormat);
			}
		}

		void PaintHeaderRow(Graphics g)
		{
			Brush brush = new SolidBrush(this.InfoForeColor);
			for (int col = 0; col < _iHexMaxHBytes; col++)
			{
				PaintColumnInfo(g, (byte)col, brush, col);
			}
		}

		void PaintColumnSeparator(Graphics g)
		{
			for (int col = GroupSize; col < _iHexMaxHBytes; col += GroupSize)
			{
				var pen = new Pen(new SolidBrush(this.InfoForeColor), 1);
				PointF headerPointF = GetColumnInfoPointF(col);
				headerPointF.X -= _charSize.Width / 2;
				g.DrawLine(pen, headerPointF, new PointF(headerPointF.X, headerPointF.Y + _recColumnInfo.Height + _recHex.Height));
				if (StringViewVisible)
				{
					PointF byteStringPointF = GetByteStringPointF(new Point(col, 0));
					headerPointF.X -= 2;
					g.DrawLine(pen, new PointF(byteStringPointF.X, byteStringPointF.Y), new PointF(byteStringPointF.X, byteStringPointF.Y + _recHex.Height));
				}
			}
		}

		void PaintHex(Graphics g, long startByte, long endByte)
		{
			Brush brush = new SolidBrush(GetDefaultForeColor());
			Brush selBrush = new SolidBrush(_selectionForeColor);
			Brush selBrushBack = new SolidBrush(_selectionBackColor);

			int counter = -1;
			long intern_endByte = Math.Min(_byteProvider.Length - 1, endByte + _iHexMaxHBytes);

			bool isKeyInterpreterActive = _keyInterpreter == null || _keyInterpreter.GetType() == typeof(KeyInterpreter);

			for (long i = startByte; i < intern_endByte + 1; i++)
			{
				counter++;
				Point gridPoint = GetGridBytePoint(counter);
				byte b = _byteProvider.ReadByte(i);

				bool isSelectedByte = i >= _bytePos && i <= (_bytePos + _selectionLength - 1) && _selectionLength != 0;

				if (isSelectedByte && isKeyInterpreterActive)
				{
					PaintHexStringSelected(g, b, selBrush, selBrushBack, gridPoint);
				}
				else
				{
					PaintHexString(g, b, brush, gridPoint);
				}
			}
		}

		void PaintHexString(Graphics g, byte b, Brush brush, Point gridPoint)
		{
			PointF bytePointF = GetBytePointF(gridPoint);

			string sB = ConvertByteToHex(b);

			g.DrawString(sB.Substring(0, 1), Font, brush, bytePointF, _stringFormat);
			bytePointF.X += _charSize.Width;
			g.DrawString(sB.Substring(1, 1), Font, brush, bytePointF, _stringFormat);
		}

		void PaintColumnInfo(Graphics g, byte b, Brush brush, int col)
		{
			PointF headerPointF = GetColumnInfoPointF(col);

			string sB = ConvertByteToHex(b);

			g.DrawString(sB.Substring(0, 1), Font, brush, headerPointF, _stringFormat);
			headerPointF.X += _charSize.Width;
			g.DrawString(sB.Substring(1, 1), Font, brush, headerPointF, _stringFormat);
		}

		void PaintHexStringSelected(Graphics g, byte b, Brush brush, Brush brushBack, Point gridPoint)
		{
			string sB = b.ToString(_hexStringFormat, System.Threading.Thread.CurrentThread.CurrentCulture);
			if (sB.Length == 1)
				sB = "0" + sB;

			PointF bytePointF = GetBytePointF(gridPoint);

			bool isLastLineChar = (gridPoint.X + 1 == _iHexMaxHBytes);
			float bcWidth = (isLastLineChar) ? _charSize.Width * 2 : _charSize.Width * 3;

			g.FillRectangle(brushBack, bytePointF.X, bytePointF.Y, bcWidth, _charSize.Height);
			g.DrawString(sB.Substring(0, 1), Font, brush, bytePointF, _stringFormat);
			bytePointF.X += _charSize.Width;
			g.DrawString(sB.Substring(1, 1), Font, brush, bytePointF, _stringFormat);
		}

		void PaintHexAndStringView(Graphics g, long startByte, long endByte)
		{
			Brush brush = new SolidBrush(GetDefaultForeColor());
			Brush selBrush = new SolidBrush(_selectionForeColor);
			Brush selBrushBack = new SolidBrush(_selectionBackColor);

			int counter = -1;
			long intern_endByte = Math.Min(_byteProvider.Length - 1, endByte + _iHexMaxHBytes);

			bool isKeyInterpreterActive = _keyInterpreter == null || _keyInterpreter.GetType() == typeof(KeyInterpreter);
			bool isStringKeyInterpreterActive = _keyInterpreter != null && _keyInterpreter.GetType() == typeof(StringKeyInterpreter);

			for (long i = startByte; i < intern_endByte + 1; i++)
			{
				counter++;
				Point gridPoint = GetGridBytePoint(counter);
				PointF byteStringPointF = GetByteStringPointF(gridPoint);
				byte b = _byteProvider.ReadByte(i);

				bool isSelectedByte = i >= _bytePos && i <= (_bytePos + _selectionLength - 1) && _selectionLength != 0;

				if (isSelectedByte && isKeyInterpreterActive)
				{
					PaintHexStringSelected(g, b, selBrush, selBrushBack, gridPoint);
				}
				else
				{
					PaintHexString(g, b, brush, gridPoint);
				}

				string s = new String(ByteCharConverter.ToChar(b), 1);

				if (isSelectedByte && isStringKeyInterpreterActive)
				{
					g.FillRectangle(selBrushBack, byteStringPointF.X, byteStringPointF.Y, _charSize.Width, _charSize.Height);
					g.DrawString(s, Font, selBrush, byteStringPointF, _stringFormat);
				}
				else
				{
					g.DrawString(s, Font, brush, byteStringPointF, _stringFormat);
				}
			}
		}

		void PaintCurrentBytesSign(Graphics g)
		{
			if (_keyInterpreter != null && _bytePos != -1 && Enabled)
			{
				if (_keyInterpreter.GetType() == typeof(KeyInterpreter))
				{
					if (_selectionLength == 0)
					{
						Point gp = GetGridBytePoint(_bytePos - _startByte);
						PointF pf = GetByteStringPointF(gp);
						Size s = new Size((int)_charSize.Width, (int)_charSize.Height);
						Rectangle r = new Rectangle((int)pf.X, (int)pf.Y, s.Width, s.Height);
						if (r.IntersectsWith(_recStringView))
						{
							r.Intersect(_recStringView);
							PaintCurrentByteSign(g, r);
						}
					}
					else
					{
						int lineWidth = (int)(_recStringView.Width - _charSize.Width);

						Point startSelGridPoint = GetGridBytePoint(_bytePos - _startByte);
						PointF startSelPointF = GetByteStringPointF(startSelGridPoint);

						Point endSelGridPoint = GetGridBytePoint(_bytePos - _startByte + _selectionLength - 1);
						PointF endSelPointF = GetByteStringPointF(endSelGridPoint);

						int multiLine = endSelGridPoint.Y - startSelGridPoint.Y;
						if (multiLine == 0)
						{
							
							Rectangle singleLine = new Rectangle(
								(int)startSelPointF.X,
								(int)startSelPointF.Y,
								(int)(endSelPointF.X - startSelPointF.X + _charSize.Width),
								(int)_charSize.Height);
							if (singleLine.IntersectsWith(_recStringView))
							{
								singleLine.Intersect(_recStringView);
								PaintCurrentByteSign(g, singleLine);
							}
						}
						else
						{
							Rectangle firstLine = new Rectangle(
								(int)startSelPointF.X,
								(int)startSelPointF.Y,
								(int)(_recStringView.X + lineWidth - startSelPointF.X + _charSize.Width),
								(int)_charSize.Height);
							if (firstLine.IntersectsWith(_recStringView))
							{
								firstLine.Intersect(_recStringView);
								PaintCurrentByteSign(g, firstLine);
							}

							if (multiLine > 1)
							{
								Rectangle betweenLines = new Rectangle(
									_recStringView.X,
									(int)(startSelPointF.Y + _charSize.Height),
									(int)(_recStringView.Width),
									(int)(_charSize.Height * (multiLine - 1)));
								if (betweenLines.IntersectsWith(_recStringView))
								{
									betweenLines.Intersect(_recStringView);
									PaintCurrentByteSign(g, betweenLines);
								}

							}

							Rectangle lastLine = new Rectangle(
								_recStringView.X,
								(int)endSelPointF.Y,
								(int)(endSelPointF.X - _recStringView.X + _charSize.Width),
								(int)_charSize.Height);
							if (lastLine.IntersectsWith(_recStringView))
							{
								lastLine.Intersect(_recStringView);
								PaintCurrentByteSign(g, lastLine);
							}
						}
					}
				}
				else
				{
					if (_selectionLength == 0)
					{
						Point gp = GetGridBytePoint(_bytePos - _startByte);
						PointF pf = GetBytePointF(gp);
						Size s = new Size((int)_charSize.Width * 2, (int)_charSize.Height);
						Rectangle r = new Rectangle((int)pf.X, (int)pf.Y, s.Width, s.Height);
						PaintCurrentByteSign(g, r);
					}
					else
					{
						int lineWidth = (int)(_recHex.Width - _charSize.Width * 5);

						Point startSelGridPoint = GetGridBytePoint(_bytePos - _startByte);
						PointF startSelPointF = GetBytePointF(startSelGridPoint);

						Point endSelGridPoint = GetGridBytePoint(_bytePos - _startByte + _selectionLength - 1);
						PointF endSelPointF = GetBytePointF(endSelGridPoint);

						int multiLine = endSelGridPoint.Y - startSelGridPoint.Y;
						if (multiLine == 0)
						{
							Rectangle singleLine = new Rectangle(
								(int)startSelPointF.X,
								(int)startSelPointF.Y,
								(int)(endSelPointF.X - startSelPointF.X + _charSize.Width * 2),
								(int)_charSize.Height);
							if (singleLine.IntersectsWith(_recHex))
							{
								singleLine.Intersect(_recHex);
								PaintCurrentByteSign(g, singleLine);
							}
						}
						else
						{
							Rectangle firstLine = new Rectangle(
								(int)startSelPointF.X,
								(int)startSelPointF.Y,
								(int)(_recHex.X + lineWidth - startSelPointF.X + _charSize.Width * 2),
								(int)_charSize.Height);
							if (firstLine.IntersectsWith(_recHex))
							{
								firstLine.Intersect(_recHex);
								PaintCurrentByteSign(g, firstLine);
							}

							if (multiLine > 1)
							{
								Rectangle betweenLines = new Rectangle(
									_recHex.X,
									(int)(startSelPointF.Y + _charSize.Height),
									(int)(lineWidth + _charSize.Width * 2),
									(int)(_charSize.Height * (multiLine - 1)));
								if (betweenLines.IntersectsWith(_recHex))
								{
									betweenLines.Intersect(_recHex);
									PaintCurrentByteSign(g, betweenLines);
								}

							}

							Rectangle lastLine = new Rectangle(
								_recHex.X,
								(int)endSelPointF.Y,
								(int)(endSelPointF.X - _recHex.X + _charSize.Width * 2),
								(int)_charSize.Height);
							if (lastLine.IntersectsWith(_recHex))
							{
								lastLine.Intersect(_recHex);
								PaintCurrentByteSign(g, lastLine);
							}
						}
					}
				}
			}
		}

		void PaintCurrentByteSign(Graphics g, Rectangle rec)
		{
			// stack overflowexception on big files - workaround
			if (rec.Top < 0 || rec.Left < 0 || rec.Width <= 0 || rec.Height <= 0)
				return;

			Bitmap myBitmap = new Bitmap(rec.Width, rec.Height);
			Graphics bitmapGraphics = Graphics.FromImage(myBitmap);

			SolidBrush greenBrush = new SolidBrush(_shadowSelectionColor);

			bitmapGraphics.FillRectangle(greenBrush, 0,
				0, rec.Width, rec.Height);

			g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.GammaCorrected;

			g.DrawImage(myBitmap, rec.Left, rec.Top);
		}

		Color GetDefaultForeColor()
		{
			if (Enabled)
				return ForeColor;
			else
				return Color.Gray;
		}
		void UpdateVisibilityBytes()
		{
			if (_byteProvider == null || _byteProvider.Length == 0)
				return;

			_startByte = (_scrollVpos + 1) * _iHexMaxHBytes - _iHexMaxHBytes;
			_endByte = (long)Math.Min(_byteProvider.Length - 1, _startByte + _iHexMaxBytes);
		}
		#endregion

		#region Positioning methods
		void UpdateRectanglePositioning()
		{
			// calc char size
			SizeF charSize = this.CreateGraphics().MeasureString("A", Font, 100, _stringFormat);
			_charSize = new SizeF((float)Math.Ceiling(charSize.Width), (float)Math.Ceiling(charSize.Height));

			// calc content bounds
			_recContent = ClientRectangle;
			_recContent.X += _recBorderLeft;
			_recContent.Y += _recBorderTop;
			_recContent.Width -= _recBorderRight + _recBorderLeft;
			_recContent.Height -= _recBorderBottom + _recBorderTop;

			if (_vScrollBarVisible)
			{
				_recContent.Width -= _vScrollBar.Width;
				_vScrollBar.Left = _recContent.X + _recContent.Width;
				_vScrollBar.Top = _recContent.Y;
				_vScrollBar.Height = _recContent.Height;
			}

			int marginLeft = 4;

			// calc line info bounds
			if (_lineInfoVisible)
			{
				_recLineInfo = new Rectangle(_recContent.X + marginLeft,
					_recContent.Y,
					(int)(_charSize.Width * 10),
					_recContent.Height);
			}
			else
			{
				_recLineInfo = Rectangle.Empty;
				_recLineInfo.X = marginLeft;
			}

			// calc line info bounds
			_recColumnInfo = new Rectangle(_recLineInfo.X + _recLineInfo.Width, _recContent.Y, _recContent.Width - _recLineInfo.Width, (int)charSize.Height + 4);
			if (_columnInfoVisible)
			{
				_recLineInfo.Y += (int)charSize.Height + 4;
				_recLineInfo.Height -= (int)charSize.Height + 4;
			}
			else
			{
				_recColumnInfo.Height = 0;
			}

			// calc hex bounds and grid
			_recHex = new Rectangle(_recLineInfo.X + _recLineInfo.Width,
				_recLineInfo.Y,
				_recContent.Width - _recLineInfo.Width,
				_recContent.Height - _recColumnInfo.Height);

			if (UseFixedBytesPerLine)
			{
				SetHorizontalByteCount(_bytesPerLine);
				_recHex.Width = (int)Math.Floor(((double)_iHexMaxHBytes) * _charSize.Width * 3 + (2 * _charSize.Width));
			}
			else
			{
				int hmax = (int)Math.Floor((double)_recHex.Width / (double)_charSize.Width);
				if (_stringViewVisible)
				{
					hmax -= 2;
					if (hmax > 1)
						SetHorizontalByteCount((int)Math.Floor((double)hmax / 4));
					else
						SetHorizontalByteCount(1);
				}
				else
				{
					if (hmax > 1)
						SetHorizontalByteCount((int)Math.Floor((double)hmax / 3));
					else
						SetHorizontalByteCount(1);
				}
				_recHex.Width = (int)Math.Floor(((double)_iHexMaxHBytes) * _charSize.Width * 3 + (2 * _charSize.Width));
			}

			if (_stringViewVisible)
			{
				_recStringView = new Rectangle(_recHex.X + _recHex.Width,
					_recHex.Y,
					(int)(_charSize.Width * _iHexMaxHBytes),
					_recHex.Height);
			}
			else
			{
				_recStringView = Rectangle.Empty;
			}

			int vmax = (int)Math.Floor((double)_recHex.Height / (double)_charSize.Height);
			SetVerticalByteCount(vmax);

			_iHexMaxBytes = _iHexMaxHBytes * _iHexMaxVBytes;

			UpdateScrollSize();
		}

		PointF GetBytePointF(long byteIndex)
		{
			Point gp = GetGridBytePoint(byteIndex);

			return GetBytePointF(gp);
		}

		PointF GetBytePointF(Point gp)
		{
			float x = (3 * _charSize.Width) * gp.X + _recHex.X;
			float y = (gp.Y + 1) * _charSize.Height - _charSize.Height + _recHex.Y;

			return new PointF(x, y);
		}
		PointF GetColumnInfoPointF(int col)
		{
			Point gp = GetGridBytePoint(col);
			float x = (3 * _charSize.Width) * gp.X + _recColumnInfo.X;
			float y = _recColumnInfo.Y;

			return new PointF(x, y);
		}

		PointF GetByteStringPointF(Point gp)
		{
			float x = (_charSize.Width) * gp.X + _recStringView.X;
			float y = (gp.Y + 1) * _charSize.Height - _charSize.Height + _recStringView.Y;

			return new PointF(x, y);
		}

		Point GetGridBytePoint(long byteIndex)
		{
			int row = (int)Math.Floor((double)byteIndex / (double)_iHexMaxHBytes);
			int column = (int)(byteIndex + _iHexMaxHBytes - _iHexMaxHBytes * (row + 1));

			Point res = new Point(column, row);
			return res;
		}
		#endregion

		#region Overridden properties
		/// <summary>
		/// Gets or sets the background color for the control.
		/// </summary>
		[DefaultValue(typeof(Color), "White")]
		public override Color BackColor
		{
			get
			{
				return base.BackColor;
			}
			set
			{
				base.BackColor = value;
			}
		}

		/// <summary>
		/// The font used to display text in the hexbox.
		/// </summary>
		public override Font Font
		{
			get
			{
				return base.Font;
			}
			set
			{
                if (value == null)
                    return;
                
				base.Font = value;
			}
		}

		/// <summary>
		/// Not used.
		/// </summary>
		[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)]
		public override string Text
		{
			get
			{
				return base.Text;
			}
			set
			{
				base.Text = value;
			}
		}

		/// <summary>
		/// Not used.
		/// </summary>
		[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), EditorBrowsable(EditorBrowsableState.Never), Bindable(false)]
		public override RightToLeft RightToLeft
		{
			get
			{
				return base.RightToLeft;
			}
			set
			{
				base.RightToLeft = value;
			}
		}
		#endregion

		#region Properties
		/// <summary>
		/// Gets or sets the background color for the disabled control.
		/// </summary>
		[Category("Appearance"), DefaultValue(typeof(Color), "WhiteSmoke")]
		public Color BackColorDisabled
		{
			get
			{
				return _backColorDisabled;
			}
			set
			{
				_backColorDisabled = value;
			}
		} Color _backColorDisabled = Color.FromName("WhiteSmoke");

		/// <summary>
		/// Gets or sets if the count of bytes in one line is fix.
		/// </summary>
		/// <remarks>
		/// When set to True, BytesPerLine property determine the maximum count of bytes in one line.
		/// </remarks>
		[DefaultValue(false), Category("Hex"), Description("Gets or sets if the count of bytes in one line is fix.")]
		public bool ReadOnly
		{
			get { return _readOnly; }
			set
			{
				if (_readOnly == value)
					return;

				_readOnly = value;
				OnReadOnlyChanged(EventArgs.Empty);
				Invalidate();
			}
		} bool _readOnly;

		/// <summary>
		/// Gets or sets the maximum count of bytes in one line.
		/// </summary>
		/// <remarks>
		/// UseFixedBytesPerLine property no longer has to be set to true for this to work
		/// </remarks>
		[DefaultValue(16), Category("Hex"), Description("Gets or sets the maximum count of bytes in one line.")]
		public int BytesPerLine
		{
			get { return _bytesPerLine; }
			set
			{
				if (_bytesPerLine == value)
					return;

				_bytesPerLine = value;
				OnBytesPerLineChanged(EventArgs.Empty);

				UpdateRectanglePositioning();
				Invalidate();
			}
		} int _bytesPerLine = 16;

		/// <summary>
		/// Gets or sets the number of bytes in a group. Used to show the group separator line (if GroupSeparatorVisible is true)
		/// </summary>
		/// <remarks>
		/// GroupSeparatorVisible property must set to true
		/// </remarks>
		[DefaultValue(4), Category("Hex"), Description("Gets or sets the byte-count between group separators (if visible).")]
		public int GroupSize
		{
			get { return _groupSize; }
			set
			{
				if (_groupSize == value)
					return;

				_groupSize = value;
				OnGroupSizeChanged(EventArgs.Empty);

				UpdateRectanglePositioning();
				Invalidate();
			}
		} int _groupSize = 4;
		/// <summary>
		/// Gets or sets if the count of bytes in one line is fix.
		/// </summary>
		/// <remarks>
		/// When set to True, BytesPerLine property determine the maximum count of bytes in one line.
		/// </remarks>
		[DefaultValue(false), Category("Hex"), Description("Gets or sets if the count of bytes in one line is fix.")]
		public bool UseFixedBytesPerLine
		{
			get { return _useFixedBytesPerLine; }
			set
			{
				if (_useFixedBytesPerLine == value)
					return;

				_useFixedBytesPerLine = value;
				OnUseFixedBytesPerLineChanged(EventArgs.Empty);

				UpdateRectanglePositioning();
				Invalidate();
			}
		} bool _useFixedBytesPerLine;

		/// <summary>
		/// Gets or sets the visibility of a vertical scroll bar.
		/// </summary>
		[DefaultValue(false), Category("Hex"), Description("Gets or sets the visibility of a vertical scroll bar.")]
		public bool VScrollBarVisible
		{
			get { return this._vScrollBarVisible; }
			set
			{
				if (_vScrollBarVisible == value)
					return;

				_vScrollBarVisible = value;

				if (_vScrollBarVisible)
					Controls.Add(_vScrollBar);
				else
					Controls.Remove(_vScrollBar);

				UpdateRectanglePositioning();
				UpdateScrollSize();

				OnVScrollBarVisibleChanged(EventArgs.Empty);
			}
		} bool _vScrollBarVisible;

		/// <summary>
		/// Gets or sets the ByteProvider.
		/// </summary>
		[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public IByteProvider ByteProvider
		{
			get { return _byteProvider; }
			set
			{
				if (_byteProvider == value)
					return;

				if (value == null)
					ActivateEmptyKeyInterpreter();
				else
					ActivateKeyInterpreter();

				if (_byteProvider != null)
					_byteProvider.LengthChanged -= new EventHandler(_byteProvider_LengthChanged);

				_byteProvider = value;
				if (_byteProvider != null)
					_byteProvider.LengthChanged += new EventHandler(_byteProvider_LengthChanged);

				OnByteProviderChanged(EventArgs.Empty);

				if (value == null) // do not raise events if value is null
				{
					_bytePos = -1;
					_byteCharacterPos = 0;
					_selectionLength = 0;

					DestroyCaret();
				}
				else
				{
					SetPosition(0, 0);
					SetSelectionLength(0);

					if (_caretVisible && Focused)
						UpdateCaret();
					else
						CreateCaret();
				}

				CheckCurrentLineChanged();
				CheckCurrentPositionInLineChanged();

				_scrollVpos = 0;

				UpdateVisibilityBytes();
				UpdateRectanglePositioning();

				Invalidate();
			}
		}

		IByteProvider _byteProvider;
		/// <summary>
		/// Gets or sets the visibility of the group separator.
		/// </summary>
		[DefaultValue(false), Category("Hex"), Description("Gets or sets the visibility of a separator vertical line.")]
		public bool GroupSeparatorVisible
		{
			get { return _groupSeparatorVisible; }
			set
			{
				if (_groupSeparatorVisible == value)
					return;

				_groupSeparatorVisible = value;
				OnGroupSeparatorVisibleChanged(EventArgs.Empty);

				UpdateRectanglePositioning();
				Invalidate();
			}
		} bool _groupSeparatorVisible = false;

		/// <summary>
		/// Gets or sets the visibility of the column info
		/// </summary>
		[DefaultValue(false), Category("Hex"), Description("Gets or sets the visibility of header row.")]
		public bool ColumnInfoVisible
		{
			get { return _columnInfoVisible; }
			set
			{
				if (_columnInfoVisible == value)
					return;

				_columnInfoVisible = value;
				OnColumnInfoVisibleChanged(EventArgs.Empty);

				UpdateRectanglePositioning();
				Invalidate();
			}
		} bool _columnInfoVisible = false;

		/// <summary>
		/// Gets or sets the visibility of a line info.
		/// </summary>
		[DefaultValue(false), Category("Hex"), Description("Gets or sets the visibility of a line info.")]
		public bool LineInfoVisible
		{
			get { return _lineInfoVisible; }
			set
			{
				if (_lineInfoVisible == value)
					return;

				_lineInfoVisible = value;
				OnLineInfoVisibleChanged(EventArgs.Empty);

				UpdateRectanglePositioning();
				Invalidate();
			}
		} bool _lineInfoVisible = false;

		/// <summary>
		/// Gets or sets the offset of a line info.
		/// </summary>
		[DefaultValue((long)0), Category("Hex"), Description("Gets or sets the offset of the line info.")]
		public long LineInfoOffset
		{
			get { return _lineInfoOffset; }
			set
			{
				if (_lineInfoOffset == value)
					return;

				_lineInfoOffset = value;

				Invalidate();
			}
		} long _lineInfoOffset = 0;

		/// <summary>
		/// Gets or sets the hex box�s border style.
		/// </summary>
		[DefaultValue(typeof(BorderStyle), "Fixed3D"), Category("Hex"), Description("Gets or sets the hex box�s border style.")]
		public BorderStyle BorderStyle
		{
			get { return _borderStyle; }
			set
			{
				if (_borderStyle == value)
					return;

				_borderStyle = value;
				switch (_borderStyle)
				{
					case BorderStyle.None:
						_recBorderLeft = _recBorderTop = _recBorderRight = _recBorderBottom = 0;
						break;
					case BorderStyle.Fixed3D:
						_recBorderLeft = _recBorderRight = SystemInformation.Border3DSize.Width;
						_recBorderTop = _recBorderBottom = SystemInformation.Border3DSize.Height;
						break;
					case BorderStyle.FixedSingle:
						_recBorderLeft = _recBorderTop = _recBorderRight = _recBorderBottom = 1;
						break;
				}

				UpdateRectanglePositioning();

				OnBorderStyleChanged(EventArgs.Empty);

			}
		} BorderStyle _borderStyle = BorderStyle.Fixed3D;

		/// <summary>
		/// Gets or sets the visibility of the string view.
		/// </summary>
		[DefaultValue(false), Category("Hex"), Description("Gets or sets the visibility of the string view.")]
		public bool StringViewVisible
		{
			get { return _stringViewVisible; }
			set
			{
				if (_stringViewVisible == value)
					return;

				_stringViewVisible = value;
				OnStringViewVisibleChanged(EventArgs.Empty);

				UpdateRectanglePositioning();
				Invalidate();
			}
		} bool _stringViewVisible;

		/// <summary>
		/// Gets or sets whether the HexBox control displays the hex characters in upper or lower case.
		/// </summary>
		[DefaultValue(typeof(HexCasing), "Upper"), Category("Hex"), Description("Gets or sets whether the HexBox control displays the hex characters in upper or lower case.")]
		public HexCasing HexCasing
		{
			get
			{
				if (_hexStringFormat == "X")
					return HexCasing.Upper;
				else
					return HexCasing.Lower;
			}
			set
			{
				string format;
				if (value == HexCasing.Upper)
					format = "X";
				else
					format = "x";

				if (_hexStringFormat == format)
					return;

				_hexStringFormat = format;
				OnHexCasingChanged(EventArgs.Empty);

				Invalidate();
			}
		}

		/// <summary>
		/// Gets and sets the starting point of the bytes selected in the hex box.
		/// </summary>
		[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public long SelectionStart
		{
			get { return _bytePos; }
			set
			{
				SetPosition(value, 0);
				ScrollByteIntoView();
				Invalidate();
			}
		}

		/// <summary>
		/// Gets and sets the number of bytes selected in the hex box.
		/// </summary>
		[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public long SelectionLength
		{
			get { return _selectionLength; }
			set
			{
				SetSelectionLength(value);
				ScrollByteIntoView();
				Invalidate();
			}
		} long _selectionLength;


		/// <summary>
		/// Gets or sets the info color used for column info and line info. When this property is null, then ForeColor property is used.
		/// </summary>
		[DefaultValue(typeof(Color), "Empty"), Category("Hex"), Description("Gets or sets the line info color. When this property is null, then ForeColor property is used.")]
		public Color InfoForeColor
		{
			get { return _infoForeColor; }
			set { _infoForeColor = value; Invalidate(); }
		} Color _infoForeColor = Color.Empty;

		/// <summary>
		/// Gets or sets the background color for the selected bytes.
		/// </summary>
		[DefaultValue(typeof(Color), "Blue"), Category("Hex"), Description("Gets or sets the background color for the selected bytes.")]
		public Color SelectionBackColor
		{
			get { return _selectionBackColor; }
			set { _selectionBackColor = value; Invalidate(); }
		} Color _selectionBackColor = Color.Blue;

		/// <summary>
		/// Gets or sets the foreground color for the selected bytes.
		/// </summary>
		[DefaultValue(typeof(Color), "White"), Category("Hex"), Description("Gets or sets the foreground color for the selected bytes.")]
		public Color SelectionForeColor
		{
			get { return _selectionForeColor; }
			set { _selectionForeColor = value; Invalidate(); }
		} Color _selectionForeColor = Color.White;

		/// <summary>
		/// Gets or sets the visibility of a shadow selection.
		/// </summary>
		[DefaultValue(true), Category("Hex"), Description("Gets or sets the visibility of a shadow selection.")]
		public bool ShadowSelectionVisible
		{
			get { return _shadowSelectionVisible; }
			set
			{
				if (_shadowSelectionVisible == value)
					return;
				_shadowSelectionVisible = value;
				Invalidate();
			}
		} bool _shadowSelectionVisible = true;

		/// <summary>
		/// Gets or sets the color of the shadow selection. 
		/// </summary>
		/// <remarks>
		/// A alpha component must be given! 
		/// Default alpha = 100
		/// </remarks>
		[Category("Hex"), Description("Gets or sets the color of the shadow selection.")]
		public Color ShadowSelectionColor
		{
			get { return _shadowSelectionColor; }
			set { _shadowSelectionColor = value; Invalidate(); }
		} Color _shadowSelectionColor = Color.FromArgb(100, 60, 188, 255);

		/// <summary>
		/// Gets the number bytes drawn horizontally.
		/// </summary>
		[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public int HorizontalByteCount
		{
			get { return _iHexMaxHBytes; }
		}

		/// <summary>
		/// Gets the number bytes drawn vertically.
		/// </summary>
		[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public int VerticalByteCount
		{
			get { return _iHexMaxVBytes; }
		}

		/// <summary>
		/// Gets the current line
		/// </summary>
		[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public long CurrentLine
		{
			get { return _currentLine; }
		} long _currentLine;

		/// <summary>
		/// Gets the current position in the current line
		/// </summary>
		[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public long CurrentPositionInLine
		{
			get { return _currentPositionInLine; }
		} int _currentPositionInLine;

		/// <summary>
		/// Gets the a value if insertion mode is active or not.
		/// </summary>
		[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public bool InsertActive
		{
			get { return _insertActive; }
			set
			{
				if (_insertActive == value)
					return;

				_insertActive = value;

				// recreate caret
				DestroyCaret();
				CreateCaret();

				// raise change event
				OnInsertActiveChanged(EventArgs.Empty);
			}
		}

		/// <summary>
		/// Gets or sets the built-in context menu.
		/// </summary>
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
		public BuiltInContextMenu BuiltInContextMenu
		{
			get { return _builtInContextMenu; }
		} BuiltInContextMenu _builtInContextMenu;


		/// <summary>
		/// Gets or sets the converter that will translate between byte and character values.
		/// </summary>
		[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public IByteCharConverter ByteCharConverter
		{
			get
			{
				if (_byteCharConverter == null)
					_byteCharConverter = new DefaultByteCharConverter();
				return _byteCharConverter;
			}
			set
			{
				if (value != null && value != _byteCharConverter)
				{
					_byteCharConverter = value;
					Invalidate();
				}
			}
		} IByteCharConverter _byteCharConverter;

		#endregion

		#region Misc
		/// <summary>
		/// Converts a byte array to a hex string. For example: {10,11} = "0A 0B"
		/// </summary>
		/// <param name="data">the byte array</param>
		/// <returns>the hex string</returns>
		string ConvertBytesToHex(byte[] data)
		{
			StringBuilder sb = new StringBuilder();
			foreach (byte b in data)
			{
				string hex = ConvertByteToHex(b);
				sb.Append(hex);
				sb.Append(" ");
			}
			if (sb.Length > 0)
				sb.Remove(sb.Length - 1, 1);
			string result = sb.ToString();
			return result;
		}
		/// <summary>
		/// Converts the byte to a hex string. For example: "10" = "0A";
		/// </summary>
		/// <param name="b">the byte to format</param>
		/// <returns>the hex string</returns>
		string ConvertByteToHex(byte b)
		{
			string sB = b.ToString(_hexStringFormat, System.Threading.Thread.CurrentThread.CurrentCulture);
			if (sB.Length == 1)
				sB = "0" + sB;
			return sB;
		}
		/// <summary>
		/// Converts the hex string to an byte array. The hex string must be separated by a space char ' '. If there is any invalid hex information in the string the result will be null.
		/// </summary>
		/// <param name="hex">the hex string separated by ' '. For example: "0A 0B 0C"</param>
		/// <returns>the byte array. null if hex is invalid or empty</returns>
		byte[] ConvertHexToBytes(string hex)
		{
			if (string.IsNullOrEmpty(hex))
				return null;
			hex = hex.Trim();
			var hexArray = hex.Split(' ');
			var byteArray = new byte[hexArray.Length];

			for (int i = 0; i < hexArray.Length; i++)
			{
				var hexValue = hexArray[i];

				byte b;
				var isByte = ConvertHexToByte(hexValue, out b);
				if (!isByte)
					return null;
				byteArray[i] = b;
			}

			return byteArray;
		}

		bool ConvertHexToByte(string hex, out byte b)
		{
			bool isByte = byte.TryParse(hex, System.Globalization.NumberStyles.HexNumber, System.Threading.Thread.CurrentThread.CurrentCulture, out b);
			return isByte;
		}

		void SetPosition(long bytePos)
		{
			SetPosition(bytePos, _byteCharacterPos);
		}

		void SetPosition(long bytePos, int byteCharacterPos)
		{
			if (_byteCharacterPos != byteCharacterPos)
			{
				_byteCharacterPos = byteCharacterPos;
			}

			if (bytePos != _bytePos)
			{
				_bytePos = bytePos;
				CheckCurrentLineChanged();
				CheckCurrentPositionInLineChanged();

				OnSelectionStartChanged(EventArgs.Empty);
			}
		}

		void SetSelectionLength(long selectionLength)
		{
			if (selectionLength != _selectionLength)
			{
				_selectionLength = selectionLength;
				OnSelectionLengthChanged(EventArgs.Empty);
			}
		}

		void SetHorizontalByteCount(int value)
		{
			if (_iHexMaxHBytes == value)
				return;

			_iHexMaxHBytes = value;
			OnHorizontalByteCountChanged(EventArgs.Empty);
		}

		void SetVerticalByteCount(int value)
		{
			if (_iHexMaxVBytes == value)
				return;

			_iHexMaxVBytes = value;
			OnVerticalByteCountChanged(EventArgs.Empty);
		}

		void CheckCurrentLineChanged()
		{
			long currentLine = (long)Math.Floor((double)_bytePos / (double)_iHexMaxHBytes) + 1;

			if (_byteProvider == null && _currentLine != 0)
			{
				_currentLine = 0;
				OnCurrentLineChanged(EventArgs.Empty);
			}
			else if (currentLine != _currentLine)
			{
				_currentLine = currentLine;
				OnCurrentLineChanged(EventArgs.Empty);
			}
		}

		void CheckCurrentPositionInLineChanged()
		{
			Point gb = GetGridBytePoint(_bytePos);
			int currentPositionInLine = gb.X + 1;

			if (_byteProvider == null && _currentPositionInLine != 0)
			{
				_currentPositionInLine = 0;
				OnCurrentPositionInLineChanged(EventArgs.Empty);
			}
			else if (currentPositionInLine != _currentPositionInLine)
			{
				_currentPositionInLine = currentPositionInLine;
				OnCurrentPositionInLineChanged(EventArgs.Empty);
			}
		}

		/// <summary>
		/// Raises the InsertActiveChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnInsertActiveChanged(EventArgs e)
		{
			if (InsertActiveChanged != null)
				InsertActiveChanged(this, e);
		}

		/// <summary>
		/// Raises the ReadOnlyChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnReadOnlyChanged(EventArgs e)
		{
			if (ReadOnlyChanged != null)
				ReadOnlyChanged(this, e);
		}

		/// <summary>
		/// Raises the ByteProviderChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnByteProviderChanged(EventArgs e)
		{
			if (ByteProviderChanged != null)
				ByteProviderChanged(this, e);
		}

		/// <summary>
		/// Raises the SelectionStartChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnSelectionStartChanged(EventArgs e)
		{
			if (SelectionStartChanged != null)
				SelectionStartChanged(this, e);
		}

		/// <summary>
		/// Raises the SelectionLengthChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnSelectionLengthChanged(EventArgs e)
		{
			if (SelectionLengthChanged != null)
				SelectionLengthChanged(this, e);
		}

		/// <summary>
		/// Raises the LineInfoVisibleChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnLineInfoVisibleChanged(EventArgs e)
		{
			if (LineInfoVisibleChanged != null)
				LineInfoVisibleChanged(this, e);
		}

		/// <summary>
		/// Raises the OnColumnInfoVisibleChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnColumnInfoVisibleChanged(EventArgs e)
		{
			if (ColumnInfoVisibleChanged != null)
				ColumnInfoVisibleChanged(this, e);
		}

		/// <summary>
		/// Raises the ColumnSeparatorVisibleChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnGroupSeparatorVisibleChanged(EventArgs e)
		{
			if (GroupSeparatorVisibleChanged != null)
				GroupSeparatorVisibleChanged(this, e);
		}

		/// <summary>
		/// Raises the StringViewVisibleChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnStringViewVisibleChanged(EventArgs e)
		{
			if (StringViewVisibleChanged != null)
				StringViewVisibleChanged(this, e);
		}

		/// <summary>
		/// Raises the BorderStyleChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnBorderStyleChanged(EventArgs e)
		{
			if (BorderStyleChanged != null)
				BorderStyleChanged(this, e);
		}

		/// <summary>
		/// Raises the UseFixedBytesPerLineChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnUseFixedBytesPerLineChanged(EventArgs e)
		{
			if (UseFixedBytesPerLineChanged != null)
				UseFixedBytesPerLineChanged(this, e);
		}

		/// <summary>
		/// Raises the GroupSizeChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnGroupSizeChanged(EventArgs e)
		{
			if (GroupSizeChanged != null)
				GroupSizeChanged(this, e);
		}

		/// <summary>
		/// Raises the BytesPerLineChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnBytesPerLineChanged(EventArgs e)
		{
			if (BytesPerLineChanged != null)
				BytesPerLineChanged(this, e);
		}

		/// <summary>
		/// Raises the VScrollBarVisibleChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnVScrollBarVisibleChanged(EventArgs e)
		{
			if (VScrollBarVisibleChanged != null)
				VScrollBarVisibleChanged(this, e);
		}

		/// <summary>
		/// Raises the HexCasingChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnHexCasingChanged(EventArgs e)
		{
			if (HexCasingChanged != null)
				HexCasingChanged(this, e);
		}

		/// <summary>
		/// Raises the HorizontalByteCountChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnHorizontalByteCountChanged(EventArgs e)
		{
			if (HorizontalByteCountChanged != null)
				HorizontalByteCountChanged(this, e);
		}

		/// <summary>
		/// Raises the VerticalByteCountChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnVerticalByteCountChanged(EventArgs e)
		{
			if (VerticalByteCountChanged != null)
				VerticalByteCountChanged(this, e);
		}

		/// <summary>
		/// Raises the CurrentLineChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnCurrentLineChanged(EventArgs e)
		{
			if (CurrentLineChanged != null)
				CurrentLineChanged(this, e);
		}

		/// <summary>
		/// Raises the CurrentPositionInLineChanged event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnCurrentPositionInLineChanged(EventArgs e)
		{
			if (CurrentPositionInLineChanged != null)
				CurrentPositionInLineChanged(this, e);
		}


		/// <summary>
		/// Raises the Copied event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnCopied(EventArgs e)
		{
			if (Copied != null)
				Copied(this, e);
		}

		/// <summary>
		/// Raises the CopiedHex event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected virtual void OnCopiedHex(EventArgs e)
		{
			if (CopiedHex != null)
				CopiedHex(this, e);
		}

		/// <summary>
		/// Raises the MouseDown event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected override void OnMouseDown(MouseEventArgs e)
		{
			System.Diagnostics.Debug.WriteLine("OnMouseDown()", "HexBox");

			if (!Focused)
				Focus();

			if (e.Button == MouseButtons.Left)
				SetCaretPosition(new Point(e.X, e.Y));

			base.OnMouseDown(e);
		}

		/// <summary>
		/// Raises the MouseWhell event
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected override void OnMouseWheel(MouseEventArgs e)
		{
			int linesToScroll = -(e.Delta * SystemInformation.MouseWheelScrollLines / 120);
			this.PerformScrollLines(linesToScroll);

			base.OnMouseWheel(e);
		}


		/// <summary>
		/// Raises the Resize event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected override void OnResize(EventArgs e)
		{
			base.OnResize(e);
			UpdateRectanglePositioning();
		}

		/// <summary>
		/// Raises the GotFocus event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected override void OnGotFocus(EventArgs e)
		{
			System.Diagnostics.Debug.WriteLine("OnGotFocus()", "HexBox");

			base.OnGotFocus(e);

			CreateCaret();
		}

		/// <summary>
		/// Raises the LostFocus event.
		/// </summary>
		/// <param name="e">An EventArgs that contains the event data.</param>
		protected override void OnLostFocus(EventArgs e)
		{
			System.Diagnostics.Debug.WriteLine("OnLostFocus()", "HexBox");

			base.OnLostFocus(e);

			DestroyCaret();
		}

		void _byteProvider_LengthChanged(object sender, EventArgs e)
		{
			UpdateScrollSize();
		}
		#endregion
	}
}