bader 0.5.0

Multi-threaded Bader Charge Analysis
Documentation
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
use crate::{
    errors::ArgumentError,
    hash::SliceMap,
    io::{FileType, WriteType, cube::Cube, vasp::Vasp},
};
use std::fmt::{Debug, Display, Write};
use std::thread::available_parallelism;

/// Indicates how many reference files are passed
#[derive(Clone)]
pub enum Reference {
    /// One file as a reference, usually either a CHGCAR_sum or spin.cube.
    One(String),
    /// Two files as a reference, these files will be summed together.
    Two(String, String),
    /// No reference, just use the density file.
    None,
}

/// Defualt values for arguments.
#[derive(Debug)]
enum DefaultValue {
    /// None
    None,
    /// Integer
    Int(usize),
    /// Float
    Float(f64),
}

/// Allowed values for arguments.
#[derive(Debug)]
enum AllowedValue {
    /// Anything
    None,
    /// Specific list
    Strs(Vec<String>),
}

/// The validated configuration for a Bader analysis run.
///
/// This struct is produced by `App::parse_args` and contains all the settings required
/// to execute the analysis, including file paths, thread counts, and physical tolerances.
#[derive(Debug)]
struct Arg {
    /// Name of the argument.
    name: String,
    /// Text displayed as help for the argument when -h is passed.
    short_help: String,
    /// Text displayed as help for the argument when --help is passed.
    long_help: String,
    /// Single character for flag e.g. -h.
    short_flag: char,
    /// Longer flag e.g. --help.
    long_flag: String,
    /// Whether the argument takes a value.
    takes_value: bool,
    /// Whether the argument takes multiple values
    multiple_values: bool,
    /// Whether the argument had a default value and if so what it is.
    default_value: DefaultValue,
    /// Whether to restrict the argument to specific values and if so what they are.
    allowed_values: AllowedValue,
}

/// The main configuration parser for the application.
///
/// This struct defines the available command-line arguments and handles the logic
/// for parsing the raw argument vector into a structured `Args` object.
///
/// # Logic
/// It supports:
/// * **Short Flags**: Single character (e.g., `-h`).
/// * **Long Flags**: Full name (e.g., `--help`).
/// * **Clusters**: Combining boolean short flags (e.g., `-xvi` equivalent to `-x -v ...`).
/// * **Positional Arguments**: Identifying the input filename amidst flags.
///
/// # Examples
/// ```
/// use bader::arguments::App;
///
/// let app = App::new();
/// let args = vec!["bca", "CHGCAR", "-t", "4"];
/// let parsed = app.parse_args(args).expect("Failed to parse args");
///
/// assert_eq!(parsed.file, "CHGCAR");
/// assert_eq!(parsed.threads, 4);
/// ```
pub struct App {
    /// What arguments it can take, [OPTIONS] in the help.
    options: Vec<Arg>,
    /// The help specific argument.
    help: Arg,
    /// The longest argument name's size.
    max_width: usize,
}

impl App {
    pub fn new() -> Self {
        // Start options
        let options = vec![
            Arg{
                name: String::from("aec"),
                short_help: String::from("Convience flag for reading both AECCARs."),
                long_help: String::from("
\tFlag for reading and summing both the AECCAR0 and AECCAR2 from a VASP calculation"),
                short_flag: 'a',
                long_flag: String::from("aec"),
                takes_value: false,
                multiple_values: false,
                default_value: DefaultValue::None,
                allowed_values: AllowedValue::None,
            },
            Arg {
                name: String::from("file type"),
                short_help: String::from("File containing spin density."),
                long_help: String::from("
\tA path to the spin density associated with the original file. This is primarily
\tfor cube files as if spin density exists in a CHGCAR it will be read automatically.
\tIf using with VASP outputs then the files for charge and spin density must only
\tcontain a single density (ie. the original file has been split)."),
                short_flag: 'f',
                long_flag: String::from("file_type"),
                takes_value: true,
                multiple_values: false,
                default_value: DefaultValue::None,
                allowed_values: AllowedValue::Strs(vec![String::from("cube"), String::from("vasp")]),
            },
            Arg {
                name: String::from("index"),
                short_help: String::from("Index of Bader atoms to be written out."),
                long_help: String::from("
\tAn index of a Bader atom to be written out, starting at 1. This flag requires
\tthe output flag to be set. Multiple atoms can only be written by repeating the
\tflag ie. bca CHGCAR -oi 1 -i 2."),
                short_flag: 'i',
                long_flag: String::from("index"),
                takes_value: true,
                multiple_values: true,
                default_value: DefaultValue::None,
                allowed_values: AllowedValue::None,
            },
            Arg {
                name: String::from("maximum distance"),
                short_help: String::from("Cut-off after which an error will be thrown for distance of Bader maximum to atom."),
                long_help: String::from("
\tThe distance allowed between Bader maximum and its associated atom, in angstrom, before
\tan error is thrown. This will cause a hard crash of the program, consider whether
\tincreasing the cut-off or adding a \"ghost atom\" at the location of the Bader
\tmaximum is more appropriate."),
                short_flag: 'm',
                long_flag: String::from("max_dist"),
                takes_value: true,
                multiple_values: false,
                default_value: DefaultValue::Float(1.0),
                allowed_values: AllowedValue::None,
            },
            Arg {
                name: String::from("output"),
                short_help: String::from("Output the Bader atoms."),
                long_help: String::from("
\tOutput the bader atoms in the same file format as the input density.
\tthis can be used in conjunction with the index flag to specify a
\tspecific atom. without the index flag it will print all the atoms."),
                short_flag: 'o',
                long_flag: String::from("output"),
                takes_value: false,
                multiple_values: false,
                default_value: DefaultValue::None,
                allowed_values: AllowedValue::None,
            },
            Arg {
                name: String::from("reference"),
                short_help: String::from("File(s) containing reference charge."),
                long_help: String::from("
\tA reference charge to do the partitioning upon. Two files can be passed
\tby using multiple flags (bca CHGCAR -r AECCAR0 -r AECCAR2). If two files are
\tpassed they are summed together."),
                short_flag: 'r',
                long_flag: String::from("ref"),
                takes_value: true,
                multiple_values: true,
                default_value: DefaultValue::None,
                allowed_values: AllowedValue::None,
            },
            Arg {
                name: String::from("silent"),
                short_help: String::from("Whether to display any output."),
                long_help: String::from("
\tRuns the program without displaying any output text or progress bars."),
                short_flag: 'x',
                long_flag: String::from("silent"),
                takes_value: false,
                multiple_values: false,
                default_value: DefaultValue::None,
                allowed_values: AllowedValue::None,
            },
            Arg {
                name: String::from("self bonding"),
                short_help: String::from("Whether to include self bonding in the critical point analysis."),
                long_help: String::from("
\tSelf bonds are removed in the pruning step by default, this option will leave them in."),
                short_flag: 'b',
                long_flag: String::from("bond"),
                takes_value: false,
                multiple_values: false,
                default_value: DefaultValue::None,
                allowed_values: AllowedValue::None,
            },
            Arg {
                name: String::from("spin"),
                short_help: String::from("File containing spin density."),
                long_help: String::from("
\tA path to the spin density associated with the original file. This is primarily
\tfor cube files as if spin density exists in a CHGCAR it will be read automatically.
\tIf using with VASP outputs then the files for charge and spin density must only
\tcontain a single density (ie. the original file has been split)."),
                short_flag: 's',
                long_flag: String::from("spin"),
                takes_value: true,
                multiple_values: false,
                default_value: DefaultValue::None,
                allowed_values: AllowedValue::None,
            },
            Arg {
                name: String::from("threads"),
                short_help: String::from("Number of threads to distribute the calculation over."),
                long_help: String::from("
\tThe number of threads to be used by the program. A default value of 0 is used
\tto allow the program to best decide how to use the available hardware. It does
\tthis by using the minimum value out of the number cores available and 12."),
                short_flag: 't',
                long_flag: String::from("threads"),
                takes_value: true,
                multiple_values: false,
                default_value: DefaultValue::Int(0),
                allowed_values: AllowedValue::None,
            },
            Arg {
                name: String::from("vacuum tolerance"),
                short_help: String::from("Cut-off at which charge is considered vacuum."),
                long_help: String::from("
\tValues of density below the supplied value are considered vacuum and are not
\tincluded in the calculation."),
                short_flag: 'v',
                long_flag: String::from("vac"),
                takes_value: true,
                multiple_values: false,
                default_value: DefaultValue::Float(1E-6),
                allowed_values: AllowedValue::None,
            },
            Arg {
                name: String::from("weight tolerance"),
                short_help: String::from("Cut-off at which contributions to the weighting will be ignored."),
                long_help: String::from("
\tValues of density below the supplied value are ignored from the weighting and
\tincluded in the calculation. By raising the tolerance the calculation speed can
\tbe increased but every ignored weight is unaccounted for in the final partitions.
\tBe sure to test this!"),
                short_flag: 'w',
                long_flag: String::from("weight"),
                takes_value: true,
                multiple_values: false,
                default_value: DefaultValue::Float(1E-6),
                allowed_values: AllowedValue::None,
            }
        ];
        // End options
        let help = Arg {
            name: String::from("help"),
            short_help: String::from("Print help (see more with '--help')"),
            long_help: String::from("Print help (see a summary with '-h')"),
            short_flag: 'h',
            long_flag: String::from("help"),
            takes_value: false,
            multiple_values: false,
            default_value: DefaultValue::None,
            allowed_values: AllowedValue::None,
        };
        let max_width = options
            .iter()
            .map(|o| {
                1 + o.long_flag.len()
                    + if o.takes_value { 7 + o.name.len() } else { 4 }
            })
            .max()
            .unwrap_or(0);
        Self {
            options,
            help,
            max_width,
        }
    }

    /// Get the text for all the options either in short or long format.
    fn get_options_text(&self, long: bool) -> String {
        self.options.iter().fold(String::new(), |mut output, o| {
            let _ = writeln!(
                output,
                " {:<width$}{}{}{}",
                // the short and long flag
                if o.takes_value {
                    format!("-{},--{} [{}]", o.short_flag, o.long_flag, o.name)
                } else {
                    format!("-{},--{}", o.short_flag, o.long_flag)
                },
                // the help text
                if long {
                    o.long_help.to_string()
                } else {
                    format!("  {}", o.short_help)
                },
                // does it have a default value
                match o.default_value {
                    DefaultValue::None =>
                        if long {
                            String::from("\n")
                        } else {
                            String::with_capacity(0)
                        },
                    DefaultValue::Int(u) =>
                        if long {
                            format!("\n\n\t[default: {}]\n", u)
                        } else {
                            format!(" [default: {}]", u)
                        },
                    DefaultValue::Float(f) =>
                        if long {
                            format!("\n\n\t[default: {}]\n", f)
                        } else {
                            format!(" [default: {}]", f)
                        },
                },
                // does it have allowed values
                match &o.allowed_values {
                    AllowedValue::None => String::with_capacity(0),
                    AllowedValue::Strs(v) =>
                        if long {
                            format!("\n\t[possible values: {:?}]\n", v)
                        } else {
                            format!(" [possible values: {:?}]", v)
                        },
                },
                width = self.max_width
            );
            output
        })
    }

    /// Get the help text in long or short formats.
    fn get_help_text(&self, long: bool) -> String {
        format!(
            " {:<width$}{}",
            format!("-{},--{}", self.help.short_flag, self.help.long_flag),
            if long {
                format!("\n\t{}", self.help.long_help)
            } else {
                format!("  {}", self.help.short_help)
            },
            width = self.max_width
        )
    }

    /// Get the `Arg` from a supplied short flag.
    fn get_option_from_short_flag(
        &self,
        f: char,
    ) -> Result<&Arg, ArgumentError<'_>> {
        if f == self.help.short_flag {
            return Err(ArgumentError::ShortHelp(self));
        }
        for opt in self.options.iter() {
            if f == opt.short_flag {
                return Ok(opt);
            }
        }
        Err(ArgumentError::NotFlag(f.to_string()))
    }

    /// Get the `Arg` from a supplied long flag.
    fn get_option_from_long_flag(
        &self,
        f: String,
    ) -> Result<&Arg, ArgumentError<'_>> {
        if f == self.help.long_flag {
            return Err(ArgumentError::LongHelp(self));
        }
        for opt in self.options.iter() {
            if f == opt.long_flag {
                return Ok(opt);
            }
        }
        Err(ArgumentError::NotFlag(f))
    }

    /// Parse arguments from flags and values.
    pub fn parse_args(
        &self,
        args: Vec<&str>,
    ) -> Result<Args, ArgumentError<'_>> {
        let mut arguments = SliceMap::<String, String>::default();
        let mut multi_arguments = SliceMap::<String, Vec<String>>::default();
        args.iter().enumerate()
                   .try_for_each(|(i, flag)| {
                       match flag.strip_prefix('-') {
                           // starts with - so is arg
                           Some(stripped_flag) => {
                               // longer than 1 char after being stripped means either cluster
                               // of flags or long flag
                               match stripped_flag.len().cmp(&1) {
                                   std::cmp::Ordering::Greater => match stripped_flag.strip_prefix('-') {
                                       // matches - again is long flag
                                       Some(long_flag) => {
                                           match self.get_option_from_long_flag(long_flag.to_string()) {
                                               // if it's in the argument list we are good and
                                               // just need to check if it takes values
                                               Ok(o) => {if o.takes_value {
                                                   let value = match args.get(i + 1) {
                                                       Some(v) => v.to_string(),
                                                       None => return Err(ArgumentError::NoValue(long_flag.to_string())),
                                                   };
                                                   if o.multiple_values {
                                                       let key = multi_arguments.entry(o.name.to_string()).or_insert(vec![]);
                                                       key.push(value);
                                                   } else {
                                                       arguments.insert(o.name.to_string(), value);
                                                   }
                                               } else {
                                                   arguments.insert(o.name.to_string(), String::with_capacity(0));
                                               };
                                               Ok(())},
                                               // else it isn't an argument
                                               Err(e) => Err(e),
                                           }
                                       },
                                       // doesn't match again so is cluster of short flags
                                       None => {
                                           stripped_flag.chars().try_for_each(|f| match self.get_option_from_short_flag(f) {
                                               // if it's in the argument list we are good and
                                               // just need to check if it takes values
                                               Ok(o) => {if o.takes_value {
                                                   let value = match args.get(i + 1) {
                                                       Some(v) => v.to_string(),
                                                       None => return Err(ArgumentError::NoValue(f.to_string())),
                                                   };
                                                   if o.multiple_values {
                                                       let key = multi_arguments.entry(o.name.to_string()).or_insert(vec![]);
                                                       key.push(value);
                                                   } else {
                                                       arguments.insert(o.name.to_string(), value);
                                                   }
                                               } else {
                                                   arguments.insert(o.name.to_string(), String::with_capacity(0));
                                               };
                                               Ok(())},
                                               // else it isn't an argument
                                               Err(e) => Err(e),
                                           })
                                       },
                                   },
                               // is 1 in length so short flag
                               std::cmp::Ordering::Equal => {
                                   let f = stripped_flag.chars().nth(0).unwrap();
                                   match self.get_option_from_short_flag(f) {
                                       // if it's in the argument list we are good and just
                                       // need to check if it takes values
                                       Ok(o) => {if o.takes_value {
                                           let value = match args.get(i + 1) {
                                               Some(v) => v.to_string(),
                                               None => return Err(ArgumentError::NoValue(stripped_flag.to_string())),
                                           };
                                           if o.multiple_values {
                                               let key = multi_arguments.entry(o.name.to_string()).or_insert(vec![]);
                                               key.push(value);
                                           } else {
                                               arguments.insert(o.name.to_string(), value);
                                           }
                                       } else {
                                           arguments.insert(o.name.to_string(), String::with_capacity(0));
                                       };
                                       Ok(())},
                                       // else it isn't an argument
                                       Err(e) => Err(e),
                                   }
                               },
                               std::cmp::Ordering::Less => Err(ArgumentError::NotFlag("-".to_string()))
                               }
                           },
                           None => Ok(()),
                       }
                   })?;
        let mut file = String::with_capacity(0);
        args.windows(2).for_each(|window| {
            let flag = window[0].to_string();
            let arg = window[1].to_string();
            // doesn't start with - so could be out file
            if !arg.starts_with('-') {
                match flag.strip_prefix('-') {
                    // previous argument does start with - so we need to check if it is a passed value
                    Some(short_flag) => match short_flag.strip_prefix('-') {
                        Some(long_flag) => {
                            if !self
                                .get_option_from_long_flag(
                                    long_flag.to_string(),
                                )
                                .unwrap()
                                .takes_value
                            {
                                file = arg;
                            }
                        }
                        None => {
                            if short_flag.len() > 1 {
                                let mut takes_value_flag = false;
                                for f in short_flag.chars() {
                                    if self
                                        .get_option_from_short_flag(f)
                                        .unwrap()
                                        .takes_value
                                    {
                                        takes_value_flag = true;
                                        break;
                                    }
                                }
                                if !takes_value_flag {
                                    file = arg;
                                }
                            } else if !self
                                .get_option_from_short_flag(
                                    // this should have a flag bu if not pass something that won't
                                    // be matched by any flag
                                    short_flag.chars().nth(0).unwrap_or(','),
                                )
                                .unwrap()
                                .takes_value
                            {
                                file = arg;
                            }
                        }
                    },
                    None => file = arg,
                }
            }
        });
        if file.is_empty() {
            return Err(ArgumentError::NoFile(self));
        }
        let file_type = match arguments.get("file type") {
            Some(ftype) => {
                let ftype = ftype.to_lowercase();
                if ftype.eq("cube") {
                    FileType::Cube(Cube {})
                } else if ftype.eq("vasp") {
                    FileType::Vasp(Vasp {})
                } else {
                    return Err(ArgumentError::NotValidValue(
                        String::from("file type"),
                        ftype,
                    ));
                }
            }
            None => parse_filetype(&file),
        };
        let weight_tolerance = match arguments.get("weight tolerance") {
            Some(w) => match w.parse::<f64>() {
                Ok(f) => f,
                Err(_) => {
                    return Err(ArgumentError::Unparsable(
                        String::from("weight tolerance"),
                        w.to_string(),
                        String::from("f64"),
                    ));
                }
            },
            None => match self
                .get_option_from_short_flag('w')
                .unwrap()
                .default_value
            {
                DefaultValue::Float(f) => f,
                _ => panic!(""),
            },
        };
        let maximum_distance = match arguments.get("maximum distance") {
            Some(m) => match m.parse::<f64>() {
                Ok(f) => f,
                Err(_) => {
                    return Err(ArgumentError::Unparsable(
                        String::from("maximum distance"),
                        m.to_string(),
                        String::from("f64"),
                    ));
                }
            },
            None => match self
                .get_option_from_short_flag('m')
                .unwrap()
                .default_value
            {
                DefaultValue::Float(f) => f,
                _ => panic!(""),
            },
        };
        let vacuum_tolerance = match arguments.get("vacuum tolerance") {
            Some(m) => match m.parse::<f64>() {
                Ok(f) => f,
                Err(_) => {
                    return Err(ArgumentError::Unparsable(
                        String::from("vacuum tolerance"),
                        m.to_string(),
                        String::from("f64"),
                    ));
                }
            },
            None => match self
                .get_option_from_short_flag('v')
                .unwrap()
                .default_value
            {
                DefaultValue::Float(f) => f,
                _ => panic!(""),
            },
        };
        let mut threads = match arguments.get("threads") {
            Some(t) => match t.parse::<usize>() {
                Ok(f) => f,
                Err(_) => {
                    return Err(ArgumentError::Unparsable(
                        String::from("threads"),
                        t.to_string(),
                        String::from("usize"),
                    ));
                }
            },
            None => match self
                .get_option_from_short_flag('t')
                .unwrap()
                .default_value
            {
                DefaultValue::Int(u) => u,
                _ => panic!(""),
            },
        };
        if threads == 0 {
            threads = match available_parallelism() {
                Ok(u) => u.get().min(12),
                Err(_) => todo!(),
            };
        }
        let output = match arguments.get("output") {
            Some(_) => match multi_arguments.get("index") {
                Some(v) => {
                    let mut a = Vec::with_capacity(v.len());
                    for i in v.iter() {
                        match i.parse::<isize>() {
                            Ok(i) => a.push(i - 1),
                            Err(_) => {
                                return Err(ArgumentError::Unparsable(
                                    String::from("index"),
                                    i.to_string(),
                                    String::from("isize"),
                                ));
                            }
                        }
                    }
                    WriteType::Atom(a)
                }
                None => WriteType::Atom(Vec::with_capacity(0)),
            },
            None => match multi_arguments.get("index") {
                Some(_) => {
                    return Err(ArgumentError::MissingDependant(
                        String::from("index"),
                        String::from("output"),
                    ));
                }
                None => WriteType::None,
            },
        };
        let reference = match multi_arguments.get("reference") {
            Some(v) => match v.len().cmp(&2) {
                std::cmp::Ordering::Less => Reference::One(v[0].to_string()),
                std::cmp::Ordering::Equal => {
                    Reference::Two(v[0].to_string(), v[1].to_string())
                }
                std::cmp::Ordering::Greater => {
                    return Err(ArgumentError::TooManyValues(
                        String::from("reference"),
                        2,
                        v.len(),
                    ));
                }
            },
            None => match arguments.get("aec") {
                Some(_) => match file_type {
                    FileType::Vasp(_) => Reference::Two(
                        String::from("AECCAR0"),
                        String::from("AECCAR2"),
                    ),
                    FileType::Cube(_) => {
                        return Err(ArgumentError::WrongFileType(
                            String::from("aec"),
                            String::from("cube"),
                        ));
                    }
                },
                None => Reference::None,
            },
        };
        let spin = arguments.get("spin").cloned();
        let silent = arguments.contains_key("silent");
        let self_bond = arguments.contains_key("self bonding");
        Ok(Args {
            file,
            file_type,
            weight_tolerance,
            maximum_distance,
            output,
            reference,
            self_bond,
            silent,
            spin,
            threads,
            vacuum_tolerance,
        })
    }
}

// To make clippy happy.
impl Default for App {
    fn default() -> Self {
        Self::new()
    }
}

impl Display for App {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let usage = String::from("Usage: bca [OPTIONS] <file>");
        let arguments =
            String::from("Arguments:\n <file>  The file to analyse.");
        let options = self.get_options_text(false);
        let help = self.get_help_text(false);
        write!(
            f,
            "{}\n\n{}\n\nOptions:\n{}{}",
            usage, arguments, options, help
        )
    }
}

impl Debug for App {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let usage = String::from("Usage: bca [OPTIONS] <file>");
        let arguments = String::from(
            "Arguments:\n <file>  The file containing the charge density to analyse.",
        );
        let options = self.get_options_text(true);
        let help = self.get_help_text(true);
        write!(
            f,
            "{}\n\n{}\n\nOptions:\n{}{}",
            usage, arguments, options, help
        )
    }
}

/// Holds the arguments passed to the program from the command-line
pub struct Args {
    /// The filename.
    pub file: String,
    /// The file format.
    pub file_type: FileType,
    /// Tolerance to disregard weights at.
    pub weight_tolerance: f64,
    /// Tolerance to disregard maxima at.
    pub maximum_distance: f64,
    /// Output Writing
    pub output: WriteType,
    /// Is there a reference file.
    pub reference: Reference,
    /// Should self bonds be included.
    pub self_bond: bool,
    /// Should the program be ran silently.
    pub silent: bool,
    /// Is there a spin density to include as well.
    pub spin: Option<String>,
    /// How many threads to use in the calculation.
    pub threads: usize,
    /// Is there a tolerance to consider a density vacuum.
    pub vacuum_tolerance: f64,
}

/// Parse the file type from the filename.
pub fn parse_filetype(fname: &str) -> FileType {
    let f = fname.to_lowercase();
    if f.contains("cube") {
        FileType::Cube(Cube {})
    } else if f.contains("car") {
        FileType::Vasp(Vasp {})
    } else {
        eprintln!("Cannot detect file type, attempting to read as VASP.");
        FileType::Vasp(Vasp {})
    }
}

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

    #[test]
    fn argument_file() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR"];
        let args = app.parse_args(v).unwrap();
        assert_eq!(args.file, String::from("CHGCAR"));
    }

    #[test]
    #[should_panic]
    fn argument_no_file() {
        let app = App::new();
        let _ = app
            .parse_args(vec!["bca"])
            .unwrap_or_else(|e| panic!("An error occurs: {}", e));
    }

    #[test]
    fn argument_file_type_default_vasp() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR"];
        let args = app.parse_args(v).unwrap();
        let flag = matches!(args.file_type, FileType::Vasp(_));
        assert!(flag);
    }

    #[test]
    fn argument_file_type_default_unknown() {
        let app = App::new();
        let v = vec!["bca", "CHG"];
        let args = app.parse_args(v).unwrap();
        let flag = matches!(args.file_type, FileType::Vasp(_));
        assert!(flag);
    }

    #[test]
    fn argument_file_type_vasp() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "-f", "vasp"];
        let args = app.parse_args(v).unwrap();
        let flag = matches!(args.file_type, FileType::Vasp(_));
        assert!(flag);
    }

    #[test]
    fn argument_file_type_default_cube() {
        let app = App::new();
        let v = vec!["bca", "charge.cube"];
        let args = app.parse_args(v).unwrap();
        let flag = matches!(args.file_type, FileType::Cube(_));
        assert!(flag);
    }

    #[test]
    fn argument_file_type_cube() {
        let app = App::new();
        let v = vec!["bca", "charge.cube", "--file_type", "cube"];
        let args = app.parse_args(v).unwrap();
        let flag = matches!(args.file_type, FileType::Cube(_));
        assert!(flag);
    }

    #[test]
    #[should_panic]
    fn argument_file_type_not_type() {
        let app = App::new();
        let _ = app
            .parse_args(vec!["bca", "CHGCAR", "-f", "basp"])
            .unwrap_or_else(|e| panic!("An error occurs: {}", e));
    }

    #[test]
    fn argument_output_atoms() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "-o"];
        let args = app.parse_args(v).unwrap();
        match args.output {
            WriteType::Atom(v) => assert!(v.is_empty()),
            _ => panic!(),
        }
    }

    #[test]
    fn argument_output_index() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "-o", "-i", "1"];
        let args = app.parse_args(v).unwrap();
        match args.output {
            WriteType::Atom(v) => assert_eq!(v, vec![0]),
            _ => panic!(),
        }
    }

    #[test]
    fn argument_output_mult_index() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "-o", "--index", "1", "-i", "3"];
        let args = app.parse_args(v).unwrap();
        match args.output {
            WriteType::Atom(v) => assert_eq!(v, vec![0, 2]),
            _ => panic!(),
        }
    }

    #[test]
    #[should_panic]
    fn argument_index_no_output() {
        let app = App::new();
        let _ = app
            .parse_args(vec!["bca", "CHGCAR", "-i", "1"])
            .unwrap_or_else(|e| panic!("An error occurs: {}", e));
    }

    #[test]
    #[should_panic]
    fn argument_index_not_parse() {
        let app = App::new();
        let _ = app
            .parse_args(vec!["bca", "CHGCAR", "-oi", "1,6"])
            .unwrap_or_else(|e| panic!("An error occurs: {}", e));
    }

    #[test]
    fn argument_spin() {
        let app = App::new();
        let v = vec!["bca", "density.cube", "-s", "spin.cube"];
        let args = app.parse_args(v).unwrap();
        assert_eq!(args.spin, Some(String::from("spin.cube")))
    }

    #[test]
    fn argument_reference_one() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "-r", "CHGCAR_sum"];
        let args = app.parse_args(v).unwrap();
        let flag = matches!(args.reference, Reference::One(_));
        assert!(flag)
    }

    #[test]
    fn argument_reference_two() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "-r", "AECCAR0", "--ref", "AECCAR2"];
        let args = app.parse_args(v).unwrap();
        let flag = matches!(args.reference, Reference::Two(_, _));
        assert!(flag)
    }

    #[test]
    fn argument_reference_none() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR"];
        let args = app.parse_args(v).unwrap();
        let flag = matches!(args.reference, Reference::None);
        assert!(flag)
    }

    #[test]
    fn argument_aeccar() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "-a"];
        let args = app.parse_args(v).unwrap();
        let flag = match args.reference {
            Reference::Two(x, y) => (x == *"AECCAR0") && (y == *"AECCAR2"),
            _ => false,
        };
        assert!(flag)
    }

    #[test]
    #[should_panic]
    fn argument_aeccar_cube() {
        let app = App::new();
        let v = vec!["bca", "charge.cube", "-a"];
        let _ = app.parse_args(v).unwrap();
    }

    #[test]
    fn argument_vacuum_tolerance_float() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "--vac", "1E-4"];
        let args = app.parse_args(v).unwrap();
        assert_eq!(args.vacuum_tolerance, 1E-4)
    }

    #[test]
    fn argument_vacuum_tolerance_default() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR"];
        let args = app.parse_args(v).unwrap();
        assert_eq!(args.vacuum_tolerance, 1E-6)
    }

    #[test]
    #[should_panic]
    fn argument_vacuum_tolerance_not_float() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "--vac", "0.00.1"];
        let _ = app
            .parse_args(v)
            .unwrap_or_else(|e| panic!("An error occurs: {}", e));
    }

    #[test]
    fn argument_weight_tolerance_float() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "--weight", "1E-4"];
        let args = app.parse_args(v).unwrap();
        assert_eq!(args.weight_tolerance, 1E-4)
    }

    #[test]
    #[should_panic]
    fn argument_weight_tolerance_not_float() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "-w", "0.00.1"];
        let _ = app
            .parse_args(v)
            .unwrap_or_else(|e| panic!("An error occurs: {}", e));
    }

    #[test]
    fn argument_maximum_distance_float() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "--max_dist", "1E-4"];
        let args = app.parse_args(v).unwrap();
        assert_eq!(args.maximum_distance, 1E-4)
    }

    #[test]
    #[should_panic]
    fn argument_maximum_distance_not_float() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "-m", "0.00.1"];
        let _ = app
            .parse_args(v)
            .unwrap_or_else(|e| panic!("An error occurs: {}", e));
    }

    #[test]
    fn argument_threads_default() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR"];
        let args = app.parse_args(v).unwrap();
        let threads = available_parallelism().unwrap().get().min(12);
        assert_eq!(args.threads, threads)
    }

    #[test]
    fn argument_threads_int() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "--threads", "1"];
        let args = app.parse_args(v).unwrap();
        assert_eq!(args.threads, 1)
    }

    #[test]
    #[should_panic]
    fn argument_threads_not_int() {
        let app = App::new();
        let v = vec!["bca", "CHGCAR", "-t", "0.1"];
        let _ = app
            .parse_args(v)
            .unwrap_or_else(|e| panic!("An error occurs: {}", e));
    }

    #[test]
    fn test_app_creation() {
        let app = App::new();
        assert!(!app.options.is_empty());
    }

    #[test]
    fn test_positional_file_parsing() {
        let app = App::new();
        // File at end
        let v1 = vec!["bca", "-t", "4", "CHGCAR"];
        let args1 = app.parse_args(v1).unwrap();
        assert_eq!(args1.file, "CHGCAR");
        assert_eq!(args1.threads, 4);

        // File in middle
        let v2 = vec!["bca", "-t", "2", "CHGCAR", "-x"];
        let args2 = app.parse_args(v2).unwrap();
        assert_eq!(args2.file, "CHGCAR");
        assert_eq!(args2.threads, 2);

        // File at start
        let v2 = vec!["bca", "CHGCAR", "-t", "2"];
        let args2 = app.parse_args(v2).unwrap();
        assert_eq!(args2.file, "CHGCAR");
        assert_eq!(args2.threads, 2);
    }

    #[test]
    fn test_short_flag_cluster() {
        let app = App::new();
        // -x (silent), -a (aec) are booleans.
        // We can combine them: -xa
        let v = vec!["bca", "CHGCAR", "-xa"];

        let args = app.parse_args(v).unwrap();
        match args.reference {
            Reference::Two(a, b) => {
                assert_eq!(a, "AECCAR0");
                assert_eq!(b, "AECCAR2");
            }
            _ => panic!("Expected AECCAR reference from -a flag"),
        }
    }
}