imzml 0.1.3

A library for reading the mass spectrometry (imaging) formats mzML and imzML.
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
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
use std::collections::VecDeque;
use std::fmt::Display;
use std::fs::File;
use std::io::BufReader;
use std::num::ParseIntError;
use std::path::{Path, PathBuf};
use std::str::Utf8Error;
//extern crate wasm_bindgen;
use std::borrow::Borrow;

use quick_xml::events::BytesStart;
use quick_xml::events::{attributes::Attribute, Event};

use crate::attributes::{AttributeValue, LIST_ATTRIBUTES};
use crate::data_processing::{DataProcessing, ProcessingMethod};
use crate::instrument::Component;
use crate::obo::ValueType;
use crate::obo::DEFAULT_ONTOLOGY;
use crate::sample::Sample;
use crate::scan::{Activation, IsolationWindow, Precursor, ScanWindow, SelectedIon};
use crate::scan_settings::ScanSettings;
use crate::{filedescription::SourceFile, obo::Ontology};
use crate::{Chromatogram, IndexedMzML};
use encoding_rs::Encoding;

use super::{
    binarydataarray::BinaryDataArray,
    filedescription::{Contact, FileDescription},
    instrument::InstrumentConfiguration,
    mzml::MzML,
    referenceableparamgroup::ReferenceableParamGroup,
    scan::{Scan, ScanList},
    software::Software,
    spectrum::Spectrum,
};

const BUF_SIZE: usize = 4096;

#[derive(Clone, Copy)]
pub enum ParserState {
    Start,
    Read(Tag),
    Processing,
    Error,
    FatalError, // Must stop here
    Finished,
}

//#[wasm_bindgen]
pub struct ImzMLParser<'a> {
    pub(super) state: ParserState,
    pub(super) breadcrumb: VecDeque<Tag>,
    pub(super) errors: VecDeque<ParseError>,

    pub(crate) ontology: &'a Ontology,

    //pub(crate) current_indexedmzml: Option<IndexedMzML>,
    pub(crate) current_mzml: Option<MzML<'a>>,

    pub(crate) ignore_uncommon_tags: bool,
    pub(crate) with_attribute_checks: bool,

    pub(super) current_referenceable_param_group: Option<ReferenceableParamGroup<'a>>,
    pub(crate) current_source_file: Option<SourceFile<'a>>,
    pub(crate) current_contact: Option<Contact<'a>>,
    pub(super) current_scan_settings: Option<ScanSettings<'a>>,
    pub(crate) current_sample: Option<Sample<'a>>,
    pub(super) current_spectrum: Option<Spectrum<'a>>,
    pub(super) current_chromatogram: Option<Chromatogram<'a>>,
    pub(crate) current_precursor: Option<Precursor<'a>>,
    pub(crate) current_isolation_window: Option<IsolationWindow<'a>>,
    pub(crate) current_selected_ion: Option<SelectedIon<'a>>,
    pub(crate) current_activation: Option<Activation<'a>>,
    pub(crate) current_software: Option<Software<'a>>,
    pub(crate) current_instrument_configuration: Option<InstrumentConfiguration<'a>>,
    pub(crate) current_component: Option<Component<'a>>,
    pub(crate) current_data_processing: Option<DataProcessing<'a>>,
    pub(crate) current_processing_method: Option<ProcessingMethod<'a>>,
    pub(super) current_scan: Option<Scan<'a>>,
    pub(super) current_scan_list: Option<ScanList<'a>>,
    pub(super) current_scan_window: Option<ScanWindow<'a>>,
    pub(super) current_binary_data_array: Option<BinaryDataArray<'a>>,
}

//#[wasm_bindgen]
pub fn parser_has_errors(parser: &ImzMLParser) -> bool {
    parser.has_errors()
}

impl<'a> ImzMLParser<'a> {
    fn new(ontology: &'a Ontology) -> Self {
        ImzMLParser {
            state: ParserState::Start,
            breadcrumb: std::collections::VecDeque::new(),
            //history: Vec::new(),
            errors: std::collections::VecDeque::new(),

            ontology,

            //current_indexedmzml: None,
            current_mzml: None,

            ignore_uncommon_tags: false,
            with_attribute_checks: false,

            current_referenceable_param_group: None,
            current_source_file: None,
            current_contact: None,
            current_scan_settings: None,
            current_sample: None,
            current_spectrum: None,
            current_chromatogram: None,
            current_precursor: None,
            current_isolation_window: None,
            current_selected_ion: None,
            current_activation: None,
            current_software: None,
            current_instrument_configuration: None,
            current_component: None,
            current_data_processing: None,
            current_processing_method: None,
            current_scan: None,
            current_scan_list: None,
            current_scan_window: None,
            current_binary_data_array: None,
        }
    }

    pub fn from_u8(
        data: &[u8],
        ontology: &'a Ontology,
    ) -> Result<ImzMLParser<'a>, FatalParseError> {
        let temp: String;

        let data = match std::str::from_utf8(data) {
            Ok(data) => data,
            Err(_) => {
                // Not UTF-8, so convert to ISO-8859-1
                temp = data.iter().map(|&c| c as char).collect();
                &temp
            }
        };

        ImzMLParser::from_str(data, ontology)
    }

    fn from_str(data: &str, ontology: &'a Ontology) -> Result<ImzMLParser<'a>, FatalParseError> {
        let mut parser = ImzMLParser::new(ontology);

        let mut reader = quick_xml::Reader::from_str(data);
        let encoding = reader.encoding();
        let mut buf = Vec::with_capacity(BUF_SIZE);

        loop {
            match reader.read_event(&mut buf) {
                Ok(event) => {
                    if let Event::Eof = &event {
                        break;
                    }

                    parser.process(encoding, event)?;
                }
                Err(error) => {
                    println!("An error occurred when reading: {}", error);
                    break;
                }
            }

            buf.clear();
        }

        Ok(parser)
    }

    pub fn from_file<P: AsRef<Path>>(
        path: P,
        ontology: Option<&'a Ontology>,
    ) -> Result<ImzMLParser<'a>, FatalParseError> {
        let ontology = match ontology {
            Some(ontology) => ontology,
            None => &DEFAULT_ONTOLOGY,
        };

        let mut path_buf: PathBuf = PathBuf::from(path.as_ref());
        path_buf.set_extension("ibd");

        let ibd_file = BufReader::new(File::open(path_buf).unwrap());

        let mut parser = ImzMLParser::new(ontology);

        match quick_xml::Reader::from_file(&path) {
            Ok(ref mut reader) => {
                let encoding = reader.encoding();
                let mut buf = Vec::with_capacity(BUF_SIZE);

                loop {
                    match reader.read_event(&mut buf) {
                        Ok(event) => {
                            if let Event::Eof = &event {
                                break;
                            }

                            parser.process(encoding, event)?;
                        }
                        Err(error) => {
                            println!(
                                "An error occurred when reading {}: {}",
                                path.as_ref().to_str().unwrap(),
                                error
                            );
                            break;
                        }
                    }

                    buf.clear();
                }
            }
            Err(error) => {
                println!(
                    "Failed to open file {}: {}",
                    path.as_ref().to_str().unwrap(),
                    error
                );
            }
        };

        Ok(parser)
    }

    pub fn current_state(&self) -> ParserState {
        self.state
    }

    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    pub fn pop_error_front(&mut self) -> Option<ParseError> {
        self.errors.pop_front()
    }

    pub fn pop_error_back(&mut self) -> Option<ParseError> {
        self.errors.pop_back()
    }

    pub fn errors(&self) -> &VecDeque<ParseError> {
        &self.errors
    }

    pub fn mzml(&mut self) -> Option<MzML<'a>> {
        self.current_mzml.take()
    }
}

//#[derive(Debug)]
//pub struct ParseError {}

/*pub(super) fn parse_u32(att: Attribute) -> Result<u32, std::num::ParseIntError> {
    std::str::from_utf8(att.value.borrow()).unwrap().parse()
    //u32::from_str_radix(std::str::from_utf8(att.value.borrow()).unwrap(), 10)
}

pub(super) fn parse_u64(att: Attribute) -> Result<u64, std::num::ParseIntError> {
    std::str::from_utf8(att.value.borrow()).unwrap().parse()
    //u64::from_str_radix(std::str::from_utf8(att.value.borrow()).unwrap(), 10)
}*/

pub(super) fn parse_usize(att: Attribute) -> Result<usize, std::num::ParseIntError> {
    std::str::from_utf8(att.value.borrow()).unwrap().parse()
    //usize::from_str_radix(std::str::from_utf8(att.value.borrow()).unwrap(), 10)
}

impl<'a> ImzMLParser<'a> {
    fn start_file(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"mzML" => self.start_mzml(e),
            // b"indexedmzML" => self.start_indexed_mzml(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag to start the file {:?}",
                    std::str::from_utf8(e.local_name())
                )))
            }
        }
    }

    // fn start_indexed_mzml(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
    //     for att in e.attributes().with_checks(self.with_attribute_checks) {
    //         match att {
    //             Ok(att) => match att.key {
    //                 b"xmlns" => {}
    //                 b"xmlns:xsi" => {}
    //                 b"xsi:schemaLocation" => {}
    //                 _ => {
    //                     self.errors.push_back(ParseError::UnexpectedAttribute((
    //                         Tag::MzML,
    //                         std::str::from_utf8(att.key).unwrap().to_string(),
    //                     )));
    //                 }
    //             },
    //             Err(error) => {
    //                 self.errors
    //                     .push_back(ParseError::XMLError((Tag::MzML, error)));
    //             }
    //         };
    //     }

    //     self.current_indexedmzml = Some(IndexedMzML::new());

    //     Ok(Tag::IndexedMzML)
    // }

    // pub(super) fn start_index_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
    //     let attributes = self.process_attributes(Tag::SourceFileRefList, &LIST_ATTRIBUTES, e);

    //     if let Some(&AttributeValue::Integer(count)) = attributes.get("count") {
    //         self.current_indexedmzml.as_mut().unwrap().index_list =
    //             Vec::with_capacity(count as usize);
    //     }

    //     Ok(Tag::IndexList)
    // }

    fn start_mzml(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        let mut accession = None;
        let mut id = None;
        let mut version = None;

        for att in e.attributes().with_checks(self.with_attribute_checks) {
            match att {
                Ok(att) => match att.key {
                    b"accession" => accession = Some(att.value),
                    b"id" => id = Some(att.value),
                    b"version" => version = Some(att.value),
                    b"xmlns" => {}
                    b"xmlns:xsi" => {}
                    b"xsi:schemaLocation" => {}
                    _ => {
                        self.errors.push_back(ParseError::UnexpectedAttribute((
                            Tag::MzML,
                            std::str::from_utf8(att.key).unwrap().to_string(),
                        )));
                    }
                },
                Err(error) => {
                    self.errors
                        .push_back(ParseError::XMLError((Tag::MzML, error)));
                }
            };
        }

        let mzml = match version {
            Some(version) => MzML::new(std::str::from_utf8(&version).unwrap(), self.ontology),
            None => {
                self.errors.push_back(ParseError::MissingAttribute((
                    Tag::MzML,
                    "version".to_string(),
                )));
                MzML::new("", self.ontology)
            }
        };

        self.current_mzml = Some(mzml);

        Ok(Tag::MzML)
    }

    fn process_indexed_mzml(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"mzML" => self.start_mzml(e),
            // b"indexList" => self.start_index_list(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in indexedMzML {}",
                    self.parse_string(Tag::IndexedMzML, e.local_name())
                )))
            }
        }
    }

    fn process_index_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            //b"index" => self.start_index(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in indexList {}",
                    self.parse_string(Tag::IndexList, e.local_name())
                )))
            }
        }
    }

    // Returns FatalParseError
    fn process_mzml(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        // cvList	1	1	Container for one or more controlled vocabulary definitions.
        // fileDescription	1	1	Information pertaining to the entire mzML file (i.e. not specific to any part of the data set) is stored here.
        // referenceableParamGroupList	0	1	Container for a list of referenceableParamGroups
        // sampleList	0	1	List and descriptions of samples.
        // softwareList	1	1	List and descriptions of software used to acquire and/or process the data in this mzML file.
        // scanSettingsList	0	1	List with the descriptions of the acquisition settings applied prior to the start of data acquisition.
        // instrumentConfigurationList	1	1	List and descriptions of instrument configurations. At least one instrument configuration MUST be specified, even if it is only to specify that the instrument is unknown. In that case, the "instrument model" term is used to indicate the unknown instrument in the instrumentConfiguration.
        // dataProcessingList	1	1	List and descriptions of data processing applied to this data.
        // run	1	1	A run in mzML should correspond to a single, consecutive and coherent set of scans on an instrument.
        match e.local_name() {
            b"cvList" => self.start_cv_list(e),
            b"fileDescription" => {
                self.current_mzml.as_mut().unwrap().file_description = Some(FileDescription::new());

                Ok(Tag::FileDescription)
            }
            b"referenceableParamGroupList" => self.start_referenceable_param_group_list(e),
            b"sampleList" => self.start_sample_list(e),
            b"softwareList" => self.start_software_list(e),
            b"scanSettingsList" => self.start_scan_settings_list(e),
            b"instrumentConfigurationList" => self.start_instrument_configuration_list(e),
            b"dataProcessingList" => self.start_data_processing_list(e),
            b"run" => self.start_run(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in mzML {}",
                    self.parse_string(Tag::MzML, e.local_name())
                )))
            }
        }
    }

    fn process_cv_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"cv" => self.start_cv(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in cvList {}",
                    self.parse_string(Tag::CVList, e.local_name())
                )))
            }
        }
    }

    fn process_file_description(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        // fileContent	1	1	This summarizes the different types of spectra that can be expected in the file. This is expected to aid processing software in skipping files that do not contain appropriate spectrum types for it. It should also describe the nativeID format used in the file by referring to an appropriate CV term.
        // sourceFileList	0	1	List and descriptions of the source files this mzML document was generated or derived from
        // contact	0	unlim	Structure allowing the use of a controlled (cvParam) or uncontrolled vocabulary (userParam), or a reference to a predefined set of these in this mzML file (paramGroupRef).

        match e.local_name() {
            b"fileContent" => Ok(Tag::FileContent),
            b"sourceFileList" => self.start_source_file_list(e),
            b"contact" => {
                self.current_contact = Some(Contact::new());

                Ok(Tag::Contact)
            }
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in fileDescription {}",
                    self.parse_string(Tag::FileDescription, e.local_name())
                )))
            }
        }
    }

    fn process_params(
        &mut self,
        encoding: &'static Encoding,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"referenceableParamGroupRef" => self.start_referenceable_param_group_ref(e),
            b"cvParam" => self.start_cv_param(encoding, e),
            b"userParam" => self.start_user_param(encoding, e),
            _ => {
                // Return the current tag as we don't know how to handle this
                let tag = *self.breadcrumb.back().unwrap();

                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in {:?} {}",
                    tag,
                    self.parse_string(tag, e.local_name())
                )))
            }
        }
    }

    fn process_source_file_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"sourceFile" => self.start_source_file(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in sourceFileList {}",
                    self.parse_string(Tag::SourceFileList, e.local_name())
                )))
            }
        }
    }

    fn process_source_file_ref_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"sourceFileRef" => self.start_source_file_ref(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in sourceFileRefList {}",
                    self.parse_string(Tag::SourceFileRefList, e.local_name())
                )))
            }
        }
    }

    fn process_referanceable_param_group_list(
        &mut self,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"referenceableParamGroup" => self.start_referenceable_param_group(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in referenceableParamGroupList {}",
                    self.parse_string(Tag::RefParamGroupList, e.local_name())
                )))
            }
        }
    }

    fn process_param_group(
        &mut self,
        encoding: &'static Encoding,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        // cvParam	0	unlim	This element holds additional data or annotation. Only controlled values are allowed here.
        //userParam	0	unlim	Uncontrolled user parameters (essentially allowing free text). Before using these, one should verify whether there is an appropriate CV term available, and if so, use the CV term instead

        match e.local_name() {
            b"cvParam" => self.start_cv_param(encoding, e),
            b"userParam" => self.start_user_param(encoding, e),
            _ => {
                let tag = *self.breadcrumb.back().unwrap();

                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in {:?} {}",
                    tag,
                    self.parse_string(tag, e.local_name())
                )))
            }
        }
    }

    fn process_sample_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"sample" => self.start_sample(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in sampleList {}",
                    self.parse_string(Tag::SampleList, e.local_name())
                )))
            }
        }
    }

    fn process_software_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"software" => self.start_software(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in softwareList {}",
                    self.parse_string(Tag::SoftwareList, e.local_name())
                )))
            }
        }
    }

    fn process_scan_settings_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"scanSettings" => self.start_scan_settings(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in scanSettingsList {}",
                    self.parse_string(Tag::ScanSettingsList, e.local_name())
                )))
            }
        }
    }

    fn process_scan_settings(
        &mut self,
        encoding: &'static Encoding,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        //referenceableParamGroupRef	0	unlim	A reference to a previously defined ParamGroup, which is a reusable container of one or more cvParams.
        //cvParam	0	unlim	This element holds additional data or annotation. Only controlled values are allowed here.
        //userParam	0	unlim	Uncontrolled user parameters (essentially allowing free text). Before using these, one should verify whether there is an appropriate CV term available, and if so, use the CV term instead
        //sourceFileRefList	0	1	List with the source files containing the acquisition settings.
        //targetList	0	1	Target list (or 'inclusion list') configured prior to the run.

        match e.local_name() {
            b"referenceableParamGroupRef" => self.start_referenceable_param_group_ref(e),
            b"cvParam" => self.start_cv_param(encoding, e),
            b"userParam" => self.start_user_param(encoding, e),
            b"sourceFileRefList" => self.start_source_file_ref_list(e),
            b"targetList" => todo!(),
            _ => {
                let tag = *self.breadcrumb.back().unwrap();

                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in {:?} {}",
                    tag,
                    self.parse_string(tag, e.local_name())
                )))
            }
        }
    }

    fn process_instrument_configuration_list(
        &mut self,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"instrumentConfiguration" => self.start_instrument_configuration(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in instrumentConfigurationList {}",
                    self.parse_string(Tag::InstrumentConfigurationList, e.local_name())
                )))
            }
        }
    }

    fn process_instrument_configuration(
        &mut self,
        encoding: &'static Encoding,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        // referenceableParamGroupRef	0	unlim	A reference to a previously defined ParamGroup, which is a reusable container of one or more cvParams.
        // cvParam	0	unlim	This element holds additional data or annotation. Only controlled values are allowed here.
        // userParam	0	unlim	Uncontrolled user parameters (essentially allowing free text). Before using these, one should verify whether there is an appropriate CV term available, and if so, use the CV term instead
        // componentList	0	1	List with the different components used in the mass spectrometer. At least one source, one mass analyzer and one detector need to be specified.
        // softwareRef	0	1	Reference to a previously defined software element

        match e.local_name() {
            b"referenceableParamGroupRef" => self.start_referenceable_param_group_ref(e),
            b"cvParam" => self.start_cv_param(encoding, e),
            b"userParam" => self.start_user_param(encoding, e),
            b"componentList" => self.start_component_list(e),
            b"softwareRef" => self.start_software_ref(e),
            _ => {
                let tag = *self.breadcrumb.back().unwrap();

                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in {:?} {}",
                    tag,
                    self.parse_string(tag, e.local_name())
                )))
            }
        }
    }

    fn process_component_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"source" | b"analyzer" | b"detector" => self.start_component(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in componentList {}",
                    self.parse_string(Tag::ComponentList, e.local_name())
                )))
            }
        }
    }

    fn process_data_processing_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"dataProcessing" => self.start_data_processing(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in dataProcessingList {}",
                    self.parse_string(Tag::DataProcessingList, e.local_name())
                )))
            }
        }
    }

    fn process_data_processing(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"processingMethod" => self.start_processing_method(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in dataProcessing {}",
                    self.parse_string(Tag::DataProcessing, e.local_name())
                )))
            }
        }
    }

    fn process_run(
        &mut self,
        encoding: &'static Encoding,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        // referenceableParamGroupRef	0	unlim	A reference to a previously defined ParamGroup, which is a reusable container of one or more cvParams.
        // cvParam	0	unlim	This element holds additional data or annotation. Only controlled values are allowed here.
        // userParam	0	unlim	Uncontrolled user parameters (essentially allowing free text). Before using these, one should verify whether there is an appropriate CV term available, and if so, use the CV term instead
        // spectrumList	0	1	All mass spectra and the acquisitions underlying them are described and attached here. Subsidiary data arrays are also both described and attached here.
        // chromatogramList	0	1	All chromatograms for this run.

        match e.local_name() {
            b"referenceableParamGroupRef" => self.start_referenceable_param_group_ref(e),
            b"cvParam" => self.start_cv_param(encoding, e),
            b"userParam" => self.start_user_param(encoding, e),
            b"spectrumList" => self.start_spectrum_list(e),
            b"chromatogramList" => self.start_chromatogram_list(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in run {}",
                    self.parse_string(Tag::Run, e.local_name())
                )))
            }
        }
    }

    fn process_spectrum_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"spectrum" => self.start_spectrum(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in spectrumList {}",
                    self.parse_string(Tag::SpectrumList, e.local_name())
                )))
            }
        }
    }

    fn process_spectrum(
        &mut self,
        encoding: &'static Encoding,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        // referenceableParamGroupRef	0	unlim	A reference to a previously defined ParamGroup, which is a reusable container of one or more cvParams.
        // cvParam	0	unlim	This element holds additional data or annotation. Only controlled values are allowed here.
        // userParam	0	unlim	Uncontrolled user parameters (essentially allowing free text). Before using these, one should verify whether there is an appropriate CV term available, and if so, use the CV term instead
        // scanList	0	1	List and descriptions of scans.
        // precursorList	0	1	List and descriptions of precursor isolations to the spectrum currently being described, ordered.
        // productList	0	1	List and descriptions of product isolations to the spectrum currently being described, ordered.
        // binaryDataArrayList	0	1	List of binary data arrays.

        match e.local_name() {
            b"referenceableParamGroupRef" => self.start_referenceable_param_group_ref(e),
            b"cvParam" => self.start_cv_param(encoding, e),
            b"userParam" => self.start_user_param(encoding, e),
            b"scanList" => {
                self.current_scan_list = Some(ScanList::new(1));
                Ok(Tag::ScanList)
            }
            b"precursorList" => self.start_precursor_list(e),
            b"productList" => todo!(),
            b"binaryDataArrayList" => self.start_binary_data_array_list(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in spectrum {}",
                    self.parse_string(Tag::Spectrum, e.local_name())
                )))
            }
        }
    }

    fn process_chromatogram_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"chromatogram" => self.start_chromatogram(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in chromatogramList {}",
                    self.parse_string(Tag::ChromatogramList, e.local_name())
                )))
            }
        }
    }

    fn process_chromatogram(
        &mut self,
        encoding: &'static Encoding,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        // referenceableParamGroupRef	0	unlim	A reference to a previously defined ParamGroup, which is a reusable container of one or more cvParams.
        // cvParam	0	unlim	This element holds additional data or annotation. Only controlled values are allowed here.
        // userParam	0	unlim	Uncontrolled user parameters (essentially allowing free text). Before using these, one should verify whether there is an appropriate CV term available, and if so, use the CV term instead
        // precursor	0	1	The method of precursor ion selection and activation
        // product	0	1	The method of product ion selection and activation in a precursor ion scan
        // binaryDataArrayList	1	1	List of binary data arrays.

        match e.local_name() {
            b"referenceableParamGroupRef" => self.start_referenceable_param_group_ref(e),
            b"cvParam" => self.start_cv_param(encoding, e),
            b"userParam" => self.start_user_param(encoding, e),
            b"precursor" => self.start_precursor(e),
            b"product" => todo!(),
            b"binaryDataArrayList" => self.start_binary_data_array_list(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in chromatogram {}",
                    self.parse_string(Tag::Spectrum, e.local_name())
                )))
            }
        }
    }

    fn process_scan_list(
        &mut self,
        encoding: &'static Encoding,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        // referenceableParamGroupRef	0	unlim	A reference to a previously defined ParamGroup, which is a reusable container of one or more cvParams.
        // cvParam	0	unlim	This element holds additional data or annotation. Only controlled values are allowed here.
        // userParam	0	unlim	Uncontrolled user parameters (essentially allowing free text). Before using these, one should verify whether there is an appropriate CV term available, and if so, use the CV term instead
        // scan	0	1	List and descriptions of scans.

        match e.local_name() {
            b"referenceableParamGroupRef" => self.start_referenceable_param_group_ref(e),
            b"cvParam" => self.start_cv_param(encoding, e),
            b"userParam" => self.start_user_param(encoding, e),
            b"scan" => self.start_scan(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in scanList {}",
                    self.parse_string(Tag::ScanList, e.local_name())
                )))
            }
        }
    }

    fn process_scan(
        &mut self,
        encoding: &'static Encoding,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        // referenceableParamGroupRef	0	unlim	A reference to a previously defined ParamGroup, which is a reusable container of one or more cvParams.
        // cvParam	0	unlim	This element holds additional data or annotation. Only controlled values are allowed here.
        // userParam	0	unlim	Uncontrolled user parameters (essentially allowing free text). Before using these, one should verify whether there is an appropriate CV term available, and if so, use the CV term instead
        // scanWindowList	0	1	Container for a list of scan windows.

        match e.local_name() {
            b"referenceableParamGroupRef" => self.start_referenceable_param_group_ref(e),
            b"cvParam" => self.start_cv_param(encoding, e),
            b"userParam" => self.start_user_param(encoding, e),
            b"scanWindowList" => self.start_scan_window_list(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in scan {}",
                    self.parse_string(Tag::Scan, e.local_name())
                )))
            }
        }
    }

    fn process_scan_window_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"scanWindow" => self.start_scan_window(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in scanWindowList {}",
                    self.parse_string(Tag::ScanWindowList, e.local_name())
                )))
            }
        }
    }

    fn process_scan_window(
        &mut self,
        encoding: &'static Encoding,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"referenceableParamGroupRef" => self.start_referenceable_param_group_ref(e),
            b"cvParam" => self.start_cv_param(encoding, e),
            b"userParam" => self.start_user_param(encoding, e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in scanWindow {}",
                    self.parse_string(Tag::ScanWindow, e.local_name())
                )))
            }
        }
    }

    fn process_precursor_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"precursor" => self.start_precursor(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in precursorList {}",
                    self.parse_string(Tag::PrecursorList, e.local_name())
                )))
            }
        }
    }

    fn process_precursor(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        // isolationWindow	0	1	This element captures the isolation (or 'selection') window configured to isolate one or more ions.
        // selectedIonList	0	1	A list of ions that were selected.
        // activation	1	1	The type and energy level used for activation.

        match e.local_name() {
            b"isolationWindow" => self.start_isolation_window(e),
            b"selectedIonList" => self.start_selected_ion_list(e), //self.start_selected_ion_list(e),
            b"activation" => self.start_activation(e),             //self.start_activation(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in precursor {}",
                    self.parse_string(Tag::Precursor, e.local_name())
                )))
            }
        }
    }

    fn process_selected_ion_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"selectedIon" => self.start_selected_ion(e),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in selectedIonList {}",
                    self.parse_string(Tag::SelectedIonList, e.local_name())
                )))
            }
        }
    }

    fn process_selected_ion(
        &mut self,
        encoding: &'static Encoding,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        //referenceableParamGroupRef	0	unlim	A reference to a previously defined ParamGroup, which is a reusable container of one or more cvParams.
        //cvParam	0	unlim	This element holds additional data or annotation. Only controlled values are allowed here.
        //userParam	0	unlim	Uncontrolled user parameters (essentially allowing free text). Before using these, one should verify whether there is an appropriate CV term available, and if so, use the CV term instead

        match e.local_name() {
            b"referenceableParamGroupRef" => self.start_referenceable_param_group_ref(e),
            b"cvParam" => self.start_cv_param(encoding, e),
            b"userParam" => self.start_user_param(encoding, e),
            _ => {
                let tag = *self.breadcrumb.back().unwrap();

                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in {:?} {}",
                    tag,
                    self.parse_string(tag, e.local_name())
                )))
            }
        }
    }

    fn process_activation(
        &mut self,
        encoding: &'static Encoding,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        //referenceableParamGroupRef	0	unlim	A reference to a previously defined ParamGroup, which is a reusable container of one or more cvParams.
        //cvParam	0	unlim	This element holds additional data or annotation. Only controlled values are allowed here.
        //userParam	0	unlim	Uncontrolled user parameters (essentially allowing free text). Before using these, one should verify whether there is an appropriate CV term available, and if so, use the CV term instead

        match e.local_name() {
            b"referenceableParamGroupRef" => self.start_referenceable_param_group_ref(e),
            b"cvParam" => self.start_cv_param(encoding, e),
            b"userParam" => self.start_user_param(encoding, e),
            _ => {
                let tag = *self.breadcrumb.back().unwrap();

                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in {:?} {}",
                    tag,
                    self.parse_string(tag, e.local_name())
                )))
            }
        }
    }

    fn process_isolation_window(
        &mut self,
        encoding: &'static Encoding,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        //referenceableParamGroupRef	0	unlim	A reference to a previously defined ParamGroup, which is a reusable container of one or more cvParams.
        //cvParam	0	unlim	This element holds additional data or annotation. Only controlled values are allowed here.
        //userParam	0	unlim	Uncontrolled user parameters (essentially allowing free text). Before using these, one should verify whether there is an appropriate CV term available, and if so, use the CV term instead

        match e.local_name() {
            b"referenceableParamGroupRef" => self.start_referenceable_param_group_ref(e),
            b"cvParam" => self.start_cv_param(encoding, e),
            b"userParam" => self.start_user_param(encoding, e),
            _ => {
                let tag = *self.breadcrumb.back().unwrap();

                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in {:?} {}",
                    tag,
                    self.parse_string(tag, e.local_name())
                )))
            }
        }
    }

    fn process_binary_data_array_list(&mut self, e: &BytesStart) -> Result<Tag, FatalParseError> {
        match e.local_name() {
            b"binaryDataArray" => {
                self.current_binary_data_array = Some(BinaryDataArray::new());
                Ok(Tag::BinaryDataArray)
            }
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in binaryDataArrayList {}",
                    self.parse_string(Tag::BinaryDataArrayList, e.local_name())
                )))
            }
        }
    }

    fn process_binary_data_array(
        &mut self,
        encoding: &'static Encoding,
        e: &BytesStart,
    ) -> Result<Tag, FatalParseError> {
        // referenceableParamGroupRef	0	unlim	A reference to a previously defined ParamGroup, which is a reusable container of one or more cvParams.
        // cvParam	0	unlim	This element holds additional data or annotation. Only controlled values are allowed here.
        // userParam	0	unlim	Uncontrolled user parameters (essentially allowing free text). Before using these, one should verify whether there is an appropriate CV term available, and if so, use the CV term instead
        // scanWindowList	0	1	Container for a list of scan windows.

        match e.local_name() {
            b"referenceableParamGroupRef" => self.start_referenceable_param_group_ref(e),
            b"cvParam" => self.start_cv_param(encoding, e),
            b"userParam" => self.start_user_param(encoding, e),
            b"binary" => Ok(Tag::Binary),
            _ => {
                // Return the current tag as we don't know how to handle this
                Err(FatalParseError::UnexpectedTag(format!(
                    "Unexpected tag in binaryDataArray {}",
                    self.parse_string(Tag::BinaryDataArray, e.local_name())
                )))
            }
        }
    }

    pub fn process(
        &mut self,
        encoding: &'static Encoding,
        ev: Event,
    ) -> Result<(), FatalParseError> {
        match &ev {
            Event::Start(e) | Event::Empty(e) => {
                //println!("Start: {:?}", self.breadcrumb);

                let current_tag = match self.breadcrumb.is_empty() {
                    true => self.start_file(e)?,
                    false => match self.breadcrumb.back() {
                        Some(tag) => match tag {
                            Tag::IndexedMzML => self.process_indexed_mzml(e),
                            Tag::MzML => self.process_mzml(e),
                            Tag::CVList => self.process_cv_list(e),
                            Tag::FileDescription => self.process_file_description(e),
                            Tag::FileContent => self.process_params(encoding, e),
                            Tag::SourceFileList => self.process_source_file_list(e),
                            Tag::SourceFile => self.process_params(encoding, e),
                            Tag::SourceFileRefList => self.process_source_file_ref_list(e),
                            Tag::Contact => self.process_params(encoding, e),
                            Tag::RefParamGroupList => {
                                self.process_referanceable_param_group_list(e)
                            }
                            Tag::RefParamGroup => self.process_param_group(encoding, e),
                            Tag::SampleList => self.process_sample_list(e),
                            Tag::Sample => self.process_params(encoding, e),
                            Tag::SoftwareList => self.process_software_list(e),
                            Tag::Software => self.process_params(encoding, e),
                            Tag::ScanSettingsList => self.process_scan_settings_list(e),
                            Tag::ScanSettings => self.process_scan_settings(encoding, e),
                            Tag::InstrumentConfigurationList => {
                                self.process_instrument_configuration_list(e)
                            }
                            Tag::InstrumentConfiguration => {
                                self.process_instrument_configuration(encoding, e)
                            }
                            Tag::ComponentList => self.process_component_list(e),
                            Tag::Component => self.process_params(encoding, e),
                            Tag::DataProcessingList => self.process_data_processing_list(e),
                            Tag::DataProcessing => self.process_data_processing(e),
                            Tag::ProcessingMethod => self.process_params(encoding, e),
                            Tag::Run => self.process_run(encoding, e),
                            Tag::SpectrumList => self.process_spectrum_list(e),
                            Tag::Spectrum => self.process_spectrum(encoding, e),
                            Tag::ScanList => self.process_scan_list(encoding, e),
                            Tag::Scan => self.process_scan(encoding, e),
                            Tag::ScanWindowList => self.process_scan_window_list(e),
                            Tag::ScanWindow => self.process_scan_window(encoding, e),
                            Tag::BinaryDataArrayList => self.process_binary_data_array_list(e),
                            Tag::BinaryDataArray => self.process_binary_data_array(encoding, e),
                            Tag::PrecursorList => self.process_precursor_list(e),
                            Tag::Precursor => self.process_precursor(e),
                            Tag::SelectedIonList => self.process_selected_ion_list(e),
                            Tag::SelectedIon => self.process_selected_ion(encoding, e),
                            Tag::Activation => self.process_activation(encoding, e),
                            Tag::IsolationWindow => self.process_isolation_window(encoding, e),
                            Tag::ChromatogramList => self.process_chromatogram_list(e),
                            Tag::Chromatogram => self.process_chromatogram(encoding, e),
                            Tag::IndexList => self.process_index_list(e),
                            _ => {
                                panic!("Unexpected tag {:?}: {:?}", tag, self.breadcrumb);
                            }
                        },
                        None => panic!("Parser in corrupt state"),
                    }?,
                };

                // Only add to breadcrumb if not an empty tag
                if let Event::Start(_e) = &ev {
                    self.breadcrumb.push_back(current_tag);
                }
            }
            Event::End(e) => {
                // Remove the last tag
                //println!("{:?}", self.breadcrumb);
                self.breadcrumb.pop_back();

                match e.local_name() {
                    //b"spectrumList" => self.end_spectrum_list(e),
                    b"binaryDataArray" => self.end_binary_data_array(),
                    b"binaryDataArrayList" => ParserState::Processing,
                    b"scanList" => self.end_scan_list(),
                    b"scan" => self.end_scan(),
                    b"spectrum" => self.end_spectrum(),
                    b"scanSettings" => self.end_scan_settings(),
                    b"scanSettingsList" => ParserState::Processing,
                    b"software" => self.end_software(),
                    b"softwareList" => ParserState::Processing,
                    b"cvList" => ParserState::Processing,
                    b"instrumentConfiguration" => self.end_instrument_configuration(),
                    b"instrumentConfigurationList" => ParserState::Processing,
                    b"componentList" => ParserState::Processing,
                    b"source" => self.end_component(e),
                    b"analyzer" => self.end_component(e),
                    b"detector" => self.end_component(e),
                    b"processingMethod" => self.end_processing_method(),
                    b"dataProcessing" => self.end_data_processing(),
                    b"dataProcessingList" => ParserState::Processing,
                    b"spectrumList" => ParserState::Processing,
                    b"sample" => self.end_sample(),
                    b"sampleList" => ParserState::Processing,
                    b"sourceFile" => self.end_source_file(),
                    b"sourceFileList" => ParserState::Processing,
                    b"contact" => self.end_contact(),
                    b"fileContent" => ParserState::Processing,
                    b"fileDescription" => ParserState::Processing,
                    b"referenceableParamGroup" => self.end_referenceable_param_group(),
                    b"referenceableParamGroupList" => ParserState::Processing,
                    b"scanWindow" => ParserState::Processing,
                    b"scanWindowList" => ParserState::Processing,
                    b"run" => ParserState::Processing,
                    b"mzML" => ParserState::Processing,
                    _ => match std::str::from_utf8(e.local_name()) {
                        Ok(name) => {
                            self.errors.push_back(ParseError::UnexpectedTag(format!(
                                "end tag {:?}: {:?}",
                                name, self.breadcrumb
                            )));
                            self.state
                        }
                        Err(error) => {
                            println!("Failed to convert tag name: {}", error);

                            ParserState::FatalError
                        }
                    },
                };
            }

            _ => {}
        };

        Ok(())
    }
}