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
use std::collections::{BTreeMap, HashMap};
use std::io::prelude::*;
use thiserror::Error;

#[cfg(feature = "serde")]
use serde::Serialize;

use super::{
    antex, clocks,
    gnss_time::GnssTime,
    hatanaka::{Compressor, Decompressor},
    header, ionex, is_comment, merge,
    merge::Merge,
    meteo, navigation, observation,
    reader::BufferedReader,
    split,
    split::Split,
    types::Type,
    writer::BufferedWriter,
    *,
};
use hifitime::Duration;

#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub enum Record {
    /// ATX record, see [antex::record::Record]
    AntexRecord(antex::Record),
    /// Clock record, see [clocks::record::Record]
    ClockRecord(clocks::Record),
    /// IONEX (Ionosphere maps) record, see [ionex::record::Record]
    IonexRecord(ionex::Record),
    /// Meteo record, see [meteo::record::Record]
    MeteoRecord(meteo::Record),
    /// Navigation record, see [navigation::record::Record]
    NavRecord(navigation::Record),
    /// Observation record, see [observation::record::Record]
    ObsRecord(observation::Record),
}

/// Record comments are high level informations, sorted by epoch
/// (timestamp) of appearance. We deduce the "associated" timestamp from the
/// previosuly parsed epoch, when parsing the record.
pub type Comments = BTreeMap<Epoch, Vec<String>>;

impl Record {
    /// Unwraps self as ANTEX record
    pub fn as_antex(&self) -> Option<&antex::Record> {
        match self {
            Record::AntexRecord(r) => Some(r),
            _ => None,
        }
    }
    /// Unwraps self as mutable reference to ANTEX record
    pub fn as_mut_antex(&mut self) -> Option<&mut antex::Record> {
        match self {
            Record::AntexRecord(r) => Some(r),
            _ => None,
        }
    }
    /// Unwraps self as CLK record
    pub fn as_clock(&self) -> Option<&clocks::Record> {
        match self {
            Record::ClockRecord(r) => Some(r),
            _ => None,
        }
    }
    /// Unwraps self as mutable CLK record
    pub fn as_mut_clock(&mut self) -> Option<&mut clocks::Record> {
        match self {
            Record::ClockRecord(r) => Some(r),
            _ => None,
        }
    }
    /// Unwraps self as IONEX record
    pub fn as_ionex(&self) -> Option<&ionex::Record> {
        match self {
            Record::IonexRecord(r) => Some(r),
            _ => None,
        }
    }
    /// Unwraps self as mutable IONEX record
    pub fn as_mut_ionex(&mut self) -> Option<&mut ionex::Record> {
        match self {
            Record::IonexRecord(r) => Some(r),
            _ => None,
        }
    }
    /// Unwraps self as MET record
    pub fn as_meteo(&self) -> Option<&meteo::Record> {
        match self {
            Record::MeteoRecord(r) => Some(r),
            _ => None,
        }
    }
    /// Returns mutable reference to Meteo record
    pub fn as_mut_meteo(&mut self) -> Option<&mut meteo::Record> {
        match self {
            Record::MeteoRecord(r) => Some(r),
            _ => None,
        }
    }
    /// Unwraps self as NAV record
    pub fn as_nav(&self) -> Option<&navigation::Record> {
        match self {
            Record::NavRecord(r) => Some(r),
            _ => None,
        }
    }
    /// Returns mutable reference to Navigation record
    pub fn as_mut_nav(&mut self) -> Option<&mut navigation::Record> {
        match self {
            Record::NavRecord(r) => Some(r),
            _ => None,
        }
    }
    /// Unwraps self as OBS record
    pub fn as_obs(&self) -> Option<&observation::Record> {
        match self {
            Record::ObsRecord(r) => Some(r),
            _ => None,
        }
    }
    /// Returns mutable reference to Observation record
    pub fn as_mut_obs(&mut self) -> Option<&mut observation::Record> {
        match self {
            Record::ObsRecord(r) => Some(r),
            _ => None,
        }
    }
    /// Streams into given file writer
    pub fn to_file(
        &self,
        header: &header::Header,
        writer: &mut BufferedWriter,
    ) -> Result<(), Error> {
        match &header.rinex_type {
            Type::MeteoData => {
                let record = self.as_meteo().unwrap();
                for (epoch, data) in record.iter() {
                    if let Ok(epoch) = meteo::record::fmt_epoch(epoch, data, header) {
                        let _ = write!(writer, "{}", epoch);
                    }
                }
            },
            Type::ObservationData => {
                let record = self.as_obs().unwrap();
                let obs_fields = &header.obs.as_ref().unwrap();
                let mut compressor = Compressor::new();
                for ((epoch, flag), (clock_offset, data)) in record.iter() {
                    let epoch =
                        observation::record::fmt_epoch(*epoch, *flag, clock_offset, data, header);
                    if let Some(_) = &obs_fields.crinex {
                        let major = header.version.major;
                        let constell = &header.constellation.as_ref().unwrap();
                        for line in epoch.lines() {
                            let line = line.to_owned() + "\n"; // helps the following .lines() iterator
                                                               // embedded in compression method
                            if let Ok(compressed) =
                                compressor.compress(major, &obs_fields.codes, constell, &line)
                            {
                                write!(writer, "{}", compressed)?;
                            }
                        }
                    } else {
                        write!(writer, "{}", epoch)?;
                    }
                }
            },
            Type::NavigationData => {
                let record = self.as_nav().unwrap();
                for (epoch, frames) in record.iter() {
                    if let Ok(epoch) = navigation::record::fmt_epoch(epoch, frames, header) {
                        let _ = write!(writer, "{}", epoch);
                    }
                }
            },
            Type::ClockData => {
                if let Some(r) = self.as_clock() {
                    for (epoch, data) in r {
                        if let Ok(epoch) = clocks::record::fmt_epoch(epoch, data) {
                            let _ = write!(writer, "{}", epoch);
                        }
                    }
                }
            },
            Type::IonosphereMaps => {
                if let Some(r) = self.as_ionex() {
                    for (index, (epoch, (_map, _, _))) in r.iter().enumerate() {
                        let _ = write!(writer, "{:6}                                                      START OF TEC MAP", index);
                        let _ = write!(
                            writer,
                            "{}                        EPOCH OF CURRENT MAP",
                            epoch::format(*epoch, None, Type::IonosphereMaps, 1)
                        );
                        let _ = write!(writer, "{:6}                                                      END OF TEC MAP", index);
                    }
                    /*
                     * not efficient browsing, but matches provided examples and common formatting.
                     * RMS and Height maps are passed after TEC maps.
                     */
                    for (index, (epoch, (_, _map, _))) in r.iter().enumerate() {
                        let _ = write!(writer, "{:6}                                                      START OF RMS MAP", index);
                        let _ = write!(
                            writer,
                            "{}                        EPOCH OF CURRENT MAP",
                            epoch::format(*epoch, None, Type::IonosphereMaps, 1)
                        );
                        let _ = write!(writer, "{:6}                                                      END OF RMS MAP", index);
                    }
                    for (index, (epoch, (_, _, _map))) in r.iter().enumerate() {
                        let _ = write!(writer, "{:6}                                                      START OF HEIGHT MAP", index);
                        let _ = write!(
                            writer,
                            "{}                        EPOCH OF CURRENT MAP",
                            epoch::format(*epoch, None, Type::IonosphereMaps, 1)
                        );
                        let _ = write!(writer, "{:6}                                                      END OF HEIGHT MAP", index);
                    }
                }
            },
            _ => panic!("record type not supported yet"),
        }
        Ok(())
    }
}

impl Default for Record {
    fn default() -> Record {
        Record::NavRecord(navigation::Record::new())
    }
}

#[derive(Error, Debug)]
pub enum Error {
    #[error("record parsing not supported for type \"{0}\"")]
    TypeError(String),
    #[error("file i/o error")]
    FileIoError(#[from] std::io::Error),
    #[error("failed to produce Navigation epoch")]
    NavEpochError(#[from] navigation::Error),
    #[error("failed to produce Clock epoch")]
    ClockEpochError(#[from] clocks::Error),
}

/// Returns true if given line matches the start   
/// of a new epoch, inside a RINEX record.
pub fn is_new_epoch(line: &str, header: &header::Header) -> bool {
    if is_comment!(line) {
        return false;
    }
    match &header.rinex_type {
        Type::AntennaData => antex::record::is_new_epoch(line),
        Type::ClockData => clocks::record::is_new_epoch(line),
        Type::IonosphereMaps => ionex::record::is_new_map(line),
        Type::NavigationData => navigation::record::is_new_epoch(line, header.version),
        Type::ObservationData => observation::record::is_new_epoch(line, header.version),
        Type::MeteoData => meteo::record::is_new_epoch(line, header.version),
    }
}

/// Builds a `Record`, `RINEX` file body content,
/// which is constellation and `RINEX` file type dependent
pub fn parse_record(
    reader: &mut BufferedReader,
    header: &mut header::Header,
) -> Result<(Record, Comments), Error> {
    let mut first_epoch = true;
    let mut content = String::default();
    let mut epoch_content = String::with_capacity(6 * 64);

    // to manage `record` comments
    let mut comments: Comments = Comments::new();
    let mut comment_ts = Epoch::default();
    let mut comment_content: Vec<String> = Vec::with_capacity(4);

    let mut decompressor = Decompressor::new();
    // record
    let mut atx_rec = antex::Record::new(); // ATX
    let mut nav_rec = navigation::Record::new(); // NAV
    let mut obs_rec = observation::Record::new(); // OBS
    let mut met_rec = meteo::Record::new(); // MET
    let mut clk_rec = clocks::Record::new(); // CLK

    // IONEX case
    //  Default map type is TEC, it will come with identified Epoch
    //  but others may exist:
    //    in this case we used the previously identified Epoch
    //    and attach other kinds of maps
    let mut ionx_rms = false;
    let mut ionx_height = false;
    let mut ionx_rec = ionex::Record::new();
    // we need to store encountered epochs, to relate RMS and H maps
    //    that might be provided in a separate sequence
    let mut ionx_epochs: Vec<Epoch> = Vec::with_capacity(128);

    for l in reader.lines() {
        // iterates one line at a time
        let line = l.unwrap();
        // COMMENTS special case
        // --> store
        // ---> append later with epoch.timestamp attached to it
        if is_comment!(line) {
            let comment = line.split_at(60).0.trim_end();
            comment_content.push(comment.to_string());
            continue;
        }
        // IONEX exponent-->data scaling use update regularly
        //  and used in TEC map parsing
        if line.contains("EXPONENT") {
            if let Some(ionex) = header.ionex.as_mut() {
                let content = line.split_at(60).0;
                if let Ok(e) = i8::from_str_radix(content.trim(), 10) {
                    *ionex = ionex.with_exponent(e); // scaling update
                }
            }
        }
        /*
         * If plain RINEX: content is passed as is
         *      if CRINEX: decompress and pass recovered content
         */

        if let Some(obs) = &header.obs {
            if let Some(crinex) = &obs.crinex {
                /*
                 * CRINEX
                 */
                let constellation = &header.constellation.as_ref().unwrap();
                if let Ok(recovered) = decompressor.decompress(
                    crinex.version.major,
                    constellation,
                    header.version.major,
                    &obs.codes,
                    // we might encounter empty lines
                    //   like missing clock offsets
                    //   and .lines() will destroy them
                    &(line.to_owned() + "\n"),
                ) {
                    content = recovered.clone();
                } else {
                    content.clear();
                }
            } else {
                /*
                 * RINEX
                 */
                if line.len() == 0 {
                    // we might encounter empty lines
                    // and the following parsers (.lines() iterator)
                    // do not like it
                    content = String::from("\n");
                } else {
                    content = line.to_string();
                }
            }
        } else {
            /*
             * RINEX
             */
            if line.len() == 0 {
                // we might encounter empty lines
                // and the following parsers (.lines() iterator)
                // do not like it
                content = String::from("\n");
            } else {
                content = line.to_string();
            }
        }

        for line in content.lines() {
            // in case of CRINEX -> RINEX < 3 being recovered,
            // we have more than 1 ligne to process
            let new_epoch = is_new_epoch(line, &header);
            ionx_rms |= ionex::record::is_new_rms_map(line);
            ionx_height |= ionex::record::is_new_height_map(line);

            if new_epoch && !first_epoch {
                match &header.rinex_type {
                    Type::NavigationData => {
                        let constellation = &header.constellation.unwrap();
                        if let Ok((e, fr)) = navigation::record::parse_epoch(
                            header.version,
                            *constellation,
                            &epoch_content,
                        ) {
                            nav_rec
                                .entry(e)
                                .and_modify(|frames| frames.push(fr.clone()))
                                .or_insert_with(|| vec![fr.clone()]);
                            //    // epoch already encountered
                            //    // add new entry
                            //    frames.push(fr);
                            //} else {
                            //    // new epoch: create entry entry
                            //    nav_rec.insert(e, vec![fr]);
                            //}
                            comment_ts = e.clone(); // for comments classification & management
                        }
                    },
                    Type::ObservationData => {
                        if let Ok((e, ck_offset, map)) =
                            observation::record::parse_epoch(&header, &epoch_content)
                        {
                            obs_rec.insert(e, (ck_offset, map));
                            comment_ts = e.0.clone(); // for comments classification & management
                        }
                    },
                    Type::MeteoData => {
                        if let Ok((e, map)) = meteo::record::parse_epoch(&header, &epoch_content) {
                            met_rec.insert(e, map);
                            comment_ts = e.clone(); // for comments classification & management
                        }
                    },
                    Type::ClockData => {
                        if let Ok((epoch, dtype, system, data)) =
                            clocks::record::parse_epoch(header.version, &epoch_content)
                        {
                            if let Some(e) = clk_rec.get_mut(&epoch) {
                                if let Some(d) = e.get_mut(&dtype) {
                                    d.insert(system, data);
                                } else {
                                    // --> new system entry for this `epoch`
                                    let mut inner: HashMap<clocks::System, clocks::Data> =
                                        HashMap::new();
                                    inner.insert(system, data);
                                    e.insert(dtype, inner);
                                }
                            } else {
                                // --> new epoch entry
                                let mut inner: HashMap<clocks::System, clocks::Data> =
                                    HashMap::new();
                                inner.insert(system, data);
                                let mut map: HashMap<
                                    clocks::DataType,
                                    HashMap<clocks::System, clocks::Data>,
                                > = HashMap::new();
                                map.insert(dtype, inner);
                                clk_rec.insert(epoch, map);
                            }
                            comment_ts = epoch.clone(); // for comments classification & management
                        }
                    },
                    Type::AntennaData => {
                        if let Ok((antenna, frequencies)) =
                            antex::record::parse_epoch(&epoch_content)
                        {
                            let mut found = false;
                            for (ant, freqz) in atx_rec.iter_mut() {
                                if *ant == antenna {
                                    for f in frequencies.iter() {
                                        freqz.push(f.clone());
                                    }
                                    found = true;
                                    break;
                                }
                            }
                            if !found {
                                atx_rec.push((antenna, frequencies));
                            }
                        }
                    },
                    Type::IonosphereMaps => {
                        if let Ok((index, epoch, map)) =
                            ionex::record::parse_map(header, &epoch_content)
                        {
                            if ionx_rms {
                                ionx_rms = false;
                                if let Some(e) = ionx_epochs.get(index) {
                                    // relate
                                    if let Some((_, rms, _)) = ionx_rec.get_mut(e) {
                                        // locate
                                        *rms = Some(map); // insert
                                    }
                                }
                            } else if ionx_height {
                                ionx_height = false;
                                if let Some(e) = ionx_epochs.get(index) {
                                    // relate
                                    if let Some((_, _, h)) = ionx_rec.get_mut(e) {
                                        // locate
                                        *h = Some(map); // insert
                                    }
                                }
                            } else {
                                // TEC map => insert epoch
                                ionx_epochs.push(epoch.clone());
                                ionx_rec.insert(epoch, (map, None, None));
                            }
                        }
                    },
                }

                // new comments ?
                if !comment_content.is_empty() {
                    comments.insert(comment_ts, comment_content.clone());
                    comment_content.clear() // reset
                }
            } //is_new_epoch() +!first

            if new_epoch {
                if !first_epoch {
                    epoch_content.clear()
                }
                first_epoch = false;
            }
            // epoch content builder
            epoch_content.push_str(&(line.to_owned() + "\n"));
        }
    }

    // --> try to build an epoch out of current residues
    // this covers
    //   + final epoch (last epoch in record)
    //   + comments parsing with empty record (empty file body)
    match &header.rinex_type {
        Type::NavigationData => {
            let constellation = &header.constellation.unwrap();
            if let Ok((e, fr)) =
                navigation::record::parse_epoch(header.version, *constellation, &epoch_content)
            {
                nav_rec
                    .entry(e)
                    .and_modify(|current| current.push(fr.clone()))
                    .or_insert_with(|| vec![fr.clone()]);
                comment_ts = e.clone(); // for comments classification & management
            }
        },
        Type::ObservationData => {
            if let Ok((e, ck_offset, map)) =
                observation::record::parse_epoch(&header, &epoch_content)
            {
                obs_rec.insert(e, (ck_offset, map));
                comment_ts = e.0.clone(); // for comments classification + management
            }
        },
        Type::MeteoData => {
            if let Ok((e, map)) = meteo::record::parse_epoch(&header, &epoch_content) {
                met_rec.insert(e, map);
                comment_ts = e.clone(); // for comments classification + management
            }
        },
        Type::ClockData => {
            if let Ok((e, dtype, system, data)) =
                clocks::record::parse_epoch(header.version, &epoch_content)
            {
                // Clocks `RINEX` files are handled a little different,
                // because we parse one line at a time, while we parsed one epoch at a time for other RINEXes.
                // One line may contribute to a previously existing epoch in the record
                // (different type of measurements etc..etc..)
                if let Some(e) = clk_rec.get_mut(&e) {
                    if let Some(d) = e.get_mut(&dtype) {
                        d.insert(system, data);
                    } else {
                        // --> new system entry for this `epoch`
                        let mut map: HashMap<
                            clocks::DataType,
                            HashMap<clocks::System, clocks::Data>,
                        > = HashMap::new();
                        let mut inner: HashMap<clocks::System, clocks::Data> = HashMap::new();
                        inner.insert(system, data);
                        map.insert(dtype, inner);
                    }
                } else {
                    // --> new epoch entry
                    let mut map: HashMap<clocks::DataType, HashMap<clocks::System, clocks::Data>> =
                        HashMap::new();
                    let mut inner: HashMap<clocks::System, clocks::Data> = HashMap::new();
                    inner.insert(system, data);
                    map.insert(dtype, inner);
                    clk_rec.insert(e, map);
                }
                comment_ts = e.clone(); // for comments classification & management
            }
        },
        Type::IonosphereMaps => {
            if let Ok((index, epoch, map)) = ionex::record::parse_map(header, &epoch_content) {
                if ionx_rms {
                    if let Some(e) = ionx_epochs.get(index) {
                        // relate
                        if let Some((_, rms, _)) = ionx_rec.get_mut(e) {
                            // locate
                            *rms = Some(map); // insert
                        }
                    }
                } else if ionx_height {
                    if let Some(e) = ionx_epochs.get(index) {
                        // relate
                        if let Some((_, _, h)) = ionx_rec.get_mut(e) {
                            // locate
                            *h = Some(map); // insert
                        }
                    }
                } else {
                    // introduce TEC+epoch
                    ionx_rec.insert(epoch, (map, None, None));
                }
            }
        },
        Type::AntennaData => {
            if let Ok((antenna, frequencies)) = antex::record::parse_epoch(&epoch_content) {
                let mut found = false;
                for (ant, freqz) in atx_rec.iter_mut() {
                    if *ant == antenna {
                        for f in frequencies.iter() {
                            freqz.push(f.clone());
                        }
                        found = true;
                        break;
                    }
                }
                if !found {
                    atx_rec.push((antenna, frequencies));
                }
            }
        },
    }
    // new comments ?
    if !comment_content.is_empty() {
        comments.insert(comment_ts, comment_content.clone());
    }
    // wrap record
    let record = match &header.rinex_type {
        Type::AntennaData => Record::AntexRecord(atx_rec),
        Type::ClockData => Record::ClockRecord(clk_rec),
        Type::IonosphereMaps => Record::IonexRecord(ionx_rec),
        Type::MeteoData => Record::MeteoRecord(met_rec),
        Type::NavigationData => Record::NavRecord(nav_rec),
        Type::ObservationData => Record::ObsRecord(obs_rec),
    };
    Ok((record, comments))
}

impl Merge for Record {
    /// Merges `rhs` into `Self` without mutable access at the expense of more memcopies
    fn merge(&self, rhs: &Self) -> Result<Self, merge::Error> {
        let mut lhs = self.clone();
        lhs.merge_mut(rhs)?;
        Ok(lhs)
    }
    /// Merges `rhs` into `Self`
    fn merge_mut(&mut self, rhs: &Self) -> Result<(), merge::Error> {
        if let Some(lhs) = self.as_mut_nav() {
            if let Some(rhs) = rhs.as_nav() {
                lhs.merge_mut(&rhs)?;
            }
        } else if let Some(lhs) = self.as_mut_obs() {
            if let Some(rhs) = rhs.as_obs() {
                lhs.merge_mut(&rhs)?;
            }
        } else if let Some(lhs) = self.as_mut_meteo() {
            if let Some(rhs) = rhs.as_meteo() {
                lhs.merge_mut(&rhs)?;
            }
        /*} else if let Some(lhs) = self.as_mut_ionex() {
        if let Some(rhs) = rhs.as_ionex() {
            lhs.merge_mut(&rhs)?;
        }*/
        } else if let Some(lhs) = self.as_mut_antex() {
            if let Some(rhs) = rhs.as_antex() {
                lhs.merge_mut(&rhs)?;
            }
        } else if let Some(lhs) = self.as_mut_clock() {
            if let Some(rhs) = rhs.as_clock() {
                lhs.merge_mut(&rhs)?;
            }
        }
        Ok(())
    }
}

impl Split for Record {
    fn split(&self, epoch: Epoch) -> Result<(Self, Self), split::Error> {
        if let Some(r) = self.as_obs() {
            let (r0, r1) = r.split(epoch)?;
            Ok((Self::ObsRecord(r0), Self::ObsRecord(r1)))
        } else if let Some(r) = self.as_nav() {
            let (r0, r1) = r.split(epoch)?;
            Ok((Self::NavRecord(r0), Self::NavRecord(r1)))
        } else if let Some(r) = self.as_meteo() {
            let (r0, r1) = r.split(epoch)?;
            Ok((Self::MeteoRecord(r0), Self::MeteoRecord(r1)))
        } else if let Some(r) = self.as_ionex() {
            let (r0, r1) = r.split(epoch)?;
            Ok((Self::IonexRecord(r0), Self::IonexRecord(r1)))
        } else if let Some(r) = self.as_clock() {
            let (r0, r1) = r.split(epoch)?;
            Ok((Self::ClockRecord(r0), Self::ClockRecord(r1)))
        } else {
            Err(split::Error::NoEpochIteration)
        }
    }
    fn split_dt(&self, _dt: Duration) -> Result<Vec<Self>, split::Error> {
        Ok(Vec::new())
    }
}

impl GnssTime for Record {
    fn timeseries(&self, dt: Duration) -> TimeSeries {
        if let Some(r) = self.as_obs() {
            r.timeseries(dt)
        } else {
            todo!()
        }
    }
    fn convert_timescale(&mut self, ts: TimeScale) {
        if let Some(r) = self.as_mut_obs() {
            r.convert_timescale(ts);
        } else if let Some(r) = self.as_mut_nav() {
            r.convert_timescale(ts);
        } else if let Some(r) = self.as_mut_meteo() {
            r.convert_timescale(ts);
        } else if let Some(r) = self.as_mut_ionex() {
            r.convert_timescale(ts);
        } else if let Some(r) = self.as_mut_clock() {
            r.convert_timescale(ts);
        }
    }
    fn with_timescale(&self, ts: TimeScale) -> Self {
        let mut s = self.clone();
        s.convert_timescale(ts);
        s
    }
}

#[cfg(feature = "processing")]
use crate::algorithm::{Filter, Preprocessing};

#[cfg(feature = "processing")]
impl Preprocessing for Record {
    fn filter(&self, f: Filter) -> Self {
        let mut s = self.clone();
        s.filter_mut(f);
        s
    }
    fn filter_mut(&mut self, f: Filter) {
        if let Some(r) = self.as_mut_obs() {
            r.filter_mut(f);
        } else if let Some(r) = self.as_mut_nav() {
            r.filter_mut(f);
        } else if let Some(r) = self.as_mut_clock() {
            r.filter_mut(f);
        } else if let Some(r) = self.as_mut_meteo() {
            r.filter_mut(f);
        } else if let Some(r) = self.as_mut_ionex() {
            r.filter_mut(f);
        }
    }
}

#[cfg(feature = "processing")]
use crate::algorithm::Decimate;

#[cfg(feature = "processing")]
impl Decimate for Record {
    fn decimate_by_ratio(&self, r: u32) -> Self {
        let mut s = self.clone();
        s.decimate_by_ratio_mut(r);
        s
    }
    fn decimate_by_ratio_mut(&mut self, r: u32) {
        if let Some(rec) = self.as_mut_obs() {
            rec.decimate_by_ratio_mut(r);
        } else if let Some(rec) = self.as_mut_nav() {
            rec.decimate_by_ratio_mut(r);
        } else if let Some(rec) = self.as_mut_meteo() {
            rec.decimate_by_ratio_mut(r);
        }
    }
    fn decimate_by_interval(&self, dt: Duration) -> Self {
        let mut s = self.clone();
        s.decimate_by_interval_mut(dt);
        s
    }
    fn decimate_by_interval_mut(&mut self, dt: Duration) {
        if let Some(rec) = self.as_mut_obs() {
            rec.decimate_by_interval_mut(dt);
        } else if let Some(rec) = self.as_mut_nav() {
            rec.decimate_by_interval_mut(dt);
        } else if let Some(rec) = self.as_mut_meteo() {
            rec.decimate_by_interval_mut(dt);
        }
    }
    fn decimate_match(&self, rhs: &Self) -> Self {
        let mut s = self.clone();
        s.decimate_match_mut(rhs);
        s
    }
    fn decimate_match_mut(&mut self, rhs: &Self) {
        if let Some(rec) = self.as_mut_obs() {
            if let Some(rhs) = rhs.as_obs() {
                rec.decimate_match_mut(rhs);
            }
        } else if let Some(rec) = self.as_mut_nav() {
            if let Some(rhs) = rhs.as_nav() {
                rec.decimate_match_mut(rhs);
            }
        } else if let Some(rec) = self.as_mut_meteo() {
            if let Some(rhs) = rhs.as_meteo() {
                rec.decimate_match_mut(rhs);
            }
        }
    }
}