Skip to main content

sidereon_core/rinex_nav/
mod.rs

1//! RINEX 3.x and 4.xx navigation-message parsing (GPS LNAV/CNAV/CNAV-2, QZSS
2//! CNAV/CNAV-2, Galileo I/NAV and F/NAV, BeiDou D1/D2).
3//!
4//! Version 4 wraps each record in a `> EPH|STO|EOP|ION SVNN MSG` frame marker but
5//! keeps the same fixed-column broadcast-orbit layout for legacy messages, so
6//! those versions share the block parser; only the record grouping differs.
7//! GPS/QZSS CNAV and CNAV-2 use a separate RINEX 4 roster and are parsed into a
8//! CNAV extension. BeiDou CNV1/CNV2/CNV3, QZSS LNAV, NavIC, SBAS, and RINEX 4
9//! GLONASS FDMA frames are recognized as frame boundaries and skipped.
10//!
11//! Reads broadcast ephemeris records out of a RINEX navigation file into the
12//! typed [`BroadcastRecord`]s the [`crate::broadcast`] evaluator consumes. This
13//! is deterministic byte-to-record parsing of a fixed-column text format, not a
14//! float recipe: there is no 0-ULP claim here, and a small in-house parser is
15//! used in preference to a heavyweight RINEX dependency (the published `rinex`
16//! crate pulls ~90 transitive crates, including computational-geometry stacks,
17//! for what is a fixed-width text read).
18//!
19//! Scope: the GPS, QZSS, Galileo, and BeiDou Keplerian record layouts, plus the
20//! GLONASS four-line state-vector layout (parsed by [`parse_glonass`] and
21//! evaluated by the [`crate::glonass`] RK4 propagator, not the Keplerian path).
22//! Unsupported constellations and message rosters are skipped so a mixed file
23//! parses without error while yielding only the supported systems.
24
25mod store;
26pub use store::{BroadcastStore, NavMessagePreference};
27
28mod write;
29pub use write::encode_nav;
30
31use crate::astro::time::model::{GnssWeekTow, TimeScale};
32use crate::astro::time::{civil, gnss};
33use crate::broadcast::{ClockPolynomial, ConstellationConstants, KeplerianElements};
34use crate::constants::{KM_TO_M, SECONDS_PER_HOUR, SECONDS_PER_WEEK};
35use crate::format::columns::{field, raw_field};
36use crate::id::{GnssSatelliteId, GnssSystem};
37use crate::ionex::GalileoNequickCoeffs;
38use crate::validate::{self, FieldError};
39
40/// Parse a fixed-column RINEX broadcast-orbit numeric field, accepting Fortran
41/// `D`/`d` exponents. `None` for a missing, blank, or malformed field. The field
42/// label matches the lenient numeric reader the RINEX family shares, so the
43/// accepted/rejected forms are identical across the readers.
44fn parse_f64(line: &str, start: usize, end: usize) -> Option<f64> {
45    let value = crate::format::columns::fortran_f64(line, start, end, "numeric field")?;
46    // The fixed-width `D19.12` serializer field cannot hold a three-digit
47    // exponent, so a value outside that range is not representable in this format.
48    // Treat it as absent (the lenient `None` the readers already use for a
49    // malformed field) so the parse/encode domains agree: a required field then
50    // surfaces as a parse error, an optional one as absent. Real broadcast values
51    // have small exponents and are unaffected.
52    write::d19_12_representable(value).then_some(value)
53}
54
55/// Fallback half-window (seconds, either side of `toe`) for a record that does
56/// not broadcast a fit interval (Galileo, BeiDou). A coarse validity guard - a
57/// stale or wrong-week product is off by at least a week, so this rejects it as
58/// "no ephemeris" rather than silently extrapolating. GPS records carry an
59/// explicit curve-fit interval (see [`BroadcastRecord::fit_interval_s`]) and use
60/// half of that instead.
61pub(crate) const MAX_EPHEMERIS_AGE_S: f64 = 4.0 * SECONDS_PER_HOUR;
62
63/// GLONASS broadcast records are valid +/-15 minutes around their reference
64/// epoch (the nominal half-hour upload cadence), so a query farther than this
65/// reports no ephemeris rather than extrapolating the RK4 integration.
66pub(crate) const GLONASS_MAX_AGE_S: f64 = 15.0 * 60.0;
67const GPS_NOMINAL_FIT_INTERVAL_S: f64 = 4.0 * SECONDS_PER_HOUR;
68const GPS_LEGACY_EXTENDED_FIT_INTERVAL_S: f64 = 8.0 * SECONDS_PER_HOUR;
69const GLONASS_FREQ_CHANNEL_MIN: i32 = -7;
70const GLONASS_FREQ_CHANNEL_MAX: i32 = 6;
71
72pub(crate) fn valid_glonass_frequency_channel(channel: i32) -> bool {
73    (GLONASS_FREQ_CHANNEL_MIN..=GLONASS_FREQ_CHANNEL_MAX).contains(&channel)
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77struct RinexVersion {
78    major: u8,
79    minor: u8,
80}
81
82impl RinexVersion {
83    fn gps_fit_interval_uses_legacy_flag(self) -> bool {
84        self.major == 3 && self.minor <= 2
85    }
86}
87
88/// Which broadcast navigation message a record carries.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum NavMessage {
91    /// GPS legacy navigation message.
92    GpsLnav,
93    /// GPS CNAV message (L2C/L5), RINEX 4 token `CNAV`.
94    GpsCnav,
95    /// GPS CNAV-2 message (L1C), RINEX 4 token `CNV2`.
96    GpsCnav2,
97    /// QZSS legacy navigation message.
98    QzssLnav,
99    /// QZSS CNAV message, RINEX 4 token `CNAV`.
100    QzssCnav,
101    /// QZSS CNAV-2 message, RINEX 4 token `CNV2`.
102    QzssCnav2,
103    /// Galileo integrity navigation message (E1/E5b dual, E1 single-frequency).
104    GalileoInav,
105    /// Galileo F/NAV message (E5a).
106    GalileoFnav,
107    /// BeiDou D1 message (MEO/IGSO satellites).
108    BeidouD1,
109    /// BeiDou D2 message (geostationary satellites).
110    BeidouD2,
111}
112
113impl NavMessage {
114    /// Whether this is a GPS/QZSS CNAV-family message.
115    pub const fn is_cnav_family(self) -> bool {
116        matches!(
117            self,
118            Self::GpsCnav | Self::GpsCnav2 | Self::QzssCnav | Self::QzssCnav2
119        )
120    }
121}
122
123/// Broadcast issue-of-data plus the navigation message identity.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub struct BroadcastIssue {
126    /// The native issue value: IODE for GPS, IODnav for Galileo.
127    pub issue: u32,
128    /// The navigation message carrying the issue value.
129    pub message: NavMessage,
130}
131
132/// A broadcast group-delay term carried by a RINEX NAV record.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum BroadcastGroupDelayTerm {
135    /// GPS LNAV TGD.
136    GpsTgd,
137    /// Galileo BGD E5a/E1.
138    GalileoBgdE5aE1,
139    /// Galileo BGD E5b/E1.
140    GalileoBgdE5bE1,
141    /// BeiDou TGD1.
142    BeidouTgd1,
143    /// BeiDou TGD2.
144    BeidouTgd2,
145    /// GPS/QZSS CNAV ISC for L1 C/A.
146    CnavIscL1Ca,
147    /// GPS/QZSS CNAV ISC for L2C.
148    CnavIscL2C,
149    /// GPS/QZSS CNAV ISC for L5 I5.
150    CnavIscL5I5,
151    /// GPS/QZSS CNAV ISC for L5 Q5.
152    CnavIscL5Q5,
153    /// GPS/QZSS CNAV-2 ISC for L1C data.
154    CnavIscL1Cd,
155    /// GPS/QZSS CNAV-2 ISC for L1C pilot.
156    CnavIscL1Cp,
157}
158
159/// A GPS/QZSS signal a CNAV-family group-delay correction applies to.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub enum CnavSignal {
162    /// L1 C/A.
163    L1Ca,
164    /// L2C.
165    L2C,
166    /// L5 I5.
167    L5I5,
168    /// L5 Q5.
169    L5Q5,
170    /// L1C pilot.
171    L1Cp,
172    /// L1C data.
173    L1Cd,
174}
175
176/// Per-signal broadcast group delays preserved from one NAV record.
177#[derive(Debug, Clone, Copy, PartialEq, Default)]
178pub struct BroadcastGroupDelays {
179    /// GPS LNAV TGD, seconds.
180    pub gps_tgd_s: Option<f64>,
181    /// Galileo BGD E5a/E1, seconds.
182    pub galileo_bgd_e5a_e1_s: Option<f64>,
183    /// Galileo BGD E5b/E1, seconds.
184    pub galileo_bgd_e5b_e1_s: Option<f64>,
185    /// BeiDou TGD1, seconds.
186    pub beidou_tgd1_s: Option<f64>,
187    /// BeiDou TGD2, seconds.
188    pub beidou_tgd2_s: Option<f64>,
189    /// GPS/QZSS CNAV ISC for L1 C/A, seconds.
190    pub cnav_isc_l1ca_s: Option<f64>,
191    /// GPS/QZSS CNAV ISC for L2C, seconds.
192    pub cnav_isc_l2c_s: Option<f64>,
193    /// GPS/QZSS CNAV ISC for L5 I5, seconds.
194    pub cnav_isc_l5i5_s: Option<f64>,
195    /// GPS/QZSS CNAV ISC for L5 Q5, seconds.
196    pub cnav_isc_l5q5_s: Option<f64>,
197    /// GPS/QZSS CNAV-2 ISC for L1C data, seconds.
198    pub cnav_isc_l1cd_s: Option<f64>,
199    /// GPS/QZSS CNAV-2 ISC for L1C pilot, seconds.
200    pub cnav_isc_l1cp_s: Option<f64>,
201}
202
203impl BroadcastGroupDelays {
204    /// Build the GPS LNAV delay set.
205    pub const fn gps_lnav(tgd_s: f64) -> Self {
206        Self {
207            gps_tgd_s: Some(tgd_s),
208            galileo_bgd_e5a_e1_s: None,
209            galileo_bgd_e5b_e1_s: None,
210            beidou_tgd1_s: None,
211            beidou_tgd2_s: None,
212            cnav_isc_l1ca_s: None,
213            cnav_isc_l2c_s: None,
214            cnav_isc_l5i5_s: None,
215            cnav_isc_l5q5_s: None,
216            cnav_isc_l1cd_s: None,
217            cnav_isc_l1cp_s: None,
218        }
219    }
220
221    /// Build the Galileo delay set.
222    pub const fn galileo(bgd_e5a_e1_s: f64, bgd_e5b_e1_s: f64) -> Self {
223        Self {
224            gps_tgd_s: None,
225            galileo_bgd_e5a_e1_s: Some(bgd_e5a_e1_s),
226            galileo_bgd_e5b_e1_s: Some(bgd_e5b_e1_s),
227            beidou_tgd1_s: None,
228            beidou_tgd2_s: None,
229            cnav_isc_l1ca_s: None,
230            cnav_isc_l2c_s: None,
231            cnav_isc_l5i5_s: None,
232            cnav_isc_l5q5_s: None,
233            cnav_isc_l1cd_s: None,
234            cnav_isc_l1cp_s: None,
235        }
236    }
237
238    /// Build the BeiDou delay set.
239    pub const fn beidou(tgd1_s: f64, tgd2_s: f64) -> Self {
240        Self {
241            gps_tgd_s: None,
242            galileo_bgd_e5a_e1_s: None,
243            galileo_bgd_e5b_e1_s: None,
244            beidou_tgd1_s: Some(tgd1_s),
245            beidou_tgd2_s: Some(tgd2_s),
246            cnav_isc_l1ca_s: None,
247            cnav_isc_l2c_s: None,
248            cnav_isc_l5i5_s: None,
249            cnav_isc_l5q5_s: None,
250            cnav_isc_l1cd_s: None,
251            cnav_isc_l1cp_s: None,
252        }
253    }
254
255    /// Build a GPS/QZSS CNAV-family delay set.
256    pub const fn cnav(
257        tgd_s: Option<f64>,
258        isc_l1ca_s: Option<f64>,
259        isc_l2c_s: Option<f64>,
260        isc_l5i5_s: Option<f64>,
261        isc_l5q5_s: Option<f64>,
262        isc_l1cd_s: Option<f64>,
263        isc_l1cp_s: Option<f64>,
264    ) -> Self {
265        Self {
266            gps_tgd_s: tgd_s,
267            galileo_bgd_e5a_e1_s: None,
268            galileo_bgd_e5b_e1_s: None,
269            beidou_tgd1_s: None,
270            beidou_tgd2_s: None,
271            cnav_isc_l1ca_s: isc_l1ca_s,
272            cnav_isc_l2c_s: isc_l2c_s,
273            cnav_isc_l5i5_s: isc_l5i5_s,
274            cnav_isc_l5q5_s: isc_l5q5_s,
275            cnav_isc_l1cd_s: isc_l1cd_s,
276            cnav_isc_l1cp_s: isc_l1cp_s,
277        }
278    }
279
280    /// Select a specific group-delay term.
281    pub const fn get(&self, term: BroadcastGroupDelayTerm) -> Option<f64> {
282        match term {
283            BroadcastGroupDelayTerm::GpsTgd => self.gps_tgd_s,
284            BroadcastGroupDelayTerm::GalileoBgdE5aE1 => self.galileo_bgd_e5a_e1_s,
285            BroadcastGroupDelayTerm::GalileoBgdE5bE1 => self.galileo_bgd_e5b_e1_s,
286            BroadcastGroupDelayTerm::BeidouTgd1 => self.beidou_tgd1_s,
287            BroadcastGroupDelayTerm::BeidouTgd2 => self.beidou_tgd2_s,
288            BroadcastGroupDelayTerm::CnavIscL1Ca => self.cnav_isc_l1ca_s,
289            BroadcastGroupDelayTerm::CnavIscL2C => self.cnav_isc_l2c_s,
290            BroadcastGroupDelayTerm::CnavIscL5I5 => self.cnav_isc_l5i5_s,
291            BroadcastGroupDelayTerm::CnavIscL5Q5 => self.cnav_isc_l5q5_s,
292            BroadcastGroupDelayTerm::CnavIscL1Cd => self.cnav_isc_l1cd_s,
293            BroadcastGroupDelayTerm::CnavIscL1Cp => self.cnav_isc_l1cp_s,
294        }
295    }
296
297    /// The total CNAV single-frequency clock adjustment (TGD - ISC), seconds.
298    ///
299    /// Callers subtract this from the satellite clock offset by passing it as the
300    /// `tgd_s` argument to the broadcast evaluator. Returns `None` when TGD or
301    /// the selected ISC is unavailable.
302    pub fn cnav_single_frequency_correction_s(&self, signal: CnavSignal) -> Option<f64> {
303        let isc = match signal {
304            CnavSignal::L1Ca => self.cnav_isc_l1ca_s,
305            CnavSignal::L2C => self.cnav_isc_l2c_s,
306            CnavSignal::L5I5 => self.cnav_isc_l5i5_s,
307            CnavSignal::L5Q5 => self.cnav_isc_l5q5_s,
308            CnavSignal::L1Cp => self.cnav_isc_l1cp_s,
309            CnavSignal::L1Cd => self.cnav_isc_l1cd_s,
310        }?;
311        Some(self.gps_tgd_s? - isc)
312    }
313
314    /// The delay term historically used for broadcast-clock evaluation.
315    ///
316    /// BeiDou has no signal choice at this store level, so it keeps the previous
317    /// TGD1 behavior. CNAV-family clock evaluation keeps the record-level
318    /// default of treating a missing TGD or L1 C/A ISC as zero. Callers that know
319    /// their signal should use [`Self::get`] or
320    /// [`Self::cnav_single_frequency_correction_s`].
321    pub const fn for_message(self, system: GnssSystem, message: NavMessage) -> Option<f64> {
322        match (system, message) {
323            (GnssSystem::Gps, NavMessage::GpsLnav) | (GnssSystem::Qzss, NavMessage::QzssLnav) => {
324                self.get(BroadcastGroupDelayTerm::GpsTgd)
325            }
326            (GnssSystem::Galileo, NavMessage::GalileoFnav) => {
327                self.get(BroadcastGroupDelayTerm::GalileoBgdE5aE1)
328            }
329            (GnssSystem::Galileo, NavMessage::GalileoInav) => {
330                self.get(BroadcastGroupDelayTerm::GalileoBgdE5bE1)
331            }
332            (GnssSystem::BeiDou, NavMessage::BeidouD1 | NavMessage::BeidouD2) => {
333                self.get(BroadcastGroupDelayTerm::BeidouTgd1)
334            }
335            (
336                GnssSystem::Gps | GnssSystem::Qzss,
337                NavMessage::GpsCnav
338                | NavMessage::GpsCnav2
339                | NavMessage::QzssCnav
340                | NavMessage::QzssCnav2,
341            ) => match (self.gps_tgd_s, self.cnav_isc_l1ca_s) {
342                (Some(tgd), Some(isc)) => Some(tgd - isc),
343                (Some(tgd), None) => Some(tgd),
344                (None, Some(isc)) => Some(-isc),
345                (None, None) => Some(0.0),
346            },
347            _ => None,
348        }
349    }
350}
351
352/// CNAV/CNAV-2 parameters that have no legacy counterpart.
353#[derive(Debug, Clone, Copy, PartialEq)]
354pub struct CnavParameters {
355    /// Semi-major axis rate ADOT (m/s), ORBIT-1 field 1.
356    pub adot_m_s: f64,
357    /// Rate of the mean-motion difference (rad/s^2), ORBIT-5 field 2.
358    pub delta_n0_dot_rad_s2: f64,
359    /// CEI data-sequence propagation epoch: WNop week plus top seconds of week.
360    pub top: GnssWeekTow,
361    /// URA_ED index, [-16, 15].
362    pub ura_ed_index: i8,
363    /// URA_NED0 index, [-16, 15].
364    pub ura_ned0_index: i8,
365    /// URA_NED1 index, [0, 7].
366    pub ura_ned1_index: u8,
367    /// URA_NED2 index, [0, 7].
368    pub ura_ned2_index: u8,
369    /// Transmission time of message t_tm, seconds of week.
370    pub transmission_time_sow: f64,
371    /// Optional decimal-coded flag bits.
372    pub flags: Option<u32>,
373}
374
375/// Nominal URA meters for a CNAV ED/NED0 index.
376///
377/// Returns `None` for the no-prediction indices 15 and -16.
378pub fn cnav_ura_nominal_m(index: i8) -> Option<f64> {
379    match index {
380        -16 | 15 => None,
381        1 => Some(2.8),
382        3 => Some(5.7),
383        5 => Some(11.3),
384        -15..=6 => Some(2.0_f64.powf(1.0 + f64::from(index) / 2.0)),
385        7..=14 => Some(2.0_f64.powi(i32::from(index) - 2)),
386        _ => None,
387    }
388}
389
390/// Time-dependent CNAV URA_NED bound in meters at GPST `t`.
391pub fn cnav_ura_ned_m(params: &CnavParameters, t: GnssWeekTow) -> Option<f64> {
392    let ned0 = cnav_ura_nominal_m(params.ura_ned0_index)?;
393    let ned1 = 2.0_f64.powi(-(14 + i32::from(params.ura_ned1_index)));
394    let ned2 = 2.0_f64.powi(-(28 + i32::from(params.ura_ned2_index)));
395    let dt_op = (f64::from(t.week) - f64::from(params.top.week)) * SECONDS_PER_WEEK
396        + (t.tow_s - params.top.tow_s);
397    let linear = ned0 + ned1 * dt_op;
398    if dt_op <= 93_600.0 {
399        Some(linear)
400    } else {
401        Some(linear + ned2 * (dt_op - 93_600.0) * (dt_op - 93_600.0))
402    }
403}
404
405/// Whether a BeiDou PRN is a geostationary satellite (BDS-2 C01-C05, BDS-3
406/// C59-C61), which take the geostationary orbit-evaluation branch.
407pub fn is_beidou_geo(sat: GnssSatelliteId) -> bool {
408    sat.system == GnssSystem::BeiDou && (sat.prn <= 5 || (59..=61).contains(&sat.prn))
409}
410
411/// A Klobuchar-8 broadcast ionosphere coefficient set (the eight alpha/beta
412/// values transmitted by GPS and BeiDou; the same model serves both, evaluated
413/// per carrier - see [`crate::ionex::klobuchar_native`]).
414#[derive(Debug, Clone, Copy, PartialEq)]
415pub struct KlobucharAlphaBeta {
416    /// Cosine-amplitude polynomial coefficients (a0..a3).
417    pub alpha: [f64; 4],
418    /// Period polynomial coefficients (b0..b3).
419    pub beta: [f64; 4],
420}
421
422/// Broadcast ionosphere-correction coefficients from a RINEX header's
423/// `IONOSPHERIC CORR` lines or RINEX 4 body `> ION` frames.
424///
425/// Captures the Klobuchar-8 sets used by GPS (`GPSA`/`GPSB`) and BeiDou
426/// (`BDSA`/`BDSB`), plus Galileo's three NeQuick-G effective-ionisation
427/// coefficients (`GAL`). QZSS and NavIC Klobuchar sets are not retained.
428#[derive(Debug, Clone, Copy, PartialEq, Default)]
429pub struct IonoCorrections {
430    /// GPS broadcast Klobuchar coefficients (`GPSA`/`GPSB`), if present.
431    pub gps: Option<KlobucharAlphaBeta>,
432    /// BeiDou broadcast Klobuchar coefficients (`BDSA`/`BDSB`), if present.
433    pub beidou: Option<KlobucharAlphaBeta>,
434    /// Galileo broadcast NeQuick-G coefficients (`GAL`), if present.
435    pub galileo: Option<GalileoNequickCoeffs>,
436}
437
438/// One parsed GLONASS broadcast record: a PZ-90.11 ECEF state vector and the
439/// clock terms, evaluated by the crate's GLONASS RK4 propagator (GLONASS is not
440/// Keplerian, so it does not use [`BroadcastRecord`]).
441#[derive(Debug, Clone, Copy, PartialEq)]
442pub struct GlonassRecord {
443    /// The transmitting satellite.
444    pub satellite_id: GnssSatelliteId,
445    /// Reference epoch as seconds past J2000 in **UTC** (leap-second-independent;
446    /// the store adds the GPS−UTC offset to compare with the GPST-aligned query).
447    pub toe_utc_j2000_s: f64,
448    /// PZ-90.11 ECEF position at the reference epoch (meters).
449    pub pos_m: [f64; 3],
450    /// PZ-90.11 ECEF velocity at the reference epoch (meters/second).
451    pub vel_m_s: [f64; 3],
452    /// Lunisolar acceleration at the reference epoch (meters/second^2).
453    pub acc_m_s2: [f64; 3],
454    /// Clock bias broadcast field (−TauN, seconds).
455    pub clk_bias: f64,
456    /// Relative frequency offset (+GammaN, dimensionless).
457    pub gamma_n: f64,
458    /// Satellite health (0 is healthy).
459    pub sv_health: f64,
460    /// FDMA frequency-channel number.
461    pub freq_channel: i32,
462}
463
464/// A GLONASS record skipped by [`parse_glonass_lenient`] because its slot is not
465/// representable as a [`GnssSatelliteId`] (an extended slot beyond the engine's
466/// PRN cap, e.g. `R28` in real BKG/IGS products).
467#[derive(Debug, Clone, PartialEq, Eq)]
468pub struct SkippedGlonass {
469    /// The 3-character satellite token as it appeared in the file (`R28`).
470    pub token: String,
471}
472
473/// The result of a lenient GLONASS parse: the representable records plus the
474/// slot tokens that were skipped.
475///
476/// Mirrors the partial-success reporting used elsewhere for unrepresentable
477/// input (`RinexObs::skipped_records`, [`crate::constellation::Catalog`]): a
478/// dropped record carries its identity rather than vanishing silently, so a
479/// caller can surface how many / which slots were skipped.
480#[derive(Debug, Clone, PartialEq, Default)]
481pub struct GlonassParse {
482    /// Records for representable slots, in file order.
483    pub records: Vec<GlonassRecord>,
484    /// Slots that could not be represented and were skipped, in file order.
485    pub skipped: Vec<SkippedGlonass>,
486}
487
488/// One parsed broadcast navigation record.
489#[derive(Debug, Clone, Copy, PartialEq)]
490pub struct BroadcastRecord {
491    /// The transmitting satellite.
492    pub satellite_id: GnssSatelliteId,
493    /// The navigation message the record carries.
494    pub message: NavMessage,
495    /// Broadcast issue-of-data for issue-matched correction products.
496    pub issue_of_data: BroadcastIssue,
497    /// Native broadcast week number (from the broadcast record).
498    pub week: u32,
499    /// Scale-tagged ephemeris reference time (`toe`).
500    pub toe: GnssWeekTow,
501    /// Scale-tagged clock reference time (`toc`).
502    pub toc: GnssWeekTow,
503    /// Keplerian orbital elements (`toe_sow` is seconds of week).
504    pub elements: KeplerianElements,
505    /// Clock polynomial (`toc_sow` is the record's own epoch, seconds of week).
506    pub clock: ClockPolynomial,
507    /// Broadcast group-delay terms carried by this message.
508    pub group_delays: BroadcastGroupDelays,
509    /// CNAV/CNAV-2 extension, present only for GPS/QZSS CNAV-family records.
510    pub cnav: Option<CnavParameters>,
511    /// Satellite health word (0 is healthy for the GPS/Galileo nominal case).
512    pub sv_health: f64,
513    /// Signal-in-space accuracy: GPS URA (m) / Galileo SISA (m).
514    pub sv_accuracy_m: f64,
515    /// GPS curve-fit interval in seconds, centered on `toe` (IS-GPS-200): the
516    /// record is valid for `toe ± fit_interval_s / 2`. `None` for Galileo and
517    /// BeiDou, which do not broadcast a fit interval in the RINEX record; those
518    /// fall back to the crate's nominal four-hour age bound.
519    pub fit_interval_s: Option<f64>,
520}
521
522impl BroadcastRecord {
523    /// Native time scale used by this record's `toe`/`toc`.
524    pub const fn time_scale(&self) -> TimeScale {
525        self.toe.system
526    }
527
528    /// The per-constellation constants this record evaluates with.
529    pub const fn constants(&self) -> ConstellationConstants {
530        match self.satellite_id.system {
531            GnssSystem::Galileo => ConstellationConstants::GALILEO,
532            GnssSystem::BeiDou => ConstellationConstants::BEIDOU,
533            // GPS (and any other Keplerian system) use the GPS constants.
534            _ => ConstellationConstants::GPS,
535        }
536    }
537
538    /// Group delay used by the broadcast-clock evaluator for this message.
539    pub fn broadcast_clock_group_delay_s(&self) -> f64 {
540        self.group_delays
541            .for_message(self.satellite_id.system, self.message)
542            .unwrap_or(0.0)
543    }
544
545    /// Build a GPS LNAV record from decoded navigation-message subframes.
546    ///
547    /// This closes the `lnav::decode -> broadcast source` half of the real-time
548    /// pipeline: feed [`crate::navigation::lnav::decode`]'s output here, collect
549    /// the records into a [`BroadcastStore`], and solve with
550    /// [`solve_broadcast`](crate::positioning::solve_broadcast). The conversion
551    /// matches the RINEX navigation parser's record exactly except for the inputs
552    /// only the air interface carries:
553    ///
554    /// - The decoded angular elements are in semicircles (and semicircles/second)
555    ///   as transmitted by GPS LNAV; they are scaled to the radians the
556    ///   [`crate::broadcast`] evaluator expects (the harmonic `cuc..cis` terms are
557    ///   already radians and `crc`/`crs` meters, so they pass through unchanged).
558    /// - The 10-bit transmitted week number is ambiguous across the GPS
559    ///   1024-week rollover, so the full (unrolled) week is taken from
560    ///   `full_week` rather than inferred from the message. The caller-supplied
561    ///   `full_week` must agree with the decoded 10-bit week
562    ///   (`full_week % 1024 == decoded.week_number`); a disagreement means the
563    ///   caller is unrolling against the wrong rollover epoch and is rejected with
564    ///   [`LnavRecordError::WeekMismatch`] rather than silently dating the
565    ///   ephemeris to the wrong GPS week.
566    /// - The fit interval is derived from the fit-interval flag together with
567    ///   IODE/IODC per IS-GPS-200N 20.3.3.4.3.1 and Table 20-XII (the table the
568    ///   older revisions numbered 20-XI): `flag = 0` is the nominal 4-hour curve
569    ///   fit; `flag = 1` is an extended fit whose length is set by IODE/IODC
570    ///   (short-term extended `IODE < 240` is 6 hours; long-term extended
571    ///   `IODE` in `240..=255` is 8/14/26 hours by IODC range). Reserved IODC
572    ///   combinations are rejected with [`LnavRecordError::FitIntervalUnsupported`].
573    /// - The 4-bit URA index maps to its IS-GPS-200N 20.3.3.3.1.3 meters value;
574    ///   index 15 (no accuracy prediction / not to be used) carries no usable
575    ///   bound and is rejected with [`LnavRecordError::NoUraPrediction`].
576    ///
577    /// LNAV is the GPS L1 C/A message, so a non-GPS `satellite_id` is rejected.
578    pub fn from_lnav(
579        decoded: &crate::navigation::lnav::LnavDecoded,
580        satellite_id: GnssSatelliteId,
581        full_week: u32,
582    ) -> Result<Self, LnavRecordError> {
583        if satellite_id.system != GnssSystem::Gps {
584            return Err(LnavRecordError::NotGps(satellite_id));
585        }
586
587        // The unrolled `full_week` must reduce to the decoded 10-bit week
588        // (IS-GPS-200N 20.3.3.3.1.1). A mismatch means the caller unrolled
589        // against the wrong rollover epoch; trusting `full_week` would date the
590        // ephemeris to the wrong GPS week, so reject it.
591        if i64::from(full_week % 1024) != decoded.week_number {
592            return Err(LnavRecordError::WeekMismatch {
593                full_week,
594                decoded_week: decoded.week_number,
595            });
596        }
597
598        let sv_accuracy_m = gps_ura_index_to_meters(decoded.ura_index)
599            .ok_or(LnavRecordError::NoUraPrediction(decoded.ura_index))?;
600        let fit_interval_s =
601            gps_fit_interval_from_flag(decoded.fit_interval_flag, decoded.iode, decoded.iodc)?;
602
603        // GPS LNAV transmits the angular ephemeris elements in semicircles and
604        // semicircles/second; the Keplerian evaluator works in radians.
605        const SEMICIRCLE_TO_RAD: f64 = core::f64::consts::PI;
606
607        let elements = KeplerianElements {
608            sqrt_a: decoded.sqrt_a,
609            e: decoded.eccentricity,
610            m0: decoded.m0 * SEMICIRCLE_TO_RAD,
611            delta_n: decoded.delta_n * SEMICIRCLE_TO_RAD,
612            omega0: decoded.omega0 * SEMICIRCLE_TO_RAD,
613            i0: decoded.i0 * SEMICIRCLE_TO_RAD,
614            omega: decoded.omega * SEMICIRCLE_TO_RAD,
615            omega_dot: decoded.omega_dot * SEMICIRCLE_TO_RAD,
616            idot: decoded.idot * SEMICIRCLE_TO_RAD,
617            cuc: decoded.cuc,
618            cus: decoded.cus,
619            crc: decoded.crc,
620            crs: decoded.crs,
621            cic: decoded.cic,
622            cis: decoded.cis,
623            toe_sow: decoded.toe as f64,
624        };
625        let clock = ClockPolynomial {
626            af0: decoded.af0,
627            af1: decoded.af1,
628            af2: decoded.af2,
629            toc_sow: decoded.toc as f64,
630        };
631
632        let toe = GnssWeekTow::new(TimeScale::Gpst, full_week, elements.toe_sow)
633            .and_then(GnssWeekTow::normalized)
634            .map_err(|_| LnavRecordError::InvalidEpoch("toe"))?;
635        let toc = GnssWeekTow::new(TimeScale::Gpst, full_week, clock.toc_sow)
636            .and_then(GnssWeekTow::normalized)
637            .map_err(|_| LnavRecordError::InvalidEpoch("toc"))?;
638
639        Ok(BroadcastRecord {
640            satellite_id,
641            message: NavMessage::GpsLnav,
642            issue_of_data: BroadcastIssue {
643                issue: decoded.iode as u32,
644                message: NavMessage::GpsLnav,
645            },
646            week: full_week,
647            toe,
648            toc,
649            elements,
650            clock,
651            group_delays: BroadcastGroupDelays::gps_lnav(decoded.tgd),
652            cnav: None,
653            sv_health: decoded.sv_health as f64,
654            sv_accuracy_m,
655            fit_interval_s: Some(fit_interval_s),
656        })
657    }
658}
659
660/// The nominal GPS user range accuracy (URA) value in meters for a 4-bit URA
661/// index N (IS-GPS-200N Section 20.3.3.3.1.3). Each value is the upper bound of
662/// the URA band the index represents. Index 15 carries no accuracy prediction
663/// (the SV is not to be used for safe navigation) and has no usable meters
664/// bound, so it returns `None` rather than a fabricated finite value.
665pub(crate) fn gps_ura_index_to_meters(index: i64) -> Option<f64> {
666    let meters = match index {
667        0 => 2.4,
668        1 => 3.4,
669        2 => 4.85,
670        3 => 6.85,
671        4 => 9.65,
672        5 => 13.65,
673        6 => 24.0,
674        7 => 48.0,
675        8 => 96.0,
676        9 => 192.0,
677        10 => 384.0,
678        11 => 768.0,
679        12 => 1536.0,
680        13 => 3072.0,
681        14 => 6144.0,
682        // 15 = no accuracy prediction / not to be used; anything outside the
683        // 4-bit range cannot occur from a decoded message either.
684        _ => return None,
685    };
686    Some(meters)
687}
688
689const GPS_FIT_INTERVAL_6H_S: f64 = 6.0 * SECONDS_PER_HOUR;
690const GPS_FIT_INTERVAL_8H_S: f64 = 8.0 * SECONDS_PER_HOUR;
691const GPS_FIT_INTERVAL_14H_S: f64 = 14.0 * SECONDS_PER_HOUR;
692const GPS_FIT_INTERVAL_26H_S: f64 = 26.0 * SECONDS_PER_HOUR;
693
694/// Curve-fit interval (seconds) for a GPS LNAV record from its fit-interval flag
695/// plus IODE/IODC, per IS-GPS-200N 20.3.3.4.3.1, 6.2.3, and Table 20-XII (the
696/// table older revisions numbered 20-XI).
697///
698/// `flag = 0` is the nominal 4-hour fit. `flag = 1` is an extended fit: IODE
699/// selects short-term extended operations (`IODE < 240`, a 6-hour fit) from
700/// long-term extended operations (`IODE` in `240..=255`), and for the long-term
701/// case the IODC range selects 8, 14, or 26 hours. Reserved IODC values and any
702/// other flag/IODE/IODC combination are rejected.
703pub(crate) fn gps_fit_interval_from_flag(
704    fit_interval_flag: i64,
705    iode: i64,
706    iodc: i64,
707) -> Result<f64, LnavRecordError> {
708    let unsupported = || LnavRecordError::FitIntervalUnsupported {
709        fit_interval_flag,
710        iode,
711        iodc,
712    };
713    match fit_interval_flag {
714        0 => Ok(GPS_NOMINAL_FIT_INTERVAL_S),
715        1 => {
716            if (0..240).contains(&iode) {
717                // Short-term extended operations (Table 20-XII, 2-14 day row).
718                // IODE is an 8-bit unsigned field, so a negative value is not a
719                // real decode and falls through to the unsupported error.
720                Ok(GPS_FIT_INTERVAL_6H_S)
721            } else if (240..=255).contains(&iode) {
722                // Long-term extended operations: IODC selects the fit length.
723                match iodc {
724                    240..=247 => Ok(GPS_FIT_INTERVAL_8H_S),
725                    248..=255 | 496 => Ok(GPS_FIT_INTERVAL_14H_S),
726                    497..=503 | 1021..=1023 => Ok(GPS_FIT_INTERVAL_26H_S),
727                    _ => Err(unsupported()),
728                }
729            } else {
730                Err(unsupported())
731            }
732        }
733        _ => Err(unsupported()),
734    }
735}
736
737/// Failure building a [`BroadcastRecord`] from decoded LNAV subframes.
738#[derive(Debug, Clone, Copy, PartialEq, Eq)]
739pub enum LnavRecordError {
740    /// LNAV is the GPS L1 C/A message; the satellite is not a GPS satellite.
741    NotGps(GnssSatelliteId),
742    /// A derived week/time-of-week value was not representable.
743    InvalidEpoch(&'static str),
744    /// The caller-supplied `full_week` does not reduce to the decoded 10-bit week
745    /// (`full_week % 1024 != decoded_week`), so it unrolls to the wrong GPS week.
746    WeekMismatch {
747        /// The caller-supplied unrolled week.
748        full_week: u32,
749        /// The 10-bit week decoded from the message.
750        decoded_week: i64,
751    },
752    /// URA index 15 (or an out-of-range index) carries no accuracy prediction.
753    NoUraPrediction(i64),
754    /// The fit-interval flag / IODE / IODC combination is reserved or otherwise
755    /// not a defined IS-GPS-200N Table 20-XII curve-fit interval.
756    FitIntervalUnsupported {
757        /// The 1-bit fit-interval flag from the message.
758        fit_interval_flag: i64,
759        /// The decoded IODE.
760        iode: i64,
761        /// The decoded IODC.
762        iodc: i64,
763    },
764}
765
766impl core::fmt::Display for LnavRecordError {
767    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
768        match self {
769            LnavRecordError::NotGps(sat) => {
770                write!(f, "LNAV is a GPS message; {sat} is not a GPS satellite")
771            }
772            LnavRecordError::InvalidEpoch(field) => {
773                write!(f, "derived {field} week/TOW is not representable")
774            }
775            LnavRecordError::WeekMismatch {
776                full_week,
777                decoded_week,
778            } => write!(
779                f,
780                "full_week {full_week} (week % 1024 = {}) disagrees with decoded 10-bit week {decoded_week}",
781                full_week % 1024
782            ),
783            LnavRecordError::NoUraPrediction(index) => {
784                write!(f, "URA index {index} carries no accuracy prediction")
785            }
786            LnavRecordError::FitIntervalUnsupported {
787                fit_interval_flag,
788                iode,
789                iodc,
790            } => write!(
791                f,
792                "fit interval flag {fit_interval_flag} with IODE {iode} / IODC {iodc} is not a defined curve-fit interval"
793            ),
794        }
795    }
796}
797
798impl std::error::Error for LnavRecordError {}
799
800fn broadcast_time_scale(system: GnssSystem) -> TimeScale {
801    match system {
802        GnssSystem::Galileo => TimeScale::Gst,
803        GnssSystem::BeiDou => TimeScale::Bdt,
804        _ => TimeScale::Gpst,
805    }
806}
807
808/// Why a RINEX NAV file could not be parsed.
809#[derive(Debug, Clone, PartialEq, Eq)]
810pub enum NavParseError {
811    /// The header did not declare a supported RINEX navigation file.
812    UnsupportedHeader(String),
813    /// No `END OF HEADER` line was found.
814    MissingHeaderEnd,
815    /// A record was shorter than its message layout requires.
816    TruncatedRecord(String),
817    /// A required numeric field was missing or unparseable.
818    BadField {
819        /// The satellite whose record holds the bad field.
820        satellite: String,
821        /// Which field failed.
822        field: &'static str,
823    },
824    /// A required header numeric field was malformed, non-finite, or out of range.
825    BadHeaderField {
826        /// Which header field failed.
827        field: &'static str,
828    },
829}
830
831impl core::fmt::Display for NavParseError {
832    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
833        match self {
834            NavParseError::UnsupportedHeader(s) => write!(f, "unsupported RINEX NAV header: {s}"),
835            NavParseError::MissingHeaderEnd => write!(f, "no END OF HEADER line"),
836            NavParseError::TruncatedRecord(s) => write!(f, "truncated navigation record for {s}"),
837            NavParseError::BadField { satellite, field } => {
838                write!(f, "bad/missing {field} field in record for {satellite}")
839            }
840            NavParseError::BadHeaderField { field } => {
841                write!(f, "bad/missing {field} field in navigation header")
842            }
843        }
844    }
845}
846
847impl std::error::Error for NavParseError {}
848
849#[derive(Debug, Clone, PartialEq, Eq)]
850pub struct SkippedNavBlock {
851    pub satellite: String,
852    pub message: String,
853}
854
855#[derive(Debug, Clone, PartialEq)]
856pub struct NavParse {
857    pub records: Vec<BroadcastRecord>,
858    pub skipped: Vec<SkippedNavBlock>,
859}
860
861/// Parse a RINEX 3.x or 4.xx navigation file into the supported GPS, QZSS,
862/// Galileo, and BeiDou Keplerian records.
863///
864/// Unsupported RINEX 4 message rosters, including BeiDou CNV1/CNV2/CNV3 and
865/// QZSS LNAV, are skipped rather than fed through the wrong layout. The records
866/// are returned in file order; selection by epoch, health, and message type is
867/// the caller's job.
868pub fn parse_nav(text: &str) -> Result<Vec<BroadcastRecord>, NavParseError> {
869    let mut lines = text.lines();
870    let version = verify_and_skip_header(&mut lines)?;
871    if version.major >= 4 {
872        parse_nav_v4(lines, version)
873    } else {
874        parse_nav_v3(lines, version)
875    }
876}
877
878/// Parse supported NAV records while dropping malformed supported body blocks.
879///
880/// Header failures remain fatal because no record boundaries are trustworthy
881/// before the file type and version are known. Unsupported constellations and
882/// unsupported version-4 messages follow the strict parser's existing skip policy.
883pub fn parse_nav_lenient(text: &str) -> Result<NavParse, NavParseError> {
884    let mut lines = text.lines();
885    let version = verify_and_skip_header(&mut lines)?;
886    let (records, skipped) = if version.major >= 4 {
887        parse_nav_v4_lenient(lines, version)
888    } else {
889        parse_nav_v3_lenient(lines, version)
890    };
891    Ok(NavParse { records, skipped })
892}
893
894/// Version-3 body: a record starts at a line whose first three columns are a
895/// system letter followed by two digits; continuation lines are column-indented.
896fn parse_nav_v3<'a, I>(
897    lines: I,
898    version: RinexVersion,
899) -> Result<Vec<BroadcastRecord>, NavParseError>
900where
901    I: Iterator<Item = &'a str>,
902{
903    let mut blocks: Vec<Vec<&str>> = Vec::new();
904    for line in lines {
905        if is_record_start(line) {
906            blocks.push(vec![line]);
907        } else if let Some(last) = blocks.last_mut() {
908            last.push(line);
909        }
910    }
911
912    let mut records = Vec::new();
913    for block in &blocks {
914        let letter = block[0].as_bytes()[0] as char;
915        match GnssSystem::from_letter(letter) {
916            Some(GnssSystem::Gps)
917            | Some(GnssSystem::Galileo)
918            | Some(GnssSystem::BeiDou)
919            | Some(GnssSystem::Qzss) => records.push(parse_keplerian_block(block, None, version)?),
920            // Recognized boundary, unsupported model (GLONASS state-vector, SBAS): skip.
921            _ => {}
922        }
923    }
924    Ok(records)
925}
926
927fn parse_nav_v3_lenient<'a, I>(
928    lines: I,
929    version: RinexVersion,
930) -> (Vec<BroadcastRecord>, Vec<SkippedNavBlock>)
931where
932    I: Iterator<Item = &'a str>,
933{
934    let mut blocks: Vec<Vec<&str>> = Vec::new();
935    for line in lines {
936        if is_record_start(line) {
937            blocks.push(vec![line]);
938        } else if let Some(last) = blocks.last_mut() {
939            last.push(line);
940        }
941    }
942
943    let mut records = Vec::new();
944    let mut skipped = Vec::new();
945    for block in &blocks {
946        let letter = block[0].as_bytes()[0] as char;
947        match GnssSystem::from_letter(letter) {
948            Some(GnssSystem::Gps)
949            | Some(GnssSystem::Galileo)
950            | Some(GnssSystem::BeiDou)
951            | Some(GnssSystem::Qzss) => match parse_keplerian_block(block, None, version) {
952                Ok(record) => records.push(record),
953                Err(error) => skipped.push(SkippedNavBlock {
954                    satellite: nav_block_satellite(block),
955                    message: error.to_string(),
956                }),
957            },
958            _ => {}
959        }
960    }
961    (records, skipped)
962}
963
964/// Version-4 body: each record is introduced by a `> EPH|STO|EOP|ION SVNN MSG`
965/// frame marker. `EPH` frames carrying a supported legacy Keplerian message use
966/// [`parse_keplerian_block`]; GPS/QZSS CNAV-family messages use
967/// [`parse_cnav_block`]. The message type is taken from the marker token (so
968/// I/NAV vs F/NAV, D1 vs D2, and GPS/QZSS CNV2 vs BeiDou CNV2 are explicit)
969/// after the marker SV and message family are cross-checked against the body
970/// line. STO/EOP/ION frames and unsupported message rosters are skipped.
971fn parse_nav_v4<'a, I>(
972    lines: I,
973    version: RinexVersion,
974) -> Result<Vec<BroadcastRecord>, NavParseError>
975where
976    I: Iterator<Item = &'a str>,
977{
978    // Group by marker line: each frame is its marker plus the body lines up to
979    // the next marker.
980    let frames = v4_frames(lines);
981    let mut records = Vec::new();
982    for (marker, body) in &frames {
983        let Some((frame_type, sv, msg_token)) = parse_v4_marker(marker) else {
984            continue;
985        };
986        if frame_type != "EPH" {
987            continue; // STO/EOP/ION carry no ephemeris.
988        }
989        let letter = sv.as_bytes().first().copied().map_or(' ', char::from);
990        let Some(system) = GnssSystem::from_letter(letter) else {
991            continue;
992        };
993        let supported = matches!(
994            system,
995            GnssSystem::Gps | GnssSystem::Galileo | GnssSystem::BeiDou | GnssSystem::Qzss
996        );
997        if !supported {
998            continue; // GLONASS/SBAS/NavIC: not a supported Keplerian system here.
999        }
1000        if let Some(message) = nav_message_from_v4_token(msg_token, system) {
1001            validate_v4_ephemeris_marker(sv, message, body)?;
1002            if message.is_cnav_family() {
1003                records.push(parse_cnav_block(body, message)?);
1004            } else {
1005                records.push(parse_keplerian_block(body, Some(message), version)?);
1006            }
1007        } else if known_v4_ephemeris_token(msg_token)
1008            && !explicitly_skipped_v4_message(msg_token, system)
1009        {
1010            return Err(NavParseError::BadField {
1011                satellite: sv.to_string(),
1012                field: "message",
1013            });
1014        }
1015    }
1016    Ok(records)
1017}
1018
1019fn parse_nav_v4_lenient<'a, I>(
1020    lines: I,
1021    version: RinexVersion,
1022) -> (Vec<BroadcastRecord>, Vec<SkippedNavBlock>)
1023where
1024    I: Iterator<Item = &'a str>,
1025{
1026    let frames = v4_frames(lines);
1027    let mut records = Vec::new();
1028    let mut skipped = Vec::new();
1029    for (marker, body) in &frames {
1030        let Some((frame_type, sv, msg_token)) = parse_v4_marker(marker) else {
1031            continue;
1032        };
1033        if frame_type != "EPH" {
1034            continue;
1035        }
1036        let letter = sv.as_bytes().first().copied().map_or(' ', char::from);
1037        let Some(system) = GnssSystem::from_letter(letter) else {
1038            continue;
1039        };
1040        let supported = matches!(
1041            system,
1042            GnssSystem::Gps | GnssSystem::Qzss | GnssSystem::Galileo | GnssSystem::BeiDou
1043        );
1044        if !supported {
1045            continue;
1046        }
1047        if let Some(message) = nav_message_from_v4_token(msg_token, system) {
1048            let parsed = validate_v4_ephemeris_marker(sv, message, body)
1049                .and_then(|()| parse_keplerian_block(body, Some(message), version));
1050            match parsed {
1051                Ok(record) => records.push(record),
1052                Err(error) => skipped.push(SkippedNavBlock {
1053                    satellite: sv.to_string(),
1054                    message: error.to_string(),
1055                }),
1056            }
1057        }
1058    }
1059    (records, skipped)
1060}
1061
1062fn nav_block_satellite(block: &[&str]) -> String {
1063    block
1064        .first()
1065        .and_then(|line| line.get(0..3))
1066        .unwrap_or("")
1067        .trim()
1068        .to_string()
1069}
1070
1071fn v4_frames<'a, I>(lines: I) -> Vec<(&'a str, Vec<&'a str>)>
1072where
1073    I: Iterator<Item = &'a str>,
1074{
1075    let mut frames: Vec<(&str, Vec<&str>)> = Vec::new();
1076    for line in lines {
1077        if is_v4_frame_marker(line) {
1078            frames.push((line, Vec::new()));
1079        } else if let Some((_, body)) = frames.last_mut() {
1080            body.push(line);
1081        }
1082    }
1083    frames
1084}
1085
1086/// Whether a version-4 line is a frame marker (`> ...`).
1087fn is_v4_frame_marker(line: &str) -> bool {
1088    line.starts_with("> ")
1089}
1090
1091/// Split a version-4 frame marker `> EPH G01 LNAV` into (frame type, SV, message
1092/// token), or `None` if it is malformed. Mirrors the RINEX-4 marker layout:
1093/// `>` then the 4-column frame class, the SV, and the message-type token.
1094fn parse_v4_marker(line: &str) -> Option<(&str, &str, &str)> {
1095    let rest = line.strip_prefix('>')?;
1096    let mut fields = rest.split_whitespace();
1097    let frame_type = fields.next()?;
1098    let sv = fields.next()?;
1099    let msg_token = fields.next()?;
1100    Some((frame_type, sv, msg_token))
1101}
1102
1103/// Map a version-4 EPH message token to the [`NavMessage`] for the supported
1104/// Keplerian messages. `CNV2` is system-overloaded: GPS/QZSS CNV2 is supported
1105/// as CNAV-2, while BeiDou CNV2 is a different roster and remains skipped.
1106fn nav_message_from_v4_token(token: &str, system: GnssSystem) -> Option<NavMessage> {
1107    match (token, system) {
1108        ("LNAV", GnssSystem::Gps) => Some(NavMessage::GpsLnav),
1109        ("CNAV", GnssSystem::Gps) => Some(NavMessage::GpsCnav),
1110        ("CNV2", GnssSystem::Gps) => Some(NavMessage::GpsCnav2),
1111        ("LNAV", GnssSystem::Qzss) => Some(NavMessage::QzssLnav),
1112        ("CNAV", GnssSystem::Qzss) => Some(NavMessage::QzssCnav),
1113        ("CNV2", GnssSystem::Qzss) => Some(NavMessage::QzssCnav2),
1114        ("INAV", GnssSystem::Galileo) => Some(NavMessage::GalileoInav),
1115        ("FNAV", GnssSystem::Galileo) => Some(NavMessage::GalileoFnav),
1116        ("D1", GnssSystem::BeiDou) => Some(NavMessage::BeidouD1),
1117        ("D2", GnssSystem::BeiDou) => Some(NavMessage::BeidouD2),
1118        _ => None,
1119    }
1120}
1121
1122fn known_v4_ephemeris_token(token: &str) -> bool {
1123    matches!(
1124        token,
1125        "LNAV" | "CNAV" | "CNV1" | "CNV2" | "CNV3" | "INAV" | "FNAV" | "D1" | "D2"
1126    )
1127}
1128
1129fn explicitly_skipped_v4_message(token: &str, system: GnssSystem) -> bool {
1130    matches!(
1131        (token, system),
1132        ("CNV1" | "CNV2" | "CNV3", GnssSystem::BeiDou)
1133    )
1134}
1135
1136fn validate_v4_ephemeris_marker(
1137    marker_sv: &str,
1138    message: NavMessage,
1139    body: &[&str],
1140) -> Result<(), NavParseError> {
1141    let Some(body_sv) = body
1142        .first()
1143        .and_then(|line| line.get(0..3))
1144        .map(str::trim)
1145        .filter(|sv| !sv.is_empty())
1146    else {
1147        return Ok(());
1148    };
1149
1150    let same_satellite = match (
1151        marker_sv.parse::<GnssSatelliteId>(),
1152        body_sv.parse::<GnssSatelliteId>(),
1153    ) {
1154        (Ok(marker), Ok(body)) => marker == body,
1155        _ => marker_sv == body_sv,
1156    };
1157
1158    if !same_satellite {
1159        return Err(NavParseError::BadField {
1160            satellite: marker_sv.to_string(),
1161            field: "frame marker",
1162        });
1163    }
1164
1165    let system = body_sv
1166        .as_bytes()
1167        .first()
1168        .and_then(|b| GnssSystem::from_letter(*b as char))
1169        .ok_or_else(|| NavParseError::BadField {
1170            satellite: body_sv.to_string(),
1171            field: "system",
1172        })?;
1173    if !nav_message_matches_system(message, system) {
1174        return Err(NavParseError::BadField {
1175            satellite: body_sv.to_string(),
1176            field: "message",
1177        });
1178    }
1179
1180    Ok(())
1181}
1182
1183fn nav_message_matches_system(message: NavMessage, system: GnssSystem) -> bool {
1184    matches!(
1185        (message, system),
1186        (NavMessage::GpsLnav, GnssSystem::Gps)
1187            | (NavMessage::GpsCnav | NavMessage::GpsCnav2, GnssSystem::Gps)
1188            | (NavMessage::QzssLnav, GnssSystem::Qzss)
1189            | (
1190                NavMessage::QzssCnav | NavMessage::QzssCnav2,
1191                GnssSystem::Qzss,
1192            )
1193            | (
1194                NavMessage::GalileoInav | NavMessage::GalileoFnav,
1195                GnssSystem::Galileo,
1196            )
1197            | (
1198                NavMessage::BeidouD1 | NavMessage::BeidouD2,
1199                GnssSystem::BeiDou,
1200            )
1201    )
1202}
1203
1204/// Parse the broadcast ionosphere coefficients from a RINEX header's
1205/// `IONOSPHERIC CORR` lines or RINEX 4 body `> ION` frames (GPS
1206/// `GPSA`/`GPSB`, BeiDou `BDSA`/`BDSB`, and Galileo `GAL`).
1207///
1208/// A complete header label pair or body frame yields the coefficient set; a
1209/// missing label or frame yields `None` for that system. Parsing is
1210/// deterministic text, not a 0-ULP target.
1211pub fn parse_iono_corrections(text: &str) -> Result<IonoCorrections, NavParseError> {
1212    parse_iono_corrections_checked(text)
1213}
1214
1215fn parse_iono_corrections_checked(text: &str) -> Result<IonoCorrections, NavParseError> {
1216    // The IONOSPHERIC CORR line is `A4,1X,4(D12.4)`: a 4-char label, a space,
1217    // then up to four coefficients in 12-wide columns.
1218    //
1219    // GPS/BeiDou are Klobuchar models with four coefficients per row
1220    // (alpha0..alpha3 / beta0..beta3); all four columns are required and a
1221    // truncated row is a malformed header, not a tolerable short line.
1222    let klobuchar_row = |line: &str| -> Result<[f64; 4], NavParseError> {
1223        Ok([
1224            strict_header_f64(line, 5, 17, "ionospheric correction")?,
1225            strict_header_f64(line, 17, 29, "ionospheric correction")?,
1226            strict_header_f64(line, 29, 41, "ionospheric correction")?,
1227            strict_header_f64(line, 41, 53, "ionospheric correction")?,
1228        ])
1229    };
1230    // Galileo is NeQuick-G with three coefficients (ai0,ai1,ai2). The fourth
1231    // column is the disturbance flag, which real/merged headers frequently leave
1232    // blank; only the three coefficients are read, so the row parses whether or
1233    // not that flag is present.
1234    let nequick_row = |line: &str| -> Result<[f64; 3], NavParseError> {
1235        Ok([
1236            strict_header_f64(line, 5, 17, "ionospheric correction")?,
1237            strict_header_f64(line, 17, 29, "ionospheric correction")?,
1238            strict_header_f64(line, 29, 41, "ionospheric correction")?,
1239        ])
1240    };
1241    let (mut gpsa, mut gpsb, mut bdsa, mut bdsb, mut gal) = (None, None, None, None, None);
1242    for line in text.lines() {
1243        if line.contains("END OF HEADER") {
1244            break;
1245        }
1246        if !line.contains("IONOSPHERIC CORR") {
1247            continue;
1248        }
1249        match line.get(0..4).map(str::trim) {
1250            Some("GPSA") => gpsa = Some(klobuchar_row(line)?),
1251            Some("GPSB") => gpsb = Some(klobuchar_row(line)?),
1252            Some("BDSA") => bdsa = Some(klobuchar_row(line)?),
1253            Some("BDSB") => bdsb = Some(klobuchar_row(line)?),
1254            Some("GAL") => {
1255                let row = nequick_row(line)?;
1256                gal = Some(GalileoNequickCoeffs {
1257                    ai0: row[0],
1258                    ai1: row[1],
1259                    ai2: row[2],
1260                });
1261            }
1262            _ => {}
1263        }
1264    }
1265    let pair = |a: Option<[f64; 4]>, b: Option<[f64; 4]>| match (a, b) {
1266        (Some(alpha), Some(beta)) => Some(KlobucharAlphaBeta { alpha, beta }),
1267        _ => None,
1268    };
1269    let mut iono = IonoCorrections {
1270        gps: pair(gpsa, gpsb),
1271        beidou: pair(bdsa, bdsb),
1272        galileo: gal,
1273    };
1274    parse_v4_body_iono_corrections(text, &mut iono)?;
1275    Ok(iono)
1276}
1277
1278fn parse_v4_body_iono_corrections(
1279    text: &str,
1280    iono: &mut IonoCorrections,
1281) -> Result<(), NavParseError> {
1282    let mut lines = text.lines();
1283    for line in lines.by_ref() {
1284        if line.contains("END OF HEADER") {
1285            break;
1286        }
1287    }
1288
1289    for (marker, body) in v4_frames(lines) {
1290        let Some((frame_type, sv, _msg_token)) = parse_v4_marker(marker) else {
1291            continue;
1292        };
1293        if frame_type != "ION" {
1294            continue;
1295        }
1296        let values = parse_v4_iono_values(sv, &body)?;
1297        match sv
1298            .as_bytes()
1299            .first()
1300            .and_then(|b| GnssSystem::from_letter(*b as char))
1301        {
1302            Some(GnssSystem::Gps) => {
1303                iono.gps = Some(KlobucharAlphaBeta {
1304                    alpha: iono_values_4(&values, 0, sv)?,
1305                    beta: iono_values_4(&values, 4, sv)?,
1306                });
1307            }
1308            Some(GnssSystem::BeiDou) => {
1309                iono.beidou = Some(KlobucharAlphaBeta {
1310                    alpha: iono_values_4(&values, 0, sv)?,
1311                    beta: iono_values_4(&values, 4, sv)?,
1312                });
1313            }
1314            Some(GnssSystem::Galileo) => {
1315                let coeffs = iono_values_3(&values, 0, sv)?;
1316                iono.galileo = Some(GalileoNequickCoeffs {
1317                    ai0: coeffs[0],
1318                    ai1: coeffs[1],
1319                    ai2: coeffs[2],
1320                });
1321            }
1322            _ => {}
1323        }
1324    }
1325    Ok(())
1326}
1327
1328fn parse_v4_iono_values(sv: &str, body: &[&str]) -> Result<Vec<f64>, NavParseError> {
1329    if body.is_empty() {
1330        return Err(NavParseError::BadField {
1331            satellite: sv.to_string(),
1332            field: "ionospheric correction",
1333        });
1334    }
1335
1336    let mut values = Vec::new();
1337    for (idx, line) in body.iter().enumerate() {
1338        let ranges: &[(usize, usize)] = if idx == 0 {
1339            &[(23, 42), (42, 61), (61, 80)]
1340        } else {
1341            &[(4, 23), (23, 42), (42, 61), (61, 80)]
1342        };
1343        for &(start, end) in ranges {
1344            let raw = raw_field(line, start, end);
1345            if raw.trim().is_empty() {
1346                continue;
1347            }
1348            values.push(
1349                validate::strict_f64(raw, "ionospheric correction")
1350                    .map_err(|error| map_record_field_error(error, sv))?,
1351            );
1352        }
1353    }
1354    Ok(values)
1355}
1356
1357fn iono_values_4(values: &[f64], start: usize, sv: &str) -> Result<[f64; 4], NavParseError> {
1358    let Some(slice) = values.get(start..start + 4) else {
1359        return Err(NavParseError::BadField {
1360            satellite: sv.to_string(),
1361            field: "ionospheric correction",
1362        });
1363    };
1364    Ok([slice[0], slice[1], slice[2], slice[3]])
1365}
1366
1367fn iono_values_3(values: &[f64], start: usize, sv: &str) -> Result<[f64; 3], NavParseError> {
1368    let Some(slice) = values.get(start..start + 3) else {
1369        return Err(NavParseError::BadField {
1370            satellite: sv.to_string(),
1371            field: "ionospheric correction",
1372        });
1373    };
1374    Ok([slice[0], slice[1], slice[2]])
1375}
1376
1377/// The leap-second count (GPS − UTC) from the header's `LEAP SECONDS` line, used
1378/// to map a GLONASS (UTC) reference epoch onto the GPST-aligned query time. The
1379/// value is the first field; `None` if the line is absent.
1380pub fn parse_leap_seconds(text: &str) -> Result<Option<f64>, NavParseError> {
1381    parse_leap_seconds_checked(text)
1382}
1383
1384fn parse_leap_seconds_checked(text: &str) -> Result<Option<f64>, NavParseError> {
1385    for line in text.lines() {
1386        if line.contains("END OF HEADER") {
1387            break;
1388        }
1389        if line.contains("LEAP SECONDS") {
1390            return strict_header_integer_f64(line, 0, 6, "leap seconds").map(Some);
1391        }
1392    }
1393    Ok(None)
1394}
1395
1396/// Seconds from the J2000 epoch (2000-01-01 12:00) to a UTC calendar instant,
1397/// via the canonical no-leap civil conversion. Bit-identical to the previous
1398/// day-count arithmetic (the Julian Day Number is offset-equal to the Hinnant
1399/// day count, and the whole-second clock fields sum exactly in `f64`).
1400fn j2000_seconds_utc(y: i64, mo: i64, d: i64, h: i64, mi: i64, s: i64) -> f64 {
1401    civil::j2000_seconds(y as i32, mo as i32, d as i32, h as i32, mi as i32, s as f64)
1402}
1403
1404/// Parse the GLONASS epoch line (`Rnn YYYY MM DD HH MM SS`) to a UTC second past
1405/// J2000.
1406fn parse_glonass_epoch(l0: &str, sat: &str) -> Result<f64, NavParseError> {
1407    let year = strict_record_int::<i64>(l0, 4, 8, "epoch", sat)?;
1408    let month = strict_record_int::<i64>(l0, 9, 11, "epoch", sat)?;
1409    let day = strict_record_int::<i64>(l0, 12, 14, "epoch", sat)?;
1410    let hour = strict_record_int::<i64>(l0, 15, 17, "epoch", sat)?;
1411    let minute = strict_record_int::<i64>(l0, 18, 20, "epoch", sat)?;
1412    let second = strict_record_int::<i64>(l0, 21, 23, "epoch", sat)?;
1413    let civil = validate::civil_datetime_with_second_policy(
1414        year,
1415        month,
1416        day,
1417        hour,
1418        minute,
1419        second as f64,
1420        validate::CivilSecondPolicy::UtcLike,
1421    )
1422    .map_err(|_| NavParseError::BadField {
1423        satellite: sat.to_string(),
1424        field: "epoch",
1425    })?;
1426    Ok(j2000_seconds_utc(
1427        civil.year,
1428        i64::from(civil.month),
1429        i64::from(civil.day),
1430        i64::from(civil.hour),
1431        i64::from(civil.minute),
1432        civil.second as i64,
1433    ))
1434}
1435
1436/// Parse a 4-line RINEX 3 GLONASS record block into a [`GlonassRecord`]
1437/// (km/(km/s)/(km/s^2) state converted to SI). A missing or unparseable field is
1438/// a [`NavParseError`], not a silently dropped record.
1439fn parse_glonass_block(block: &[&str]) -> Result<GlonassRecord, NavParseError> {
1440    let l0 = block[0];
1441    let sat = l0.get(0..3).unwrap_or("").trim().to_string();
1442    if block.len() < 4 {
1443        return Err(NavParseError::TruncatedRecord(sat));
1444    }
1445    let bad = |what: &'static str| NavParseError::BadField {
1446        satellite: sat.clone(),
1447        field: what,
1448    };
1449    let satellite_id: GnssSatelliteId = sat.parse().map_err(|_| bad("prn"))?;
1450    let toe_utc_j2000_s = parse_glonass_epoch(l0, &sat)?;
1451    let clk_bias = parse_f64(l0, 23, 42).ok_or_else(|| bad("clock bias"))?;
1452    let gamma_n = parse_f64(l0, 42, 61).ok_or_else(|| bad("gamma_n"))?;
1453    let o1 = orbit_row(block[1]);
1454    let o2 = orbit_row(block[2]);
1455    let o3 = orbit_row(block[3]);
1456    let km = |v: Option<f64>, what: &'static str| v.map(|x| x * KM_TO_M).ok_or_else(|| bad(what));
1457    let g = |v: Option<f64>, what: &'static str| v.ok_or_else(|| bad(what));
1458    Ok(GlonassRecord {
1459        satellite_id,
1460        toe_utc_j2000_s,
1461        pos_m: [km(o1[0], "x")?, km(o2[0], "y")?, km(o3[0], "z")?],
1462        vel_m_s: [km(o1[1], "vx")?, km(o2[1], "vy")?, km(o3[1], "vz")?],
1463        acc_m_s2: [km(o1[2], "ax")?, km(o2[2], "ay")?, km(o3[2], "az")?],
1464        clk_bias,
1465        gamma_n,
1466        sv_health: g(o1[3], "health")?,
1467        freq_channel: glonass_frequency_channel(g(o2[3], "frequency channel")?, &sat)?,
1468    })
1469}
1470
1471/// Parse all GLONASS (`R`) records from a RINEX 3.x navigation file, in file
1472/// order; selection is the caller's job. A malformed *supported* record is a
1473/// [`NavParseError`] rather than a silently dropped one, but a record for a slot
1474/// the engine cannot represent (an extended GLONASS slot beyond the PRN cap, e.g.
1475/// `R28` in real BKG/IGS products) is skipped rather than rejecting the whole
1476/// file - the same treatment unsupported constellations get in
1477/// [`parse_nav_v3`]. (Version-4 GLONASS frames are not yet parsed.)
1478pub fn parse_glonass(text: &str) -> Result<Vec<GlonassRecord>, NavParseError> {
1479    Ok(parse_glonass_lenient(text)?.records)
1480}
1481
1482/// Like [`parse_glonass`], but also returns the slots that were skipped because
1483/// they are not representable as a [`GnssSatelliteId`] (an extended slot beyond
1484/// the PRN cap, e.g. `R28`).
1485///
1486/// [`parse_glonass`] drops that list silently; use this when a caller needs to
1487/// surface how many / which records were skipped, consistent with the
1488/// lenient-skip reporting elsewhere in the crate. A malformed *representable*
1489/// record is still a [`NavParseError`], not a skip.
1490pub fn parse_glonass_lenient(text: &str) -> Result<GlonassParse, NavParseError> {
1491    let mut lines = text.lines();
1492    verify_and_skip_header(&mut lines)?;
1493    let mut blocks: Vec<Vec<&str>> = Vec::new();
1494    for line in lines {
1495        if is_record_start(line) {
1496            blocks.push(vec![line]);
1497        } else if let Some(last) = blocks.last_mut() {
1498            last.push(line);
1499        }
1500    }
1501    let mut out = GlonassParse::default();
1502    for block in blocks.iter().filter(|b| b[0].starts_with('R')) {
1503        // A GLONASS slot beyond the engine's PRN cap is not representable as a
1504        // `GnssSatelliteId`. Skip such a record (one out-of-range slot must not
1505        // discard every other satellite's ephemeris) instead of erroring, but
1506        // record its identity so it is not lost silently; a representable slot
1507        // with a malformed numeric field still errors.
1508        let sat = block[0].get(0..3).unwrap_or("").trim();
1509        if sat.parse::<GnssSatelliteId>().is_err() {
1510            out.skipped.push(SkippedGlonass {
1511                token: sat.to_string(),
1512            });
1513            continue;
1514        }
1515        out.records.push(parse_glonass_block(block)?);
1516    }
1517    Ok(out)
1518}
1519
1520/// Skip the header, returning the RINEX version. Major versions 3 and 4 share
1521/// the fixed-column orbit layout; version 4 wraps each record in a frame marker
1522/// line (see [`parse_v4_marker`]), which is why `parse_nav` dispatches on it.
1523fn verify_and_skip_header<'a, I>(lines: &mut I) -> Result<RinexVersion, NavParseError>
1524where
1525    I: Iterator<Item = &'a str>,
1526{
1527    let mut version_seen: Option<RinexVersion> = None;
1528    for line in lines.by_ref() {
1529        if line.contains("RINEX VERSION / TYPE") {
1530            // Column 0-8 holds the version; column 20 the file type ('N' = NAV).
1531            let version = line.get(0..9).unwrap_or("").trim();
1532            let detected = parse_rinex_version(version);
1533            let is_nav = line.get(20..21) == Some("N");
1534            match (detected, is_nav) {
1535                (Some(v), true) => version_seen = Some(v),
1536                _ => {
1537                    return Err(NavParseError::UnsupportedHeader(
1538                        line.trim_end().to_string(),
1539                    ))
1540                }
1541            }
1542        }
1543        if line.contains("END OF HEADER") {
1544            return version_seen.ok_or_else(|| {
1545                NavParseError::UnsupportedHeader("no RINEX VERSION / TYPE".to_string())
1546            });
1547        }
1548    }
1549    Err(NavParseError::MissingHeaderEnd)
1550}
1551
1552fn parse_rinex_version(version: &str) -> Option<RinexVersion> {
1553    let (major, minor) = version.split_once('.')?;
1554    let major = major.trim().parse::<u8>().ok()?;
1555    if !matches!(major, 3 | 4) {
1556        return None;
1557    }
1558    let minor_digits = minor
1559        .chars()
1560        .take_while(char::is_ascii_digit)
1561        .collect::<String>();
1562    if minor_digits.is_empty() {
1563        return None;
1564    }
1565    let minor = minor_digits.parse::<u8>().ok()?;
1566    Some(RinexVersion { major, minor })
1567}
1568
1569fn is_record_start(line: &str) -> bool {
1570    let Some(token) = line.get(0..3) else {
1571        return false;
1572    };
1573    let b = token.as_bytes();
1574    let prn = token[1..].trim();
1575    b[0].is_ascii_alphabetic()
1576        && (1..=2).contains(&prn.len())
1577        && prn.bytes().all(|byte| byte.is_ascii_digit())
1578}
1579
1580/// The four broadcast-orbit values of a continuation line (columns 4/23/42/61).
1581fn orbit_row(line: &str) -> [Option<f64>; 4] {
1582    [
1583        parse_f64(line, 4, 23),
1584        parse_f64(line, 23, 42),
1585        parse_f64(line, 42, 61),
1586        parse_f64(line, 61, 80),
1587    ]
1588}
1589
1590fn raw_orbit_field(line: &str, field_index: usize) -> &str {
1591    const RANGES: [(usize, usize); 4] = [(4, 23), (23, 42), (42, 61), (61, 80)];
1592    let (start, end) = RANGES[field_index];
1593    raw_field(line, start, end)
1594}
1595
1596#[derive(Debug, Clone, Copy)]
1597struct ClockReferenceEpoch {
1598    week: u32,
1599    sow: f64,
1600}
1601
1602fn parse_keplerian_block(
1603    block: &[&str],
1604    message_override: Option<NavMessage>,
1605    version: RinexVersion,
1606) -> Result<BroadcastRecord, NavParseError> {
1607    let l0 = block.first().copied().unwrap_or("");
1608    let sat = l0.get(0..3).unwrap_or("").trim().to_string();
1609    if block.len() < 8 {
1610        return Err(NavParseError::TruncatedRecord(sat));
1611    }
1612    let bad = |what: &'static str| NavParseError::BadField {
1613        satellite: sat.clone(),
1614        field: what,
1615    };
1616
1617    let letter = l0
1618        .as_bytes()
1619        .first()
1620        .copied()
1621        .map(|b| b as char)
1622        .ok_or_else(|| bad("system"))?;
1623    let system = GnssSystem::from_letter(letter).ok_or_else(|| bad("system"))?;
1624    let satellite_id: GnssSatelliteId = sat.parse().map_err(|_| bad("prn"))?;
1625
1626    // Clock line: epoch (-> toc) and the af0/af1/af2 polynomial.
1627    let time_scale = broadcast_time_scale(system);
1628    let toc_epoch = parse_toc(l0, &sat, time_scale)?;
1629    let toc_sow = toc_epoch.sow;
1630    let af0 = parse_f64(l0, 23, 42).ok_or_else(|| bad("af0"))?;
1631    let af1 = parse_f64(l0, 42, 61).ok_or_else(|| bad("af1"))?;
1632    let af2 = parse_f64(l0, 61, 80).ok_or_else(|| bad("af2"))?;
1633
1634    let o1 = orbit_row(block[1]);
1635    let o2 = orbit_row(block[2]);
1636    let o3 = orbit_row(block[3]);
1637    let o4 = orbit_row(block[4]);
1638    let o5 = orbit_row(block[5]);
1639    let o6 = orbit_row(block[6]);
1640
1641    let g = |v: Option<f64>, what: &'static str| v.ok_or_else(|| bad(what));
1642
1643    let elements = KeplerianElements {
1644        crs: g(o1[1], "crs")?,
1645        delta_n: g(o1[2], "deltaN")?,
1646        m0: g(o1[3], "m0")?,
1647        cuc: g(o2[0], "cuc")?,
1648        e: g(o2[1], "e")?,
1649        cus: g(o2[2], "cus")?,
1650        sqrt_a: g(o2[3], "sqrtA")?,
1651        toe_sow: g(o3[0], "toe")?,
1652        cic: g(o3[1], "cic")?,
1653        omega0: g(o3[2], "omega0")?,
1654        cis: g(o3[3], "cis")?,
1655        i0: g(o4[0], "i0")?,
1656        crc: g(o4[1], "crc")?,
1657        omega: g(o4[2], "omega")?,
1658        omega_dot: g(o4[3], "omegaDot")?,
1659        idot: g(o5[0], "idot")?,
1660    };
1661    let clock = ClockPolynomial {
1662        af0,
1663        af1,
1664        af2,
1665        toc_sow,
1666    };
1667
1668    let week = finite_integral_u32(g(o5[2], "week")?, "week", &sat)?;
1669    let toe = GnssWeekTow::new(time_scale, week, elements.toe_sow)
1670        .and_then(GnssWeekTow::normalized)
1671        .map_err(|_| bad("toe"))?;
1672    let toc = GnssWeekTow::new(time_scale, toc_epoch.week, clock.toc_sow)
1673        .and_then(GnssWeekTow::normalized)
1674        .map_err(|_| bad("toc"))?;
1675    let message = if let Some(message) = message_override {
1676        message
1677    } else {
1678        match system {
1679            GnssSystem::Galileo => galileo_message(g(o5[1], "data sources")?, &sat)?,
1680            GnssSystem::BeiDou => {
1681                if is_beidou_geo(satellite_id) {
1682                    NavMessage::BeidouD2
1683                } else {
1684                    NavMessage::BeidouD1
1685                }
1686            }
1687            GnssSystem::Qzss => NavMessage::QzssLnav,
1688            _ => NavMessage::GpsLnav,
1689        }
1690    };
1691    let issue_of_data = BroadcastIssue {
1692        issue: finite_integral_u32(g(o1[0], "issue of data")?, "issue of data", &sat)?,
1693        message,
1694    };
1695
1696    let sv_accuracy_m = g(o6[0], "accuracy")?;
1697    let sv_health = g(o6[1], "health")?;
1698    let group_delays = match system {
1699        GnssSystem::Gps => BroadcastGroupDelays::gps_lnav(g(o6[2], "gps tgd")?),
1700        // RINEX Galileo ORBIT-6 carries BGD E5a/E1 in field 3 and BGD E5b/E1 in
1701        // field 4; both are part of the message representation regardless of
1702        // which one a clock consumer later selects.
1703        GnssSystem::Galileo => {
1704            BroadcastGroupDelays::galileo(g(o6[2], "bgd e5a/e1")?, g(o6[3], "bgd e5b/e1")?)
1705        }
1706        GnssSystem::BeiDou => {
1707            BroadcastGroupDelays::beidou(g(o6[2], "beidou tgd1")?, g(o6[3], "beidou tgd2")?)
1708        }
1709        _ => BroadcastGroupDelays::default(),
1710    };
1711
1712    // Only GPS LNAV broadcasts a curve-fit interval (ORBIT-7 field 2); Galileo
1713    // and BeiDou leave that column blank or spare, so they carry no fit interval.
1714    let fit_interval_s = match system {
1715        GnssSystem::Gps => {
1716            Some(gps_fit_interval_s(block[7], version).map_err(|()| bad("fit interval"))?)
1717        }
1718        _ => None,
1719    };
1720
1721    Ok(BroadcastRecord {
1722        satellite_id,
1723        message,
1724        issue_of_data,
1725        week,
1726        toe,
1727        toc,
1728        elements,
1729        clock,
1730        group_delays,
1731        cnav: None,
1732        sv_health,
1733        sv_accuracy_m,
1734        fit_interval_s,
1735    })
1736}
1737
1738fn parse_cnav_block(block: &[&str], message: NavMessage) -> Result<BroadcastRecord, NavParseError> {
1739    let l0 = block.first().copied().unwrap_or("");
1740    let sat = l0.get(0..3).unwrap_or("").trim().to_string();
1741    let is_cnav2 = matches!(message, NavMessage::GpsCnav2 | NavMessage::QzssCnav2);
1742    let required_lines = if is_cnav2 { 10 } else { 9 };
1743    if block.len() < required_lines {
1744        return Err(NavParseError::TruncatedRecord(sat));
1745    }
1746    let bad = |what: &'static str| NavParseError::BadField {
1747        satellite: sat.clone(),
1748        field: what,
1749    };
1750
1751    let letter = l0
1752        .as_bytes()
1753        .first()
1754        .copied()
1755        .map(|b| b as char)
1756        .ok_or_else(|| bad("system"))?;
1757    GnssSystem::from_letter(letter).ok_or_else(|| bad("system"))?;
1758    let satellite_id: GnssSatelliteId = sat.parse().map_err(|_| bad("prn"))?;
1759    let toc_epoch = parse_toc(l0, &sat, TimeScale::Gpst)?;
1760    let af0 = parse_f64(l0, 23, 42).ok_or_else(|| bad("af0"))?;
1761    let af1 = parse_f64(l0, 42, 61).ok_or_else(|| bad("af1"))?;
1762    let af2 = parse_f64(l0, 61, 80).ok_or_else(|| bad("af2"))?;
1763
1764    let o1 = orbit_row(block[1]);
1765    let o2 = orbit_row(block[2]);
1766    let o3 = orbit_row(block[3]);
1767    let o4 = orbit_row(block[4]);
1768    let o5 = orbit_row(block[5]);
1769    let o6 = orbit_row(block[6]);
1770    let o8 = orbit_row(block[8]);
1771    let o9 = if is_cnav2 {
1772        Some(orbit_row(block[9]))
1773    } else {
1774        None
1775    };
1776
1777    let g = |v: Option<f64>, what: &'static str| v.ok_or_else(|| bad(what));
1778    let elements = KeplerianElements {
1779        crs: g(o1[1], "crs")?,
1780        delta_n: g(o1[2], "deltaN0")?,
1781        m0: g(o1[3], "m0")?,
1782        cuc: g(o2[0], "cuc")?,
1783        e: g(o2[1], "e")?,
1784        cus: g(o2[2], "cus")?,
1785        sqrt_a: g(o2[3], "sqrtA0")?,
1786        toe_sow: toc_epoch.sow,
1787        cic: g(o3[1], "cic")?,
1788        omega0: g(o3[2], "omega0")?,
1789        cis: g(o3[3], "cis")?,
1790        i0: g(o4[0], "i0")?,
1791        crc: g(o4[1], "crc")?,
1792        omega: g(o4[2], "omega")?,
1793        omega_dot: g(o4[3], "omegaDot")?,
1794        idot: g(o5[0], "idot")?,
1795    };
1796    let clock = ClockPolynomial {
1797        af0,
1798        af1,
1799        af2,
1800        toc_sow: toc_epoch.sow,
1801    };
1802
1803    let week = toc_epoch.week;
1804    let toe = GnssWeekTow::new(TimeScale::Gpst, week, elements.toe_sow)
1805        .and_then(GnssWeekTow::normalized)
1806        .map_err(|_| bad("toe"))?;
1807    let toc = GnssWeekTow::new(TimeScale::Gpst, week, clock.toc_sow)
1808        .and_then(GnssWeekTow::normalized)
1809        .map_err(|_| bad("toc"))?;
1810    let wn_op = finite_integral_u32(
1811        g(if is_cnav2 { o9.unwrap()[1] } else { o8[1] }, "wn_op")?,
1812        "wn_op",
1813        &sat,
1814    )?;
1815    let top_sow = g(o3[0], "top")?;
1816    let top = GnssWeekTow::new(TimeScale::Gpst, wn_op, top_sow)
1817        .and_then(GnssWeekTow::normalized)
1818        .map_err(|_| bad("top"))?;
1819    let ura_ed_index = finite_integral_i8(g(o6[0], "ura_ed")?, "ura_ed", -16, 15, &sat)?;
1820    let ura_ned0_index = finite_integral_i8(g(o5[2], "ura_ned0")?, "ura_ned0", -16, 15, &sat)?;
1821    let ura_ned1_index = finite_integral_u8(g(o5[3], "ura_ned1")?, "ura_ned1", 0, 7, &sat)?;
1822    let ura_ned2_index = finite_integral_u8(g(o6[3], "ura_ned2")?, "ura_ned2", 0, 7, &sat)?;
1823    let health_max = if is_cnav2 { 1 } else { 7 };
1824    let sv_health = f64::from(finite_integral_u8(
1825        g(o6[1], "health")?,
1826        "health",
1827        0,
1828        health_max,
1829        &sat,
1830    )?);
1831    let transmission_time_sow = g(if is_cnav2 { o9.unwrap()[0] } else { o8[0] }, "t_tm")?;
1832    let flags = optional_integral_u32(
1833        if is_cnav2 {
1834            raw_orbit_field(block[9], 2)
1835        } else {
1836            raw_orbit_field(block[8], 2)
1837        },
1838        "flags",
1839        &sat,
1840    )?;
1841
1842    let tgd = optional_cnav_delay(raw_orbit_field(block[6], 2), "tgd", &sat)?;
1843    let isc_l1ca = optional_cnav_delay(raw_orbit_field(block[7], 0), "isc_l1ca", &sat)?;
1844    let isc_l2c = optional_cnav_delay(raw_orbit_field(block[7], 1), "isc_l2c", &sat)?;
1845    let isc_l5i5 = optional_cnav_delay(raw_orbit_field(block[7], 2), "isc_l5i5", &sat)?;
1846    let isc_l5q5 = optional_cnav_delay(raw_orbit_field(block[7], 3), "isc_l5q5", &sat)?;
1847    let (isc_l1cd, isc_l1cp) = if is_cnav2 {
1848        (
1849            optional_cnav_delay(raw_orbit_field(block[8], 0), "isc_l1cd", &sat)?,
1850            optional_cnav_delay(raw_orbit_field(block[8], 1), "isc_l1cp", &sat)?,
1851        )
1852    } else {
1853        (None, None)
1854    };
1855
1856    let cnav = CnavParameters {
1857        adot_m_s: g(o1[0], "adot")?,
1858        delta_n0_dot_rad_s2: g(o5[1], "deltaN0Dot")?,
1859        top,
1860        ura_ed_index,
1861        ura_ned0_index,
1862        ura_ned1_index,
1863        ura_ned2_index,
1864        transmission_time_sow,
1865        flags,
1866    };
1867    let sv_accuracy_m = cnav_ura_nominal_m(ura_ed_index).unwrap_or(8192.0);
1868    let issue = (elements.toe_sow / 300.0).round() as u32;
1869
1870    Ok(BroadcastRecord {
1871        satellite_id,
1872        message,
1873        issue_of_data: BroadcastIssue { issue, message },
1874        week,
1875        toe,
1876        toc,
1877        elements,
1878        clock,
1879        group_delays: BroadcastGroupDelays::cnav(
1880            tgd, isc_l1ca, isc_l2c, isc_l5i5, isc_l5q5, isc_l1cd, isc_l1cp,
1881        ),
1882        cnav: Some(cnav),
1883        sv_health,
1884        sv_accuracy_m,
1885        fit_interval_s: Some(3.0 * SECONDS_PER_HOUR),
1886    })
1887}
1888
1889/// The GPS curve-fit interval in seconds from the ORBIT-7 fit-interval field.
1890/// RINEX 3.03+ and 4.xx record this field in hours. Legacy RINEX 3.02 and older
1891/// files may carry the broadcast 0/1 fit-interval flag instead, where 1 means
1892/// more than four hours rather than one hour. Per IS-GPS-200 the decoded value
1893/// is the total interval centered on `toe`; a zero or absent field denotes the
1894/// nominal four hours.
1895///
1896/// A blank/absent field is the legitimate nominal case (some products omit it);
1897/// a present but non-numeric field is a malformed record, reported as `Err` so
1898/// the caller can raise the same `BadField` error as for other numeric fields
1899/// rather than silently substituting four hours.
1900fn gps_fit_interval_s(orbit7: &str, version: RinexVersion) -> Result<f64, ()> {
1901    let value = match field(orbit7, 23, 42) {
1902        None => 0.0,
1903        Some(_) => parse_f64(orbit7, 23, 42).ok_or(())?,
1904    };
1905    if value == 0.0 {
1906        Ok(GPS_NOMINAL_FIT_INTERVAL_S)
1907    } else if version.gps_fit_interval_uses_legacy_flag() && value == 1.0 {
1908        Ok(GPS_LEGACY_EXTENDED_FIT_INTERVAL_S)
1909    } else {
1910        Ok(value * SECONDS_PER_HOUR)
1911    }
1912}
1913
1914/// Classify a Galileo record from its data-source word (orbit-5 field 1): source
1915/// bit 1 is F/NAV, source bits 0/2 are I/NAV. Bits 8/9 describe the clock-pair
1916/// frequency and do not determine the navigation message type.
1917fn galileo_message(data_sources: f64, sat: &str) -> Result<NavMessage, NavParseError> {
1918    let word = finite_integral_u32(data_sources, "data sources", sat)?;
1919    if word & 0b010 != 0 {
1920        Ok(NavMessage::GalileoFnav)
1921    } else if word & 0b101 != 0 {
1922        Ok(NavMessage::GalileoInav)
1923    } else {
1924        // No source bit set: default to I/NAV (the operational E1 message).
1925        Ok(NavMessage::GalileoInav)
1926    }
1927}
1928
1929fn finite_integral_u32(value: f64, field: &'static str, sat: &str) -> Result<u32, NavParseError> {
1930    validate::finite(value, field).map_err(|error| map_record_field_error(error, sat))?;
1931    if value < 0.0 || value > f64::from(u32::MAX) || value.trunc() != value {
1932        return Err(NavParseError::BadField {
1933            satellite: sat.to_string(),
1934            field,
1935        });
1936    }
1937    Ok(value as u32)
1938}
1939
1940fn finite_integral_i8(
1941    value: f64,
1942    field: &'static str,
1943    min: i8,
1944    max: i8,
1945    sat: &str,
1946) -> Result<i8, NavParseError> {
1947    validate::finite(value, field).map_err(|error| map_record_field_error(error, sat))?;
1948    if value < f64::from(min) || value > f64::from(max) || value.trunc() != value {
1949        return Err(NavParseError::BadField {
1950            satellite: sat.to_string(),
1951            field,
1952        });
1953    }
1954    Ok(value as i8)
1955}
1956
1957fn finite_integral_u8(
1958    value: f64,
1959    field: &'static str,
1960    min: u8,
1961    max: u8,
1962    sat: &str,
1963) -> Result<u8, NavParseError> {
1964    validate::finite(value, field).map_err(|error| map_record_field_error(error, sat))?;
1965    if value < f64::from(min) || value > f64::from(max) || value.trunc() != value {
1966        return Err(NavParseError::BadField {
1967            satellite: sat.to_string(),
1968            field,
1969        });
1970    }
1971    Ok(value as u8)
1972}
1973
1974fn optional_integral_u32(
1975    raw: &str,
1976    field: &'static str,
1977    sat: &str,
1978) -> Result<Option<u32>, NavParseError> {
1979    if raw.trim().is_empty() {
1980        return Ok(None);
1981    }
1982    let value =
1983        validate::strict_f64(raw, field).map_err(|error| map_record_field_error(error, sat))?;
1984    finite_integral_u32(value, field, sat).map(Some)
1985}
1986
1987fn optional_cnav_delay(
1988    raw: &str,
1989    field: &'static str,
1990    sat: &str,
1991) -> Result<Option<f64>, NavParseError> {
1992    if raw.trim().is_empty() {
1993        return Ok(None);
1994    }
1995    let value =
1996        validate::strict_f64(raw, field).map_err(|error| map_record_field_error(error, sat))?;
1997    if !write::d19_12_representable(value) {
1998        return Err(NavParseError::BadField {
1999            satellite: sat.to_string(),
2000            field,
2001        });
2002    }
2003    let mut rendered = String::new();
2004    write::push_d19_12(&mut rendered, value);
2005    let mut sentinel = String::new();
2006    write::push_d19_12(&mut sentinel, -4096.0 * 2.0_f64.powi(-35));
2007    if rendered == sentinel {
2008        Ok(None)
2009    } else {
2010        Ok(Some(value))
2011    }
2012}
2013
2014fn glonass_frequency_channel(value: f64, sat: &str) -> Result<i32, NavParseError> {
2015    const FIELD: &str = "frequency channel";
2016    validate::finite(value, FIELD).map_err(|error| map_record_field_error(error, sat))?;
2017    let channel = value as i32;
2018    if value.trunc() != value || !valid_glonass_frequency_channel(channel) {
2019        return Err(NavParseError::BadField {
2020            satellite: sat.to_string(),
2021            field: FIELD,
2022        });
2023    }
2024    Ok(channel)
2025}
2026
2027fn strict_header_f64(
2028    line: &str,
2029    start: usize,
2030    end: usize,
2031    field: &'static str,
2032) -> Result<f64, NavParseError> {
2033    validate::strict_f64(raw_field(line, start, end), field).map_err(map_header_field_error)
2034}
2035
2036fn strict_header_integer_f64(
2037    line: &str,
2038    start: usize,
2039    end: usize,
2040    field: &'static str,
2041) -> Result<f64, NavParseError> {
2042    let value = strict_header_f64(line, start, end, field)?;
2043    if value.trunc() != value {
2044        return Err(NavParseError::BadHeaderField { field });
2045    }
2046    Ok(value)
2047}
2048
2049fn strict_record_int<T>(
2050    line: &str,
2051    start: usize,
2052    end: usize,
2053    field: &'static str,
2054    satellite: &str,
2055) -> Result<T, NavParseError>
2056where
2057    T: core::str::FromStr,
2058{
2059    validate::strict_int::<T>(raw_field(line, start, end), field)
2060        .map_err(|error| map_record_field_error(error, satellite))
2061}
2062
2063fn map_record_field_error(error: FieldError, satellite: &str) -> NavParseError {
2064    NavParseError::BadField {
2065        satellite: satellite.to_string(),
2066        field: error.field(),
2067    }
2068}
2069
2070fn map_header_field_error(error: FieldError) -> NavParseError {
2071    NavParseError::BadHeaderField {
2072        field: error.field(),
2073    }
2074}
2075
2076/// Parse the clock reference epoch from the SV/epoch line into week and seconds
2077/// of week in the record's broadcast time scale.
2078fn parse_toc(
2079    l0: &str,
2080    sat: &str,
2081    time_scale: TimeScale,
2082) -> Result<ClockReferenceEpoch, NavParseError> {
2083    let year = strict_record_int::<i64>(l0, 4, 8, "toc epoch", sat)?;
2084    let month = strict_record_int::<i64>(l0, 9, 11, "toc epoch", sat)?;
2085    let day = strict_record_int::<i64>(l0, 12, 14, "toc epoch", sat)?;
2086    let hour = strict_record_int::<i64>(l0, 15, 17, "toc epoch", sat)?;
2087    let minute = strict_record_int::<i64>(l0, 18, 20, "toc epoch", sat)?;
2088    let second = strict_record_int::<i64>(l0, 21, 23, "toc epoch", sat)?;
2089    let civil = validate::civil_datetime_with_second_policy(
2090        year,
2091        month,
2092        day,
2093        hour,
2094        minute,
2095        second as f64,
2096        validate::CivilSecondPolicy::Continuous,
2097    )
2098    .map_err(|_| NavParseError::BadField {
2099        satellite: sat.to_string(),
2100        field: "toc epoch",
2101    })?;
2102    let month = i64::from(civil.month);
2103    let day = i64::from(civil.day);
2104    let week = gnss::week_from_calendar(time_scale, civil.year, month, day).ok_or_else(|| {
2105        NavParseError::BadField {
2106            satellite: sat.to_string(),
2107            field: "toc epoch",
2108        }
2109    })?;
2110    let sow = gnss::seconds_of_week_from_calendar(
2111        civil.year,
2112        month,
2113        day,
2114        i64::from(civil.hour),
2115        i64::from(civil.minute),
2116        civil.second as i64,
2117    );
2118    Ok(ClockReferenceEpoch { week, sow })
2119}
2120
2121#[cfg(all(test, sidereon_repo_tests))]
2122mod tests;