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
use ansi_term::Color;
use ec::State;
use regex::Regex;
use std::collections::HashSet;
use std::io;
use std::io::Write;
use std::num::NonZeroUsize;
use std::path::PathBuf;

// TODO This is deprecated and should be
// replaced with
//     ec = {package = "edhex_core", version = "0.1.0}
// in Cargo.toml.  But that's only going to
// work for after Rust 1.26.0  Far enough in the future, use the Cargo.toml way.
extern crate edhex_core as ec;


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

static DEFAULT_BEFORE_CONTEXT:usize = 10;
static DEFAULT_AFTER_CONTEXT:usize= 10;


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


fn print_help(state:&State) {
    print!("Input/output is hex unless toggled to decimal with 'x'
h           This (h)elp
<Enter>     Print current byte(s) and move forward to next line of byte(s)
j           (j)ump back to previous line of byte(s) and print
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 bytes de ad be ef exist after current index, move there and print
?deadbeef   If bytes de ad be ef exist before current index, move there and print
/           Perform last search again starting at next byte
?           Perform last search (backwards) again starting at previous byte
k           Delete/(k)ill byte at current index and print new line of byte(s)
7dk         Move to byte 7d, (k)ill that byte, and print from there.
1d,72k      Move to byte 1d; (k)ill bytes 1d - 72 inclusive; print from there
/deadbeef/k If bytes de ad be ef exist after current index, move there,
              (k)ill those bytes, and print
i           Prompt you to enter bytes which will be (i)nserted at current index
72i         Move to byte number 72; prompt you to enter bytes to (i)nsert there
/deadbeef/i If bytes de ad be ef exist after current index, move there
              and prompt you to enter bytes which will be (i)nserted there
12,3dp      (p)rint bytes 12 - 3d inclusive, move to byte 12
l           (l)oad a new file.
L           (L)oad state from a file.  Fails if file you were editing is gone.
m           Toggle whether or not characters are printed after bytes
n           Toggle whether or not byte (n)umbers are printed before bytes
o           Toggle using c(o)lor
p           (p)rint current line of byte(s) (depending on 'W')
P           Save (P)references to file (width, color, etc.)
r           (r)ead preferences from a file.
R           Toggle (R)ead-only mode
s           Print (s)tate of toggles, 'W'idth, etc.
S           (S)ave state to a file except the bytes you're editing.
t3d         Print 0x3d lines of con(t)extual bytes after current line [Default {}]
T3d         Print 0x3d lines of con(T)extual bytes before current line [Default {}]
u           (u)pdate filename to write to
U           Toggle (U)nderlining main line
v           Insert a (v)isual break in the display at the current byte.
            NOTE: This does not insert a byte in the file.  It's just display.
V           Remove a (V)isual break if one is at the current byte.
x           Toggle reading input and displaying output as he(x) or decimal
w           Actually (w)rite changes to the file on disk
W3d         Set (W)idth to 0x3d.  i.e. print a linebreak every 3d bytes [Default {}]
q           (q)uit
",
    ec::hex_unless_dec_with_radix(DEFAULT_BEFORE_CONTEXT, state.prefs.radix),
    ec::hex_unless_dec_with_radix(DEFAULT_AFTER_CONTEXT, state.prefs.radix),
    ec::hex_unless_dec_with_radix(ec::DEFAULT_WIDTH, state.prefs.radix)
);
}

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

    ec::bytes_from_string(&input)
}


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


    fn from_state_and_line(state:&mut 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<direction>[/?]) *(?P<bytes>[0-9a-fA-F]+) *$").unwrap();
        let re_search_again = Regex::new(r"^ *(?P<direction>[/?]) *$").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>[hijkmnopqRrsSlLPuUvVwx]).*$").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 re_before_context = Regex::new(r"^ *T *(?P<before_context>[0-9A-Fa-f]+) *$").unwrap();
        let re_after_context = Regex::new(r"^ *t *(?P<after_context>[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_again        = re_search_again.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 is_before_context      = re_before_context.is_match(line);
        let is_after_context       = re_after_context.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_again {
            re_search_again
        }
        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_before_context {
            re_before_context
        }
        else if is_after_context {
            re_after_context
        }
        else if is_width {
            re_width
        }
        else {
            re_matches_nothing
        };

        let caps = re.captures(line);

        if is_pluses {
            let num_pluses = ec::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 ec::bytes_from_string(caps.unwrap().name("bytes").unwrap().as_str()) {
                Ok(needle) => {
                    if let Some(offset) = ec::index_of_bytes(&needle, &state.all_bytes[state.index..], true) {
                        Ok(Command{
                            range: (state.index + offset, state.index + offset),
                            command: 'i',
                            args: vec![],
                        })
                    }
                    else {
                        Err(format!("{} not found", ec::string_from_bytes(&needle)))
                    }
                },
                Err(error) => {
                    Err(error)
                }
            }
        }

        else if is_search_kill {
            match ec::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) = ec::index_of_bytes(&needle, &state.all_bytes[state.index..], true) {
                        Ok(Command{
                            range: (state.index + offset, state.index + offset + needle_num_bytes - 1),
                            command: 'k',
                            args: vec![],
                        })
                    }
                    else {
                        Err(format!("{} not found", ec::string_from_bytes(&needle)))
                    }
                },
                Err(error) => {
                    Err(error)
                }
            }
        }

        else if is_search_again {
            if state.last_search.is_none() {
                return Err(format!("No previous search."));
            }

            let needle = state.last_search.to_owned().unwrap();

            let caps = caps.unwrap();
            let forward = caps.name("direction").unwrap().as_str() == "/";

            /* Notice looking after current byte */
            let haystack = if forward {
                &state.all_bytes[(state.index + 1)..]
            }
            else {
                &state.all_bytes[..(state.index.saturating_sub(1))]
            };

            if let Some(offset) = ec::index_of_bytes(&needle, haystack, forward) {
                if forward {
                    Ok(Command{
                        range: (state.index + 1 + offset, state.index + 1 + offset),
                        command: 'g',
                        args: vec![],
                    })
                }
                else {
                    Ok(Command{
                        range: (offset, offset),
                        command: 'g',
                        args: vec![],
                    })
                }
            }
            else {
                Err(format!("{} not found", ec::string_from_bytes(&needle)))
            }
        }

        else if is_search {
            let caps = caps.unwrap();
            let forward = caps.name("direction").unwrap().as_str() == "/";
            match ec::bytes_from_string(caps.name("bytes").unwrap().as_str()) {
                Ok(needle) => {
                    state.last_search = Some(needle.to_owned());

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

        else if is_minuses {
            let num_minuses = ec::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_before_context {
            let caps = caps.unwrap();
            let given = caps.name("before_context").unwrap().as_str();
            if let Ok(before_context) = usize::from_str_radix(given, state.prefs.radix) {
              Ok(Command{
                  range: (usize::from(before_context), usize::from(before_context)),
                  command: 'T',
                  args: vec![],
              })
            }
            else {
                Err(format!("Can't interpret {} as a number", given))
            }
        }

        else if is_after_context {
            let caps = caps.unwrap();
            let given = caps.name("after_context").unwrap().as_str();
            if let Ok(after_context) = usize::from_str_radix(given, state.prefs.radix) {
              Ok(Command{
                  range: (usize::from(after_context), usize::from(after_context)),
                  command: 't',
                  args: vec![],
              })
            }
            else {
                Err(format!("Can't interpret {} as a number", given))
            }
        }

        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.prefs.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.prefs.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.prefs.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.prefs.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' {
                            '☃'
                        }
                        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.prefs.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 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));
            }
        }
    }
}


/// 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;
        state.print_bytes();
        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;
                    state.print_bytes();
                    Ok(state.index)
                }
            },
            Err(error) => {
                Err(error)
            },
        }
    }
}


pub fn cargo_version() -> Result<String, String> {
    if let Some(version) = option_env!("CARGO_PKG_VERSION") {
        return Ok(String::from(version));
    }
    return Err("Version unknown (not compiled with cargo)".to_string());
}


pub fn update_filename(state: &mut ec::State) {
    let filename = ec::read_string_from_user(Some("Enter new filename: "));
    if filename.is_err() {
        println!("? {:?}", filename);
        return;
    }
    let filename = filename.unwrap();

    state.filename = filename;

    /* Nothing's been written to that file yet, so */
    state.unsaved_changes = true;
}


pub fn load_state_from_file(state: &mut ec::State) {
    let filename = ec::read_string_from_user(Some(
                    "Enter filename from which to load state: "));
    if filename.is_ok() {
        match State::read_from_filename(&filename.unwrap()) {
            Ok(new_state) => {
                *state = new_state;
            },
            Err(err) => {
                println!("? {}", err);
            }
        }
    }
    else {
        println!("? {:?}", filename);
    }
}


pub fn load_new_file(state: &mut ec::State) {
	if state.unsaved_changes {
		let unsaved_prompt = "You have unsaved changes.  Carry on? (y/n): ";
		println!("{}", unsaved_prompt);
		let yeses = vec!["y", "Y", "Yes", "yes"];
		let nos   = vec!["n", "N", "No",  "no"];
		let carry_on = loop {
			let carry_on_s = ec::read_string_from_user(Some(""));
			if carry_on_s.is_err() {
				println!("? {:?}", carry_on_s);
				return;
			}
			let carry_on_s = carry_on_s.unwrap();

			if yeses.contains(&carry_on_s.as_str()) {
				break true;
			}
			if nos.contains(&carry_on_s.as_str()) {
				break false;
			}
			println!("{}", unsaved_prompt);
		};
		if !carry_on {
			return;
		}
	}

    let filename = ec::read_string_from_user(Some(
            "Enter filename from which to load bytes: "));
    if filename.is_err() {
        println!("? {:?}", filename);
        return;
    }
    let filename = filename.unwrap();

    let maybe_all_bytes =
            ec::all_bytes_from_filename(&filename);
    if maybe_all_bytes.is_ok() {
        state.filename = filename;
        state.all_bytes = maybe_all_bytes.unwrap();
        return;
    }

    match maybe_all_bytes {
        Err(ec::AllBytesFromFilenameError::NotARegularFile) => {
            println!("? {} is not a regular file", filename);
        },
        Err(ec::AllBytesFromFilenameError::FileDoesNotExist) => {
            println!("? {} does not exist", filename);
            println!("Use 'u' to just change filename");
        },
        _ => {
            println!("? {:?}", maybe_all_bytes);
        },
    }
}


pub fn load_prefs(state: &mut ec::State) {
    let pref_path = ec::preferences_file_path();
    let filename = ec::read_string_from_user(Some(&format!(
            "Enter filename from which to load preferences [{}]: ",
                    pref_path.display())));
    if filename.is_ok() {
        let mut filename = filename.unwrap();
        if filename == "" {
            if let Some(pref_path_s) = pref_path.to_str() {
                filename = pref_path_s.to_owned();
            }
            else {
                println!("? Default path ({}) is not valid unicode.",
                        pref_path.display());
                return;
            }
        }

        let result = ec::Preferences::read_from_filename(&filename);
        if result.is_ok() {
            state.prefs = result.unwrap();
        }
        else {
            println!("? {:?}", result);
        }
    }
    else {
        println!("? {:?}", filename);
    }
}


pub fn write_out(state: &mut ec::State) {
    if state.readonly {
        println!("? Read-only mode");
        return;
    }
    
    /* Early return if write unsuccessful */
    if state.filename != "" {
        let result = std::fs::write(&state.filename, &state.all_bytes);
        if result.is_err() {
            println!("? (Couldn't write to {})", state.filename);
            return;
        }
    }
    else {
        let filename = ec::read_string_from_user(Some("Enter filename: "));
        if filename.is_err() {
            println!("? {:?}", filename);
            return;
        }
        let filename = filename.unwrap();

        /* filename is a string */
        let result = std::fs::write(&filename, &state.all_bytes);
        if result.is_err() {
            println!("? (Couldn't write to given filename '{}')", filename);
            return;
        }

        state.filename = filename;
        println!("Write successfull, changing filename to '{}'", state.filename);
    }

    state.unsaved_changes = false;
}


/// If `filename` is "", open an empty buffer
pub fn actual_runtime(filename:&str, pipe_mode:bool, color:bool, readonly:bool,
        prefs_path: PathBuf, state_path: PathBuf) -> i32 {
    let default_prefs = ec::Preferences {
        show_prompt: !pipe_mode,
        color: color,
        before_context: if pipe_mode {0} else {DEFAULT_BEFORE_CONTEXT},
        after_context: if pipe_mode {0} else {DEFAULT_AFTER_CONTEXT},
        ..ec::Preferences::default()
    };

    /* Use a state file if one is present */
    let maybe_state = ec::State::read_from_path(&state_path);
    let mut state = if maybe_state.is_ok() {
        maybe_state.unwrap()
    }
    else {
        ec::State {
            prefs: default_prefs,
            unsaved_changes: (filename == ""),
            filename: filename.to_owned(),
            readonly: readonly,
            index: 0,
            breaks: HashSet::new(),
            all_bytes: if filename == "" {
                Vec::new()
            }
            else {
                let maybe_all_bytes = ec::all_bytes_from_filename(filename);
                if maybe_all_bytes.is_ok() {
                    maybe_all_bytes.unwrap()
                }
                else {
                    match maybe_all_bytes {
                        Err(ec::AllBytesFromFilenameError::NotARegularFile) => {
                            println!("{} is not a regular file", filename);
                            return 1;
                        },
                        Err(ec::AllBytesFromFilenameError::FileDoesNotExist) => {
                            Vec::new()
                        },
                        _ => {
                            println!("Cannot read {}", filename);
                            return 1;
                        }
                    }
                }
            },
            last_search: None,
        }
    };

    /* Use a config file if one is present */
    if let Ok(prefs) = ec::Preferences::read_from_path(&prefs_path) {
        state.prefs = prefs;
    }

    if !pipe_mode {
        println!("{}", Color::Yellow.paint("h for help"));
        println!("\n{}", state);
        println!();
        state.print_bytes();
    }

    // TODO Below here should be a function called main_loop()
    loop {
        if state.prefs.show_prompt {
            print!("*");
        }
        io::stdout().flush().unwrap();
        let input = match ec::get_input_or_die() {
            Ok(input) => input,
            Err(errcode) => {
                return errcode;
            }
        };

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

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

                    /* Go to */
                    'g' => {
                        match ec::move_to(&mut state, command.range.0) {
                            Ok(_) => {
                                state.print_bytes();
                            },
                            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;
                                state.print_bytes_sans_context(state.range());
                            },
                            Err(error) => {
                                println!("? ({})", error);
                            },
                        }
                    },

                    /* Help */
                    'h' => {
                        print_help(&state);
                    },

                    /* User wants to go up a line */
                    'j' => {
                        if state.empty() {
                            println!("? (Empty file)");
                            continue;
                        };

                        let width = usize::from(state.prefs.width);
                        let first_byte_to_show_index =
                                state.index.saturating_sub(width);
                        state.index = first_byte_to_show_index;
                        state.print_bytes();
                    }


                    /* '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;
                        state.unsaved_changes = true;
                        state.print_bytes();
                    },


                    /* Load new file */
                    'l' => {
                        load_new_file(&mut state);
                    }

                    /* Load state from a file */
                    'L' => {
                        load_state_from_file(&mut state);
                    },

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

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

                    /* Toggle color */
                    'o' => {
                        state.prefs.color = !state.prefs.color;
                        if !pipe_mode {
                            if state.prefs.color {
                                println!("{} mode on", state.pretty_color_state());
                            }
                            else {
                                println!("No color mode");
                            }
                        }
                    },

                    /* Toggle underlining non-context line */
                    'U' => {
                        state.prefs.underline_main_line =
                                if state.prefs.underline_main_line {
                                    false
                                }
                                else {
                                    true
                                };
                    }


                    /* Insert a break in the display at current byte */
                    'v' => {
                        state.breaks.insert(state.index);
                    },

                    /* Remove a break in the display at current byte */
                    'V' => {
                        state.breaks.remove(&state.index);
                    },

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

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

                        state.move_index_then_print_bytes();
                    }

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

                        skip_bad_range!(command, state.all_bytes);
                        state.index = command.range.0;
                        state.print_bytes_and_move_index();
                    },

                    /* 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(new_index) =
                                state.print_bytes_sans_context(
                                (command.range.0, command.range.1)) {
                            state.index = new_index;
                        }
                        else {
                            println!("? (no bytes in range {:?})",
                                    command.range);
                        }
                    },

                    /* Save preferences to a file */
                    'P' => {
                        ec::save_to_path_or_default(&(state.prefs),
                                "Enter filename to save preferences",
                                ec::preferences_file_path());
                    },


                    /* Load preferences from a file */
                    'r' => {
                        load_prefs(&mut state);
                    },

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

                        state.print_bytes();
                    },

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

                    /* Toggle readonly mode */
                    'R' => {
                        state.readonly = !state.readonly;
                    },

                    /* Write state to a file */
                    'S' => {
                        ec::save_to_path_or_default(&state,
                                "Enter filename to save state",
                                ec::state_file_path());
                    },

                    /* Print state */
                    's' => {
                        println!("{}", state);
                    },

                    /* Change after_context */
                    't' => {
                        state.prefs.after_context = usize::from(command.range.0);
                    },

                    /* Change before_context */
                    'T' => {
                        state.prefs.before_context = usize::from(command.range.0);
                    },

                    /* (u)pdate iflename */
                    'u' => {
                        update_filename(&mut state);
                    },

                    /* Write out */
                    'w' => {
                        write_out(&mut state);
                    },

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

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