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
use std::cmp::min;
use std::fmt;
use std::num::NonZeroUsize;
use std::fs::File;
use std::io;
use std::io::Read;
use std::io::Write;
use regex::Regex;
use ansi_term::Color;
use ansi_term::Color::Fixed;
use unicode_segmentation::UnicodeSegmentation;


macro_rules! skip_bad_range {
    ($command:expr, $all_bytes:expr) => {
        if $command.bad_range(&$all_bytes) {
            println!("? (bad range)");
            continue;
        }
    };
}


/* Byte formatting stuff lifted from hexyl */
const COLOR_NULL: Color = Fixed(1);
const COLOR_ASCII_PRINTABLE: Color = Color::Cyan;
const COLOR_ASCII_WHITESPACE: Color = Color::Green;
const COLOR_ASCII_OTHER: Color = Color::Purple;
const COLOR_NONASCII: Color = Color::Yellow;

pub enum ByteCategory {
    Null,
    AsciiPrintable,
    AsciiWhitespace,
    AsciiOther,
    NonAscii,
}

#[derive(Copy, Clone)]
struct Byte(u8);

impl Byte {
    fn category(self) -> ByteCategory {
        if self.0 == 0x00 {
            ByteCategory::Null
        } else if self.0.is_ascii_graphic() {
            ByteCategory::AsciiPrintable
        } else if self.0.is_ascii_whitespace() {
            ByteCategory::AsciiWhitespace
        } else if self.0.is_ascii() {
            ByteCategory::AsciiOther
        } else {
            ByteCategory::NonAscii
        }
    }

    fn color(self) -> &'static Color {
        use crate::ByteCategory::*;

        match self.category() {
            Null => &COLOR_NULL,
            AsciiPrintable => &COLOR_ASCII_PRINTABLE,
            AsciiWhitespace => &COLOR_ASCII_WHITESPACE,
            AsciiOther => &COLOR_ASCII_OTHER,
            NonAscii => &COLOR_NONASCII,
        }
    }

    fn as_char(self) -> char {
        use crate::ByteCategory::*;

        match self.category() {

            /* hexyl uses 0 here, depending on color to distinguish */
            Null => '•',
            AsciiPrintable => self.0 as char,
            AsciiWhitespace if self.0 == 0x20 => ' ',
            AsciiWhitespace => '_',
            AsciiOther => '•',
            NonAscii => '×',
        }
    }
}

#[derive(Debug)]
struct Command {
    range: (usize, usize),
    command: char,
    args: Vec<String>,
}


fn print_help() {
    print!("Input/output is hex unless toggled to decimal with 'x'
?            This help
<Enter>      Print current byte(s) and move forward to next set of byte(s)
3d4          Move to byte number 3d4 and print from there
+            Move 1 byte forward and print from there
+++          Move 3 bytes forward and print from there
-            Move 1 byte back and print from there
+3d4         Move 3d4 bytes forward and print from there
-3d4         Move 3d4 bytes back and print from there
$            Move to last byte and print it
/deadbeef    If the bytes de ad be ef exist after the current index, move there
               and print.
k            Delete (kill) byte at current index and print new line of byte(s)
7dk          Move to byte 7d, delete that byte, and print from there.
1d,72k       Move to byte 1d, delete bytes 1d - 72 inclusive, and print from there.
/deadbeef/k  If the bytes de ad be ef exist after the current index, move there,
               delete those bytes, and print.
i            Prompt you to write out bytes which will be inserted at current index
72i          Move to byte number 72 and prompt you to enter bytes which will be
               inserted there.
/deadbeef/i  If the bytes de ad be ef exist after the current index, move there
               and prompt you to enter bytes which will be inserted there.
12,3dp       Print bytes 12 - 3d inclusive, move to leftmost byte printed on the
               last line.
m            Toggle whether or not characters are printed after bytes
n            Toggle whether or not byte numbers are printed before bytes
o            Toggle using color
p            Print current line of byte(s) (depending on 'W')
s            Print state of all toggles and 'W'idth
x            Toggle interpreting inputs and displaying output as hex or decimal
w            Actually write changes to the file on disk
W3d          Print a linebreak every 3d bytes [Default 0x10]
q            quit
");
}


fn string_from_bytes(bytes:&[u8]) -> String {
    let mut to_return = "".to_owned();
    for &byte in bytes {
        to_return += &padded_byte(byte);
    }
    return to_return;
}


fn index_of_bytes(needle:&[u8], haystack:&[u8]) -> Option<usize> {
    let needle_num_bytes = if needle.len() == 0 {
        return None;
    }
    else {
        needle.len()
    };

    for index in 0..haystack.len() {
        let range = (index, index + needle_num_bytes - 1);

        if bad_range(&haystack.to_vec(), range) {
            return None;
        }


        if &haystack[range.0..=range.1] == needle {
            return Some(index);
        }
        else {

        }
    }

    None
}


fn bytes_from_string(nibbles_s:&str) -> Result<Vec<u8>, String> {
    // TODO Allow general whitespace, not just literal spaces
    let re_bytes = Regex::new(r"^ *([0-9a-fA-F][0-9a-fA-F] *)* *$").unwrap();
    if re_bytes.is_match(&nibbles_s) {
        let nibbles_v:Vec<String> = nibbles_s.replace(" ", "").chars().map(|x| x.to_string()).collect();
        Ok(nibbles_v.chunks(2).map(|x| x.join("")).map(|x| u8::from_str_radix(&x, 16).unwrap()).collect())
    }
    else {
        Err(format!("Couldn't interpret '{}' as a sequence of bytes", &nibbles_s))
    }
}


fn read_bytes_from_user() -> Result<Vec<u8>, String> {
    print!("> ");
    io::stdout().flush().unwrap();
    let input = match get_input_or_die() {
        Ok(input) => input,
        Err(_errcode) => {
            return Err("Couldn't read input".to_owned());
        }
    };

    bytes_from_string(&input)
}


// TODO: This should take a usize..=usize range object
fn bad_range(bytes: &Vec<u8>, range: (usize, usize)) -> bool {
    bytes.len() == 0 || range.1 >= bytes.len()
}


/// Returns new index
fn move_to(state:&mut State, index:usize) -> Result<usize, String> {
    if state.empty() {
        Err("Empty file".to_owned())
    }
    else {
        let _max_index = match state.max_index() {
            Ok(max) => max,
            Err(error) => {
                return Err(error);
            },
        };

        if index > _max_index {
            Err(format!("{} > {} = maximum index", index, _max_index))
        }
        else {
            state.index = index;
            Ok(index)
        }
    }
}


impl Command {
    fn bad_range(&self, all_bytes: &Vec<u8>) -> bool {
        bad_range(all_bytes, self.range)
    }


    fn from_state_and_line(state:&State, line: &str) -> Result<Command, String> {
        // TODO Make these constants outside of this function so they don't get
        // created over and over
        // TODO Allow general whitespace, not just literal spaces
        let re_blank_line = Regex::new(r"^ *$").unwrap();
        let re_pluses = Regex::new(r"^ *(?P<pluses>\++) *$").unwrap();
        let re_minuses = Regex::new(r"^ *(?P<minuses>\-+) *$").unwrap();
        let re_search = Regex::new(r"^ */(?P<bytes>[0-9a-fA-F]+) *$").unwrap();
        let re_search_kill = Regex::new(r"^ */(?P<bytes>[0-9a-fA-F]+)/k *$").unwrap();
        let re_search_insert = Regex::new(r"^ */(?P<bytes>[0-9a-fA-F]+)/i *$").unwrap();
        let re_single_char_command = Regex::new(r"^ *(?P<command>[?mnopsxqwik]).*$").unwrap();
        let re_range = Regex::new(r"^ *(?P<begin>[0-9a-fA-F.$]+) *, *(?P<end>[0-9a-fA-F.$]+) *(?P<the_rest>.*) *$").unwrap();
        let re_specified_index = Regex::new(r"^ *(?P<index>[0-9A-Fa-f.$]+) *(?P<the_rest>.*) *$").unwrap();
        let re_offset_index = Regex::new(r"^ *(?P<sign>[-+])(?P<offset>[0-9A-Fa-f]+) *(?P<the_rest>.*) *$").unwrap();
        let re_matches_nothing = Regex::new(r"^a\bc").unwrap();
        let re_width = Regex::new(r"^ *W *(?P<width>[0-9A-Fa-f]+) *$").unwrap();

        let is_blank_line          = re_blank_line.is_match(line);
        let is_single_char_command = re_single_char_command.is_match(line);
        let is_pluses              = re_pluses.is_match(line);
        let is_minuses             = re_minuses.is_match(line);
        let is_range               = re_range.is_match(line);
        let is_search              = re_search.is_match(line);
        let is_search_kill         = re_search_kill.is_match(line);
        let is_search_insert       = re_search_insert.is_match(line);
        let is_specified_index     = re_specified_index.is_match(line);
        let is_offset_index        = re_offset_index.is_match(line);
        let is_width               = re_width.is_match(line);

        let re = if is_blank_line {
            re_blank_line
        }
        else if is_single_char_command {
            re_single_char_command
        }
        else if is_search {
            re_search
        }
        else if is_search_insert {
            re_search_insert
        }
        else if is_search_kill {
            re_search_kill
        }
        else if is_pluses {
            re_pluses
        }
        else if is_minuses {
            re_minuses
        }
        else if is_range {
            re_range
        }
        else if is_specified_index {
            re_specified_index
        }
        else if is_offset_index {
            re_offset_index
        }
        else if is_width {
            re_width
        }
        else {
            re_matches_nothing
        };

        let caps = re.captures(line);

        if is_pluses {
            let num_pluses = num_graphemes(caps.unwrap().name("pluses").unwrap().as_str());
            Ok(Command{
                range: (num_pluses, num_pluses),
                command: 'G',
                args: vec![],
            })
        }

        else if is_search_insert {
            match bytes_from_string(caps.unwrap().name("bytes").unwrap().as_str()) {
                Ok(needle) => {
                    if let Some(offset) = index_of_bytes(&needle, &state.all_bytes[state.index..]) {
                        Ok(Command{
                            range: (state.index + offset, state.index + offset),
                            command: 'i',
                            args: vec![],
                        })
                    }
                    else {
                        Err(format!("{} not found", string_from_bytes(&needle)))
                    }
                },
                Err(error) => {
                    Err(error)
                }
            }
        }

        else if is_search_kill {
            match bytes_from_string(caps.unwrap().name("bytes").unwrap().as_str()) {
                Ok(needle) => {
                    let needle_num_bytes = if needle.len() == 0 {
                        return Err("Searching for empty string".to_owned());
                    }
                    else {
                        needle.len()
                    };

                    if let Some(offset) = index_of_bytes(&needle, &state.all_bytes[state.index..]) {
                        Ok(Command{
                            range: (state.index + offset, state.index + offset + needle_num_bytes - 1),
                            command: 'k',
                            args: vec![],
                        })
                    }
                    else {
                        Err(format!("{} not found", string_from_bytes(&needle)))
                    }
                },
                Err(error) => {
                    Err(error)
                }
            }
        }

        else if is_search {
            match bytes_from_string(caps.unwrap().name("bytes").unwrap().as_str()) {
                Ok(needle) => {
                    if let Some(offset) = index_of_bytes(&needle, &state.all_bytes[state.index..]) {
                        Ok(Command{
                            range: (state.index + offset, state.index + offset),
                            command: 'g',
                            args: vec![],
                        })
                    }
                    else {
                        Err(format!("{} not found", string_from_bytes(&needle)))
                    }
                },
                Err(error) => {
                    Err(error)
                }
            }
        }

        else if is_minuses {
            let num_minuses = num_graphemes(caps.unwrap().name("minuses").unwrap().as_str());
            Ok(Command{
                range: (num_minuses, num_minuses),
                command: 'H',
                args: vec![],
            })
        }

        else if is_single_char_command {
            let command = caps.unwrap().name("command").unwrap().as_str().chars().next().unwrap();
            if command == 'p' {
                Ok(Command{
                    range: (state.index, state.index),
                    command: 'Q',
                    args: vec![],
                })
            }
            else {
                Ok(Command{
                    range: (state.index, state.index),
                    command: command,
                    args: vec![],
                })
            }
        }

        else if is_blank_line {
            Ok(Command{
                range: (state.index, state.index),
                command: '\n',
                args: vec![],
            })
        }

        else if is_width {
            // println!("is_width");
            let caps = caps.unwrap();
            if let Some(width) = NonZeroUsize::new(usize::from_str_radix(caps.name("width").unwrap().as_str(), state.radix).unwrap()) {
              Ok(Command{
                  range: (usize::from(width), usize::from(width)),
                  command: 'W',
                  args: vec![],
              })
            }
            else {
                Err("Width must be positive".to_owned())
            }
        }

        else if is_range {
            if state.empty() {
                return Err("Empty file".to_owned());
            }

            let _max_index = match state.max_index() {
                Ok(max) => max,
                Err(error) => {
                    return Err(format!("? ({})", error));
                },
            };

            // println!("is_range");
            let caps = caps.unwrap();
            let begin = number_dot_dollar(state.index, _max_index,
                    caps.name("begin").unwrap().as_str(), state.radix);
            if begin.is_err() {
                // Why on Earth doesn't this work?
                // return Err(begin.unwrap());
                return Err("Can't understand beginning of range.".to_owned());
            }
            let begin = begin.unwrap();
            let end = number_dot_dollar(state.index, _max_index,
                    caps.name("end").unwrap().as_str(), state.radix);
            if end.is_err() {
                // Why on Earth doesn't this work?
                // return end;
                return Err("Can't understand end of range.".to_owned());
            }
            let end = end.unwrap();

            let the_rest = caps.name("the_rest").unwrap().as_str().trim();
            if the_rest.len() == 0 {
                Err("No arguments given".to_owned())
            }
            else {
                Ok(Command{
                    range: (begin, end),
                    command: the_rest.chars().next().unwrap(),
                    args: the_rest[1..].split_whitespace().map(|x| x.to_owned()).collect(),
                })
            }
        }

        else if is_specified_index {
            if state.empty() {
                return Err("Empty file".to_owned());
            }

            let _max_index = match state.max_index() {
                Ok(max) => max,
                Err(error) => {
                    return Err(format!("? ({})", error));
                },
            };

            // println!("is_specified_index");
            let caps = caps.unwrap();
            let specific_index = number_dot_dollar(state.index, _max_index,
                    caps.name("index").unwrap().as_str(), state.radix);
            if specific_index.is_err() {
                // Why on Earth doesn't this work?
                // return specific_index;
                return Err("Can't understand index.".to_owned());
            }
            let specific_index = specific_index.unwrap();
            let the_rest = caps.name("the_rest").unwrap().as_str().trim().to_owned();
            if the_rest.len() == 0 {
                Ok(Command{
                    range: (specific_index, specific_index),
                    command: 'g',
                    args: vec![],
                })
            }
            else {
                let command = the_rest.chars().next().unwrap();
                let args = the_rest[1..].split_whitespace()
                        .map(|x| x.to_owned()).collect();
                Ok(Command{
                    range: (specific_index, specific_index),
                    command:
                        if command == 'p' {
                            'P'
                        }
                        else {
                          command
                        },
                    args: args,
                })
            }
        }

        else if is_offset_index {
            // println!("is_specified_index");
            let caps = caps.unwrap();
            let as_string = caps.name("offset").unwrap().as_str();
            let index_offset = usize::from_str_radix(as_string, state.radix);
            if index_offset.is_err() {
                return Err(format!("{} is not a number", as_string));
            }
            let index_offset = index_offset.unwrap();
            let sign = caps.name("sign").unwrap().as_str();
            let begin = match sign {
                "+" => state.index + index_offset,
                "-" => state.index - index_offset,
                _   => {
                    return Err(format!("Unknown sign {}", sign));
                }
            };
            let range = (begin, begin);
            let the_rest = caps.name("the_rest").unwrap().as_str();
            if the_rest.len() == 0 {
                Ok(Command{
                    range: range,
                    command: 'g',
                    args: vec![],
                })
            }
            else {
                Ok(Command{
                    range: range,
                    command: the_rest.chars().next().unwrap(),
                    args: the_rest[1..].split_whitespace().map(|x| x.to_owned()).collect(),
                })
            }
        }

        else {
            Err(format!("Unable to parse '{}'", line.trim()))
        }
    }
}


fn string_from_radix(radix: u32) -> String {
    if radix == 10 {
        "decimal".to_owned()
    }
    else {
        "hex".to_owned()
    }
}


fn get_input_or_die() -> Result<String, i32> {
    let mut input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(_num_bytes) => {

            /* EOF Return error of 0 to indicate time for a clean exit.  */
            if _num_bytes == 0 {
                Err(0)
            }
            else {
                Ok(input.trim().to_string())
            }
        }
        Err(_) => {
            println!("Unable to read input");
            Err(3)
        }
    }
}


fn num_bytes_or_die(open_file: &Option<std::fs::File>) -> Result<usize, i32> {
    if open_file.is_none() {
        return Ok(0);
    }

    let metadata = open_file.as_ref().unwrap().metadata();
    match metadata {
        Ok(metadata) => {
            Ok(metadata.len() as usize)
        }
        Err(_) => {
            println!("Couldn't find file size");
            Err(2)
        }
    }
}


fn formatted_byte(byte:u8, color:bool) -> String {
    if color {
        Byte(byte).color().paint(padded_byte(byte)).to_string()
    }
    else {
        padded_byte(byte)
    }
}


fn chared_byte(byte:u8, color:bool) -> String {
    if color {
        Byte(byte).color().paint(String::from(Byte(byte).as_char())).to_string()
    }
    else {
        Byte(byte).as_char().to_string()
    }
}


fn padded_byte(byte:u8) -> String {
    format!("{:02x}", byte)
}


fn max_bytes_line(bytes:&[u8], width:NonZeroUsize) -> usize {
    if bytes.len() == 0 {
        0
    }
    else {
        (bytes.len() - 1) / usize::from(width)
    }
}


fn bytes_line_range(bytes:&[u8], line_number:usize, width:NonZeroUsize) -> std::ops::Range<usize> {
    let width = usize::from(width);
    if line_number * width < bytes.len() {
        let end_index = min(bytes.len(), line_number * width + width);
        line_number * width..end_index
    }
    else {
        0..0
    }
}


fn bytes_line(bytes:&[u8], line_number:usize, width:NonZeroUsize) -> &[u8] {
    &bytes[bytes_line_range(bytes, line_number, width)]
}


fn chars_line(bytes:&[u8], line_number:usize, width:NonZeroUsize, color:bool) -> String {
    let mut to_return:String = "".to_owned();
    for index in bytes_line_range(bytes, line_number, width) {
        to_return += &String::from(chared_byte(bytes[index], color));
    }
    to_return
}



#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_padded_byte() {
        assert_eq!(padded_byte(2), "02");
        assert_eq!(padded_byte(10), "0a");
    }

    #[test]
    fn test_index_of_bytes() {
        let haystack = vec![0xde, 0xad, 0xbe, 0xef];
        assert_eq!(index_of_bytes(&vec![], &haystack), None);
        assert_eq!(index_of_bytes(&vec![0xad, 0xbe], &haystack), Some(1));
        assert_eq!(index_of_bytes(&vec![0xad, 0xbe, 0xef], &haystack), Some(1));
        assert_eq!(index_of_bytes(&vec![0xad, 0xbe, 0xef, 0xef], &haystack), None);
        assert_eq!(index_of_bytes(&vec![0xde,], &haystack), Some(0));
    }


    #[test]
    fn test_max_bytes_line() {
        let _1 = NonZeroUsize::new(1).unwrap();
        let _2 = NonZeroUsize::new(2).unwrap();
        let _3 = NonZeroUsize::new(3).unwrap();
        let _4 = NonZeroUsize::new(4).unwrap();
        let _5 = NonZeroUsize::new(5).unwrap();
        let _6 = NonZeroUsize::new(6).unwrap();
        let _7 = NonZeroUsize::new(7).unwrap();
        let _8 = NonZeroUsize::new(8).unwrap();
        let bytes = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
        assert_eq!(max_bytes_line(&bytes, _1), 12);
        let bytes = vec![8, 6, 7, 5, 3, 0, 9,];
        assert_eq!(max_bytes_line(&bytes, _1), 6);
        assert_eq!(max_bytes_line(&bytes, _2), 3);
        assert_eq!(max_bytes_line(&bytes, _3), 2);
        assert_eq!(max_bytes_line(&bytes, _4), 1);
        assert_eq!(max_bytes_line(&bytes, _5), 1);
        assert_eq!(max_bytes_line(&bytes, _6), 1);
        assert_eq!(max_bytes_line(&bytes, _7), 0);
        assert_eq!(max_bytes_line(&bytes, _8), 0);
        let bytes = vec![8, 6, 7, 5, 3, 0,];
        assert_eq!(max_bytes_line(&bytes, _1), 5);
        assert_eq!(max_bytes_line(&bytes, _2), 2);
        assert_eq!(max_bytes_line(&bytes, _3), 1);
        assert_eq!(max_bytes_line(&bytes, _4), 1);
        assert_eq!(max_bytes_line(&bytes, _5), 1);
        assert_eq!(max_bytes_line(&bytes, _6), 0);
        assert_eq!(max_bytes_line(&bytes, _7), 0);
        assert_eq!(max_bytes_line(&bytes, _8), 0);
        let bytes = vec![8, 6, 7,];
        assert_eq!(max_bytes_line(&bytes, _1), 2);
        assert_eq!(max_bytes_line(&bytes, _2), 1);
        assert_eq!(max_bytes_line(&bytes, _3), 0);
        assert_eq!(max_bytes_line(&bytes, _4), 0);
        assert_eq!(max_bytes_line(&bytes, _5), 0);
        let bytes = vec![8, 6,];
        assert_eq!(max_bytes_line(&bytes, _1), 1);
        assert_eq!(max_bytes_line(&bytes, _2), 0);
        assert_eq!(max_bytes_line(&bytes, _3), 0);
        assert_eq!(max_bytes_line(&bytes, _4), 0);
        let bytes = vec![8,];
        assert_eq!(max_bytes_line(&bytes, _1), 0);
        assert_eq!(max_bytes_line(&bytes, _2), 0);
        assert_eq!(max_bytes_line(&bytes, _3), 0);
        assert_eq!(max_bytes_line(&bytes, _4), 0);
        let bytes = vec![];
        assert_eq!(max_bytes_line(&bytes, _1), 0);
        assert_eq!(max_bytes_line(&bytes, _2), 0);
        assert_eq!(max_bytes_line(&bytes, _3), 0);
        assert_eq!(max_bytes_line(&bytes, _4), 0);
    }

    #[test]
    fn test_num_graphemes() {
        assert_eq!(num_graphemes("hey, there"), 10);
        assert_eq!(num_graphemes("दीपक"), 3);
        assert_eq!(num_graphemes("ﷺ"), 1);
        assert_eq!(num_graphemes("père"), 4);
    }

    #[test]
    fn test_bytes_line() {
        let bytes = vec![];
        let _1 = NonZeroUsize::new(1).unwrap();
        let _2 = NonZeroUsize::new(2).unwrap();
        let _3 = NonZeroUsize::new(3).unwrap();
        let _4 = NonZeroUsize::new(4).unwrap();
        let _5 = NonZeroUsize::new(5).unwrap();
        let _6 = NonZeroUsize::new(6).unwrap();
        let _7 = NonZeroUsize::new(7).unwrap();
        let _8 = NonZeroUsize::new(8).unwrap();
        assert_eq!(bytes_line(&bytes, 0, _1).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 0, _2).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 1, _1).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 1, _2).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 2, _1).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 2, _2).to_owned(), vec![]);
        let bytes = vec![8, 6, 7, 5, 3, 0, 9,];
        assert_eq!(bytes_line(&bytes, 0, _1).to_owned(), vec![8,]);
        assert_eq!(bytes_line(&bytes, 1, _1).to_owned(), vec![6,]);
        assert_eq!(bytes_line(&bytes, 2, _1).to_owned(), vec![7,]);
        assert_eq!(bytes_line(&bytes, 3, _1).to_owned(), vec![5,]);
        assert_eq!(bytes_line(&bytes, 4, _1).to_owned(), vec![3,]);
        assert_eq!(bytes_line(&bytes, 5, _1).to_owned(), vec![0,]);
        assert_eq!(bytes_line(&bytes, 6, _1).to_owned(), vec![9,]);
        assert_eq!(bytes_line(&bytes, 7, _1).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 8, _1).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 9, _1).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 0, _2).to_owned(), vec![8, 6,]);
        assert_eq!(bytes_line(&bytes, 1, _2).to_owned(), vec![7, 5,]);
        assert_eq!(bytes_line(&bytes, 2, _2).to_owned(), vec![3, 0,]);
        assert_eq!(bytes_line(&bytes, 3, _2).to_owned(), vec![9,]);
        assert_eq!(bytes_line(&bytes, 4, _2).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 5, _2).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 0, _3).to_owned(), vec![8, 6, 7,]);
        assert_eq!(bytes_line(&bytes, 1, _3).to_owned(), vec![5, 3, 0,]);
        assert_eq!(bytes_line(&bytes, 2, _3).to_owned(), vec![9,]);
        assert_eq!(bytes_line(&bytes, 3, _3).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 4, _3).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 0, _4).to_owned(), vec![8, 6, 7, 5,]);
        assert_eq!(bytes_line(&bytes, 1, _4).to_owned(), vec![3, 0, 9,]);
        assert_eq!(bytes_line(&bytes, 2, _4).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 3, _4).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 4, _4).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 0, _5).to_owned(), vec![8, 6, 7, 5, 3,]);
        assert_eq!(bytes_line(&bytes, 1, _5).to_owned(), vec![0, 9,]);
        assert_eq!(bytes_line(&bytes, 2, _5).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 3, _5).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 0, _6).to_owned(), vec![8, 6, 7, 5, 3, 0,]);
        assert_eq!(bytes_line(&bytes, 1, _6).to_owned(), vec![9,]);
        assert_eq!(bytes_line(&bytes, 2, _6).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 3, _6).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 0, _7).to_owned(), vec![8, 6, 7, 5, 3, 0, 9,]);
        assert_eq!(bytes_line(&bytes, 1, _7).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 2, _7).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 3, _7).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 0, _8).to_owned(), vec![8, 6, 7, 5, 3, 0, 9,]);
        assert_eq!(bytes_line(&bytes, 1, _8).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 2, _8).to_owned(), vec![]);
        assert_eq!(bytes_line(&bytes, 3, _8).to_owned(), vec![]);
    }
}


fn print_state(state:&State) {
    println!("At byte {} of {}", lino(&state),
            hex_unless_dec_with_radix(state.all_bytes.len(), state.radix));
    if state.show_byte_numbers {
        println!("Printing byte numbers in {}",
            string_from_radix(state.radix));
    };
    if state.show_chars {
        println!("Printing char representations after bytes");
    };
    println!("Interpreting input numbers as {}",
            string_from_radix(state.radix));
    println!("Printing a newline every {} bytes",
            hex_unless_dec_with_radix(usize::from(state.width), state.radix));
    if state.unsaved_changes {
        println!("Unwritten changes");
    }
    else {
        println!("No unwritten changes");
    }
}


/// returns index of the byte in the 0-th column of the last row printed
fn print_bytes(state:&State, range:(usize, usize)) -> Option<usize> {
    if state.empty() {
        return None;
    }

    let max = state.max_index();
    if max.is_err() {
        println!("? ({:?})", max);
        return None;
    }
    let max = max.unwrap();

    let from = range.0;
    let to = min(max, range.1);
    if bad_range(&state.all_bytes, (from, to)) {
      println!("? (Bad range: ({}, {}))", range.0, range.1);
      return None;
    }

    let bytes = &state.all_bytes[from..=to];
    let max_bytes_line_num = max_bytes_line(bytes, state.width);
    let mut left_col_byte_num = from;
    for bytes_line_num in 0..=max_bytes_line_num {
        if bytes_line_num != 0 {
            left_col_byte_num += usize::from(state.width);
        }
        if state.show_byte_numbers {
            if state.radix == 10 {
                print!("{:>5}{}|", left_col_byte_num, state.n_padding);
            }
            else {
                print!("{:>5x}{}|", left_col_byte_num, state.n_padding);
            }
        }
        let cur_line = bytes_line(bytes, bytes_line_num, state.width);
        let with_color = cur_line.iter().map(|x| formatted_byte(*x, true))
                .collect::<Vec<String>>().join(" ");
        let sans_color = cur_line.iter().map(|x| formatted_byte(*x, false))
                .collect::<Vec<String>>().join(" ");
        if state.color {
            print!("{}", with_color);
        }
        else {
            print!("{}", sans_color);
        }
        let expected_length = usize::from(state.width) * 3 - 1;
        for _ in num_graphemes(&sans_color)..expected_length {
            print!(" ");
        }
        // TODO Do this padding stuff format!  Unclear why previous attempts
        // have failed.
        if state.show_chars {
            print!("|   {}", chars_line(bytes, bytes_line_num, state.width,
                state.color));
        }
        println!();
        left_col_byte_num = from + bytes_line_num * usize::from(state.width);
    }
    Some(left_col_byte_num)
}


/// .len gives the number of bytes
/// .chars.count() gives the number of characters (which counts è as two characters.
/// The human concept is unicode "graphemes" or "glyphs" defined to be what
/// think they are.
fn num_graphemes(unicode_string: &str) -> usize {
    return unicode_string.graphemes(true).count();
}

fn number_dot_dollar(index:usize, _max_index:usize, input:&str, radix:u32)
        -> Result<usize, String> {
    match input {
        "$" => Ok(_max_index),
        "." => Ok(index),
        something_else => {
            if let Ok(number) = usize::from_str_radix(input, radix) {
                Ok(number)
            }
            else {
                return Err(format!("{} isn't a number in base {}", something_else, radix));
            }
        }
    }
}


fn hex_unless_dec_with_radix(number:usize, radix:u32) -> String {
    let letter = if radix == 10 {
        'd'
    }
    else {
        'x'
    };

    format!("0{}{}", letter, hex_unless_dec(number, radix))
}


fn hex_unless_dec(number:usize, radix:u32) -> String {
    if radix == 10 {
        format!("{}", number)
    }
    else {
        format!("{:x}", number)
    }
}


fn lino(state:&State) -> String {
    hex_unless_dec_with_radix(state.index, state.radix)
}


struct State {
    radix: u32,
    show_byte_numbers: bool,
    show_chars: bool,
    unsaved_changes: bool,
    filename: String,

    show_prompt: bool,
    color: bool,

    /* Current byte number, 0 to len -1 */
    index: usize,

    width: NonZeroUsize,

    /* The bytes in memory */
    all_bytes: Vec<u8>,

    /* Spaces to put between a byte number and a byte when displaying */
    n_padding: String,
}


impl fmt::Debug for State {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "radix: {}|unsaved_changes: {}|show_byte_numbers: {}|show_chars: {}|index: {}|width: {}|n_padding: '{}'|filename: {}|",
                self.radix, self.unsaved_changes, self.show_byte_numbers,
                self.show_chars, self.index, self.width, self.n_padding,
                self.filename)
    }
}


impl State {
    fn empty(&self) -> bool {
        self.all_bytes.len() == 0
    }

    fn range(&self) -> (usize, usize) {
        (self.index, self.index + usize::from(self.width) - 1)
    }

    fn max_index(&self) -> Result<usize, String> {
        if self.all_bytes.len() == 0 {
            Err("No bytes, so no max index.".to_owned())
        }
        else {
            Ok(self.all_bytes.len() - 1)
        }
    }
}

/// Returns new index number
fn minuses(state:&mut State, num_minuses:usize) -> Result<usize, String> {
    if state.empty() {
        Err("Empty file".to_owned())
    }
    else if state.index == 0 {
        Err("already at 0th byte".to_owned())
    }
    else if state.index < num_minuses {
        Err(format!("Going back {} bytes would take you beyond the 0th byte", num_minuses))
    }
    else {
        state.index -= num_minuses;
        print_bytes(&state, state.range());
        Ok(state.index)
    }
}

/// Returns new index number
fn pluses(state:&mut State, num_pluses:usize) -> Result<usize, String> {
    if state.empty() {
        Err("Empty file".to_owned())
    }
    else {
        match state.max_index() {
            Ok(max) => {
                if state.index == max {
                    Err("already at last byte".to_owned())
                }
                else if state.index + num_pluses > max {
                    Err(format!("Moving {} bytes would put you past last byte", num_pluses))
                }
                else {
                    state.index += num_pluses;
                    print_bytes(&state, state.range());
                    Ok(state.index)
                }
            },
            Err(error) => {
                Err(error)
            },
        }
    }
}


pub fn actual_runtime(filename:&str, quiet:bool, color:bool) -> i32 {
    let file = match File::open(filename) {
        Ok(filehandle) => {
            Some(filehandle)
        },
        Err(error) => {
            if error.kind() == std::io::ErrorKind::NotFound {
                None
            }
            else {
                return 3;
            }
        }
    };

    let original_num_bytes = match num_bytes_or_die(&file) {
        Ok(num_bytes) => {
            num_bytes
        },
        Err(errcode) => {
            return errcode;
        }
    };

    /* Read all bytes into memory just like real ed */
    // TODO A real hex editor needs to buffer
    let mut all_bytes = Vec::new();
    if file.is_some() {
        match file.unwrap().read_to_end(&mut all_bytes) {
            Err(_) => {
                println!("Couldn't read {}", filename);
                return 4;
            },
            Ok(num_bytes_read) => {
                if num_bytes_read != original_num_bytes {
                    println!("Only read {} of {} bytes of {}", num_bytes_read,
                            original_num_bytes, filename);
                    return 5;
                }
            }
        }
    }


    // TODO Below here should be a function called main_loop()
    let mut state = State{
        radix: 16,
        filename: filename.to_owned(),
        show_byte_numbers: true,
        show_prompt: !quiet,
        color: color,
        show_chars: true,
        unsaved_changes: false,
        index: 0,
        width: NonZeroUsize::new(16).unwrap(),
        all_bytes: all_bytes,
        // TODO calculate based on longest possible index
        n_padding: "      ".to_owned(),
    };

    if !quiet {
        println!("{} bytes\n? for help\n",
                hex_unless_dec(state.all_bytes.len(), state.radix));
        print_state(&state);
        println!();
        print_bytes(&state, state.range());
    }

    loop {
        if state.show_prompt {
            print!("*");
        }
        io::stdout().flush().unwrap();
        let input = match get_input_or_die() {
            Ok(input) => input,
            Err(errcode) => {
                return errcode;
            }
        };

        match Command::from_state_and_line(&state, &input) {
            Ok(command) => {
                // println!("{:?}", command);
                match command.command {

                    /* Error */
                    'e' => {
                        println!("?");
                        continue;
                    },

                    /* Go to */
                    'g' => {
                        match move_to(&mut state, command.range.0) {
                            Ok(_) => {
                                print_bytes(&state, state.range());
                            },
                            Err(error) => {
                                println!("? ({})", error);
                            }
                        }
                    },

                    /* +'s */
                    'G' => {
                        match pluses(&mut state, command.range.0) {
                            Err(error) => {
                                println!("? ({})", error);
                            },
                            Ok(_) => {
                                continue;
                            }
                        }
                    },

                    /* -'s */
                    'H' => {
                        match minuses(&mut state, command.range.0) {
                            Err(error) => {
                                println!("? ({})", error);
                            },
                            Ok(_) => {
                                continue;
                            }
                        }
                    },

                    /* insert */
                    'i' => {
                        match read_bytes_from_user() {
                            Ok(entered_bytes) => {
                                state.index = command.range.1;
                                // TODO Find the cheapest way to do this (maybe
                                // make state.all_bytes a better container)
                                // TODO Do this with split_off
                                let mut new = Vec::with_capacity(state.all_bytes.len() + entered_bytes.len());
                                for i in 0..state.index {
                                    new.push(state.all_bytes[i]);
                                }
                                // TODO Could use Vec::splice here
                                for i in 0..entered_bytes.len() {
                                    new.push(entered_bytes[i]);
                                }
                                for i in state.index..state.all_bytes.len() {
                                    new.push(state.all_bytes[i]);
                                }
                                state.all_bytes = new;
                                state.unsaved_changes = true;
                                print_bytes(&state, state.range());
                            },
                            Err(error) => {
                                println!("? ({})", error);
                            },
                        }
                    },

                    /* Help */
                    '?'|'h' => {
                        print_help();
                    },

                    /* 'k'ill byte(s) (Can't use 'd' because that's a hex
                    * character! */
                    'k' => {
                        if state.empty() {
                            println!("? (Empty file");
                            continue;
                        }
                        skip_bad_range!(command, state.all_bytes);
                        let mut right_half = state.all_bytes.split_off(command.range.0);
                        right_half = right_half.split_off(command.range.1 - command.range.0 + 1);
                        state.all_bytes.append(&mut right_half);
                        state.index = command.range.0;
                        print_bytes(&state, state.range());
                    },

                    /* Toggle showing char representations of bytes */
                    'm' => {
                        state.show_chars = !state.show_chars;
                        if !quiet {
                            println!("{}", state.show_chars);
                        }
                    },

                    /* Toggle showing byte number */
                    'n' => {
                        state.show_byte_numbers = !state.show_byte_numbers;
                        if !quiet {
                            println!("{}", state.show_byte_numbers);
                        }
                    },

                    /* Toggle color */
                    'o' => {
                        state.color = !state.color;
                        if !quiet {
                            println!("{}", state.color);
                        }
                    },


                    /* Toggle hex/dec */
                    'x' => {
                        state.radix = if state.radix == 16 {
                            10
                        }
                        else {
                            16
                        }
                    },

                    /* User pressed enter */
                    '\n' => {
                        if state.empty() {
                            println!("? (Empty file)");
                            continue;
                        };

                        match state.max_index() {
                            Ok(max) => {
                                let width = usize::from(state.width);
                                let first_byte_to_show_index = state.index + width;
                                let last_byte_to_show_index = min(
                                        first_byte_to_show_index + width - 1,
                                                max);
                                if first_byte_to_show_index > max {
                                    println!("? (already showing last byte at index {})",
                                            hex_unless_dec(last_byte_to_show_index,
                                                    state.radix));
                                }
                                else {
                                    state.index = first_byte_to_show_index;
                                    print_bytes(&state, (first_byte_to_show_index,
                                            last_byte_to_show_index));
                                }
                            },
                            Err(error) => {
                                println!("? ({})", error);
                            }
                        }
                    }

                    /* Print byte(s) at one place, width long */
                    'P' => {
                        if state.empty() {
                            println!("? (Empty file)");
                            continue;
                        };

                        skip_bad_range!(command, state.all_bytes);
                        state.index = command.range.0;
                        if let Some(last_left_col_index) = print_bytes(&state, state.range()) {
                            state.index = last_left_col_index;
                        }
                        else {
                            println!("? (bad range {:?}", state.range());
                        }
                    },

                    /* Print byte(s) with range */
                    'p' => {
                        if state.empty() {
                            println!("? (Empty file)");
                            continue;
                        };

                        skip_bad_range!(command, state.all_bytes);
                        state.index = command.range.0;
                        if let Some(last_left_col_index) = print_bytes(&state, (command.range.0, command.range.1)) {
                        state.index = last_left_col_index;
                        }
                        else {
                            println!("? (bad range {:?}", command.range);
                        }
                    },

                    /* Print byte(s) at *current* place, width long */
                    'Q' => {
                        if state.empty() {
                            println!("? (Empty file)");
                            continue;
                        };

                        print_bytes(&state, state.range());
                    },

                    /* Quit */
                    'q' => {
                        return 0;
                    },

                    /* Print state */
                    's' => {
                        print_state(&state);
                    },

                    /* Write out */
                    'w' => {
                        let result = std::fs::write(filename, &state.all_bytes);
                        if result.is_err() {
                            println!("? (Couldn't write to {})", state.filename);
                        }
                    },

                    /* Change width */
                    'W' => {
                        if let Some(width) = NonZeroUsize::new(command.range.0) {
                            state.width = width;
                        }
                    },

                    /* Catchall error */
                    _ => {
                        println!("? (Don't understand command '{}')", command.command);
                        continue;
                    },
                }
            },
            Err(error) => {
                println!("? ({})", error);
                continue;
            }
        }
    }
}