astrodynamics-gnss 0.9.8

GNSS domain layer (SP3, broadcast ephemeris, multi-GNSS single-point positioning, ionosphere/troposphere, DOP) built on the astrodynamics core
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
//! Hatanaka (CRINEX) observation-file decoder.
//!
//! Reconstructs the plain RINEX observation **text** from a Compact RINEX
//! (CRINEX) stream, reproducing the `CRX2RNX` algorithm. Two stream revisions
//! are handled: **CRINEX 1.0** (which compacts a RINEX 2 observation file) and
//! **CRINEX 3.0** (which compacts a RINEX 3 observation file). The expanded text
//! is what [`crate::rinex_obs::RinexObs`] then parses.
//!
//! # What CRINEX is
//!
//! CRINEX is a lossless, line-oriented ASCII recompression of a RINEX
//! observation file. The plain RINEX header is copied through unchanged (it is
//! never compressed); only the data body is differenced. The body uses two
//! difference engines:
//!
//! - a per-character **text** difference (epoch descriptor line and the trailing
//!   LLI/SSI flag string of each satellite line); and
//! - a per-observation higher-order **integer** difference (each observation
//!   column, and the receiver clock offset), with arc (re)initialization marked
//!   inline by an `order&value` token.
//!
//! The algorithm is fully specified by Hatanaka (2008) and the RNXCMP toolset.
//! This is a deterministic byte-to-text transform, not a float recipe — there is
//! no 0-ULP claim here, exactly as for the SP3 and RINEX-NAV readers. The
//! reconstructed numbers are formatted with the same fixed-decimal layout the
//! reference `crx2rnx` emits (value scaled back by `10^-decimals`, right-aligned
//! in the field) and each output line has its trailing blanks trimmed, which is
//! what makes the expansion reproduce the reference byte-for-byte.
//!
//! # Memory
//!
//! The difference state is bounded: the engines hold only the previous epoch's
//! per-satellite reference values, not the whole stream. [`decode_to`] is the
//! line-at-a-time form — it pushes each reconstructed line to a sink as it is
//! produced, so the *decoder itself* never buffers the full expansion. Note that
//! the [`decode`] convenience does collect the entire expanded text into one
//! `String`; for a multi-megabyte daily file prefer `decode_to` with a streaming
//! sink (e.g. feeding a record consumer) so the expansion is processed
//! incrementally.

use std::collections::HashMap;

use crate::parse::{raw_field as field, raw_field_from as field_from};
use crate::{Error, Result};

/// CRINEX stream revision (the `CRINEX VERS / TYPE` line).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CrinexVersion {
    /// CRINEX 1.0 — compacts a RINEX 2 observation file.
    V1,
    /// CRINEX 3.0 — compacts a RINEX 3 observation file.
    V3,
}

/// The compression order used by the historical `RNX2CRX` (and the only order a
/// reset token may request without exceeding the classic `M = 5` history). It is
/// carried per token, so this is only a sanity ceiling.
const MAX_ORDER: usize = 6;

/// Width of one RINEX-3 observation field: `F14.3` value + LLI + SSI.
const OBS_FIELD_WIDTH: usize = 16;
/// Width of the numeric part of one observation field (`F14.3`).
const OBS_VALUE_WIDTH: usize = 14;

/// Decode a CRINEX (Hatanaka) observation stream into the plain RINEX
/// observation text it expands to, returning the whole text as a `String`.
///
/// Supports CRINEX 1.0 (RINEX 2 host) and CRINEX 3.0 (RINEX 3 host). Returns
/// [`Error::Parse`] with a human-readable reason on a malformed stream.
pub fn decode(crinex_text: &str) -> Result<String> {
    let mut out = String::with_capacity(crinex_text.len() * 4);
    decode_to(crinex_text, |line| {
        out.push_str(line);
        out.push('\n');
    })?;
    Ok(out)
}

/// Streaming decode: reconstruct the plain RINEX observation text one line at a
/// time, pushing each line (without its trailing newline) to `emit`.
///
/// This is the bounded-memory form: the difference engines retain only the
/// previous epoch's state, so a multi-megabyte daily file never holds its full
/// expansion in a single buffer. [`decode`] is the collecting convenience.
pub fn decode_to<W: FnMut(&str)>(crinex_text: &str, mut emit: W) -> Result<()> {
    let mut decoder = Decoder::new();
    let mut lines = crinex_text.lines();
    decoder.read_crinex_header(&mut lines, &mut emit)?;
    decoder.read_body(&mut lines, &mut emit)?;
    Ok(())
}

/// Per-observation / clock higher-order integer difference engine.
///
/// Mirrors the Hatanaka `NumDiff`: a value is the original decimal scaled to an
/// integer; the engine holds a small history and reconstructs the next value
/// from a delta using the signed binomial (Pascal) coefficients for the current
/// order. The order ramps up to `level` as samples arrive and is reset by an
/// `order&value` token (arc reinitialization).
#[derive(Debug, Clone)]
struct NumDiff {
    /// Iteration counter (current effective order), clamped to `level`.
    m: usize,
    /// Target compression level (order) for this arc.
    level: usize,
    /// History buffer, most-recent first.
    buf: [i64; MAX_ORDER],
}

impl NumDiff {
    /// Initialize a fresh arc seeded with `data` at the given `level`. The seed
    /// is the recovered value of the init sample.
    fn new(data: i64, level: usize) -> Self {
        let mut buf = [0i64; MAX_ORDER];
        buf[0] = data;
        Self { m: 0, level, buf }
    }

    /// Reinitialize the arc (the `order&value` reset token): clear the order,
    /// set the new level, and seed the history with the recovered value.
    fn force_init(&mut self, data: i64, level: usize) {
        self.m = 0;
        self.level = level;
        self.rotate(data);
    }

    /// Push a recovered value into the history buffer (most-recent first).
    fn rotate(&mut self, data: i64) {
        self.buf.copy_within(0..MAX_ORDER - 1, 1);
        self.buf[0] = data;
    }

    /// Recover the next value from its delta, advancing the order toward
    /// `level`.
    fn decompress(&mut self, delta: i64) -> i64 {
        if self.m < self.level {
            self.m += 1;
        }
        let b = &self.buf;
        let new = match self.m {
            1 => delta + b[0],
            2 => delta + 2 * b[0] - b[1],
            3 => delta + 3 * b[0] - 3 * b[1] + b[2],
            4 => delta + 4 * b[0] - 6 * b[1] + 4 * b[2] - b[3],
            5 => delta + 5 * b[0] - 10 * b[1] + 10 * b[2] - 5 * b[3] + b[4],
            6 => delta + 6 * b[0] - 15 * b[1] + 20 * b[2] - 15 * b[3] + 6 * b[4] - b[5],
            // m starts at 0 and is incremented before use, and `level` is
            // capped at MAX_ORDER, so m is always in 1..=MAX_ORDER here.
            _ => delta + b[0],
        };
        self.rotate(new);
        new
    }
}

/// Per-character text difference engine (Hatanaka `TextDiff`), used for the
/// epoch descriptor line and each satellite's LLI/SSI flag string.
///
/// State is the last reconstructed string. A space keeps the buffered byte; an
/// `&` blanks it; any other byte overwrites it. Input longer than the buffer
/// appends verbatim.
#[derive(Debug, Default, Clone)]
struct TextDiff {
    buffer: Vec<u8>,
}

impl TextDiff {
    /// Replace the buffer wholesale (a forced reinit / first sample).
    fn force_init(&mut self, data: &str) {
        self.buffer = data.as_bytes().to_vec();
    }

    /// Apply a compressed line against the current buffer and return the
    /// reconstructed string.
    fn decompress(&mut self, data: &str) -> String {
        let bytes = data.as_bytes();
        if bytes.len() > self.buffer.len() {
            self.buffer.extend_from_slice(&bytes[self.buffer.len()..]);
        }
        for (i, &byte) in bytes.iter().enumerate() {
            if byte == b' ' {
                continue;
            }
            if let Some(slot) = self.buffer.get_mut(i) {
                *slot = if byte == b'&' { b' ' } else { byte };
            }
        }
        // CRINEX text is ASCII; lossy is unreachable for valid input but keeps
        // this panic-free on a stray byte.
        String::from_utf8_lossy(&self.buffer).into_owned()
    }
}

/// CRINEX decoder state machine.
struct Decoder {
    version: CrinexVersion,
    /// Number of observation codes declared per constellation letter, used to
    /// know how many observation fields each satellite line carries.
    obs_count: HashMap<char, usize>,
    /// Mono-constellation letter for a RINEX-2 file whose SV tokens omit the
    /// system letter (set from the header `RINEX VERSION / TYPE`).
    default_system: Option<char>,
    /// Epoch descriptor text-diff engine.
    epoch_diff: TextDiff,
    /// Receiver-clock-offset difference engine.
    clock_diff: Option<NumDiff>,
    /// Per-satellite observation difference engines, keyed by SV token.
    obs_diff: HashMap<String, Vec<Option<NumDiff>>>,
    /// Per-satellite flag (LLI/SSI) text-diff engines.
    flag_diff: HashMap<String, TextDiff>,
}

impl Decoder {
    fn new() -> Self {
        Self {
            version: CrinexVersion::V3,
            obs_count: HashMap::new(),
            default_system: None,
            epoch_diff: TextDiff::default(),
            clock_diff: None,
            obs_diff: HashMap::new(),
            flag_diff: HashMap::new(),
        }
    }

    /// Consume the two CRINEX header lines (dropped) and then copy the embedded
    /// plain RINEX header through verbatim up to and including `END OF HEADER`,
    /// recording the per-system observation-code counts and the file version
    /// along the way.
    fn read_crinex_header<'a, I, W>(&mut self, lines: &mut I, emit: &mut W) -> Result<()>
    where
        I: Iterator<Item = &'a str>,
        W: FnMut(&str),
    {
        // Line 1: CRINEX VERS / TYPE — selects the stream grammar.
        let l1 = lines
            .next()
            .ok_or_else(|| Error::Parse("CRINEX stream is empty".into()))?;
        let crx_ver = field(l1, 0, 20).trim();
        self.version = match crx_ver {
            v if v.starts_with("1.0") || v.starts_with("1.") => CrinexVersion::V1,
            v if v.starts_with("3.0") || v.starts_with("3.") => CrinexVersion::V3,
            other => {
                return Err(Error::Parse(format!(
                    "unsupported CRINEX version {other:?} (expected 1.0 or 3.0)"
                )))
            }
        };
        if !l1.contains("CRINEX VERS") {
            return Err(Error::Parse(
                "missing CRINEX VERS / TYPE header line".into(),
            ));
        }
        // Line 2: CRINEX PROG / DATE — dropped (it is the compaction stamp, not
        // part of the reconstructed RINEX).
        lines
            .next()
            .ok_or_else(|| Error::Parse("CRINEX header missing PROG / DATE line".into()))?;

        // Copy the embedded plain RINEX header verbatim, tracking obs counts.
        let mut current_sys: Option<char> = None;
        let mut remaining_codes = 0usize;
        let mut saw_end = false;
        for raw in lines.by_ref() {
            let line = raw.trim_end_matches(['\r', '\n']);
            emit(line);

            if line.len() >= 80 || line.len() >= 61 {
                // labelled header records carry the label at cols 60..80
            }
            let label = field(line, 60, 80).trim();

            match label {
                "RINEX VERSION / TYPE" => {
                    // RINEX 2 SV tokens may omit the constellation letter for a
                    // single-system file; capture it for V1 streams.
                    let sys_field = field(line, 40, 41).trim();
                    if let Some(c) = sys_field.chars().next() {
                        if c != 'M' {
                            self.default_system = Some(c);
                        }
                    }
                }
                "# / TYPES OF OBSERV" => {
                    // RINEX 2 observation-code count (shared across systems).
                    let n = field(line, 0, 6).trim().parse::<usize>().unwrap_or(0);
                    if n > 0 {
                        if let Some(sys) = self.default_system {
                            self.obs_count.insert(sys, n);
                        }
                        // RINEX 2 has one shared list; record under a sentinel
                        // so a mono-system file resolves even if the letter was
                        // 'M'.
                        self.obs_count.entry(' ').or_insert(n);
                    }
                }
                "SYS / # / OBS TYPES" => {
                    let sys_field = field(line, 0, 1).trim();
                    if let Some(c) = sys_field.chars().next() {
                        current_sys = Some(c);
                        let n = field(line, 3, 6).trim().parse::<usize>().unwrap_or(0);
                        self.obs_count.insert(c, n);
                        remaining_codes = n;
                    }
                    // continuation lines (blank system field) carry no count.
                    let _ = (current_sys, remaining_codes);
                }
                "END OF HEADER" => {
                    saw_end = true;
                    break;
                }
                _ => {}
            }
        }
        if !saw_end {
            return Err(Error::Parse(
                "CRINEX embedded RINEX header has no END OF HEADER".into(),
            ));
        }
        Ok(())
    }

    /// Decode the epoch records following the header.
    fn read_body<'a, I, W>(&mut self, lines: &mut I, emit: &mut W) -> Result<()>
    where
        I: Iterator<Item = &'a str>,
        W: FnMut(&str),
    {
        match self.version {
            CrinexVersion::V3 => self.read_body_v3(lines, emit),
            CrinexVersion::V1 => self.read_body_v1(lines, emit),
        }
    }

    // ----------------------------------------------------------------- V3 ---

    fn read_body_v3<'a, I, W>(&mut self, lines: &mut I, emit: &mut W) -> Result<()>
    where
        I: Iterator<Item = &'a str>,
        W: FnMut(&str),
    {
        while let Some(raw) = lines.next() {
            let line = raw.trim_end_matches(['\r', '\n']);
            if line.is_empty() {
                // A stray blank between records (rare); skip.
                continue;
            }
            // Epoch descriptor. A reset is marked by a leading '>' (the rest of
            // the line is taken literally), otherwise the line is a TextDiff
            // delta of the previous descriptor. The leading '>' is kept in the
            // text-diff buffer so the delta lines' column offsets line up with
            // the full RINEX-3 epoch line (the seconds digits sit one column to
            // the right of where they would be in a '>'-stripped buffer).
            let descriptor = if line.starts_with('>') {
                self.epoch_diff.force_init(line);
                self.epoch_diff.decompress("")
            } else {
                self.epoch_diff.decompress(line)
            };

            // The reconstructed full epoch line is
            // "> YYYY MM DD HH MM SS.sssssss  F NN<svlist>": the epoch flag is at
            // column 31, the satellite count at columns 32..35, and the 3-char SV
            // tokens begin at column 41.
            let numsat = field(&descriptor, 32, 35)
                .trim()
                .parse::<usize>()
                .map_err(|_| {
                    Error::Parse(format!(
                        "CRINEX V3 epoch has unparsable satellite count: {descriptor:?}"
                    ))
                })?;
            let flag = field(&descriptor, 31, 32).trim().parse::<u8>().unwrap_or(0);

            // Event records (flag > 1) carry header/comment lines rather than
            // observation lines, and the clock-offset record is omitted for them
            // entirely. Emit the epoch line (no clock), then reproduce the
            // `numsat` event lines verbatim, and skip all differencing.
            if flag > 1 {
                emit(trim_end(field(&descriptor, 0, 35)));
                for _ in 0..numsat {
                    if let Some(extra) = lines.next() {
                        emit(extra.trim_end_matches(['\r', '\n']));
                    }
                }
                continue;
            }

            // The clock offset is its own line (a NumDiff token, possibly blank).
            let clock_line = lines
                .next()
                .ok_or_else(|| Error::Parse("CRINEX V3 epoch missing clock line".into()))?
                .trim_end_matches(['\r', '\n']);
            let clock_text = self.decode_clock(clock_line)?;

            // Emit the reconstructed epoch line: everything before the SV list
            // (cols 0..35) plus the clock. The SV list is not part of a RINEX-3
            // epoch line. The optional receiver clock offset is an `F15.12`
            // field at columns 41..56, with columns 35..41 reserved blank, so
            // the head is padded to column 41 before the clock is appended.
            let head = field(&descriptor, 0, 35);
            let mut epoch_out = head.to_string();
            if !clock_text.is_empty() {
                while epoch_out.len() < 41 {
                    epoch_out.push(' ');
                }
            }
            epoch_out.push_str(&clock_text);
            emit(trim_end(&epoch_out));

            let sv_list = self.sv_tokens_v3(&descriptor, numsat)?;

            for sv in &sv_list {
                let data_line = lines.next().ok_or_else(|| {
                    Error::Parse("CRINEX V3 epoch truncated: missing satellite line".into())
                })?;
                let n_obs = self.obs_count_for(sv);
                let out =
                    self.decode_sat_line_v3(sv, data_line.trim_end_matches(['\r', '\n']), n_obs)?;
                emit(trim_end(&out));
            }
        }
        Ok(())
    }

    /// Extract `numsat` 3-character SV tokens from the V3 epoch descriptor.
    fn sv_tokens_v3(&self, descriptor: &str, numsat: usize) -> Result<Vec<String>> {
        // The RINEX-3 epoch line pads the satellite list to column 41 of the
        // full line (the '>' is kept in the descriptor buffer); the 3-char SV
        // tokens run from there.
        let list = field_from(descriptor, 41);
        let bytes = list.as_bytes();
        let mut out = Vec::with_capacity(numsat);
        for i in 0..numsat {
            let start = i * 3;
            let end = start + 3;
            if end > bytes.len() {
                return Err(Error::Parse(format!(
                    "CRINEX V3 epoch SV list shorter than {numsat} satellites"
                )));
            }
            out.push(list[start..end].to_string());
        }
        Ok(out)
    }

    /// Observation-code count for an SV token's constellation.
    fn obs_count_for(&self, sv: &str) -> usize {
        let sys = sv.chars().next().unwrap_or(' ');
        self.obs_count
            .get(&sys)
            .or_else(|| self.obs_count.get(&' '))
            .copied()
            .unwrap_or(0)
    }

    /// Decode one satellite's observation line for a V3 stream: `n_obs`
    /// difference-coded observation tokens followed by the TextDiff flag string.
    fn decode_sat_line_v3(&mut self, sv: &str, line: &str, n_obs: usize) -> Result<String> {
        // The observation tokens are whitespace-separated; the remainder after
        // the last consumed token is the flag string. We walk the line token by
        // token, tracking byte offsets so we know where the flags begin.
        let engines = self
            .obs_diff
            .entry(sv.to_string())
            .or_insert_with(|| vec![None; n_obs]);
        if engines.len() < n_obs {
            engines.resize(n_obs, None);
        }

        let mut values: Vec<Option<i64>> = Vec::with_capacity(n_obs);
        let mut cursor = 0usize;
        let bytes = line.as_bytes();

        for obs_index in 0..n_obs {
            // Skip the single separating blank between fields (the compressor
            // writes exactly one space between tokens; a doubled space marks a
            // blanked observation).
            if obs_index > 0 {
                if cursor < bytes.len() && bytes[cursor] == b' ' {
                    cursor += 1;
                } else if cursor >= bytes.len() {
                    // No more tokens on the line: the rest are blank.
                    values.push(None);
                    continue;
                }
            }
            // A blanked observation: the field is empty (immediately another
            // separator or end of the data section).
            if cursor >= bytes.len() || bytes[cursor] == b' ' {
                values.push(None);
                continue;
            }
            // Read the token up to the next space.
            let tok_start = cursor;
            while cursor < bytes.len() && bytes[cursor] != b' ' {
                cursor += 1;
            }
            let token = &line[tok_start..cursor];
            let recovered = self.apply_obs_token(sv, obs_index, token)?;
            values.push(Some(recovered));
        }

        // The flag string is whatever remains. In RNX2CRX output the flags are
        // separated from the last observation token by a single space.
        let flag_raw = if cursor < bytes.len() {
            let rest = &line[cursor..];
            rest.strip_prefix(' ').unwrap_or(rest)
        } else {
            ""
        };
        let flags = self
            .flag_diff
            .entry(sv.to_string())
            .or_default()
            .decompress(flag_raw);

        Ok(format_sat_line(sv, &values, &flags))
    }

    /// Apply one observation token (reset `order&value`, or a plain delta) and
    /// return the recovered scaled integer.
    fn apply_obs_token(&mut self, sv: &str, obs_index: usize, token: &str) -> Result<i64> {
        let engines = self.obs_diff.get_mut(sv).expect("engines inserted above");
        let slot = &mut engines[obs_index];
        if let Some((order, value)) = parse_reset(token)? {
            match slot {
                Some(e) => e.force_init(value, order),
                None => *slot = Some(NumDiff::new(value, order)),
            }
            Ok(value)
        } else {
            let delta = token.trim().parse::<i64>().map_err(|_| {
                Error::Parse(format!(
                    "CRINEX observation delta {token:?} is not an integer"
                ))
            })?;
            match slot {
                Some(e) => Ok(e.decompress(delta)),
                None => Err(Error::Parse(format!(
                    "CRINEX observation {sv}[{obs_index}] has a delta before any arc init"
                ))),
            }
        }
    }

    /// Decode the per-epoch receiver clock offset line into the formatted clock
    /// text appended to the epoch line (empty when no clock is carried).
    fn decode_clock(&mut self, line: &str) -> Result<String> {
        let token = line.trim();
        if token.is_empty() {
            return Ok(String::new());
        }
        let value = if let Some((order, v)) = parse_reset(token)? {
            match &mut self.clock_diff {
                Some(e) => e.force_init(v, order),
                None => self.clock_diff = Some(NumDiff::new(v, order)),
            }
            v
        } else {
            let delta = token.trim().parse::<i64>().map_err(|_| {
                Error::Parse(format!("CRINEX clock delta {token:?} is not an integer"))
            })?;
            match &mut self.clock_diff {
                Some(e) => e.decompress(delta),
                None => {
                    return Err(Error::Parse(
                        "CRINEX clock delta before any clock arc init".into(),
                    ))
                }
            }
        };
        // The receiver clock offset is recorded scaled by 10^12 (picoseconds of
        // the original .12f field) and printed back as `%15.12f`.
        Ok(format!("{:15.12}", value as f64 / 1.0e12))
    }

    // ----------------------------------------------------------------- V1 ---

    fn read_body_v1<'a, I, W>(&mut self, lines: &mut I, emit: &mut W) -> Result<()>
    where
        I: Iterator<Item = &'a str>,
        W: FnMut(&str),
    {
        while let Some(raw) = lines.next() {
            let line = raw.trim_end_matches(['\r', '\n']);
            if line.is_empty() {
                continue;
            }
            // CRINEX 1.0 stores the epoch line without RINEX-2's leading blank
            // column, but crx2rnx restores it on output and keeps the restored,
            // space-prefixed line as the text-difference base for the next epoch.
            // Mirror that: seed the engine with the leading space (on reset) so
            // both the reconstruction and the standard column offsets are right.
            // V1 epoch descriptor reset is marked by a leading '&'.
            let descriptor = if let Some(stripped) = line.strip_prefix('&') {
                self.epoch_diff.force_init(&format!(" {stripped}"));
                self.epoch_diff.decompress("")
            } else {
                self.epoch_diff.decompress(line)
            };

            // V1 epoch line: " YY MM DD HH MM SS.sssssss  F NN<svlist>".
            // numsat is at cols 29..32 of the reconstructed RINEX-2 epoch line
            // (which the descriptor mirrors, leading space included).
            let numsat = field(&descriptor, 29, 32)
                .trim()
                .parse::<usize>()
                .map_err(|_| {
                    Error::Parse(format!(
                        "CRINEX V1 epoch has unparsable satellite count: {descriptor:?}"
                    ))
                })?;
            let flag = field(&descriptor, 26, 29).trim().parse::<u8>().unwrap_or(0);

            // Event records (flag > 1) carry header/comment lines rather than
            // observation lines, and the clock-offset record is omitted for them
            // entirely. Emit the epoch header line (cols 0..32, no clock, no SV
            // list), then reproduce the `numsat` event lines verbatim.
            if flag > 1 {
                emit(trim_end(field(&descriptor, 0, 32)));
                for _ in 0..numsat {
                    if let Some(extra) = lines.next() {
                        emit(extra.trim_end_matches(['\r', '\n']));
                    }
                }
                continue;
            }

            // Clock line (its own NumDiff line, possibly blank).
            let clock_line = lines
                .next()
                .ok_or_else(|| Error::Parse("CRINEX V1 epoch missing clock line".into()))?
                .trim_end_matches(['\r', '\n']);
            let clock_text = self.decode_clock_v1(clock_line)?;

            // Reconstruct the RINEX-2 epoch line(s). The SV list wraps after 12
            // satellites with a 32-space continuation pad.
            let sv_list = self.sv_tokens_v1(&descriptor, numsat)?;
            let epoch_lines = format_epoch_v1(&descriptor, &sv_list, &clock_text);
            for l in &epoch_lines {
                emit(trim_end(l));
            }

            for sv in &sv_list {
                let data_line = lines.next().ok_or_else(|| {
                    Error::Parse("CRINEX V1 epoch truncated: missing satellite line".into())
                })?;
                let n_obs = self.obs_count_for(sv);
                let (values, flags) =
                    self.decode_sat_values_v1(sv, data_line.trim_end_matches(['\r', '\n']), n_obs)?;
                for l in format_sat_lines_v1(&values, &flags) {
                    emit(trim_end(&l));
                }
            }
        }
        Ok(())
    }

    fn decode_clock_v1(&mut self, line: &str) -> Result<String> {
        let token = line.trim();
        if token.is_empty() {
            return Ok(String::new());
        }
        let value = if let Some((order, v)) = parse_reset(token)? {
            match &mut self.clock_diff {
                Some(e) => e.force_init(v, order),
                None => self.clock_diff = Some(NumDiff::new(v, order)),
            }
            v
        } else {
            let delta = token
                .parse::<i64>()
                .map_err(|_| Error::Parse(format!("CRINEX V1 clock delta {token:?} invalid")))?;
            match &mut self.clock_diff {
                Some(e) => e.decompress(delta),
                None => {
                    return Err(Error::Parse(
                        "CRINEX V1 clock delta before any clock arc init".into(),
                    ))
                }
            }
        };
        // RINEX 2 prints the receiver clock offset as `%12.9f` on its own.
        Ok(format!("{:12.9}", value as f64 / 1.0e9))
    }

    fn sv_tokens_v1(&self, descriptor: &str, numsat: usize) -> Result<Vec<String>> {
        // RINEX-2 SV list starts at col 32 of the epoch line; tokens are 3 chars
        // and may omit the constellation letter for a mono-system file.
        let list = field_from(descriptor, 32);
        let bytes = list.as_bytes();
        let mut out = Vec::with_capacity(numsat);
        for i in 0..numsat {
            let start = i * 3;
            let end = start + 3;
            if end > bytes.len() {
                return Err(Error::Parse(format!(
                    "CRINEX V1 epoch SV list shorter than {numsat} satellites"
                )));
            }
            let mut tok = list[start..end].to_string();
            if tok.starts_with(' ') {
                if let Some(sys) = self.default_system {
                    let prn = tok.trim();
                    tok = format!("{sys}{prn:>2}");
                }
            }
            out.push(tok);
        }
        Ok(out)
    }

    fn decode_sat_values_v1(
        &mut self,
        sv: &str,
        line: &str,
        n_obs: usize,
    ) -> Result<(Vec<Option<i64>>, String)> {
        let engines = self
            .obs_diff
            .entry(sv.to_string())
            .or_insert_with(|| vec![None; n_obs]);
        if engines.len() < n_obs {
            engines.resize(n_obs, None);
        }

        let mut values: Vec<Option<i64>> = Vec::with_capacity(n_obs);
        let mut cursor = 0usize;
        let bytes = line.as_bytes();
        for obs_index in 0..n_obs {
            if obs_index > 0 {
                if cursor < bytes.len() && bytes[cursor] == b' ' {
                    cursor += 1;
                } else if cursor >= bytes.len() {
                    values.push(None);
                    continue;
                }
            }
            if cursor >= bytes.len() || bytes[cursor] == b' ' {
                values.push(None);
                continue;
            }
            let tok_start = cursor;
            while cursor < bytes.len() && bytes[cursor] != b' ' {
                cursor += 1;
            }
            let token = &line[tok_start..cursor];
            let recovered = self.apply_obs_token(sv, obs_index, token)?;
            values.push(Some(recovered));
        }
        let flag_raw = if cursor < bytes.len() {
            let rest = &line[cursor..];
            rest.strip_prefix(' ').unwrap_or(rest)
        } else {
            ""
        };
        let flags = self
            .flag_diff
            .entry(sv.to_string())
            .or_default()
            .decompress(flag_raw);
        Ok((values, flags))
    }
}

/// Parse a reset token `order&value` (e.g. `3&126298057858`). Returns
/// `Ok(Some((order, value)))` for a reset, `Ok(None)` for a plain delta, and an
/// error for a malformed reset.
fn parse_reset(token: &str) -> Result<Option<(usize, i64)>> {
    let token = token.trim();
    if let Some(amp) = token.find('&') {
        let order = token[..amp]
            .parse::<usize>()
            .map_err(|_| Error::Parse(format!("CRINEX reset order in {token:?} invalid")))?;
        if order == 0 || order > MAX_ORDER {
            return Err(Error::Parse(format!(
                "CRINEX reset order {order} out of range 1..={MAX_ORDER}"
            )));
        }
        let value = token[amp + 1..]
            .parse::<i64>()
            .map_err(|_| Error::Parse(format!("CRINEX reset value in {token:?} invalid")))?;
        Ok(Some((order, value)))
    } else {
        Ok(None)
    }
}

/// Format one reconstructed V3 satellite line: the SV token, then each
/// observation as a 16-column field (`F14.3` value + LLI + SSI), with the flag
/// string supplying the LLI/SSI characters.
fn format_sat_line(sv: &str, values: &[Option<i64>], flags: &str) -> String {
    let mut out = String::with_capacity(3 + values.len() * OBS_FIELD_WIDTH);
    out.push_str(sv);
    let flag_bytes = flags.as_bytes();
    for (i, value) in values.iter().enumerate() {
        match value {
            Some(v) => out.push_str(&format_value(*v)),
            None => {
                for _ in 0..OBS_VALUE_WIDTH {
                    out.push(' ');
                }
            }
        }
        // LLI + SSI from the flag string (2 chars per observation).
        let lli = flag_bytes.get(i * 2).copied().unwrap_or(b' ');
        let ssi = flag_bytes.get(i * 2 + 1).copied().unwrap_or(b' ');
        if value.is_some() {
            out.push(lli as char);
            out.push(ssi as char);
        } else {
            out.push(' ');
            out.push(' ');
        }
    }
    out
}

/// Format a single scaled integer observation as the RINEX `F14.3` text the
/// reference `crx2rnx` emits: the value `value * 1e-3` right-aligned in 14
/// columns. A **negative** value in `(-1, 0)` drops its leading zero (`-0.920`
/// is written `-.920`) — the documented RNXCMP formatting idiosyncrasy; a
/// non-negative sub-one value keeps the zero (`0.216`, `0.000`). Formatting from
/// the scaled integer keeps the three decimals exact (no binary-float rounding
/// of the fractional part).
fn format_value(scaled: i64) -> String {
    let negative = scaled < 0;
    let magnitude = scaled.unsigned_abs();
    let whole = magnitude / 1000;
    let frac = magnitude % 1000;
    let body = if negative && whole == 0 {
        format!("-.{frac:03}")
    } else {
        format!("{}{}.{:03}", if negative { "-" } else { "" }, whole, frac)
    };
    format!("{body:>14}")
}

/// Format the RINEX-2 epoch line(s) from the reconstructed descriptor, SV list,
/// and clock text, wrapping the SV list after 12 satellites.
fn format_epoch_v1(descriptor: &str, sv_list: &[String], clock_text: &str) -> Vec<String> {
    // The fixed epoch header (date + flag + count) is cols 0..32 of the
    // descriptor.
    let head = field(descriptor, 0, 32).to_string();
    let mut lines = Vec::new();
    let first_chunk = sv_list
        .iter()
        .take(12)
        .cloned()
        .collect::<Vec<_>>()
        .join("");
    let mut first = format!("{head}{first_chunk}");
    if !clock_text.is_empty() {
        // The RINEX-2 receiver clock offset sits at columns 68..80 of the first
        // epoch line, regardless of satellite count: pad the (up-to-12) SV slots
        // to column 68 before appending it.
        while first.len() < 68 {
            first.push(' ');
        }
        first.push_str(clock_text);
    }
    lines.push(first);
    let mut idx = 12;
    while idx < sv_list.len() {
        let chunk = sv_list[idx..(idx + 12).min(sv_list.len())].join("");
        lines.push(format!("{:32}{chunk}", ""));
        idx += 12;
    }
    lines
}

/// Format the RINEX-2 observation line(s) for one satellite, wrapping after 5
/// observations per line (RINEX 2 layout: 16-col fields).
fn format_sat_lines_v1(values: &[Option<i64>], flags: &str) -> Vec<String> {
    let flag_bytes = flags.as_bytes();
    let mut lines = Vec::new();
    let mut line = String::new();
    for (i, value) in values.iter().enumerate() {
        if i > 0 && i % 5 == 0 {
            lines.push(std::mem::take(&mut line));
        }
        match value {
            Some(v) => line.push_str(&format_value(*v)),
            None => {
                for _ in 0..OBS_VALUE_WIDTH {
                    line.push(' ');
                }
            }
        }
        let lli = flag_bytes.get(i * 2).copied().unwrap_or(b' ');
        let ssi = flag_bytes.get(i * 2 + 1).copied().unwrap_or(b' ');
        if value.is_some() {
            line.push(lli as char);
            line.push(ssi as char);
        } else {
            line.push(' ');
            line.push(' ');
        }
    }
    lines.push(line);
    lines
}

/// Trim trailing spaces from a reconstructed line (the reference `crx2rnx`
/// strips trailing blanks from every output line).
fn trim_end(line: &str) -> &str {
    line.trim_end_matches(' ')
}

#[cfg(test)]
mod tests;