Skip to main content

hpr_flightdata/
eggtimer.rs

1//! An Eggtimer's flight data, as the flight computer's own download writes it: the Eggtimer
2//! Classic's and TRS's over a serial cable, the Quantum's and Proton's from their WiFi page.
3//!
4//! The file is comma-separated text: one header row naming the columns, then one row per sample,
5//! every column on the row's time. There is no preamble and the header states no units (a
6//! European locale's spreadsheet may save it with semicolons, *Cells* below):
7//!
8//! ```text
9//! T,Alt,Veloc,FAlt,FVeloc,LDA,LowV,Apogee,N-O,Drogue,Main
10//! 0,0,0,0,0,0,0,0,0,0,0
11//! 0.05,4,80,0.8,16,0,0,0,0,0,0
12//! 0.1,9,100,2.44,32.8,0,0,0,0,0,0
13//! ```
14//!
15//! **Layouts.** The first column is the time, `T`, and the second the barometric altitude, `Alt`.
16//! Then come the logger's figures, which differ by model and firmware: a raw velocity, a filtered
17//! altitude and velocity (`FAlt`, `Filt_Alt` or `KAlt`, then `FVeloc` or `KVeloc`), and on the
18//! Proton the accelerometer's figures. Last come the event markers, from `LDA` on. The Classic's
19//! manual shows `T,Alt,Veloc,KAlt,KVeloc,LDA,BurnT,LowV,Apogee,N-O,CHA,CHB` (*Eggtimer Flight
20//! Computer User's Manual*, firmware 1.52, board RevD, p37), the TRS's
21//! `T,Alt,Veloc,FAlt,FVeloc,LDA,LowV,Apogee,N-O,Drogue,Main` (*Eggtimer TRS Flight Computer User's
22//! Manual*, firmware 2.07, p37), and an older guide `T`, `Alt`, `VRaw`, `VFilt` (*Using Excel to
23//! Graph Eggtimer Flight Data*, p3). The project's sample logs add a layout without the raw
24//! velocity (`T,Alt,FAlt,FVeloc,…`) and the Proton's 22 columns, whose accelerometer columns are
25//! named `AccelG`, `AccelFPSS`, `VAccel`, `AltAccel` and filtered `FAccel…` where its manual writes
26//! `Accel`, `AccelFPSS`, `VelocAcc` and `AltAcc` (*Eggtimer Proton User's Guide*, software 2.01C,
27//! p45). The Proton lets its owner name each deployment channel, up to 8 characters, and writes
28//! that name in the header (Proton p26; *Eggtimer Proton Release Notes*, version 2.01C, p2), so a
29//! marker column may carry any name.
30//!
31//! A file is this layout if its first line that isn't blank is comma-separated, or
32//! semicolon-separated if it holds a semicolon, names `T` then `Alt`, and names at least one more
33//! column this reader knows (the table below). That keeps out a
34//! PerfectFlite export (`Time,Altitude,…`) and an RRC3's (`Time,Altitude,Pressure,…`).
35//!
36//! **Units.** The header states none. Each column, what it is read as, and where that comes from:
37//!
38//! | Column | Read as | From |
39//! |---|---|---|
40//! | `T` | the clock: seconds, or milliseconds when the step says so (below) | the Classic's and TRS's manuals (p37) and the Excel guide (p3): milliseconds; the Quantum's (*Eggtimer Quantum User's Guide*, software 1.09G, p38) and Proton's (p45): seconds |
41//! | `Alt` | [`Quantity::AltitudeAboveGround`], ft | the Classic and TRS manuals (p37) state feet; the Quantum and Proton manuals state no unit for the download, but give every height in feet (Quantum p24: launch detect "50’-500’"), and no Eggtimer manual offers meters |
42//! | `FAlt`, `Filt_Alt`, `KAlt` | [`Quantity::AltitudeAboveGround`], ft: the logger's filtered `Alt` | Quantum p38, Proton p45; Classic p37 ("the two K fields are filtered data") |
43//! | `Veloc`, `VRaw` | [`Quantity::Speed`], ft/s: the change in `Alt` over the step | Classic and TRS p37 ("velocity in ft/sec"); Quantum p38, Proton p45; checked against `Alt` (below) |
44//! | `FVeloc`, `KVeloc`, `VFilt` | [`Quantity::Speed`], ft/s: the change in the filtered altitude over the step | Quantum p38, Proton p46; the Excel guide (p3, p7: "Velocity in ft/sec"); checked against the filtered altitude (below) |
45//! | `Accel` | [`Quantity::Acceleration`], g × 9.806 65 m/s² (standard gravity) | Proton p45 ("in G's") |
46//! | `AccelG`, `FAccelG` | [`Quantity::Acceleration`], g × 9.806 65 m/s² | the name; Proton p45 |
47//! | `AccelFPSS`, `FAccelFPSS` | [`Quantity::Acceleration`], ft/s² | Proton p45 ("ft/sec^2"); the name |
48//! | `VAccel`, `VelocAcc`, `FAccelVel` | [`Quantity::Speed`], ft/s, from the accelerometer | Proton p45 ("the velocity derived from the accelerometer in ft/sec") |
49//! | `AltAccel`, `AltAcc`, `FAccelAlt` | [`Quantity::InertialAltitude`], ft | Proton p45 ("the DISTANCE TRAVELED derived from the accelerometer in ft.") |
50//! | `LDA`, `LowV`, `Apogee`, `N-O`, `Drogue`, `Main`, `AUX`, `BurnT`, `CHA`, `CHB`, `CH1`…, `MaxV`, `MaxA`, `Boost#1`…, `BO#1`…, and any column after `LDA` | [`Quantity::Unrecognized`], as written: an event marker (below) | Quantum p38–39, Proton p46 |
51//!
52//! No Eggtimer manual offers a unit other than feet: the Classic's, TRS's, Quantum's and Proton's
53//! manuals and release notes name no meter or metric setting. Each column whose name doesn't state
54//! its unit gets a note on the record saying how it was read, once per name.
55//!
56//! **Speeds checked.** A speed is read in feet per second only if the rows bear out that it is its
57//! altitude's change over the step: `Veloc` and `VRaw` of `Alt`, `FVeloc`, `KVeloc` and `VFilt` of
58//! the first filtered altitude, within 1 % or 1 ft/s, on at least 90 % of the rows after the first.
59//! A speed that falls short is kept as written, [`Quantity::Unrecognized`], with a note; a file of
60//! one row, or a filtered speed with no filtered altitude, has nothing to check, and is read as the
61//! manual says. As of 2026-10-12, over the 43 Eggtimer files among the project's sample logs, the
62//! least share is 95.9 %, and with the clock read in the wrong unit, a factor of 1,000 off, at
63//! most 9.5 %: the check also guards the time's unit (below).
64//!
65//! **Filtered altitudes checked.** A filtered altitude must scale to `Alt` as a filter of it can:
66//! the one multiplier that best takes `Alt` to it, with no offset (a least-squares fit through
67//! zero), must lie from 0.1 to 2. A filter lags the altitude, under it on the way up and over it
68//! on the way down; on a steady climb at `v` ft/s to `H` ft, a lag of `τ` s moves the multiplier
69//! by about `1.5 v τ / H`, while a lost decimal place writes a value 10 times over. A file whose
70//! filtered altitude lies outside is refused ([`LogError::Unit`]): its numbers can't be trusted,
71//! the clock's among them, as a seconds clock written without its decimal point reads as
72//! milliseconds. As of 2026-10-15, over the 44 Eggtimer files the project's sample logs read, every
73//! one with a filtered altitude, the multiplier lies from 0.900 to 1.000; a 45th, whose decimal
74//! points a spreadsheet took out (`12.34` written `1234`), gives 99.9 and is refused.
75//!
76//! **The accelerometer.** As of 2026-10-12, in the 4 of those files with an accelerometer,
77//! `AccelFPSS` is about 32 times `AccelG` (32.17 ft/s² is one g), `VAccel` tracks the sum of
78//! `AccelFPSS` over the steps, and `AccelG`'s median before the start of flight (`T` below 0) is
79//! 0 to 0.2 g. Standing on the pad, an accelerometer that keeps gravity reads 1 g, so the Proton's
80//! acceleration has gravity taken out. Its manual doesn't say so; its release notes have it
81//! calibrate the accelerometer as it is armed, standing up (2.01C, p8). A note on the record says
82//! whether this file's acceleration holds gravity, from its own pad reading: taken out below
83//! 0.5 g, held within 0.5 g of 1 g, not known otherwise or with no rows before the start of
84//! flight. The values are kept as written either way. The `F`-prefixed accelerometer columns are
85//! read as their unfiltered namesakes, as `FAlt` is `Alt` filtered: no manual describes them.
86//!
87//! **The time's unit.** The Classic's and TRS's downloads, and the older guide's, write `T` in
88//! milliseconds; the Quantum's and Proton's in seconds; and the sample logs hold eleven-column
89//! files in both. The logger takes 4 to 33 samples a second going up and 1 to 10 coming down
90//! (Classic p19–20; Quantum p25), so a step between rows is 0.03 to 1 in seconds and 30 to 1,000
91//! in milliseconds. The reader takes the median step between rows: above 5, a factor of 5 clear of
92//! either range, `T` is in milliseconds; otherwise in seconds. In the CSV download, a median step
93//! above 1 and below 30 is neither, and the file is refused ([`LogError::Unit`]): a seconds clock
94//! whose decimal points were taken out writes 0.05 as 5. (The terminal download's coast settles
95//! its clock instead, below.) A file of one row has no step, and
96//! is read in seconds. A note on the record says which, and why. The terminal download's table
97//! checks this, and its altitudes' feet, against the coast too (below).
98//!
99//! **Event markers.** The manuals put the markers last, from `LDA` on: each is 0 at every sample
100//! but the one that triggers its event, where the Quantum's and Proton's manuals say it holds "the
101//! RAW altitude data", in feet (Quantum p38; Proton p46). `MaxV` and `MaxA` hold the top speed and
102//! acceleration instead, ft/s and ft/s² (*Eggtimer Proton Release Notes*, version 1.02N, p13: "now
103//! referenced to the actual value"); in the sample logs they are the whole part of `VAccel` and
104//! `AccelFPSS` on their row. A marker may also be held from its event to the end of the file, as 3
105//! marker columns among the 43 sample files are (as of 2026-10-12). Each marker column is kept as a
106//! channel as written, [`Quantity::Unrecognized`]: its 0 means "no event", not 0 ft, so converting
107//! it as a height would mislead. One note on the record lists them. Each run of non-zero samples is
108//! an [`Event`] named as the column (a name past 80 characters cut short, as a note quotes it), at
109//! the run's first sample, up to [`MAX_EVENTS_PER_MARKER`] a column; past that, the rises are
110//! counted in a note. An event that happened at a raw altitude of exactly 0 ft can't be told from
111//! no event, and is lost. A column after `LDA` whose name this reader doesn't know, such as a
112//! Proton channel's own name, is read as a marker, with a note.
113//!
114//! **The primary track.** [`FlightLog::altitude_m`] is `Alt`, the barometer's raw altitude above
115//! the logger's zero. The vertical speed is `Veloc` (or `VRaw`), the barometer's; without it, or
116//! with it kept as written because its check failed, the filtered `FVeloc` (or `KVeloc`, `VFilt`),
117//! also the barometer's, with a note. `VAccel` is the
118//! accelerometer's, a channel only. The file names no model, serial number or flight, so the logger
119//! reads `Eggtimer`.
120//!
121//! **Cells.** Lines end in CR, LF, CR LF or CR CR LF (a blank line after every row, which is
122//! skipped). A semicolon-separated file, as a European locale's spreadsheet saves the download, may
123//! write its numbers with a decimal comma: the mark is settled once for the file, a comma only if
124//! no number is written with a point and one is written with a comma before other than three
125//! digits, and a cell in the other mark is no number, so a thousands separator is never read as a
126//! decimal mark. A note says which. A row whose every cell is empty, as some downloads end with hundreds of, is skipped
127//! and counted in a note. An empty cell, or a row shorter than the header, leaves a gap, `NaN`,
128//! counted per column in a note. A cell that isn't a number, a row longer than the header, an empty
129//! time, and a time that doesn't increase are refused, naming the line. A column this reader
130//! doesn't know, before `LDA`, is kept as written, [`Quantity::Unrecognized`], with a note.
131//!
132//! **Where this comes from.** The layouts and units are the manuals' above; the time-unit rule, the
133//! blank-row rule and the column names they don't show are the sample logs'. Debrief's reader
134//! (`lib/parsers/eggtimer.ts`, MIT, the project owner's own) also tells milliseconds from seconds
135//! by the median step, over the first 60 rows with its line at 3. Where this reader departs from
136//! it: it keeps every column and reads the markers as events, where Debrief maps the time, the
137//! altitude and one velocity; it takes the raw `Veloc` as the vertical speed where Debrief prefers
138//! the filtered one; it reads the layouts without `Veloc`, which Debrief doesn't recognize; and it
139//! refuses what Debrief passes over, naming the line. Debrief's note that the logger can be set to
140//! metric units cites no source, and none of the manuals above offers such a setting.
141//!
142//! **The terminal download.** A TRS's flight can also be downloaded in a terminal program, which
143//! prints three parts: the flight settings, the summary data ("apogee, length of flight, maximum
144//! velocity, etc.") and the detail data, the table above (*Eggtimer TRS Flight Computer User's
145//! Manual*, firmware 2.07, p35). The manual shows the first two over a page (p36) and the table
146//! after them (p37); the file the terminal captures holds all three, as [`LogFormat::EggtimerText`]:
147//!
148//! ```text
149//! Flight Summary:
150//! Eggtimer TRS 2.07    Flight Settings
151//! ...Drogue <1=Normal,2=Backup,0=OFF>...1
152//! ...Main Altitude <50-2000 by 50, 0=OFF>...600
153//! ...Frequency (Ctrl-F to change)...915
154//! ...ID Code...3
155//! ...MY EGGTIMER
156//! ASL Alt.: 1200 ft
157//! Base Temp: 70.0 F
158//! Apogee: 1500 ft
159//! T @ Apogee: 9.500
160//! Max Velocity: 400 ft/sec
161//! T @ Max Velocity: 1.300
162//! Altitude @ Main Deploy: 590 ft
163//! T @ Main Deploy: 40.000
164//! T,Alt,Veloc,Filt_Alt,FVeloc,LDA,LowV,Apogee,N-O,Drogue,Main
165//! 0,0,0.00,0.00,0.00,0,0,0,0,0,0
166//! ```
167//!
168//! Firmware 2.10 writes `Main Alt`, `Freq`, `Max Veloc`, `Alt @ …` and `T @ Drogue` where 2.07
169//! writes `Main Altitude`, `Frequency`, `Max Velocity`, `Altitude @ …` and `T @ Drogue Deploy`.
170//!
171//! A file is this layout if a title, a line `Eggtimer <model> <firmware>` ending in `Flight
172//! Settings` (or followed by a line `Flight Settings`, as the manual's example prints it, p36), comes
173//! before an Eggtimer header row, both within the first [`MAX_PREAMBLE_LINES`] lines that aren't
174//! blank. A `Flight Summary:` heading may come before the title; any other line there is counted
175//! in a note. The CSV download opens with its header row, so it is never this layout.
176//!
177//! What the reader keeps:
178//!
179//! - **The table**, read as [`read`] reads the CSV download, every rule above the same, but for
180//!   its clock and its altitudes, each settled by two checks that agree ([ADR-258][adr-258] §2),
181//!   the coast's below; an error names the file's line.
182//! - **The title**: the logger, such as `Eggtimer TRS`, and its last word, if it starts with a
183//!   digit, as the firmware.
184//! - **The flight settings**, the lines `...<setting>...<value>`, listed as written in one note.
185//!   A settings line with no value is the name the owner gave the flight computer (the manual's
186//!   settings screen shows `MY EGGTIMER`, p24): free text that may name a person, it is left out
187//!   of the record and only counted.
188//! - **`ASL Alt.`**, "the measured ASL altitude of the launch site" (p36), as
189//!   [`Stated::ground_elevation_msl_m`], and **`Apogee`** as [`Stated::apogee_m`]: each read by
190//!   its unit mark, `ft` (or `m`), with a note; without one it is kept as written. In both sample
191//!   files the stated apogee is the table's highest `Alt`, so it is above the logger's zero.
192//! - **The summary's times**, `T @ …` and `Time @ LDA`, as [`Event`]s, in seconds: the manual's
193//!   download writes them in `secs.` and its LDA at 0.700 secs. is "700ms into the flight" (p36,
194//!   p37); the sample files leave the mark out. A time that is its marker's event in the table,
195//!   within half a millisecond, is that event, kept once: `Apogee` is `Apogee`'s, `LDA` `LDA`'s,
196//!   `Unlock` `LowV`'s (the end of the Mach lockout, p37), `N-O` and `Nose-Over` `N-O`'s, `Drogue`
197//!   and `Drogue Deploy` `Drogue`'s, `Main` and `Main Deploy` `Main`'s. As of 2026-10-13, in both
198//!   sample files, every such time is its marker's to the millisecond. Any other time, such as `T
199//!   @ Max Velocity`, or one that differs from its marker's, is an event of its own named as the
200//!   summary names it, a difference noted. A time of 0 is no event: the manual writes zeroes for a
201//!   channel that didn't fire (p25). Nor is a time past the table's last: no event of the flight
202//!   comes after its last sample, so such a time isn't in seconds, and it is kept as written in a
203//!   note rather than read in another unit on one check. The events are in time order, the
204//!   table's first where two share a time.
205//! - **The other summary lines**, listed as written in one note: the base temperature with its
206//!   unit mark (`F` in the sample files, `C` in the manual's example), the flight time, the beep
207//!   code, the top speed and acceleration, and the heights at each event; `Last Flight Phase` with
208//!   its meaning, from the manual's codes (p37).
209//!
210//! Each note lists at most 40 lines, the rest counted. The summary's figures beside the table's
211//! are the logger's own and are never put in place of HPR Sim's readings.
212//!
213//! **The coast check.** The terminal download's clock and altitudes rest on two checks each, not
214//! one ([ADR-258][adr-258] §2): `T` on its step (above) and the coast, `Alt` and its filtered
215//! `FAlt` (`Filt_Alt`, `KAlt`) on the manuals' feet (above) and the coast. In the coast just before
216//! the top nothing pushes the rocket and, as it slows, its drag fades: its altitude curves down
217//! at gravity, 32.17 ft/s² in feet and seconds, 9.81 m/s² in meters. The reader fits a parabola,
218//! by least squares, to each altitude over the 3 s up to the window's end (each row the median of
219//! the 5 rows about it within the window, so that a spike of one or two rows is passed over), and
220//! reads its curvature as a share of standard gravity:
221//!
222//! - The window ends at `Alt`'s top: the highest median of 5 rows, then the highest row among
223//!   those 5. A charge marked at or before the top ends it at the row before: `Apogee`, `N-O`, a
224//!   deployment channel (`Drogue`, `Main`, `AUX`, `CHA`, `CHB`, `CH1`…) or a column the reader
225//!   doesn't know; an Eggtimer can fire one on the way up, and its canopy's drag would add to
226//!   gravity. Then a jump in the 4 s before the end, a row more than half the window's rise from
227//!   its median (an ejection's pressure), or a motor's marker there (`BurnT`, `BO#…`, `Boost#…`),
228//!   ends it at the row before, again until neither is left. `LDA`, `LowV`, `MaxV` and `MaxA`
229//!   change nothing on the rocket.
230//! - The coast must hold 6 rows with an altitude (the manuals' slowest climb, 4 samples a second,
231//!   puts 12 in 3 s), the table must reach back the whole 3 s, the altitude must rise over them,
232//!   and the parabola must turn down and top out within 1 s of the window's end, so that the
233//!   window is the slow end of the coast, where a rocket's own drag is a few hundredths of a g.
234//! - A slowing of 0.7 to 1.3 g bears a unit out: drag near the top is small, and feet and meters
235//!   are 3.28 apart, so at most one is within it. A clock 1,000 times off puts the slowing 10⁶
236//!   times off.
237//!
238//! `T` is read in the step's unit when `Alt` slows at 0.7 to 1.3 g in feet or in meters on that
239//! clock; otherwise, or with no coast to fit, the file is refused ([`LogError::Unit`]): nothing
240//! in it would have a time. `Alt` is read in feet when it slows at 0.7 to 1.3 g in feet;
241//! otherwise it is kept as written, [`Quantity::Unrecognized`], the record holding no barometric
242//! altitude, and so is each speed that is its change. Each filtered altitude is fitted over the
243//! same window and read in feet, or kept as written with its speed, the same way. A note on the
244//! record says which, with the window and the slowing.
245//!
246//! What can't be seen: a canopy this Eggtimer didn't fire, out within 4 s of the window's end with
247//! no jump. One out longer before the top is no matter: a canopy whose drag grows as the speed
248//! squared, `g (v / v_t)²` for a descent rate `v_t`, stops a rising rocket within `(v_t / g) π/2`,
249//! so one out more than 4 s before has `v_t` over `8g/π` and slows the 3 s up to the top by at
250//! most `v_t tan(3g / v_t) / 3 s`, 2.05 g, which reads 0.62 g in feet, short of the band. As of
251//! 2026-10-13, in the 3 terminal downloads among the project's sample logs (two text files, one
252//! RTF), `Alt` slows at 0.96 to 1.02 g in feet and the filtered altitudes at 1.01 to 1.04 g; one
253//! window ends at the row before the `Apogee` marker, one before a jump and one at the top.
254//!
255//! **The download saved as RTF.** A terminal capture pasted into a text editor and saved as an
256//! RTF document is the same text wrapped in RTF's markup, [`LogFormat::EggtimerRtf`]. The reader
257//! unwraps it, not parses it ([ADR-258][adr-258] §4): it keeps the document's plain text, by a
258//! small subset of the RTF specification ([`read_rtf`] lists it), and reads that as the terminal
259//! download above, an error naming the document's line. As of 2026-10-13, of the three sample
260//! files filed as RTF, one is such a document, written by a Mac's text editor, a line of text a
261//! line of the file, and holding four downloads one after another: the first is read and the
262//! others counted in a note. The other two hold no Eggtimer download and are refused by name.
263//! Its downloads' firmware writes most summary times without the TRS manual's spacing
264//! (`T@Apogee`), so they are kept as written; the one with it lies far past the table's last
265//! sample, so it can't be in seconds, and it is kept as written too, never an event.
266//!
267//! [adr-258]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0258-aerospacenus-board-and-a-phone-apps-csv-before-the-rest.md
268
269use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
270
271use crate::error::LogError;
272use crate::log::{Channel, Event, FlightLog, LogFormat, Quantity, Stated};
273use crate::perfectflite::FOOT_M;
274use crate::table::{self, Notes, finite, number, numbered_lines, short};
275
276/// The format's name in errors.
277const FORMAT: &str = "Eggtimer CSV";
278
279/// The median step between rows above which `T` is read in milliseconds. At the manuals' 1 to 33
280/// samples a second, a step is 0.03 to 1 in seconds and 30 to 1,000 in milliseconds: 5 is a
281/// factor of 5 clear of the first and 6 of the second.
282const MILLISECONDS_ABOVE: f64 = 5.0;
283
284/// The median steps between rows, ends excluded, that are neither seconds nor milliseconds at the
285/// manuals' rates: above 1 s and below 30 ms. A file with one is refused: one whose decimal
286/// points were taken out writes 0.05 s as 5 and 0.25 s as 25.
287const NEITHER_UNIT: (f64, f64) = (1.0, 30.0);
288
289/// How far a speed may be from its altitude's change over the step and still count as that
290/// change, in the file's units: 1 %, or 1 ft/s, whichever is larger. The cells are rounded to
291/// whole feet or hundredths, and a few rows fall across a change of sampling rate.
292const SPEED_MATCH_RELATIVE: f64 = 0.01;
293const SPEED_MATCH_FT_S: f64 = 1.0;
294
295/// The least share of the rows after the first on which a speed must be its altitude's change
296/// over the step for the reader to read it in feet per second; below it, the column is kept as
297/// written. As of 2026-10-12, over the 43 Eggtimer files among the project's sample logs, the
298/// least share is 95.9 %, and with the clock read in the wrong unit, a factor of 1,000 off, the
299/// most is 9.5 %: 90 % sits between the two, near the first.
300const SPEED_MATCH_SHARE: f64 = 0.9;
301
302/// How far a filtered altitude may scale from `Alt` and still be read in feet: the least-squares
303/// factor through zero that takes `Alt` to it, `Σ(filtered × Alt) / Σ Alt²` over the rows holding
304/// both, must lie from 0.1 to 2. A filter that follows the altitude lags it: under it on the way
305/// up, by more the less of the climb the file holds, and over it on the way down, by little, as
306/// the descent is slow. A lag of `τ` at a speed `v` over a climb or a descent of height `H` moves
307/// the factor by about `1.5 v τ / H`: 0.1 holds for a climb of 1.7 `v τ` or more, and a descent
308/// at 100 ft/s, `τ` a second, stays under 2 from 150 ft. A decimal place lost writes a
309/// value 10 times over, two places 100 times: 2 is a factor of 5 below the first. As of
310/// 2026-10-15, over the 44 Eggtimer files the project's sample logs read, every one with a
311/// filtered altitude, the factor lies from 0.900 to 1.000; in a semicolon-separated file whose
312/// decimal points were taken out, `12.34` written `1234`, it is 99.9, and the file is refused.
313const FILTERED_SCALE: std::ops::RangeInclusive<f64> = 0.1..=2.0;
314
315/// The most events one marker column gives; past it, the column's rises are counted in a note
316/// instead. A marker marks one event of the flight (Quantum p38, Proton p46): as of 2026-10-12, no
317/// marker column among the 43 Eggtimer files in the project's sample logs rises more than once.
318/// The cap keeps a file whose marker flips on every row from filling the record with events.
319pub const MAX_EVENTS_PER_MARKER: usize = 16;
320
321/// The pad reading, in g, below which an acceleration is taken to have gravity out, and within
322/// which of 1 g to have it in: halfway between the two.
323const GRAVITY_READING_G: f64 = 0.5;
324
325/// The most names a note lists; past it, the rest are counted.
326const MAX_LISTED: usize = 6;
327
328/// What a column is.
329#[derive(Debug, Clone, Copy, PartialEq, Eq)]
330enum Kind {
331    /// `Alt`: the barometer's raw altitude, ft.
332    Altitude,
333    /// `FAlt`, `Filt_Alt`, `KAlt`: the barometric altitude filtered, ft.
334    FilteredAltitude,
335    /// `Veloc`, `VRaw`: the change in `Alt` over the step, ft/s.
336    RawSpeed,
337    /// `FVeloc`, `KVeloc`, `VFilt`: the change in the filtered altitude over the step, ft/s.
338    FilteredSpeed,
339    /// The accelerometer in g.
340    AccelerationG,
341    /// The accelerometer in ft/s².
342    AccelerationFtS2,
343    /// The accelerometer's velocity, ft/s.
344    InertialSpeed,
345    /// The accelerometer's distance traveled, ft.
346    InertialAltitude,
347    /// An event marker: 0, or at its event the raw altitude (or, for `MaxV` and `MaxA`, the
348    /// speed or acceleration).
349    Marker,
350    /// A column the reader doesn't know.
351    Unknown,
352}
353
354impl Kind {
355    /// What the column measures, and the factor that takes it to SI.
356    fn quantity(self) -> (Quantity, f64) {
357        match self {
358            Self::Altitude | Self::FilteredAltitude => (Quantity::AltitudeAboveGround, FOOT_M),
359            Self::RawSpeed | Self::FilteredSpeed | Self::InertialSpeed => (Quantity::Speed, FOOT_M),
360            Self::AccelerationG => (Quantity::Acceleration, STANDARD_GRAVITY_MPS2),
361            Self::AccelerationFtS2 => (Quantity::Acceleration, FOOT_M),
362            Self::InertialAltitude => (Quantity::InertialAltitude, FOOT_M),
363            Self::Marker | Self::Unknown => (Quantity::Unrecognized, 1.0),
364        }
365    }
366}
367
368/// The column names the reader knows, but for the time and the markers, as the manuals and the
369/// sample logs write them.
370const KNOWN: [(&str, Kind); 21] = [
371    ("Alt", Kind::Altitude),
372    ("FAlt", Kind::FilteredAltitude),
373    ("Filt_Alt", Kind::FilteredAltitude),
374    ("KAlt", Kind::FilteredAltitude),
375    ("Veloc", Kind::RawSpeed),
376    ("VRaw", Kind::RawSpeed),
377    ("FVeloc", Kind::FilteredSpeed),
378    ("KVeloc", Kind::FilteredSpeed),
379    ("VFilt", Kind::FilteredSpeed),
380    ("Accel", Kind::AccelerationG),
381    ("AccelG", Kind::AccelerationG),
382    ("FAccelG", Kind::AccelerationG),
383    ("AccelFPSS", Kind::AccelerationFtS2),
384    ("FAccelFPSS", Kind::AccelerationFtS2),
385    ("VAccel", Kind::InertialSpeed),
386    ("VelocAcc", Kind::InertialSpeed),
387    ("FAccelVel", Kind::InertialSpeed),
388    ("AltAccel", Kind::InertialAltitude),
389    ("AltAcc", Kind::InertialAltitude),
390    ("FAccelAlt", Kind::InertialAltitude),
391    // The first of the markers: every column after it is one too.
392    ("LDA", Kind::Marker),
393];
394
395/// The marker names the manuals and the sample logs write, `LDA` aside; `CH`, `BO#` and `Boost#`
396/// followed by digits are matched by their shape ([`kind_of`]).
397const MARKERS: [&str; 11] = [
398    "LowV", "Apogee", "N-O", "Drogue", "Main", "AUX", "BurnT", "CHA", "CHB", "MaxV", "MaxA",
399];
400
401/// What a column name is; `None` for one the reader doesn't know.
402fn kind_of(name: &str) -> Option<Kind> {
403    if let Some((_, kind)) = KNOWN.iter().find(|(known, _)| *known == name) {
404        return Some(*kind);
405    }
406    let numbered = |prefix: &str| {
407        name.strip_prefix(prefix)
408            .is_some_and(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
409    };
410    (MARKERS.contains(&name) || numbered("CH") || numbered("BO#") || numbered("Boost#"))
411        .then_some(Kind::Marker)
412}
413
414/// The separator of a header row that is an Eggtimer's, `None` for one that isn't: `T` then
415/// `Alt`, then at least one more name the reader knows, separated by commas, or else by
416/// semicolons. Commas are tried first, as a Proton's channel may be named with a semicolon.
417fn header_separator(line: &str) -> Option<char> {
418    [',', ';'].into_iter().find(|&separator| {
419        let mut names = line.split(separator).map(str::trim);
420        names.next() == Some("T")
421            && names.next() == Some("Alt")
422            && names.any(|name| kind_of(name).is_some())
423    })
424}
425
426/// Whether the text is an Eggtimer's download, judged from its first line that isn't blank, never
427/// the file's name.
428pub(crate) fn recognizes(text: &str) -> bool {
429    numbered_lines(text)
430        .map(|(_, line)| line.trim())
431        .find(|line| !line.is_empty())
432        .is_some_and(|line| header_separator(line).is_some())
433}
434
435/// One column of the file, as the header names it.
436struct Column {
437    name: String,
438    kind: Kind,
439}
440
441impl Column {
442    /// Whether the column's name states its unit: `AccelG` and `FAccelG` name g, `AccelFPSS` and
443    /// `FAccelFPSS` ft/s². No other name the reader knows does.
444    fn names_its_unit(&self) -> bool {
445        match self.kind {
446            Kind::AccelerationG => self.name.ends_with('G'),
447            Kind::AccelerationFtS2 => self.name.ends_with("FPSS"),
448            _ => false,
449        }
450    }
451}
452
453/// Reads an Eggtimer's flight data from its text.
454///
455/// # Errors
456///
457/// [`LogError::NotThisFormat`] if the first line that isn't blank isn't an Eggtimer header row
458/// (`T`, `Alt` and a name this reader knows); [`LogError::Syntax`] for a header column with no
459/// name, a row longer than the header, a cell that isn't a number, an empty time, a time that
460/// doesn't increase, or rows that hold too few of the cells the header names;
461/// [`LogError::NoData`] if there are no rows.
462pub fn read(text: &str) -> Result<FlightLog, LogError> {
463    read_table(text, Checks::Csv)
464}
465
466/// How the table's clock and altitudes are decided: as the CSV download's are, the clock by its
467/// step and the altitudes by the manuals, or, for the terminal download, each also by the coast
468/// (module docs, *The coast check*).
469#[derive(Debug, Clone, Copy, PartialEq, Eq)]
470enum Checks {
471    Csv,
472    Coast,
473}
474
475/// The table read as [`read`] reads it, its units decided by `checks`; [`LogError::Unit`] for a
476/// clock the coast doesn't bear out, naming the header's line.
477fn read_table(text: &str, checks: Checks) -> Result<FlightLog, LogError> {
478    let mut lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
479    let Some((header_line, header)) = lines.next() else {
480        return Err(LogError::NotThisFormat {
481            format: FORMAT,
482            message: "the file is empty".to_owned(),
483        });
484    };
485    let Some(separator) = header_separator(header) else {
486        return Err(LogError::NotThisFormat {
487            format: FORMAT,
488            message: format!(
489                "its first line, {:?}, isn't an Eggtimer header row: `T`, `Alt` and the \
490                 Eggtimer's columns, such as `Veloc` or `LDA`",
491                short(header)
492            ),
493        });
494    };
495    let mut notes = Notes::default();
496    let columns = header_columns(header, separator, header_line, &mut notes)?;
497    let rows_text = || {
498        numbered_lines(text)
499            .filter(|(number, line)| *number > header_line && !line.trim().is_empty())
500    };
501    let decimal_comma = separator != ','
502        && table::decimal_comma_shown(
503            rows_text().flat_map(|(_, line)| line.split(separator).map(str::trim)),
504        );
505    if separator != ',' {
506        notes.push(format!(
507            "the cells are separated by semicolons, as a European locale's export writes them; a \
508             number's decimal mark is a {}",
509            if decimal_comma { "comma" } else { "point" }
510        ));
511    }
512
513    // Each row's cells as numbers, `NaN` where empty; a row leaves out the cells past its end.
514    let mut rows: Vec<(usize, Vec<f64>)> = Vec::new();
515    let mut cells_written = 0_usize;
516    let mut blank_rows = 0_usize;
517    for (number, line) in lines {
518        let cells: Vec<&str> = line.split(separator).map(str::trim).collect();
519        if cells.iter().all(|cell| cell.is_empty()) {
520            blank_rows += 1;
521            continue;
522        }
523        if cells.len() > columns.len() + 1 {
524            return Err(syntax(
525                number,
526                format!(
527                    "the row has {} cells and the header names {}",
528                    cells.len(),
529                    columns.len() + 1
530                ),
531            ));
532        }
533        let values = row_values(&cells, &columns, number, decimal_comma)?;
534        cells_written = cells_written.saturating_add(cells.len());
535        rows.push((number, values));
536        if crate::log::too_sparse(columns.len() + 1, rows.len(), cells_written) {
537            return Err(syntax(
538                number,
539                format!(
540                    "{} rows hold {cells_written} of the {} cells the header's {} columns name: \
541                     too few for the header to be this file's",
542                    rows.len(),
543                    rows.len().saturating_mul(columns.len() + 1),
544                    columns.len() + 1
545                ),
546            ));
547        }
548    }
549    if rows.is_empty() {
550        return Err(LogError::NoData { format: FORMAT });
551    }
552    build(columns, &rows, blank_rows, notes, header_line, checks)
553}
554
555/// The header's columns after the time, each with what it is. The time is `T` and the altitude
556/// `Alt`, checked by [`header_separator`].
557fn header_columns(
558    header: &str,
559    separator: char,
560    line: usize,
561    notes: &mut Notes,
562) -> Result<Vec<Column>, LogError> {
563    let mut columns = Vec::new();
564    let mut after_lda = false;
565    for (index, name) in header.split(separator).map(str::trim).enumerate().skip(1) {
566        if name.is_empty() {
567            return Err(syntax(
568                line,
569                format!("the header's column {} has no name", index + 1),
570            ));
571        }
572        let kind = match kind_of(name) {
573            Some(kind) => kind,
574            None if after_lda => {
575                notes.push(format!(
576                    "the column {:?} isn't one this reader knows; it comes after `LDA`, where the \
577                     manuals put only event markers, and was read as one",
578                    short(name)
579                ));
580                Kind::Marker
581            }
582            None => {
583                notes.push(format!(
584                    "the column {:?} isn't one this reader knows, and was kept as written",
585                    short(name)
586                ));
587                Kind::Unknown
588            }
589        };
590        after_lda |= name == "LDA";
591        columns.push(Column {
592            name: name.to_owned(),
593            kind,
594        });
595    }
596    Ok(columns)
597}
598
599/// A row's cells as numbers in the file's units, the time first; `NaN` for an empty cell. The
600/// time must be there. A number is in the file's decimal mark, settled once for the file.
601fn row_values(
602    cells: &[&str],
603    columns: &[Column],
604    line: usize,
605    decimal_comma: bool,
606) -> Result<Vec<f64>, LogError> {
607    let mut values = Vec::with_capacity(cells.len());
608    for (index, cell) in cells.iter().enumerate() {
609        if cell.is_empty() {
610            if index == 0 {
611                return Err(syntax(
612                    line,
613                    "the time, the row's first cell, is empty".to_owned(),
614                ));
615            }
616            values.push(f64::NAN);
617            continue;
618        }
619        let Some(value) = table::number_in_mark(cell, decimal_comma) else {
620            let under = match index.checked_sub(1).and_then(|at| columns.get(at)) {
621                Some(column) => short(&column.name),
622                None => "T".to_owned(),
623            };
624            return Err(syntax(
625                line,
626                format!(
627                    "{:?} in cell {}, under {under:?}, isn't a number",
628                    short(cell),
629                    index + 1
630                ),
631            ));
632        };
633        values.push(value);
634    }
635    Ok(values)
636}
637
638/// The record from the rows read: the clock, every channel, the events and the notes.
639fn build(
640    mut columns: Vec<Column>,
641    rows: &[(usize, Vec<f64>)],
642    blank_rows: usize,
643    mut notes: Notes,
644    header_line: usize,
645    checks: Checks,
646) -> Result<FlightLog, LogError> {
647    // The time, strictly increasing, in the file's unit.
648    let mut written_time = Vec::with_capacity(rows.len());
649    for (number, values) in rows {
650        // Invariant: `row_values` refuses a row whose time is empty, and a stored row has a cell.
651        let time = values.first().copied().unwrap_or(f64::NAN);
652        if let Some(&last) = written_time.last()
653            && time <= last
654        {
655            return Err(syntax(
656                *number,
657                format!("the time {time} comes at or before the one above it, {last}"),
658            ));
659        }
660        written_time.push(time);
661    }
662    let clock = time_unit(&written_time);
663    // The terminal download's coast check settles its clock on its own (module docs).
664    if let Some((_, median)) = clock
665        && checks == Checks::Csv
666        && median > NEITHER_UNIT.0
667        && median < NEITHER_UNIT.1
668    {
669        return Err(LogError::Unit {
670            format: FORMAT,
671            line: header_line,
672            message: format!(
673                "the median step between rows of `T` is {}. That is neither seconds nor \
674                 milliseconds at the manuals' 1 to 33 samples a second (0.03 to 1 s, 30 to \
675                 1,000 ms). A file whose decimal points were taken out writes 0.05 s as 5",
676                plain(median, 3)
677            ),
678        });
679    }
680    let units_per_second = clock.map_or(1.0, |(per_second, _)| per_second);
681    let time_s: Vec<f64> = written_time
682        .iter()
683        .map(|time| time / units_per_second)
684        .collect();
685
686    // Each column's values as written; a row that stops short leaves gaps.
687    let written: Vec<Vec<f64>> = (1..=columns.len())
688        .map(|index| {
689            rows.iter()
690                .map(|(_, values)| values.get(index).copied().unwrap_or(f64::NAN))
691                .collect()
692        })
693        .collect();
694    let step_s: Vec<f64> = time_s.windows(2).map(|pair| pair[1] - pair[0]).collect();
695    let coast = match checks {
696        Checks::Csv => None,
697        Checks::Coast => Some(coast_units(
698            &columns,
699            &written,
700            &time_s,
701            clock,
702            header_line,
703        )?),
704    };
705    filtered_checks(&columns, &written, header_line)?;
706    let speeds = speed_checks(&mut columns, &written, &step_s, &mut notes);
707
708    // One note per name decided, so a header repeating a name doesn't repeat its note. On the
709    // terminal download's path, an altitude the coast doesn't bear out is kept as written, and
710    // so is a speed that is its change.
711    let decided = |index: usize| {
712        coast
713            .as_ref()
714            .and_then(|units| units.altitudes.get(index).cloned().flatten())
715    };
716    let mut unit_notes = vec![match &coast {
717        Some(units) => units.clock.clone(),
718        None => time_note(clock),
719    }];
720    let mut kept: Vec<usize> = Vec::new();
721    match decided(0) {
722        Some((note, keep)) => {
723            unit_notes.push(note);
724            if keep {
725                kept.push(0);
726            }
727        }
728        None => unit_notes.push(altitude_note(&columns, &written)),
729    }
730    let mut noted: Vec<&str> = Vec::new();
731    for (index, (column, check)) in columns.iter().zip(&speeds).enumerate() {
732        let decision = decided(index).filter(|_| column.kind == Kind::FilteredAltitude);
733        let of_kept = check.filter(|check| {
734            matches!(column.kind, Kind::RawSpeed | Kind::FilteredSpeed)
735                && decided(check.altitude).is_some_and(|(_, keep)| keep)
736        });
737        if decision.as_ref().is_some_and(|(_, keep)| *keep) || of_kept.is_some() {
738            kept.push(index);
739        }
740        if noted.contains(&column.name.as_str()) {
741            continue;
742        }
743        let note = match (decision, of_kept) {
744            (Some((note, _)), _) => Some(note),
745            (None, Some(check)) => {
746                let altitude = columns
747                    .get(check.altitude)
748                    .map(|altitude| short(&altitude.name))
749                    .unwrap_or_default();
750                Some(format!(
751                    "`{}` kept as written: it is the change in `{altitude}` over the step, and \
752                     `{altitude}` is kept as written",
753                    short(&column.name)
754                ))
755            }
756            (None, None) => unit_note(column, *check, &columns),
757        };
758        if let Some(note) = note {
759            noted.push(&column.name);
760            unit_notes.push(note);
761        }
762    }
763    for index in kept {
764        if let Some(column) = columns.get_mut(index) {
765            column.kind = Kind::Unknown;
766        }
767    }
768    unit_notes.extend(gravity_note(&columns, &written, &written_time));
769    unit_notes.extend(marker_note(&columns));
770
771    let mut log = FlightLog {
772        format: LogFormat::EggtimerCsv,
773        logger: "Eggtimer".to_owned(),
774        serial_number: None,
775        firmware: None,
776        flight_number: None,
777        stated: Stated::default(),
778        time_s: time_s.clone(),
779        altitude_m: Vec::new(),
780        vertical_speed_m_s: None,
781        temperature_k: None,
782        battery_v: None,
783        channels: Vec::with_capacity(columns.len()),
784        events: Vec::new(),
785        notes: unit_notes,
786    };
787    for (column, values) in columns.iter().zip(&written) {
788        let gaps = values.iter().filter(|value| value.is_nan()).count();
789        if gaps > 0 {
790            notes.push(format!(
791                "the column {:?} leaves {gaps} {} empty: {}",
792                short(&column.name),
793                if gaps == 1 { "cell" } else { "cells" },
794                if gaps == 1 {
795                    "it is a gap"
796                } else {
797                    "they are gaps"
798                }
799            ));
800        }
801        // A value in g that the factor makes infinite is refused on its row's line (ADR-258 §3).
802        let (quantity, factor) = column.kind.quantity();
803        let mut si = Vec::with_capacity(values.len());
804        for ((line, _), value) in rows.iter().zip(values) {
805            si.push(finite(value * factor, FORMAT, *line, &column.name)?);
806        }
807        log.channels.push(Channel {
808            column: column.name.clone(),
809            quantity,
810            time_s: time_s.clone(),
811            values: si,
812        });
813    }
814    log.events = events(&columns, &written, &time_s, &mut notes);
815
816    // The primary track: `Alt`, unless it is kept as written, and the barometer's raw speed, or
817    // its filtered one. Invariant: `Alt` is the header's name after `T` (`header_separator`), so it is
818    // the first channel.
819    log.altitude_m = columns
820        .first()
821        .filter(|column| column.kind == Kind::Altitude)
822        .and(log.channels.first())
823        .map(|channel| channel.values.clone())
824        .unwrap_or_default();
825    let speed = |kind: Kind| {
826        columns
827            .iter()
828            .zip(&log.channels)
829            .find(|(column, _)| column.kind == kind)
830            .map(|(column, channel)| (column.name.as_str(), channel.values.clone()))
831    };
832    if let Some((_, values)) = speed(Kind::RawSpeed) {
833        log.vertical_speed_m_s = Some(values);
834    } else if let Some((name, values)) = speed(Kind::FilteredSpeed) {
835        log.notes.push(format!(
836            "the file has no raw velocity, `Veloc`, read as a speed; the vertical speed is its \
837             filtered barometric {name:?}"
838        ));
839        log.vertical_speed_m_s = Some(values);
840    }
841    if blank_rows > 0 {
842        log.notes.push(format!(
843            "{blank_rows} rows hold only empty cells, and were skipped"
844        ));
845    }
846    log.notes.extend(notes.into_vec());
847    Ok(log)
848}
849
850/// Each filtered altitude checked against `Alt`: one whose least-squares factor on `Alt` lies
851/// outside [`FILTERED_SCALE`] refuses the file, its numbers not to be trusted, naming the header's
852/// line. A file whose `Alt` is zero on every row has nothing to check against.
853fn filtered_checks(columns: &[Column], written: &[Vec<f64>], line: usize) -> Result<(), LogError> {
854    // `Alt` is the first column: the header's name after `T` (`header_separator`).
855    let Some(altitude) = written.first() else {
856        return Ok(());
857    };
858    for (column, filtered) in columns.iter().zip(written) {
859        if column.kind != Kind::FilteredAltitude {
860            continue;
861        }
862        let (mut product, mut square) = (0.0_f64, 0.0_f64);
863        for (&f, &a) in filtered.iter().zip(altitude) {
864            if f.is_finite() && a.is_finite() {
865                product += f * a;
866                square += a * a;
867            }
868        }
869        if square == 0.0 {
870            continue;
871        }
872        let factor = product / square;
873        if FILTERED_SCALE.contains(&factor) {
874            continue;
875        }
876        let measured = if factor.is_finite() {
877            format!(
878                "it is {} times `Alt` by a least-squares fit",
879                plain(factor, 3)
880            )
881        } else {
882            "its least-squares factor on `Alt` isn't a finite number".to_owned()
883        };
884        return Err(LogError::Unit {
885            format: FORMAT,
886            line,
887            message: format!(
888                "`{}` isn't a filter of `Alt`: {measured}. That is outside the 0.1 to 2 a filter of \
889                 the altitude can be, so the file's numbers can't be trusted. A file whose \
890                 decimal points were taken out writes `12.34` as `1234`, 100 times over",
891                short(&column.name)
892            ),
893        });
894    }
895    Ok(())
896}
897
898/// What the rows say of a speed: the column of the altitude it should be the change of, and on
899/// how many of the rows after the first it is, of how many can be checked.
900#[derive(Debug, Clone, Copy)]
901struct SpeedCheck {
902    altitude: usize,
903    matching: usize,
904    rows: usize,
905}
906
907/// Each speed checked against the altitude it should be the change of: `Veloc` and `VRaw` against
908/// `Alt`, `FVeloc`, `KVeloc` and `VFilt` against the file's first filtered altitude. A speed that
909/// matches on fewer than [`SPEED_MATCH_SHARE`] of the rows checked is kept as written, with a
910/// note; the others get their check, `None` for a column that isn't a speed or has no altitude to
911/// check it against.
912fn speed_checks(
913    columns: &mut [Column],
914    written: &[Vec<f64>],
915    step_s: &[f64],
916    notes: &mut Notes,
917) -> Vec<Option<SpeedCheck>> {
918    let filtered = columns
919        .iter()
920        .position(|column| column.kind == Kind::FilteredAltitude);
921    let mut checks = vec![None; columns.len()];
922    for (index, check) in checks.iter_mut().enumerate() {
923        // `Alt` is the first column: the header's name after `T` (`header_separator`).
924        let altitude = match columns.get(index).map(|column| column.kind) {
925            Some(Kind::RawSpeed) => Some(0),
926            Some(Kind::FilteredSpeed) => filtered,
927            _ => None,
928        };
929        let (Some(altitude), Some(speed)) = (altitude, written.get(index)) else {
930            continue;
931        };
932        let Some(altitude_values) = written.get(altitude) else {
933            continue;
934        };
935        let (matching, rows) = speed_matches(speed, altitude_values, step_s);
936        // Row counts are far below 2^52, where an `f64` holds every whole number.
937        let enough = rows == 0 || matching as f64 >= SPEED_MATCH_SHARE * rows as f64;
938        if enough {
939            *check = Some(SpeedCheck {
940                altitude,
941                matching,
942                rows,
943            });
944            continue;
945        }
946        let altitude_name = columns
947            .get(altitude)
948            .map(|column| short(&column.name))
949            .unwrap_or_default();
950        if let Some(column) = columns.get_mut(index) {
951            notes.push(format!(
952                "`{}` kept as written, not read as a speed: it is the change in \
953                 `{altitude_name}` over the step, within 1 % or 1 ft/s. That holds in only {matching} of \
954                 {rows} rows after the first, under the 90 % the reader asks",
955                short(&column.name)
956            ));
957            column.kind = Kind::Unknown;
958        }
959    }
960    checks
961}
962
963/// On how many rows after the first a speed is its altitude's change over the step, within 1 %
964/// or 1 ft/s, of how many hold both and a finite change.
965fn speed_matches(speed: &[f64], altitude: &[f64], step_s: &[f64]) -> (usize, usize) {
966    let (mut rows, mut matching) = (0_usize, 0_usize);
967    for (row, step) in step_s.iter().enumerate() {
968        let (Some(&low), Some(&high), Some(&value)) =
969            (altitude.get(row), altitude.get(row + 1), speed.get(row + 1))
970        else {
971            continue;
972        };
973        let change = (high - low) / step;
974        if !(change.is_finite() && value.is_finite()) {
975            continue;
976        }
977        rows += 1;
978        if (value - change).abs() <= (SPEED_MATCH_RELATIVE * change.abs()).max(SPEED_MATCH_FT_S) {
979            matching += 1;
980        }
981    }
982    (matching, rows)
983}
984
985/// The events: each run of non-zero samples in a marker column, at its first sample, row by row
986/// and in the file's order within a row; past [`MAX_EVENTS_PER_MARKER`] in one column, the rest
987/// counted in a note. An event's name is the column's, cut as a note quotes it.
988fn events(
989    columns: &[Column],
990    written: &[Vec<f64>],
991    time_s: &[f64],
992    notes: &mut Notes,
993) -> Vec<Event> {
994    struct Marker<'a> {
995        name: String,
996        values: &'a [f64],
997        kept: usize,
998        left_out: usize,
999    }
1000    let mut markers: Vec<Marker> = columns
1001        .iter()
1002        .zip(written)
1003        .filter(|(column, _)| column.kind == Kind::Marker)
1004        .map(|(column, values)| Marker {
1005            name: short(&column.name),
1006            values,
1007            kept: 0,
1008            left_out: 0,
1009        })
1010        .collect();
1011    let marked = |value: f64| value != 0.0 && !value.is_nan();
1012    let mut events = Vec::new();
1013    for (row, time) in time_s.iter().enumerate() {
1014        for marker in &mut markers {
1015            let value = marker.values.get(row).copied().unwrap_or(f64::NAN);
1016            let before = row
1017                .checked_sub(1)
1018                .and_then(|above| marker.values.get(above))
1019                .is_some_and(|&above| marked(above));
1020            if !marked(value) || before {
1021                continue;
1022            }
1023            if marker.kept < MAX_EVENTS_PER_MARKER {
1024                marker.kept += 1;
1025                events.push(Event {
1026                    time_s: *time,
1027                    name: marker.name.clone(),
1028                });
1029            } else {
1030                marker.left_out += 1;
1031            }
1032        }
1033    }
1034    for marker in markers.iter().filter(|marker| marker.left_out > 0) {
1035        notes.push(format!(
1036            "the marker {:?} rises {} more times than the {MAX_EVENTS_PER_MARKER} kept as events",
1037            marker.name, marker.left_out
1038        ));
1039    }
1040    events
1041}
1042
1043/// The time's units in a second, 1 or 1,000, decided from the median step between rows, and that
1044/// median; `None` for a file of one row, with no step. Dividing by 1,000 keeps a whole number of
1045/// milliseconds the nearest `f64` to its seconds, where multiplying by 0.001 can miss it by one
1046/// step.
1047fn time_unit(written: &[f64]) -> Option<(f64, f64)> {
1048    let mut steps: Vec<f64> = written.windows(2).map(|pair| pair[1] - pair[0]).collect();
1049    if steps.is_empty() {
1050        return None;
1051    }
1052    steps.sort_by(f64::total_cmp);
1053    // Invariant: `steps` isn't empty (above), so `middle` is a place in it, and so is the one
1054    // before it when the count is even.
1055    let middle = steps.len() / 2;
1056    let median = if steps.len().is_multiple_of(2) {
1057        (steps[middle - 1] + steps[middle]) / 2.0
1058    } else {
1059        steps[middle]
1060    };
1061    let per_second = if median > MILLISECONDS_ABOVE {
1062        1000.0
1063    } else {
1064        1.0
1065    };
1066    Some((per_second, median))
1067}
1068
1069/// The clock's unit as [`time_unit`] decides it, by name.
1070fn clock_unit(per_second: f64) -> &'static str {
1071    if per_second == 1.0 {
1072        "seconds"
1073    } else {
1074        "milliseconds"
1075    }
1076}
1077
1078/// What the step says of the clock, as a note writes it after `from the step`.
1079fn step_evidence(median: f64) -> String {
1080    format!(
1081        "the median step between rows is {}. A step above 5 is read as milliseconds. At \
1082         the manuals' 1 to 33 samples a second, a step is 0.03 to 1 in seconds and 30 to 1,000 in \
1083         milliseconds",
1084        plain(median, 4)
1085    )
1086}
1087
1088/// The note saying how the CSV download's `T` was read: by its step, or in seconds for a file of
1089/// one row.
1090fn time_note(clock: Option<(f64, f64)>) -> String {
1091    match clock {
1092        Some((per_second, median)) => format!(
1093            "`T` read in {}, from the step: {}",
1094            clock_unit(per_second),
1095            step_evidence(median)
1096        ),
1097        None => "`T` read in seconds, assumed: the file holds one row, so there is no step \
1098                 between rows to tell seconds from milliseconds"
1099            .to_owned(),
1100    }
1101}
1102
1103// The coast check: the terminal download's second check of its clock and altitudes.
1104
1105/// How long, s, the coast window is: the altitude is fitted over the 3 s up to the window's end.
1106/// Longer windows reach back to faster flight, where drag adds more to gravity; shorter ones leave
1107/// the fit to a barometer's noise. As of 2026-10-13, over the 3 s windows of the 3 terminal
1108/// downloads among the project's sample logs, `Alt` slows at 0.96 to 1.02 g in feet.
1109const COAST_WINDOW_S: f64 = 3.0;
1110
1111/// How far before the window's end, s, a jump in the altitude or a motor's marker ends the window
1112/// early. A canopy whose drag grows as the speed squared, `g (v / v_t)²` for a descent rate `v_t`,
1113/// stops a rising rocket within `(v_t / g) π/2`; so one out more than 4 s before the top has `v_t`
1114/// over `8g/π`, and over a 3 s window ending at the top it slows the rocket by at most
1115/// `v_t tan(3g / v_t) / 3 s`, under 2.05 g (`tan(x)/x` at `x = 3π/8`), which a parabola's fit
1116/// weights toward the window's middle and lowers further: read in feet, 0.62 g, short of
1117/// [`COAST_BAND`]. A canopy out within 4 s of the end is ended at, by its charge's marker or its
1118/// jump.
1119const COAST_SEARCH_S: f64 = 4.0;
1120
1121/// How far, as a share of the altitude's rise over the window, a row's altitude may be from its
1122/// neighbors' median before it is a jump: an ejection's pressure, or a canopy opening. A coast
1123/// rises `g W²/2` over a window `W` into its top, 145 ft over 3 s. As of 2026-10-13, in the 3
1124/// terminal downloads among the project's sample logs, a row in the window strays from its
1125/// median by under a quarter of the window's rise, and the one jump that ends a window by several
1126/// times it.
1127const COAST_JUMP_SHARE: f64 = 0.5;
1128
1129/// The rows on each side of a row whose median is its level: 2, so that a spike of one or two rows
1130/// is passed over.
1131const LEVEL_ROWS: usize = 2;
1132
1133/// The fewest rows with an altitude the coast window must hold: twice the parabola's three
1134/// figures. The manuals' slowest climb, 4 samples a second (Classic p19), puts 12 in 3 s.
1135const COAST_ROWS: usize = 6;
1136
1137/// How far, s, from the window's end the parabola fitted to it may top out: the window must end
1138/// near the coast's top, where the rocket is slow and its drag small. A window that ends 1 s
1139/// before its top ends at about 1 g's fall of 1 s, 9.8 m/s, where a rocket's drag is a few
1140/// hundredths of a g.
1141const COAST_TOP_S: f64 = 1.0;
1142
1143/// How fast, as a share of standard gravity, the altitude must slow over the coast for a unit to
1144/// be read: gravity alone near the top, and the drag left there. Feet and meters are 3.28 apart,
1145/// so at most one unit falls within it; a clock 1,000 times off puts the slowing 10⁶ times off.
1146const COAST_BAND: (f64, f64) = (0.7, 1.3);
1147
1148/// The most times the coast window may be cut short at a jump or a motor's marker before the
1149/// reader gives up on finding a clean coast: a flight has a few such rows near its top, and a
1150/// file with more, such as one spike every few rows, would otherwise cost a scan of the window
1151/// for each.
1152const COAST_CUTS: usize = 16;
1153
1154/// What a marker column marks, for the coast window.
1155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1156enum MarkerRole {
1157    /// A detection that changes nothing on the rocket: launch, the end of the Mach lockout, the
1158    /// top speed and acceleration.
1159    Detection,
1160    /// The motor: a burnout or a boost; within [`COAST_SEARCH_S`] of the window's end, it ends
1161    /// the window.
1162    Motor,
1163    /// A charge, or a detection a charge may fire at: the apogee, the nose-over, a deployment
1164    /// channel, and any name the reader doesn't know (a Proton's owner names its channels). One at
1165    /// or before the top ends the window.
1166    Charge,
1167}
1168
1169/// What a marker column marks, by its name.
1170fn marker_role(name: &str) -> MarkerRole {
1171    let numbered = |prefix: &str| {
1172        name.strip_prefix(prefix)
1173            .is_some_and(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
1174    };
1175    if ["LDA", "LowV", "MaxV", "MaxA"].contains(&name) {
1176        MarkerRole::Detection
1177    } else if name == "BurnT" || numbered("BO#") || numbered("Boost#") {
1178        MarkerRole::Motor
1179    } else {
1180        MarkerRole::Charge
1181    }
1182}
1183
1184/// The coast window and how fast each altitude column slows over it.
1185struct Coast {
1186    /// The window as a note describes it: its rows, its times and what ends it.
1187    window: String,
1188    /// For each column, as [`Column`]s are, how fast it slows over the window, its unit per
1189    /// second squared (positive slowing as it rises); `None` for a column that isn't an altitude
1190    /// or can't be fitted.
1191    slowing: Vec<Option<f64>>,
1192}
1193
1194/// The median of `values`' finite numbers from `row - half` to `row + half`, with `half` at most
1195/// [`LEVEL_ROWS`] and shrunk to stay within `from..=to`, so that the level of a steady climb is
1196/// the climb; `NaN` without one.
1197fn level(values: &[f64], from: usize, to: usize, row: usize) -> f64 {
1198    let half = LEVEL_ROWS
1199        .min(row.saturating_sub(from))
1200        .min(to.saturating_sub(row));
1201    let mut near: Vec<f64> = values
1202        .get(row.saturating_sub(half)..=row.saturating_add(half).min(to))
1203        .unwrap_or_default()
1204        .iter()
1205        .copied()
1206        .filter(|value| value.is_finite())
1207        .collect();
1208    if near.is_empty() {
1209        return f64::NAN;
1210    }
1211    near.sort_by(f64::total_cmp);
1212    let middle = near.len() / 2;
1213    // Invariant: `near` isn't empty, so `middle` and, for an even count, the one before it are in
1214    // it.
1215    if near.len().is_multiple_of(2) {
1216        (near[middle - 1] + near[middle]) / 2.0
1217    } else {
1218        near[middle]
1219    }
1220}
1221
1222/// The least-squares parabola through points `(x, y)`: its slope and its second derivative at
1223/// `x = 0`; `None` where they aren't defined.
1224fn parabola(points: &[(f64, f64)]) -> Option<(f64, f64)> {
1225    let (mut s, mut t) = ([0.0_f64; 5], [0.0_f64; 3]);
1226    for &(x, y) in points {
1227        let mut power = 1.0;
1228        for (order, sum) in s.iter_mut().enumerate() {
1229            *sum += power;
1230            if let Some(moment) = t.get_mut(order) {
1231                *moment += power * y;
1232            }
1233            power *= x;
1234        }
1235    }
1236    // The normal equations, `[s0 s1 s2; s1 s2 s3; s2 s3 s4] (a, b, c) = (t0, t1, t2)`, by Cramer's
1237    // rule.
1238    let det = |m: [[f64; 3]; 3]| {
1239        m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
1240            - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
1241            + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
1242    };
1243    let matrix = [[s[0], s[1], s[2]], [s[1], s[2], s[3]], [s[2], s[3], s[4]]];
1244    let whole = det(matrix);
1245    let solve = |column: usize| {
1246        let mut m = matrix;
1247        for (row, value) in m.iter_mut().zip(t) {
1248            row[column] = value;
1249        }
1250        det(m) / whole
1251    };
1252    let (slope, half_curvature) = (solve(1), solve(2));
1253    (slope.is_finite() && half_curvature.is_finite()).then_some((slope, 2.0 * half_curvature))
1254}
1255
1256/// The coast window before `Alt`'s top (module docs, *The coast check*) and how fast each altitude
1257/// column slows over it; why there is none otherwise.
1258fn coast(columns: &[Column], written: &[Vec<f64>], time_s: &[f64]) -> Result<Coast, String> {
1259    // Invariant: `Alt` is the header's name after `T` (`header_separator`), so it is the first column.
1260    let alt = written.first().map_or(&[][..], Vec::as_slice);
1261    let count = alt.len().min(time_s.len());
1262    let Some(last) = count.checked_sub(1) else {
1263        return Err("the table has no rows".to_owned());
1264    };
1265    let levels: Vec<f64> = (0..count).map(|row| level(alt, 0, last, row)).collect();
1266    let highest = |values: &[f64], from: usize| {
1267        values
1268            .iter()
1269            .enumerate()
1270            .filter(|(_, value)| value.is_finite())
1271            .fold(
1272                None,
1273                |best: Option<(usize, f64)>, (row, &value)| match best {
1274                    Some((_, high)) if high >= value => best,
1275                    _ => Some((from + row, value)),
1276                },
1277            )
1278            .map(|(row, _)| row)
1279    };
1280    // The top: the highest level, a median that passes over a spike, then the highest row
1281    // within the rows that median takes in, as a median lags a sharp top.
1282    let Some(top) = highest(&levels, 0).and_then(|row| {
1283        let from = row.saturating_sub(LEVEL_ROWS);
1284        highest(
1285            alt.get(from..=row.saturating_add(LEVEL_ROWS).min(last))?,
1286            from,
1287        )
1288    }) else {
1289        return Err("`Alt` holds no number".to_owned());
1290    };
1291    let time = |row: usize| time_s.get(row).copied().unwrap_or(f64::NAN);
1292    let marked = |values: &[f64], row: usize| {
1293        values
1294            .get(row)
1295            .is_some_and(|value| *value != 0.0 && !value.is_nan())
1296    };
1297    let markers = |role: MarkerRole| {
1298        columns
1299            .iter()
1300            .zip(written)
1301            .filter(move |(column, _)| {
1302                column.kind == Kind::Marker && marker_role(&column.name) == role
1303            })
1304            .map(|(column, values)| (short(&column.name), values.as_slice()))
1305    };
1306
1307    // The window ends at the top, or before the first charge at or before it.
1308    let mut end = top;
1309    let mut ending = "up to the altitude's top".to_owned();
1310    let charge = markers(MarkerRole::Charge)
1311        .filter_map(|(name, values)| {
1312            (0..=top)
1313                .find(|row| marked(values, *row))
1314                .map(|row| (row, name))
1315        })
1316        .min_by_key(|(row, _)| *row);
1317    if let Some((row, name)) = charge {
1318        let Some(before) = row.checked_sub(1) else {
1319            return Err(format!(
1320                "`{name}` is marked on the first row, before any coast"
1321            ));
1322        };
1323        end = before;
1324        ending = format!(
1325            "up to the row before the marker `{name}` at {} s",
1326            plain(time(row), 3)
1327        );
1328    }
1329    // The first row at or after a time, at or before `end`: the times strictly increase (the
1330    // reader refuses a file whose time doesn't), so a binary search finds it.
1331    let first_from = |end: usize, from_s: f64| {
1332        let row = time_s
1333            .get(..=end)
1334            .map_or(0, |times| times.partition_point(|t| *t < from_s));
1335        (row <= end).then_some(row)
1336    };
1337    let motors: Vec<(String, &[f64])> = markers(MarkerRole::Motor).collect();
1338    // Then before the first jump, or motor marker, within the search span before the end; each
1339    // move ends it earlier, so the loop ends, after at most `COAST_CUTS` moves.
1340    let mut cuts = 0;
1341    let first = loop {
1342        let end_s = time(end);
1343        let Some(first) = first_from(end, end_s - COAST_WINDOW_S) else {
1344            return Err("the table holds no row before the window's end".to_owned());
1345        };
1346        if time(0) > end_s - COAST_WINDOW_S {
1347            return Err(format!(
1348                "the table starts {} s before the coast's end, {}, short of the {} s window",
1349                plain(end_s - time(0), 3),
1350                ending,
1351                plain(COAST_WINDOW_S, 1)
1352            ));
1353        }
1354        let rise = level(alt, 0, last, end) - level(alt, 0, last, first);
1355        if rise.is_nan() || rise <= 0.0 {
1356            return Err(format!(
1357                "`Alt` doesn't rise over the {} s {ending}",
1358                plain(COAST_WINDOW_S, 1)
1359            ));
1360        }
1361        let from = first_from(end, end_s - COAST_SEARCH_S).unwrap_or(end);
1362        let stop = (from..=end).find_map(|row| {
1363            let value = alt.get(row).copied().unwrap_or(f64::NAN);
1364            let level = levels.get(row).copied().unwrap_or(f64::NAN);
1365            if value.is_finite() && (value - level).abs() > COAST_JUMP_SHARE * rise {
1366                return Some((
1367                    row,
1368                    format!(
1369                        "up to the row before `Alt` jumps at {} s",
1370                        plain(time(row), 3)
1371                    ),
1372                ));
1373            }
1374            motors
1375                .iter()
1376                .find(|(_, values)| {
1377                    marked(values, row) && !row.checked_sub(1).is_some_and(|up| marked(values, up))
1378                })
1379                .map(|(name, _)| {
1380                    (
1381                        row,
1382                        format!(
1383                            "up to the row before the motor's marker `{name}` at {} s",
1384                            plain(time(row), 3)
1385                        ),
1386                    )
1387                })
1388        });
1389        match stop {
1390            Some((row, why)) => {
1391                cuts += 1;
1392                if cuts > COAST_CUTS {
1393                    return Err(format!(
1394                        "the coast window is cut short more than {COAST_CUTS} times by jumps or \
1395                         motor markers before the top, the last {why}"
1396                    ));
1397                }
1398                let Some(before) = row.checked_sub(1) else {
1399                    return Err(format!("the coast window ends at the first row, {why}"));
1400                };
1401                end = before;
1402                ending = why;
1403            }
1404            None => break first,
1405        }
1406    };
1407
1408    let (start_s, end_s) = (time(first), time(end));
1409    let window = format!(
1410        "the rows from {} s to {} s, {ending}",
1411        plain(start_s, 3),
1412        plain(end_s, 3)
1413    );
1414    let fit = |values: &[f64]| {
1415        let points: Vec<(f64, f64)> = (first..=end)
1416            .map(|row| (time(row) - end_s, level(values, first, end, row)))
1417            .filter(|(_, value)| value.is_finite())
1418            .collect();
1419        (points.len(), parabola(&points))
1420    };
1421    let (rows, alt_fit) = fit(alt);
1422    if rows < COAST_ROWS {
1423        return Err(format!(
1424            "over {window}, `Alt` holds {rows} numbers, under the {COAST_ROWS} the reader asks"
1425        ));
1426    }
1427    let Some((slope, curvature)) = alt_fit.filter(|(_, curvature)| *curvature < 0.0) else {
1428        return Err(format!(
1429            "over {window}, the parabola fitted to `Alt` doesn't turn down"
1430        ));
1431    };
1432    let top_after_s = -slope / curvature;
1433    if top_after_s.abs() > COAST_TOP_S {
1434        return Err(format!(
1435            "over {window}, the parabola fitted to `Alt` tops out {} s from the window's end, \
1436             further than the {} s the reader asks",
1437            plain(top_after_s, 2),
1438            plain(COAST_TOP_S, 1)
1439        ));
1440    }
1441    let slowing = columns
1442        .iter()
1443        .zip(written)
1444        .enumerate()
1445        .map(|(index, (column, values))| match column.kind {
1446            Kind::Altitude if index == 0 => Some(-curvature),
1447            Kind::FilteredAltitude => match fit(values) {
1448                (rows, Some((_, curvature))) if rows >= COAST_ROWS => Some(-curvature),
1449                _ => None,
1450            },
1451            _ => None,
1452        })
1453        .collect();
1454    Ok(Coast { window, slowing })
1455}
1456
1457/// Standard gravity in feet per second squared.
1458fn gravity_ft_s2() -> f64 {
1459    STANDARD_GRAVITY_MPS2 / FOOT_M
1460}
1461
1462/// Whether a slowing, in g, is within [`COAST_BAND`].
1463fn in_band(slowing_g: f64) -> bool {
1464    (COAST_BAND.0..=COAST_BAND.1).contains(&slowing_g)
1465}
1466
1467/// The terminal download's clock and altitudes, decided by the step and the manuals and checked
1468/// against the coast (module docs, *The coast check*): the clock's note, and for each column, as
1469/// [`Column`]s are, the note deciding an altitude and whether it is kept as written.
1470struct CoastUnits {
1471    clock: String,
1472    altitudes: Vec<Option<(String, bool)>>,
1473}
1474
1475/// Decides the terminal download's clock and altitudes (module docs, *The coast check*);
1476/// [`LogError::Unit`] on the header's line for a clock the coast doesn't bear out.
1477fn coast_units(
1478    columns: &[Column],
1479    written: &[Vec<f64>],
1480    time_s: &[f64],
1481    clock: Option<(f64, f64)>,
1482    header_line: usize,
1483) -> Result<CoastUnits, LogError> {
1484    let refuse = |message: String| LogError::Unit {
1485        format: FORMAT,
1486        line: header_line,
1487        message,
1488    };
1489    let Some((per_second, median)) = clock else {
1490        return Err(refuse(
1491            "the clock `T` can't be settled: the table holds one row, so it has no step and no \
1492             coast to tell seconds from milliseconds"
1493                .to_owned(),
1494        ));
1495    };
1496    let unit = clock_unit(per_second);
1497    let coast = coast(columns, written, time_s).map_err(|why| {
1498        refuse(format!(
1499            "the clock `T` is in {unit} by its step, but no coast bears that out: {why}"
1500        ))
1501    })?;
1502    let g_ft = gravity_ft_s2();
1503    let slowing = coast.slowing.first().copied().flatten().unwrap_or(f64::NAN);
1504    let (in_feet, in_meters) = (slowing / g_ft, slowing / STANDARD_GRAVITY_MPS2);
1505    let length = if in_band(in_feet) {
1506        "feet"
1507    } else if in_band(in_meters) {
1508        "meters"
1509    } else {
1510        return Err(refuse(format!(
1511            "the clock `T` is in {unit} by its step. But on that clock `Alt` slows at {} g in \
1512             feet and {} g in meters over {}. Neither is in the {} to {} g the reader \
1513             takes",
1514            plain(in_feet, 3),
1515            plain(in_meters, 3),
1516            coast.window,
1517            plain(COAST_BAND.0, 1),
1518            plain(COAST_BAND.1, 1)
1519        )));
1520    };
1521    let band = format!("{} to {} g", plain(COAST_BAND.0, 1), plain(COAST_BAND.1, 1));
1522    let clock_note = format!(
1523        "`T` read in {unit}, from the step and the coast: {}. On that clock `Alt` slows at {} g \
1524         in {length} over {}. The reader takes {band} in feet or in meters, and a clock \
1525         1,000 times off would put that slowing 10⁶ times off",
1526        step_evidence(median),
1527        plain(if length == "feet" { in_feet } else { in_meters }, 3),
1528        coast.window
1529    );
1530    let alt_feet = length == "feet";
1531    let altitudes = columns
1532        .iter()
1533        .zip(&coast.slowing)
1534        .enumerate()
1535        .map(|(index, (column, slowing))| {
1536            let name = short(&column.name);
1537            match column.kind {
1538                Kind::Altitude if index == 0 && alt_feet => Some((
1539                    format!(
1540                        "`{name}` read in feet, from the manual and the coast: {ALTITUDE_MANUALS}. \
1541                         Over {}, it slows at {} g in feet, within the {band} the reader takes. \
1542                         In meters it would be {} g{}",
1543                        coast.window,
1544                        plain(in_feet, 3),
1545                        plain(in_meters, 3),
1546                        accelerometer_ratio(columns, written)
1547                    ),
1548                    false,
1549                )),
1550                Kind::Altitude if index == 0 => Some((
1551                    format!(
1552                        "`{name}` kept as written: the manuals give feet, but over {}, it slows \
1553                         at {} g in feet and {} g in meters. The reader takes {band} in \
1554                         feet. The record holds no barometric altitude",
1555                        coast.window,
1556                        plain(in_feet, 3),
1557                        plain(in_meters, 3)
1558                    ),
1559                    true,
1560                )),
1561                Kind::FilteredAltitude => Some(match slowing.map(|value| value / g_ft) {
1562                    Some(g) if in_band(g) => (
1563                        format!(
1564                            "`{name}` read in feet, from the manual and the coast: it is the \
1565                             logger's filtered `Alt` (Quantum p38, Proton p45), in feet. Over \
1566                             {}, it slows at {} g in feet, within the {band} the reader takes",
1567                            coast.window,
1568                            plain(g, 3)
1569                        ),
1570                        false,
1571                    ),
1572                    Some(g) => (
1573                        format!(
1574                            "`{name}` kept as written: the manuals give it in feet, as the \
1575                             logger's filtered `Alt` (Quantum p38, Proton p45). But over {}, it \
1576                             slows at {} g in feet, outside the {band} the reader takes",
1577                            coast.window,
1578                            plain(g, 3)
1579                        ),
1580                        true,
1581                    ),
1582                    None => (
1583                        format!(
1584                            "`{name}` kept as written: the manuals give it in feet, as the \
1585                             logger's filtered `Alt` (Quantum p38, Proton p45). But no parabola \
1586                             can be fitted to it over {}",
1587                            coast.window
1588                        ),
1589                        true,
1590                    ),
1591                }),
1592                _ => None,
1593            }
1594        })
1595        .collect();
1596    Ok(CoastUnits {
1597        clock: clock_note,
1598        altitudes,
1599    })
1600}
1601
1602/// The note saying how `Alt` was read in feet; for a file with the accelerometer in both g and
1603/// ft/s², what the two say of each other.
1604fn altitude_note(columns: &[Column], written: &[Vec<f64>]) -> String {
1605    format!(
1606        "`Alt` read in feet, from the manual: {ALTITUDE_MANUALS}{}",
1607        accelerometer_ratio(columns, written)
1608    )
1609}
1610
1611/// What the manuals say of `Alt`'s unit, as a note quotes it.
1612const ALTITUDE_MANUALS: &str = "the Classic and TRS manuals (p37) state feet. The Quantum and \
1613                                Proton manuals give every height in feet, and no Eggtimer manual \
1614                                offers meters";
1615
1616/// For a file with the accelerometer in both g and ft/s², what the two say of each other, as a
1617/// clause the altitude's note ends with; empty otherwise.
1618fn accelerometer_ratio(columns: &[Column], written: &[Vec<f64>]) -> String {
1619    let mut note = String::new();
1620    let find = |names: &[&str]| {
1621        columns
1622            .iter()
1623            .zip(written)
1624            .find(|(column, _)| names.contains(&column.name.as_str()))
1625    };
1626    if let (Some((g_column, g)), Some((ft_column, ft_s2))) =
1627        (find(&["AccelG", "Accel"]), find(&["AccelFPSS"]))
1628    {
1629        // The least-squares ratio of the two through zero.
1630        let (mut product, mut square) = (0.0, 0.0);
1631        for (g, ft_s2) in g.iter().zip(ft_s2) {
1632            if g.is_finite() && ft_s2.is_finite() {
1633                product += g * ft_s2;
1634                square += g * g;
1635            }
1636        }
1637        let ratio = product / square;
1638        if ratio.is_finite() {
1639            note.push_str(&format!(
1640                ". The file's `{}` is {} times its `{}`, and one g is 32.17 ft/s²",
1641                ft_column.name,
1642                plain(ratio, 2),
1643                g_column.name
1644            ));
1645        }
1646    }
1647    note
1648}
1649
1650/// The note saying how a column other than `Alt` was read, `None` for one whose name states its
1651/// unit, or that is kept as written. `check` is what the rows say of a speed.
1652fn unit_note(column: &Column, check: Option<SpeedCheck>, columns: &[Column]) -> Option<String> {
1653    let name = short(&column.name);
1654    let evidence = |what: &str| match check {
1655        Some(check) if check.rows > 0 => format!(
1656            "It is the change in `{}` over the step, within 1 % or 1 ft/s. That holds in {} of {} \
1657             rows after the first, where the reader asks 90 %",
1658            columns
1659                .get(check.altitude)
1660                .map(|altitude| short(&altitude.name))
1661                .unwrap_or_default(),
1662            check.matching,
1663            check.rows
1664        ),
1665        Some(_) => format!("The file has one row, so no step to check it against {what} on"),
1666        None => format!("The file has no {what} to check it against"),
1667    };
1668    let note = match column.kind {
1669        Kind::FilteredAltitude => format!(
1670            "`{name}` read in feet, from the manual: it is the logger's filtered `Alt` (Quantum \
1671             p38, Proton p45), in the same unit"
1672        ),
1673        Kind::RawSpeed => format!(
1674            "`{name}` read in feet per second, from the manual: the Classic and TRS manuals (p37) \
1675             give the velocity in ft/sec. The Proton's manual (p45) gives it as the change in `Alt` over the \
1676             step. {}",
1677            evidence("`Alt`")
1678        ),
1679        Kind::FilteredSpeed => format!(
1680            "`{name}` read in feet per second, from the manual: the Proton's manual (p46) gives \
1681             it as the filtered altitude's change over the step. The Excel guide (p7) \
1682             graphs the velocity in ft/sec. {}",
1683            evidence("filtered altitude")
1684        ),
1685        Kind::AccelerationG if !column.names_its_unit() => format!(
1686            "`{name}` read in g, from the manual: the Proton's manual (p45) gives the \
1687             accelerometer's raw value in G's"
1688        ),
1689        Kind::AccelerationFtS2 if !column.names_its_unit() => format!(
1690            "`{name}` read in feet per second squared, from the manual: the Proton's manual \
1691             (p45) gives the accelerometer's data in ft/sec^2"
1692        ),
1693        Kind::InertialSpeed => format!(
1694            "`{name}` read in feet per second, from the manual: the Proton's manual (p45) gives \
1695             the accelerometer's velocity in ft/sec"
1696        ),
1697        Kind::InertialAltitude => format!(
1698            "`{name}` read in feet, from the manual: the Proton's manual (p45) gives the \
1699             accelerometer's distance traveled in ft"
1700        ),
1701        Kind::Altitude
1702        | Kind::AccelerationG
1703        | Kind::AccelerationFtS2
1704        | Kind::Marker
1705        | Kind::Unknown => return None,
1706    };
1707    Some(note)
1708}
1709
1710/// The note saying whether the file's acceleration has gravity in it, judged from its first
1711/// acceleration column on the pad: the median of its rows before the start of flight, where `T`
1712/// is below 0 (the Proton's `T` counts from the start of flight, p45). Standing on the pad, an
1713/// accelerometer that keeps gravity reads 1 g and one that takes it out 0. `None` for a file
1714/// without one.
1715fn gravity_note(columns: &[Column], written: &[Vec<f64>], written_time: &[f64]) -> Option<String> {
1716    let ft_s2_per_g = STANDARD_GRAVITY_MPS2 / FOOT_M;
1717    let mut accelerations = columns
1718        .iter()
1719        .zip(written)
1720        .filter_map(|(column, values)| match column.kind {
1721            Kind::AccelerationG => Some((column, values, 1.0)),
1722            Kind::AccelerationFtS2 => Some((column, values, ft_s2_per_g)),
1723            _ => None,
1724        });
1725    let (column, values, per_g) = accelerations.next()?;
1726    let others = if accelerations.next().is_some() {
1727        ". The file's other acceleration columns are the same accelerometer's"
1728    } else {
1729        ""
1730    };
1731    let name = short(&column.name);
1732    let mut pad: Vec<f64> = written_time
1733        .iter()
1734        .zip(values)
1735        .filter(|(time, value)| **time < 0.0 && value.is_finite())
1736        .map(|(_, value)| value / per_g)
1737        .collect();
1738    let source = "The Proton's manual doesn't say, and its release notes (2.01C, p8) have it \
1739                  calibrate the accelerometer as it is armed, standing up";
1740    if pad.is_empty() {
1741        return Some(format!(
1742            "`{name}` may or may not hold gravity, not known. The file has no rows before the \
1743             start of flight (`T` below 0) to read the pad on. {source}{others}"
1744        ));
1745    }
1746    pad.sort_by(f64::total_cmp);
1747    // Invariant: `pad` isn't empty (above), so `middle` is a place in it, and so is the one
1748    // before it when the count is even.
1749    let middle = pad.len() / 2;
1750    let median = if pad.len().is_multiple_of(2) {
1751        (pad[middle - 1] + pad[middle]) / 2.0
1752    } else {
1753        pad[middle]
1754    };
1755    let reading = format!(
1756        "its median over the {} rows before the start of flight (`T` below 0) is {} g. An \
1757         accelerometer that keeps gravity reads 1 g standing still, and one that takes it out \
1758         reads 0. {source}{others}",
1759        pad.len(),
1760        plain(median, 2)
1761    );
1762    Some(if median.abs() < GRAVITY_READING_G {
1763        format!("`{name}` has gravity taken out, from the pad: {reading}")
1764    } else if (median - 1.0).abs() < GRAVITY_READING_G {
1765        format!("`{name}` holds gravity, from the pad: {reading}")
1766    } else {
1767        format!("`{name}` may or may not hold gravity, not known: {reading}")
1768    })
1769}
1770
1771/// The note listing the marker columns, kept as written; `None` for a file without one.
1772fn marker_note(columns: &[Column]) -> Option<String> {
1773    let markers: Vec<String> = columns
1774        .iter()
1775        .filter(|column| column.kind == Kind::Marker)
1776        .map(|column| format!("`{}`", short(&column.name)))
1777        .take(MAX_LISTED + 1)
1778        .collect();
1779    let count = columns
1780        .iter()
1781        .filter(|column| column.kind == Kind::Marker)
1782        .count();
1783    if count == 0 {
1784        return None;
1785    }
1786    let speeds = if columns
1787        .iter()
1788        .any(|column| column.name == "MaxV" || column.name == "MaxA")
1789    {
1790        ". At that sample the Proton's release notes (1.02N, p13) put the top speed, ft/s, in \
1791         `MaxV` and the top acceleration, ft/s², in `MaxA`"
1792    } else {
1793        ""
1794    };
1795    Some(format!(
1796        "the marker columns, kept as written: {}. Each is 0 but at the sample that marks its \
1797         event. There the Quantum's and Proton's manuals (p38, p46) put the raw altitude, in \
1798         feet{speeds}",
1799        list(&markers, count)
1800    ))
1801}
1802
1803/// Names joined as `a`, `a and b`, or `a, b and c`; of more than [`MAX_LISTED`], the first few
1804/// and a count of the rest. `count` is how many there are; `names` may hold only the first.
1805fn list(names: &[String], count: usize) -> String {
1806    if count > MAX_LISTED {
1807        let shown = MAX_LISTED - 1;
1808        return format!(
1809            "{} and {} more columns",
1810            names.get(..shown).unwrap_or(names).join(", "),
1811            count - shown
1812        );
1813    }
1814    match names {
1815        [] => String::new(),
1816        [only] => only.clone(),
1817        [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
1818    }
1819}
1820
1821/// A number as a note writes it: rounded to `decimals` places, trailing zeros dropped.
1822fn plain(value: f64, decimals: usize) -> String {
1823    let text = format!("{value:.decimals$}");
1824    if text.contains('.') {
1825        text.trim_end_matches('0').trim_end_matches('.').to_owned()
1826    } else {
1827        text
1828    }
1829}
1830
1831fn syntax(line: usize, message: String) -> LogError {
1832    LogError::Syntax {
1833        format: FORMAT,
1834        line,
1835        message,
1836    }
1837}
1838
1839// The terminal download: the flight settings and the flight summary, then the table above.
1840
1841/// The terminal download's name in errors.
1842const TEXT_FORMAT: &str = "Eggtimer text";
1843
1844/// The most lines that aren't blank the reader looks through for the title and the table's
1845/// header row. The manual's download (TRS p36) and the sample logs' put about 30 before the
1846/// header.
1847pub const MAX_PREAMBLE_LINES: usize = 200;
1848
1849/// The most items one note about the preamble lists, each cut as a note quotes it; past it, the
1850/// rest are counted.
1851const MAX_PREAMBLE_ITEMS: usize = 40;
1852
1853/// How far apart, s, a summary's time and a marker's event may be and still be the same moment:
1854/// half a millisecond, the summary's last digit.
1855const SAME_TIME_S: f64 = 0.000_5;
1856
1857/// What each `Last Flight Phase` code means (TRS manual p37).
1858const FLIGHT_PHASES: [&str; 10] = [
1859    "flight not started",
1860    "waiting for LDA",
1861    "LDA reached",
1862    "not used",
1863    "not used",
1864    "Mach lockout expired",
1865    "nose-over",
1866    "drogue",
1867    "main deployed",
1868    "landing detected",
1869];
1870
1871/// Whether the text is an Eggtimer's terminal download: a title `Eggtimer … Flight Settings`, then
1872/// an Eggtimer header row, within the first [`MAX_PREAMBLE_LINES`] lines that aren't blank.
1873pub(crate) fn recognizes_text(text: &str) -> bool {
1874    split_download(text).is_some()
1875}
1876
1877/// A terminal download, split: its title, the preamble's lines after it, and the table.
1878struct Download<'a> {
1879    /// The title's words between `Eggtimer` and `Flight Settings`, such as `TRS 2.07`.
1880    title: &'a str,
1881    /// How many lines that aren't blank come before the title, `Flight Summary:` aside.
1882    before_title: usize,
1883    /// The lines between the title and the table's header row, blank ones left out, each
1884    /// trimmed.
1885    preamble: Vec<&'a str>,
1886    /// The text from the header row on.
1887    table: &'a str,
1888    /// The header row's line number in the file.
1889    header_line: usize,
1890}
1891
1892/// The download's parts; `None` unless a title `Eggtimer … Flight Settings`, or a line
1893/// `Eggtimer …` over a line `Flight Settings`, comes before an Eggtimer header row, both within
1894/// the first [`MAX_PREAMBLE_LINES`] lines that aren't blank.
1895fn split_download(text: &str) -> Option<Download<'_>> {
1896    let mut title: Option<&str> = None;
1897    // A line `Eggtimer …` that doesn't end in `Flight Settings`, which the next line may finish.
1898    let mut pending: Option<&str> = None;
1899    let mut before_title = 0_usize;
1900    let mut preamble = Vec::new();
1901    let lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
1902    for (number, line) in lines.take(MAX_PREAMBLE_LINES) {
1903        let trimmed = line.trim();
1904        if let Some(title) = title {
1905            if header_separator(trimmed) == Some(',') {
1906                // `line` is a slice of `text`: the table starts where it does.
1907                let start = (line.as_ptr() as usize).checked_sub(text.as_ptr() as usize)?;
1908                return Some(Download {
1909                    title,
1910                    before_title,
1911                    preamble,
1912                    table: text.get(start..)?,
1913                    header_line: number,
1914                });
1915            }
1916            preamble.push(trimmed);
1917            continue;
1918        }
1919        if let Some(words) = pending.take() {
1920            if trimmed == "Flight Settings" {
1921                title = Some(words);
1922                continue;
1923            }
1924            before_title += 1;
1925        }
1926        if let Some(rest) = trimmed.strip_prefix("Eggtimer ") {
1927            match rest.strip_suffix("Flight Settings") {
1928                Some(words) => title = Some(words.trim()),
1929                None => pending = Some(rest.trim()),
1930            }
1931        } else if header_separator(trimmed) == Some(',') {
1932            // A table with no title before it is the CSV download's.
1933            return None;
1934        } else if trimmed != "Flight Summary:" {
1935            before_title += 1;
1936        }
1937    }
1938    None
1939}
1940
1941/// The logger's model and firmware from the title's words: the last word the firmware if it
1942/// starts with a digit, such as `2.07`, the words before it the model, such as `TRS`.
1943fn title_words(words: &str) -> (String, Option<String>) {
1944    let words: Vec<&str> = words.split_whitespace().collect();
1945    match words.split_last() {
1946        Some((last, model)) if last.starts_with(|c: char| c.is_ascii_digit()) => {
1947            (short(&model.join(" ")), Some(short(last)))
1948        }
1949        _ => (short(&words.join(" ")), None),
1950    }
1951}
1952
1953/// A preamble's items as a note lists them: the first [`MAX_PREAMBLE_ITEMS`] kept, the rest
1954/// counted.
1955#[derive(Default)]
1956struct Items {
1957    kept: Vec<String>,
1958    left_out: usize,
1959}
1960
1961impl Items {
1962    fn push(&mut self, item: String) {
1963        if self.kept.len() < MAX_PREAMBLE_ITEMS {
1964            self.kept.push(item);
1965        } else {
1966            self.left_out += 1;
1967        }
1968    }
1969
1970    fn is_empty(&self) -> bool {
1971        self.kept.is_empty()
1972    }
1973
1974    /// The items joined by `separator`, and a count of those left out.
1975    fn joined(&self, separator: &str) -> String {
1976        let mut text = self.kept.join(separator);
1977        if self.left_out > 0 {
1978            text.push_str(&format!("{separator}and {} more", self.left_out));
1979        }
1980        text
1981    }
1982}
1983
1984/// What the preamble after the title states.
1985#[derive(Default)]
1986struct Preamble {
1987    /// The flight settings, each label and value as written.
1988    settings: Items,
1989    /// How many settings lines hold no value: the name the owner gave the flight computer.
1990    names: usize,
1991    /// The summary's lines not read into the record, as written.
1992    summary: Items,
1993    /// `ASL Alt.`, m above sea level.
1994    ground_m: Option<f64>,
1995    /// `Apogee`, m above the logger's zero.
1996    apogee_m: Option<f64>,
1997    /// Each summary time, `T @ …` or `Time @ …`: the event's name as written, and s.
1998    times: Vec<(String, f64)>,
1999    /// How many of the times carry a unit mark, such as `secs.`.
2000    marked_times: usize,
2001    /// The notes saying how the heights were read.
2002    unit_notes: Vec<String>,
2003}
2004
2005/// Reads the preamble's lines after the title.
2006fn read_preamble(lines: &[&str]) -> Preamble {
2007    let mut preamble = Preamble::default();
2008    for line in lines {
2009        if let Some(body) = line.strip_prefix("...") {
2010            match body.rsplit_once("...") {
2011                Some((label, value)) => preamble.settings.push(format!(
2012                    "`{}` {}",
2013                    short(label.trim()),
2014                    short(value.trim())
2015                )),
2016                None => preamble.names += 1,
2017            }
2018            continue;
2019        }
2020        let Some((key, value)) = line.split_once(':') else {
2021            preamble.summary.push(format!("`{}`", short(line)));
2022            continue;
2023        };
2024        let (key, value) = (key.trim(), value.trim());
2025        let as_written = format!("`{}`", short(&format!("{key}: {value}")));
2026        let event = key
2027            .strip_prefix("T @")
2028            .or_else(|| key.strip_prefix("Time @"))
2029            .map(str::trim)
2030            .filter(|name| !name.is_empty());
2031        match (key, event) {
2032            (_, Some(name)) if preamble.times.len() < MAX_PREAMBLE_LINES => {
2033                match summary_time(value) {
2034                    Some((time_s, marked)) => {
2035                        preamble.times.push((short(name), time_s));
2036                        preamble.marked_times += usize::from(marked);
2037                    }
2038                    None => preamble.summary.push(as_written),
2039                }
2040            }
2041            ("ASL Alt." | "Apogee", _) => {
2042                let (field, what) = if key == "Apogee" {
2043                    (
2044                        &mut preamble.apogee_m,
2045                        "the logger's apogee above its zero, kept beside the table's altitudes",
2046                    )
2047                } else {
2048                    (
2049                        &mut preamble.ground_m,
2050                        "the launch site's elevation above sea level, as the logger measured it",
2051                    )
2052                };
2053                match (field.is_some(), height(value)) {
2054                    (false, Some((height_m, unit))) => {
2055                        *field = Some(height_m);
2056                        preamble.unit_notes.push(format!(
2057                            "`{key}` read in {unit}, from its unit mark: the flight summary \
2058                             writes {}; {what} (TRS manual p36)",
2059                            short(value)
2060                        ));
2061                    }
2062                    (false, None) => {
2063                        preamble.unit_notes.push(format!(
2064                            "`{key}` kept as written, with no unit mark the reader knows: the \
2065                             flight summary writes {:?}, where the TRS manual's writes `ft` (p36)",
2066                            short(value)
2067                        ));
2068                        preamble.summary.push(as_written);
2069                    }
2070                    (true, _) => preamble.summary.push(as_written),
2071                }
2072            }
2073            ("Last Flight Phase", _) => {
2074                let meaning = value
2075                    .parse::<usize>()
2076                    .ok()
2077                    .and_then(|code| FLIGHT_PHASES.get(code));
2078                preamble.summary.push(match meaning {
2079                    Some(meaning) => format!("{as_written} ({meaning}, TRS manual p37)"),
2080                    None => as_written,
2081                });
2082            }
2083            _ => preamble.summary.push(as_written),
2084        }
2085    }
2086    preamble
2087}
2088
2089/// A height as the summary writes it, such as `1500 ft`: m, and the unit's name; `None` without a
2090/// number and a unit mark `ft` or `m`.
2091fn height(value: &str) -> Option<(f64, &'static str)> {
2092    let mut words = value.split_whitespace();
2093    let written = number(words.next()?, false)?;
2094    let unit = words.next()?;
2095    if words.next().is_some() {
2096        return None;
2097    }
2098    match unit {
2099        "ft" => Some((written * FOOT_M, "feet")),
2100        "m" => Some((written, "meters")),
2101        _ => None,
2102    }
2103}
2104
2105/// A time as the summary writes it, such as `9.500` or `9.500 secs.`: s, and whether it carries
2106/// a unit mark; `None` for anything else.
2107fn summary_time(value: &str) -> Option<(f64, bool)> {
2108    let mut words = value.split_whitespace();
2109    let seconds = number(words.next()?, false)?;
2110    let marked = match (words.next(), words.next()) {
2111        (None, _) => false,
2112        (Some("secs." | "secs" | "sec." | "sec" | "s"), None) => true,
2113        _ => return None,
2114    };
2115    Some((seconds, marked))
2116}
2117
2118/// The table's marker for an event the summary names: the summary's `Unlock` is the end of the
2119/// Mach lockout, which the `LowV` marker marks (TRS manual p37).
2120fn marker_for(summary_name: &str) -> Option<&'static str> {
2121    match summary_name {
2122        "Apogee" => Some("Apogee"),
2123        "Unlock" => Some("LowV"),
2124        "N-O" | "Nose-Over" => Some("N-O"),
2125        "Drogue" | "Drogue Deploy" => Some("Drogue"),
2126        "Main" | "Main Deploy" => Some("Main"),
2127        "LDA" => Some("LDA"),
2128        _ => None,
2129    }
2130}
2131
2132/// Reads an Eggtimer TRS's flight from its terminal download: the flight settings and the flight
2133/// summary, then the table the CSV download writes, read as [`read`] reads it.
2134///
2135/// # Errors
2136///
2137/// [`LogError::NotThisFormat`] if no title `Eggtimer … Flight Settings` comes before an Eggtimer
2138/// header row within the first [`MAX_PREAMBLE_LINES`] lines that aren't blank; otherwise what
2139/// [`read`] refuses in the table, naming the file's line; [`LogError::Unit`] on the header's line
2140/// for a clock its step and the coast don't both bear out (module docs, *The coast check*).
2141pub fn read_text(text: &str) -> Result<FlightLog, LogError> {
2142    read_download(text, TEXT_FORMAT, &|line| line)
2143}
2144
2145/// A terminal download read as [`read_text`] reads it, its errors naming `format` and the line
2146/// `file_line` gives for each of the text's lines: the line itself in a text file, the RTF
2147/// document's line in [`read_rtf`].
2148fn read_download(
2149    text: &str,
2150    format: &'static str,
2151    file_line: &dyn Fn(usize) -> usize,
2152) -> Result<FlightLog, LogError> {
2153    let Some(download) = split_download(text) else {
2154        return Err(LogError::NotThisFormat {
2155            format,
2156            message: format!(
2157                "no title `Eggtimer … Flight Settings` comes before an Eggtimer header row, \
2158                 such as `T,Alt,Veloc,…`, within the first {MAX_PREAMBLE_LINES} lines that \
2159                 aren't blank"
2160            ),
2161        });
2162    };
2163    let shift = download.header_line.saturating_sub(1);
2164    let mut log = read_table(download.table, Checks::Coast).map_err(|error| match error {
2165        LogError::Syntax { line, message, .. } => LogError::Syntax {
2166            format,
2167            line: file_line(line.saturating_add(shift)),
2168            message,
2169        },
2170        LogError::Unit { line, message, .. } => LogError::Unit {
2171            format,
2172            line: file_line(line.saturating_add(shift)),
2173            message,
2174        },
2175        LogError::NoData { .. } => LogError::NoData { format },
2176        LogError::NotThisFormat { message, .. } => LogError::NotThisFormat { format, message },
2177        other => other,
2178    })?;
2179    let (model, firmware) = title_words(download.title);
2180    log.format = LogFormat::EggtimerText;
2181    log.logger = if model.is_empty() {
2182        "Eggtimer".to_owned()
2183    } else {
2184        format!("Eggtimer {model}")
2185    };
2186    log.firmware = firmware;
2187    let preamble = read_preamble(&download.preamble);
2188    log.stated.apogee_m = preamble.apogee_m;
2189    log.stated.ground_elevation_msl_m = preamble.ground_m;
2190    log.notes.extend(preamble.unit_notes.iter().cloned());
2191    summary_events(&mut log, &preamble);
2192    if !preamble.settings.is_empty() {
2193        log.notes.push(format!(
2194            "the flight settings, as the file writes them: {}",
2195            preamble.settings.joined("; ")
2196        ));
2197    }
2198    if preamble.names > 0 {
2199        log.notes.push(format!(
2200            "{} of the flight settings holds no setting: the name its owner gave the flight \
2201             computer (TRS manual p24). The name is left out of the record as free text that may \
2202             name a person",
2203            if preamble.names == 1 {
2204                "1 line".to_owned()
2205            } else {
2206                format!("{} lines", preamble.names)
2207            }
2208        ));
2209    }
2210    if !preamble.summary.is_empty() {
2211        log.notes.push(format!(
2212            "the flight summary's other lines, as the file writes them: {}",
2213            preamble.summary.joined("; ")
2214        ));
2215    }
2216    if download.before_title > 0 {
2217        log.notes.push(format!(
2218            "{} lines before the title `Eggtimer … Flight Settings` weren't read",
2219            download.before_title
2220        ));
2221    }
2222    Ok(log)
2223}
2224
2225/// The summary's times read as events, with the notes saying how: a time that is its marker's
2226/// event in the table, to [`SAME_TIME_S`], is that event; one of no marker, or of another time,
2227/// is an event of its own, named as the summary names it; a time of 0 is no event, as the manual
2228/// writes zeroes for a channel that didn't fire (TRS p25); a time past the table's last, by more
2229/// than [`SAME_TIME_S`], is no event either, as no event of the flight comes after its last
2230/// sample: such a time isn't in seconds. The events end up in time order, the table's first where
2231/// two share a time.
2232fn summary_events(log: &mut FlightLog, preamble: &Preamble) {
2233    if preamble.times.is_empty() {
2234        return;
2235    }
2236    let (mut same, mut own, mut differ, mut zero, mut past) = (
2237        Items::default(),
2238        Items::default(),
2239        Items::default(),
2240        Items::default(),
2241        Items::default(),
2242    );
2243    let last_s = log.time_s.last().copied().unwrap_or(0.0);
2244    let mut events = Vec::new();
2245    for (name, time_s) in &preamble.times {
2246        if *time_s == 0.0 {
2247            zero.push(format!("`{name}`"));
2248            continue;
2249        }
2250        if *time_s > last_s + SAME_TIME_S {
2251            past.push(format!("`{name}` {}", plain(*time_s, 3)));
2252            continue;
2253        }
2254        let marker = marker_for(name);
2255        let marked: Vec<f64> = log
2256            .events
2257            .iter()
2258            .filter(|event| Some(event.name.as_str()) == marker)
2259            .map(|event| event.time_s)
2260            .collect();
2261        match (marker, marked.first()) {
2262            (Some(marker), Some(_))
2263                if marked
2264                    .iter()
2265                    .any(|marked_s| (marked_s - time_s).abs() <= SAME_TIME_S) =>
2266            {
2267                same.push(format!("`{name}` at `{marker}`"));
2268                continue;
2269            }
2270            (Some(marker), Some(marked_s)) => differ.push(format!(
2271                "`{name}` at {} s, the marker `{marker}` at {} s",
2272                plain(*time_s, 3),
2273                plain(*marked_s, 3)
2274            )),
2275            _ => own.push(format!("`{name}`")),
2276        }
2277        events.push(Event {
2278            time_s: *time_s,
2279            name: name.clone(),
2280        });
2281    }
2282    let how = if preamble.marked_times == preamble.times.len() {
2283        "`T @` and `Time @` read in seconds, from their unit mark: the flight summary writes \
2284         `secs.` after each, as the TRS manual's download does (p36)"
2285    } else {
2286        "`T @` and `Time @` read in seconds, from the manual: the TRS manual's download writes \
2287         the flight summary's times in `secs.` (p36). The same download writes its LDA at \
2288         0.700 secs. as \"700ms into the flight\" (p37)"
2289    };
2290    // Said only of times read: those of 0 and those past the table aren't.
2291    if !(same.is_empty() && own.is_empty() && differ.is_empty()) {
2292        log.notes.push(how.to_owned());
2293    }
2294    if !same.is_empty() {
2295        log.notes.push(format!(
2296            "the flight summary's times are its table markers' to the millisecond, one event \
2297             each, the marker's: {}",
2298            same.joined(", ")
2299        ));
2300    }
2301    if !own.is_empty() {
2302        log.notes.push(format!(
2303            "the flight summary's times of no marker in the table, each an event of its own: {}",
2304            own.joined(", ")
2305        ));
2306    }
2307    if !differ.is_empty() {
2308        log.notes.push(format!(
2309            "the flight summary's times that differ from their markers' in the table, both kept \
2310             as events: {}",
2311            differ.joined("; ")
2312        ));
2313    }
2314    if !zero.is_empty() {
2315        log.notes.push(format!(
2316            "the flight summary's times of 0, no event, as the TRS manual writes zeroes for a \
2317             channel that didn't fire (p25): {}",
2318            zero.joined(", ")
2319        ));
2320    }
2321    if !past.is_empty() {
2322        log.notes.push(format!(
2323            "the flight summary's times past the table's last, {} s, kept as written and not \
2324             read as events. No event of the flight comes after its last sample, so those times \
2325             aren't in seconds: {}",
2326            plain(last_s, 3),
2327            past.joined(", ")
2328        ));
2329    }
2330    log.events.extend(events);
2331    log.events
2332        .sort_by(|first, second| first.time_s.total_cmp(&second.time_s));
2333}
2334
2335// The terminal download saved inside an RTF document (ADR-258 §4).
2336
2337/// The RTF-wrapped download's name in errors.
2338const RTF_FORMAT: &str = "Eggtimer RTF";
2339
2340/// The deepest an RTF document's groups may nest. Word processors nest a few levels, a style or a
2341/// table a few more; a document deeper than this is refused rather than tracked.
2342pub const MAX_RTF_DEPTH: usize = 64;
2343
2344/// The most letters of a control word the reader keeps: the RTF specification caps a control word
2345/// at 32 characters. A longer one is read to its end and matches no word the reader knows.
2346const MAX_CONTROL_WORD: usize = 32;
2347
2348/// The most fallback characters a `\ucN` may ask to be skipped after each `\uN`; the
2349/// specification's default is 1.
2350const MAX_FALLBACK: usize = 16;
2351
2352/// What Windows code page 1252 maps bytes 0x80 to 0x9F to, in order; `None` for the five bytes it
2353/// leaves undefined. From 0xA0 on, the code page is ISO 8859-1, whose bytes are the same Unicode
2354/// code points (the Unicode Consortium's mapping table for it, `CP1252.TXT`).
2355const CP1252_80_9F: [Option<char>; 32] = [
2356    Some('\u{20ac}'),
2357    None,
2358    Some('\u{201a}'),
2359    Some('\u{0192}'),
2360    Some('\u{201e}'),
2361    Some('\u{2026}'),
2362    Some('\u{2020}'),
2363    Some('\u{2021}'),
2364    Some('\u{02c6}'),
2365    Some('\u{2030}'),
2366    Some('\u{0160}'),
2367    Some('\u{2039}'),
2368    Some('\u{0152}'),
2369    None,
2370    Some('\u{017d}'),
2371    None,
2372    None,
2373    Some('\u{2018}'),
2374    Some('\u{2019}'),
2375    Some('\u{201c}'),
2376    Some('\u{201d}'),
2377    Some('\u{2022}'),
2378    Some('\u{2013}'),
2379    Some('\u{2014}'),
2380    Some('\u{02dc}'),
2381    Some('\u{2122}'),
2382    Some('\u{0161}'),
2383    Some('\u{203a}'),
2384    Some('\u{0153}'),
2385    None,
2386    Some('\u{017e}'),
2387    Some('\u{0178}'),
2388];
2389
2390/// Whether the text is an RTF document: it opens with `{\rtf`, after any byte-order mark and
2391/// white space.
2392pub(crate) fn recognizes_rtf(text: &str) -> bool {
2393    text.trim_start_matches(|c: char| c == '\u{feff}' || c.is_whitespace())
2394        .starts_with("{\\rtf")
2395}
2396
2397/// An RTF document's plain text, its lines each mapped to the document's line it starts on.
2398#[derive(Debug, Default)]
2399struct Unwrapped {
2400    /// The text, its lines ended by `\n` alone.
2401    text: String,
2402    /// For each of the text's lines, the document's line, from 1, that it starts on.
2403    starts: Vec<usize>,
2404    /// Whether the next character written starts a line.
2405    at_line_start: bool,
2406    /// Escaped bytes the document's code page leaves undefined, or in a code page the reader
2407    /// doesn't map, each read as U+FFFD.
2408    unmapped: usize,
2409    /// Characters after the document's closing brace that aren't white space, left unread.
2410    after_end: usize,
2411}
2412
2413impl Unwrapped {
2414    /// Writes a character found on the document's line `line`; CR and LF end a line.
2415    fn push(&mut self, c: char, line: usize) {
2416        if c == '\r' || c == '\n' {
2417            self.line_break(line);
2418            return;
2419        }
2420        if self.at_line_start {
2421            self.starts.push(line);
2422            self.at_line_start = false;
2423        }
2424        self.text.push(c);
2425    }
2426
2427    /// Ends the text's line, at the document's line `line`.
2428    fn line_break(&mut self, line: usize) {
2429        if self.at_line_start {
2430            self.starts.push(line);
2431        }
2432        self.text.push('\n');
2433        self.at_line_start = true;
2434    }
2435
2436    /// The document's line that the text's line `line`, from 1, starts on; past the last, the
2437    /// last's.
2438    fn file_line(&self, line: usize) -> usize {
2439        line.checked_sub(1)
2440            .and_then(|index| self.starts.get(index))
2441            .or(self.starts.last())
2442            .copied()
2443            .unwrap_or(1)
2444    }
2445}
2446
2447/// One group's state: whether its text is skipped, as a destination the reader doesn't read, and
2448/// how many fallback characters follow each `\uN` in it.
2449#[derive(Debug, Clone, Copy)]
2450struct Group {
2451    skip: bool,
2452    fallback: usize,
2453}
2454
2455/// A refusal of the RTF document's markup at its line.
2456fn rtf_syntax(line: usize, message: String) -> LogError {
2457    LogError::Syntax {
2458        format: RTF_FORMAT,
2459        line,
2460        message,
2461    }
2462}
2463
2464/// The plain text of an RTF document, by the subset of the RTF specification that
2465/// [`read_rtf`] lists.
2466fn unwrap_rtf(document: &str) -> Result<Unwrapped, LogError> {
2467    let mut out = Unwrapped {
2468        at_line_start: true,
2469        ..Unwrapped::default()
2470    };
2471    let mut chars = document
2472        .strip_prefix('\u{feff}')
2473        .unwrap_or(document)
2474        .chars();
2475    let mut line = 1_usize;
2476    let mut groups: Vec<Group> = Vec::new();
2477    let mut opened = false;
2478    let mut code_page_1252 = true;
2479    // Fallback characters left to skip after a `\uN`.
2480    let mut skip_fallback = 0_usize;
2481    while let Some(c) = chars.next() {
2482        match c {
2483            '\r' => {
2484                if chars.as_str().starts_with('\n') {
2485                    chars.next();
2486                }
2487                line += 1;
2488            }
2489            '\n' => line += 1,
2490            '{' => {
2491                if groups.len() >= MAX_RTF_DEPTH {
2492                    return Err(rtf_syntax(
2493                        line,
2494                        format!("the document's groups nest deeper than {MAX_RTF_DEPTH}"),
2495                    ));
2496                }
2497                let group = groups.last().copied().unwrap_or(Group {
2498                    skip: false,
2499                    fallback: 1,
2500                });
2501                groups.push(group);
2502                opened = true;
2503                skip_fallback = 0;
2504            }
2505            '}' => {
2506                if groups.pop().is_none() {
2507                    return Err(rtf_syntax(
2508                        line,
2509                        "a `}` closes a group that was never opened".to_owned(),
2510                    ));
2511                }
2512                skip_fallback = 0;
2513                if groups.is_empty() {
2514                    out.after_end = chars.filter(|c| !c.is_whitespace()).count();
2515                    return Ok(out);
2516                }
2517            }
2518            _ if groups.is_empty() => {
2519                if !c.is_whitespace() {
2520                    return Err(rtf_syntax(
2521                        line,
2522                        "text comes before the document's opening `{`".to_owned(),
2523                    ));
2524                }
2525            }
2526            '\\' => {
2527                let skip = groups.last().is_some_and(|group| group.skip);
2528                let Some(next) = chars.next() else {
2529                    break;
2530                };
2531                if next.is_ascii_alphabetic() {
2532                    let mut word = String::new();
2533                    word.push(next);
2534                    while let Some(letter) = chars.as_str().chars().next() {
2535                        if !letter.is_ascii_alphabetic() {
2536                            break;
2537                        }
2538                        chars.next();
2539                        if word.len() <= MAX_CONTROL_WORD {
2540                            word.push(letter);
2541                        }
2542                    }
2543                    let parameter = control_parameter(&mut chars);
2544                    if chars.as_str().starts_with(' ') {
2545                        chars.next();
2546                    }
2547                    control_word(
2548                        &word,
2549                        parameter,
2550                        &mut ControlState {
2551                            out: &mut out,
2552                            groups: &mut groups,
2553                            chars: &mut chars,
2554                            line: &mut line,
2555                            code_page_1252: &mut code_page_1252,
2556                            skip_fallback: &mut skip_fallback,
2557                        },
2558                    );
2559                    continue;
2560                }
2561                let symbol = match next {
2562                    '\\' | '{' | '}' => Some(next),
2563                    '\'' => {
2564                        let high = chars.next().and_then(|c| c.to_digit(16));
2565                        let low = chars.next().and_then(|c| c.to_digit(16));
2566                        let (Some(high), Some(low)) = (high, low) else {
2567                            return Err(rtf_syntax(
2568                                line,
2569                                "a `\\'` escape isn't followed by two hexadecimal digits"
2570                                    .to_owned(),
2571                            ));
2572                        };
2573                        let c = code_page_character(high * 16 + low, code_page_1252);
2574                        if c.is_none() && !skip && skip_fallback == 0 {
2575                            out.unmapped += 1;
2576                        }
2577                        Some(c.unwrap_or(char::REPLACEMENT_CHARACTER))
2578                    }
2579                    '~' => Some('\u{a0}'),
2580                    '_' => Some('-'),
2581                    '\r' | '\n' => {
2582                        // `\` at a line's end is `\par`.
2583                        if !skip {
2584                            out.line_break(line);
2585                        }
2586                        if next == '\r' && chars.as_str().starts_with('\n') {
2587                            chars.next();
2588                        }
2589                        line += 1;
2590                        continue;
2591                    }
2592                    // `\*` marks a destination a reader that doesn't know it may skip: this one
2593                    // skips every such destination.
2594                    '*' => {
2595                        if let Some(group) = groups.last_mut() {
2596                            group.skip = true;
2597                        }
2598                        continue;
2599                    }
2600                    // `\-`, an optional hyphen, and the symbols the reader doesn't know.
2601                    _ => None,
2602                };
2603                if let Some(c) = symbol
2604                    && !skip
2605                {
2606                    if skip_fallback > 0 {
2607                        skip_fallback -= 1;
2608                    } else {
2609                        out.push(c, line);
2610                    }
2611                }
2612            }
2613            _ => {
2614                if groups.last().is_some_and(|group| group.skip) {
2615                    continue;
2616                }
2617                if skip_fallback > 0 {
2618                    skip_fallback -= 1;
2619                } else if c == '\t' || !c.is_control() {
2620                    out.push(c, line);
2621                }
2622            }
2623        }
2624    }
2625    if opened {
2626        Err(rtf_syntax(
2627            line,
2628            format!(
2629                "the document ends with {} groups open: its braces don't balance",
2630                groups.len()
2631            ),
2632        ))
2633    } else {
2634        Err(LogError::NotThisFormat {
2635            format: RTF_FORMAT,
2636            message: "the file holds no RTF group, `{\\rtf…}`".to_owned(),
2637        })
2638    }
2639}
2640
2641/// What a control word may change as [`unwrap_rtf`] reads it.
2642struct ControlState<'a, 'b> {
2643    out: &'a mut Unwrapped,
2644    groups: &'a mut Vec<Group>,
2645    chars: &'a mut std::str::Chars<'b>,
2646    line: &'a mut usize,
2647    code_page_1252: &'a mut bool,
2648    skip_fallback: &'a mut usize,
2649}
2650
2651/// Acts on one control word and its number, if any.
2652fn control_word(word: &str, parameter: Option<i64>, state: &mut ControlState<'_, '_>) {
2653    let skip = state.groups.last().is_some_and(|group| group.skip);
2654    match word {
2655        "fonttbl" | "colortbl" | "stylesheet" | "info" | "pict" | "object" => {
2656            if let Some(group) = state.groups.last_mut() {
2657                group.skip = true;
2658            }
2659        }
2660        "uc" => {
2661            if let Some(group) = state.groups.last_mut() {
2662                group.fallback = usize::try_from(parameter.unwrap_or(1))
2663                    .map_or(0, |count| count.min(MAX_FALLBACK));
2664            }
2665        }
2666        "ansicpg" => *state.code_page_1252 = parameter == Some(1252),
2667        "mac" | "pc" | "pca" => *state.code_page_1252 = false,
2668        "bin" => {
2669            // The data's bytes aren't text: skipped, however many it states, to the document's
2670            // end at most.
2671            let count = usize::try_from(parameter.unwrap_or(0)).unwrap_or(0);
2672            for _ in 0..count {
2673                match state.chars.next() {
2674                    Some('\n') => *state.line += 1,
2675                    Some(_) => {}
2676                    None => break,
2677                }
2678            }
2679        }
2680        _ if skip => {}
2681        "u" => {
2682            // A signed 16-bit number, negative for the code points from 0x8000.
2683            let code = parameter.unwrap_or(0);
2684            let code = if code < 0 { code + 0x1_0000 } else { code };
2685            let c = u32::try_from(code)
2686                .ok()
2687                .and_then(char::from_u32)
2688                .unwrap_or(char::REPLACEMENT_CHARACTER);
2689            state.out.push(c, *state.line);
2690            *state.skip_fallback = state.groups.last().map_or(1, |group| group.fallback);
2691        }
2692        "par" | "line" | "sect" | "page" | "row" => state.out.line_break(*state.line),
2693        "tab" | "cell" => state.out.push('\t', *state.line),
2694        _ => {
2695            if let Some(c) = word_character(word) {
2696                state.out.push(c, *state.line);
2697            }
2698        }
2699    }
2700}
2701
2702/// A control word's number, if one follows: an optional `-` and digits, read saturating at the
2703/// `i64` range, so a number of any length is read without overflow.
2704fn control_parameter(chars: &mut std::str::Chars<'_>) -> Option<i64> {
2705    let mut ahead = chars.as_str().chars();
2706    let negative = ahead.next() == Some('-') && ahead.next().is_some_and(|c| c.is_ascii_digit());
2707    if negative {
2708        chars.next();
2709    }
2710    let mut value: Option<i64> = None;
2711    while let Some(digit) = chars.as_str().chars().next().and_then(|c| c.to_digit(10)) {
2712        chars.next();
2713        value = Some(
2714            value
2715                .unwrap_or(0)
2716                .saturating_mul(10)
2717                .saturating_add(i64::from(digit)),
2718        );
2719    }
2720    value.map(|value| if negative { -value } else { value })
2721}
2722
2723/// The character a `\'hh` byte stands for: ASCII below 0x80; from 0x80, Windows 1252's if that
2724/// is the document's code page, `None` where it leaves the byte undefined or in another code page.
2725fn code_page_character(byte: u32, code_page_1252: bool) -> Option<char> {
2726    match byte {
2727        0..0x80 => char::from_u32(byte),
2728        _ if !code_page_1252 => None,
2729        0x80..0xa0 => usize::try_from(byte - 0x80)
2730            .ok()
2731            .and_then(|index| CP1252_80_9F.get(index))
2732            .copied()
2733            .flatten(),
2734        _ => char::from_u32(byte),
2735    }
2736}
2737
2738/// The character a control word writes, for the few words that write one.
2739fn word_character(word: &str) -> Option<char> {
2740    match word {
2741        "emdash" => Some('\u{2014}'),
2742        "endash" => Some('\u{2013}'),
2743        "emspace" | "enspace" | "qmspace" => Some(' '),
2744        "bullet" => Some('\u{2022}'),
2745        "lquote" => Some('\u{2018}'),
2746        "rquote" => Some('\u{2019}'),
2747        "ldblquote" => Some('\u{201c}'),
2748        "rdblquote" => Some('\u{201d}'),
2749        _ => None,
2750    }
2751}
2752
2753/// Whether a line of a download's text could be one of its table's rows: it opens with a digit,
2754/// a sign or a point. A line that doesn't, after a table, is the next download's lead-in, such as
2755/// its `Flight Summary:` heading.
2756fn row_like(line: &str) -> bool {
2757    line.trim_start()
2758        .starts_with(|c: char| c.is_ascii_digit() || matches!(c, '-' | '+' | '.'))
2759}
2760
2761/// The lines, from 1, of each download's title after the line `after_line`: a line `Eggtimer …`
2762/// ending in `Flight Settings`, or followed by a line `Flight Settings`, as [`split_download`]
2763/// reads a title.
2764fn later_titles(text: &str, after_line: usize) -> Vec<usize> {
2765    let lines: Vec<(usize, &str)> = numbered_lines(text)
2766        .map(|(number, line)| (number, line.trim()))
2767        .filter(|(number, line)| *number > after_line && !line.is_empty())
2768        .collect();
2769    lines
2770        .iter()
2771        .enumerate()
2772        .filter(|(index, (_, line))| {
2773            line.strip_prefix("Eggtimer ").is_some_and(|rest| {
2774                rest.ends_with("Flight Settings")
2775                    || lines
2776                        .get(index + 1)
2777                        .is_some_and(|(_, next)| *next == "Flight Settings")
2778            })
2779        })
2780        .map(|(_, (number, _))| *number)
2781        .collect()
2782}
2783
2784/// Reads an Eggtimer TRS's terminal download saved inside an RTF document, as a text editor saves
2785/// what a terminal program captured: the document's plain text, unwrapped from its markup, read
2786/// as [`read_text`] reads a terminal download ([ADR-258][adr-258] §4).
2787///
2788/// The text is unwrapped by the subset of the RTF specification (Microsoft, *Rich Text Format
2789/// (RTF) Specification*, version 1.9.1, 2008) that a saved terminal capture needs:
2790///
2791/// - groups, `{` to `}`, nested at most [`MAX_RTF_DEPTH`] deep; the document is one group, and
2792///   an unbalanced brace is refused;
2793/// - control words, `\` and letters, then an optional signed number and one space ending the
2794///   word, which isn't text; a number of any length is read saturating, never overflowing;
2795/// - `\par`, `\line`, `\sect`, `\page` and `\row` as line breaks, and `\` at a line's end as
2796///   `\par`; `\tab` and `\cell` as a tab; `\emdash`, `\endash`, `\bullet`, the space words and
2797///   the quote words as their characters;
2798/// - control symbols: `\\`, `\{` and `\}` as the character; `\~` a no-break space, `\_` a hyphen,
2799///   `\-` nothing; `\'hh` a byte in the document's code page, Windows 1252 (`\ansi`, the default,
2800///   or `\ansicpg1252`), any other code page's bytes from 0x80 counted and read as U+FFFD;
2801/// - `\uN` a Unicode character, the `\ucN` fallback characters after it skipped;
2802/// - destinations skipped whole: a group opening `\*`, and the font, color and style tables, the
2803///   document's information, pictures and objects; `\binN`'s N bytes skipped;
2804/// - raw line ends, other control words and other control symbols ignored, as the specification
2805///   says a reader may.
2806///
2807/// The work is one pass with a stack of groups, no recursion, and the text is never longer than
2808/// the document.
2809///
2810/// A document may hold several downloads one after another, each with its title, settings,
2811/// summary and table. A record holds one flight: the first download is read, its table ending at
2812/// its last row before the next download's lead-in, and the others are counted in a note with the
2813/// lines of their titles. An error names the RTF document's line.
2814///
2815/// [adr-258]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0258-aerospacenus-board-and-a-phone-apps-csv-before-the-rest.md
2816///
2817/// # Errors
2818///
2819/// [`LogError::NotThisFormat`] if the file isn't an RTF document, or if its text holds no Eggtimer
2820/// download: no title `Eggtimer … Flight Settings` before an Eggtimer header row within the first
2821/// [`MAX_PREAMBLE_LINES`] lines that aren't blank; [`LogError::Syntax`] for RTF markup the reader
2822/// refuses (unbalanced braces, groups nested deeper than [`MAX_RTF_DEPTH`], a `\'` escape without
2823/// two hexadecimal digits); otherwise what [`read_text`] refuses, naming the document's line.
2824pub fn read_rtf(text: &str) -> Result<FlightLog, LogError> {
2825    if !recognizes_rtf(text) {
2826        return Err(LogError::NotThisFormat {
2827            format: RTF_FORMAT,
2828            message: "the file doesn't open with `{\\rtf`, an RTF document's opening group"
2829                .to_owned(),
2830        });
2831    }
2832    let unwrapped = unwrap_rtf(text)?;
2833    let Some(first) = split_download(&unwrapped.text) else {
2834        return Err(LogError::NotThisFormat {
2835            format: RTF_FORMAT,
2836            message: format!(
2837                "the RTF document's text holds no Eggtimer terminal download. No title \
2838                 `Eggtimer … Flight Settings` comes before an Eggtimer header row, such as \
2839                 `T,Alt,Veloc,…`, within the first {MAX_PREAMBLE_LINES} lines that aren't blank"
2840            ),
2841        });
2842    };
2843    let others = later_titles(&unwrapped.text, first.header_line);
2844    // The first download ends at its last row-like line before the next one's title.
2845    let download = match others.first() {
2846        Some(&next_title) => {
2847            let last_row = numbered_lines(&unwrapped.text)
2848                .take_while(|(number, _)| *number < next_title)
2849                .filter(|(_, line)| row_like(line))
2850                .map(|(number, _)| number)
2851                .last()
2852                .unwrap_or(first.header_line)
2853                .max(first.header_line);
2854            // The text's lines end in `\n` alone, so its line `last_row` ends at that newline.
2855            let end = unwrapped
2856                .text
2857                .match_indices('\n')
2858                .nth(last_row.saturating_sub(1))
2859                .map_or(unwrapped.text.len(), |(at, _)| at);
2860            unwrapped.text.get(..end).unwrap_or(&unwrapped.text)
2861        }
2862        None => unwrapped.text.as_str(),
2863    };
2864    let mut log = read_download(download, RTF_FORMAT, &|line| unwrapped.file_line(line))?;
2865    log.format = LogFormat::EggtimerRtf;
2866    log.notes.insert(
2867        0,
2868        "the text was unwrapped from an RTF document, as a text editor saves a terminal \
2869         program's capture. The document's groups, control words and escapes were taken out, and its \
2870         paragraph and line breaks were read as the download's lines. A line named is the \
2871         document's"
2872            .to_owned(),
2873    );
2874    if !others.is_empty() {
2875        let lines: Vec<String> = others
2876            .iter()
2877            .take(MAX_LISTED)
2878            .map(|line| unwrapped.file_line(*line).to_string())
2879            .collect();
2880        let more = others.len().saturating_sub(MAX_LISTED);
2881        log.notes.push(format!(
2882            "the document holds {} Eggtimer downloads one after another. The first was read, as \
2883             a record holds one flight. The titles of those that weren't are on lines {}{}",
2884            others.len() + 1,
2885            lines.join(", "),
2886            if more > 0 {
2887                format!(" and {more} more")
2888            } else {
2889                String::new()
2890            }
2891        ));
2892    }
2893    if unwrapped.unmapped > 0 {
2894        log.notes.push(format!(
2895            "{} escaped bytes were read as U+FFFD. They are undefined in the document's code page, \
2896             or in a code page the reader doesn't map (it maps Windows 1252)",
2897            unwrapped.unmapped
2898        ));
2899    }
2900    if unwrapped.after_end > 0 {
2901        log.notes.push(format!(
2902            "{} characters after the document's closing brace weren't read",
2903            unwrapped.after_end
2904        ));
2905    }
2906    Ok(log)
2907}
2908
2909#[cfg(test)]
2910mod tests {
2911    use super::*;
2912
2913    const TRS: &str = "T,Alt,Veloc,FAlt,FVeloc,LDA,LowV,Apogee,N-O,Drogue,Main";
2914
2915    fn close(a: f64, b: f64) -> bool {
2916        (a - b).abs() <= 1e-12 * b.abs().max(1.0)
2917    }
2918
2919    /// The text before a note's first `: `, which must be the same for every file decided the
2920    /// same way.
2921    fn prefix(note: &str) -> &str {
2922        note.split(": ").next().unwrap_or(note)
2923    }
2924
2925    #[test]
2926    fn recognizes_the_eggtimer_headers_and_no_others() {
2927        for header in [
2928            TRS,
2929            "T,Alt,Veloc,Filt_Alt,FVeloc,LDA,LowV,Apogee,N-O,Drogue,Main",
2930            "T,Alt,FAlt,FVeloc,LDA,LowV,Apogee,N-O,Drogue,Main,AUX",
2931            "T,Alt,Veloc,KAlt,KVeloc,LDA,BurnT,LowV,Apogee,N-O,CHA,CHB",
2932            "T, Alt, VRaw, VFilt",
2933            "T,Alt,Veloc,AccelG,AccelFPSS,VAccel,AltAccel,FAlt,FVeloc,FAccelG,FAccelFPSS,\
2934             FAccelVel,FAccelAlt,LDA,MaxV,MaxA,BO#1,LowV,Apogee,N-O,CH1,CH2",
2935            "T,Alt,Apogee",
2936            "T;Alt;Veloc;Filt_Alt;FVeloc;LDA;LowV;Apogee;N-O;Drogue;Main",
2937        ] {
2938            assert!(recognizes(&format!("\r\n{header}\r\n0,0\r\n")), "{header}");
2939        }
2940        for text in [
2941            "",
2942            "T,Alt\n",
2943            "T,Alt,Foo\n",
2944            "T\tAlt\tVeloc\n",
2945            "t,alt,veloc\n",
2946            "Time,Altitude,Velocity\n",
2947            "Time,Altitude,Pressure,Velocity,Temperature,Events,Voltages\n",
2948            "Alt,T,Veloc\n",
2949            "# T,Alt,Veloc\n",
2950            "T;Alt;Foo\n",
2951            "Time;Altitude;Pressure;Velocity;Temperature;Events;Voltages;\n",
2952        ] {
2953            assert!(!recognizes(text), "{text:?}");
2954        }
2955        assert_eq!(kind_of("CH12"), Some(Kind::Marker));
2956        assert_eq!(kind_of("Boost#3"), Some(Kind::Marker));
2957        assert_eq!(kind_of("CH"), None);
2958        assert_eq!(kind_of("BO#x"), None);
2959    }
2960
2961    /// The TRS layout in seconds: feet and feet per second to SI, the markers kept as written and
2962    /// read as events, the raw barometric velocity the vertical speed.
2963    #[test]
2964    fn reads_the_layout_in_seconds() {
2965        let text = format!(
2966            "{TRS}\n\
2967             0,0,0,0,0,0,0,0,0,0,0\n\
2968             0.05,10,200,2,40,0,0,0,0,0,0\n\
2969             0.1,25,300,7,100,25,0,0,0,0,0\n\
2970             0.15,30,100,13.5,130,0,0,30,0,0,0\n\
2971             0.2,29,-20,18,90,0,0,0,29,29,0\n"
2972        );
2973        let log = read(&text).unwrap();
2974        assert_eq!(log.format, LogFormat::EggtimerCsv);
2975        assert_eq!(log.logger, "Eggtimer");
2976        assert_eq!(log.time_s, [0.0, 0.05, 0.1, 0.15, 0.2]);
2977        assert!(close(log.altitude_m[2], 25.0 * 0.3048));
2978        let speed = log.vertical_speed_m_s.as_deref().unwrap();
2979        assert!(close(speed[1], 200.0 * 0.3048));
2980        assert_eq!(log.channels.len(), 10);
2981        assert_eq!(log.channels[2].quantity, Quantity::AltitudeAboveGround);
2982        assert!(close(log.channels[2].values[3], 13.5 * 0.3048));
2983        assert_eq!(log.channels[3].quantity, Quantity::Speed);
2984        // The markers as written, in feet: 0 is "no event".
2985        assert_eq!(log.channels[4].column, "LDA");
2986        assert_eq!(log.channels[4].quantity, Quantity::Unrecognized);
2987        assert_eq!(log.channels[4].values, [0.0, 0.0, 25.0, 0.0, 0.0]);
2988        let events: Vec<(f64, &str)> = log
2989            .events
2990            .iter()
2991            .map(|event| (event.time_s, event.name.as_str()))
2992            .collect();
2993        assert_eq!(
2994            events,
2995            [
2996                (0.1, "LDA"),
2997                (0.15, "Apogee"),
2998                (0.2, "N-O"),
2999                (0.2, "Drogue")
3000            ]
3001        );
3002        assert_eq!(log.notes.len(), 6, "{:?}", log.notes);
3003        assert_eq!(
3004            log.notes[0],
3005            "`T` read in seconds, from the step: the median step between rows is 0.05. A \
3006             step above 5 is read as milliseconds. At the manuals' 1 to 33 samples a second, \
3007             a step is 0.03 to 1 in seconds and 30 to 1,000 in milliseconds"
3008        );
3009        assert_eq!(
3010            log.notes[1],
3011            "`Alt` read in feet, from the manual: the Classic and TRS manuals (p37) state feet. \
3012             The Quantum and Proton manuals give every height in feet, and no Eggtimer manual \
3013             offers meters"
3014        );
3015        assert_eq!(
3016            log.notes[2],
3017            "`Veloc` read in feet per second, from the manual: the Classic and TRS manuals (p37) \
3018             give the velocity in ft/sec. The Proton's manual (p45) gives it as the change in `Alt` over the \
3019             step. It is the change in `Alt` over the step, within 1 % or 1 ft/s. That holds in 4 \
3020             of 4 rows after the first, where the reader asks 90 %"
3021        );
3022        assert!(log.notes[3].starts_with("`FAlt` read in feet, from the manual: "));
3023        assert!(
3024            log.notes[4].starts_with("`FVeloc` read in feet per second, from the manual: ")
3025                && log.notes[4].contains("the change in `FAlt` over the step")
3026                && log.notes[4].contains("in 4 of 4 rows after the first"),
3027            "{}",
3028            log.notes[4]
3029        );
3030        assert_eq!(
3031            log.notes[5],
3032            "the marker columns, kept as written: `LDA`, `LowV`, `Apogee`, `N-O`, `Drogue` and \
3033             `Main`. Each is 0 but at the sample that marks its event. There the Quantum's \
3034             and Proton's manuals (p38, p46) put the raw altitude, in feet"
3035        );
3036    }
3037
3038    /// A median step above 5 is milliseconds; at 5 or below, seconds. The notes' text before the
3039    /// first `: ` is the same for files decided the same way.
3040    #[test]
3041    fn the_step_decides_the_time_unit() {
3042        let rows = |step: f64| -> String {
3043            (0..4)
3044                .map(|i| format!("{},{},{}\n", f64::from(i) * step, i * 10, 0))
3045                .collect()
3046        };
3047        let millis = read(&format!("T,Alt,LDA\n{}", rows(50.0))).unwrap();
3048        assert_eq!(millis.time_s, [0.0, 0.05, 0.1, 0.15]);
3049        assert!(millis.notes[0].starts_with("`T` read in milliseconds, from the step: "));
3050        assert!(millis.notes[0].contains("median step between rows is 50."));
3051        let slow = read(&format!("T,Alt,LDA\n{}", rows(1000.0))).unwrap();
3052        assert_eq!(prefix(&slow.notes[0]), prefix(&millis.notes[0]));
3053        assert!(slow.notes[0].contains("is 1000."));
3054
3055        // At the line between the two, 5, a step is neither unit's at the manuals' rates, and
3056        // the file is refused either side of it.
3057        for step in [5.0, 5.01] {
3058            let refused = read(&format!("T,Alt,LDA\n{}", rows(step)));
3059            assert!(matches!(refused, Err(LogError::Unit { .. })), "{step}");
3060        }
3061        let seconds = read(&format!("T,Alt,LDA\n{}", rows(0.5))).unwrap();
3062        assert_eq!(
3063            prefix(&seconds.notes[0]),
3064            "`T` read in seconds, from the step"
3065        );
3066
3067        // The median, not the mean: a long pause doesn't turn seconds into milliseconds.
3068        let paused = read("T,Alt,LDA\n0,0,0\n0.05,1,0\n0.1,2,0\n100,3,0\n").unwrap();
3069        assert_eq!(paused.time_s, [0.0, 0.05, 0.1, 100.0]);
3070
3071        let one = read("T,Alt,LDA\n120,4,0\n").unwrap();
3072        assert_eq!(one.time_s, [120.0]);
3073        assert!(one.notes[0].starts_with("`T` read in seconds, assumed: "));
3074    }
3075
3076    /// The Proton's columns: g and ft/s² to m/s², the accelerometer's velocity and distance, the
3077    /// two accelerations' ratio in the altitude's note; `MaxV` and `MaxA` markers as written.
3078    #[test]
3079    fn reads_the_accelerometer_columns() {
3080        let text = "T,Alt,Veloc,AccelG,AccelFPSS,VAccel,AltAccel,LDA,MaxV,MaxA,CH1\r\
3081                    -0.1,0,0,0,0,0,0,0,0,0,0\r\
3082                    0,1,10,2,64.4,0,0,0,0,0,0\r\
3083                    0.1,12,110,10,321.7,40,2,0,0,321,0\r\
3084                    0.2,40,280,5,160.9,80,9,40,80,0,0\r";
3085        let log = read(text).unwrap();
3086        assert_eq!(log.time_s, [-0.1, 0.0, 0.1, 0.2]);
3087        let quantities: Vec<Quantity> = log.channels.iter().map(|c| c.quantity).collect();
3088        assert_eq!(
3089            quantities,
3090            [
3091                Quantity::AltitudeAboveGround,
3092                Quantity::Speed,
3093                Quantity::Acceleration,
3094                Quantity::Acceleration,
3095                Quantity::Speed,
3096                Quantity::InertialAltitude,
3097                Quantity::Unrecognized,
3098                Quantity::Unrecognized,
3099                Quantity::Unrecognized,
3100                Quantity::Unrecognized,
3101            ]
3102        );
3103        assert!(close(log.channels[2].values[2], 10.0 * 9.806_65));
3104        assert!(close(log.channels[3].values[2], 321.7 * 0.3048));
3105        assert!(close(log.channels[4].values[3], 80.0 * 0.3048));
3106        assert!(close(log.channels[5].values[3], 9.0 * 0.3048));
3107        assert_eq!(log.channels[7].values, [0.0, 0.0, 0.0, 80.0]);
3108        let names: Vec<&str> = log.events.iter().map(|event| event.name.as_str()).collect();
3109        assert_eq!(names, ["MaxA", "LDA", "MaxV"]);
3110        assert!(
3111            log.notes[1].ends_with(
3112                ". The file's `AccelFPSS` is 32.17 times its `AccelG`, and one g is 32.17 ft/s²"
3113            ),
3114            "{}",
3115            log.notes[1]
3116        );
3117        // `AccelG` and `AccelFPSS` name their units, so get no unit note.
3118        assert!(log.notes[2].starts_with("`Veloc` read in feet per second, from the manual: "));
3119        assert!(log.notes[3].starts_with("`VAccel` read in feet per second, from the manual: "));
3120        assert!(log.notes[4].starts_with("`AltAccel` read in feet, from the manual: "));
3121        assert_eq!(
3122            log.notes[5],
3123            "`AccelG` has gravity taken out, from the pad: its median over the 1 rows before the \
3124             start of flight (`T` below 0) is 0 g. An accelerometer that keeps gravity reads \
3125             1 g standing still, and one that takes it out reads 0. The Proton's manual doesn't \
3126             say, and its release notes (2.01C, p8) have it calibrate the accelerometer as it is \
3127             armed, standing up. The file's other acceleration columns are the same accelerometer's"
3128        );
3129        assert!(
3130            log.notes[6].starts_with(
3131                "the marker columns, kept as written: `LDA`, `MaxV`, `MaxA` and `CH1`. "
3132            ) && log.notes[6].ends_with(
3133                ". At that sample the Proton's release notes (1.02N, p13) put the top speed, \
3134                     ft/s, in `MaxV` and the top acceleration, ft/s², in `MaxA`"
3135            ),
3136            "{}",
3137            log.notes[6]
3138        );
3139        assert_eq!(log.notes.len(), 7, "{:?}", log.notes);
3140    }
3141
3142    /// The Proton manual's `Accel` doesn't name its unit, so it gets a note, and is the one the
3143    /// altitude's note and the gravity note name, as written. A pad reading near 1 g holds
3144    /// gravity; one near neither, or no rows before the start of flight, leaves it not known.
3145    #[test]
3146    fn the_acceleration_unit_and_gravity_are_noted() {
3147        let log = read(
3148            "T,Alt,Accel,AccelFPSS,LDA
3149-0.1,0,1,32.2,0
31500,0,1.1,35.4,0
31510.1,3,6,193,3
3152",
3153        )
3154        .unwrap();
3155        let notes = log.notes.join("\n");
3156        assert!(
3157            notes.contains(
3158                "`Accel` read in g, from the manual: the Proton's manual (p45) gives the \
3159                 accelerometer's raw value in G's"
3160            ),
3161            "{notes}"
3162        );
3163        assert!(
3164            notes.contains("The file's `AccelFPSS` is 32.17 times its `Accel`"),
3165            "{notes}"
3166        );
3167        assert!(
3168            notes.contains(
3169                "`Accel` holds gravity, from the pad: its median over the 1 rows before the start \
3170                 of flight (`T` below 0) is 1 g"
3171            ),
3172            "{notes}"
3173        );
3174        assert!(!notes.contains("AccelG"), "{notes}");
3175        assert!(close(log.channels[1].values[0], 9.806_65));
3176
3177        let unsure = read(
3178            "T,Alt,AccelG,LDA
3179-0.2,0,3,0
3180-0.1,0,3,0
31810,1,4,0
3182",
3183        )
3184        .unwrap();
3185        assert!(
3186            unsure.notes.iter().any(|note| note.starts_with(
3187                "`AccelG` may or may not hold gravity, not known: its median over the 2 rows \
3188                 before the start of flight (`T` below 0) is 3 g"
3189            )),
3190            "{:?}",
3191            unsure.notes
3192        );
3193        let no_pad = read(
3194            "T,Alt,FAccelFPSS,LDA
31950,0,0,0
31960.1,1,64,0
3197",
3198        )
3199        .unwrap();
3200        assert!(
3201            no_pad.notes.iter().any(|note| note.starts_with(
3202                "`FAccelFPSS` may or may not hold gravity, not known. The file has no rows before \
3203                 the start of flight"
3204            )),
3205            "{:?}",
3206            no_pad.notes
3207        );
3208        // A pad reading in ft/s² is judged in g.
3209        let in_ft = read(
3210            "T,Alt,AccelFPSS,LDA
3211-0.1,0,32.2,0
32120,1,40,0
3213",
3214        )
3215        .unwrap();
3216        assert!(
3217            in_ft
3218                .notes
3219                .iter()
3220                .any(|note| note.starts_with("`AccelFPSS` holds gravity, from the pad: ")),
3221            "{:?}",
3222            in_ft.notes
3223        );
3224    }
3225
3226    /// A speed that isn't its altitude's change over the step on 90 % of the rows is kept as
3227    /// written, and the vertical speed falls to the filtered one; at 90 % it is read.
3228    #[test]
3229    fn a_speed_that_isnt_its_altitudes_change_is_kept_as_written() {
3230        // Every `Veloc` is 1,000 times the change: a clock in milliseconds read as seconds would
3231        // do this.
3232        let text = "T,Alt,Veloc,FAlt,FVeloc,LDA
32330,0,0,0,0,0
32341,10,10000,5,5,0
32352,30,20000,15,10,0
3236";
3237        let log = read(text).unwrap();
3238        assert_eq!(log.channels[1].column, "Veloc");
3239        assert_eq!(log.channels[1].quantity, Quantity::Unrecognized);
3240        assert_eq!(log.channels[1].values, [0.0, 10000.0, 20000.0]);
3241        assert_eq!(log.channels[3].quantity, Quantity::Speed);
3242        assert_eq!(
3243            log.vertical_speed_m_s.as_deref(),
3244            Some(&[0.0, 5.0 * 0.3048, 10.0 * 0.3048][..])
3245        );
3246        let notes = log.notes.join("\n");
3247        assert!(
3248            notes.contains(
3249                "`Veloc` kept as written, not read as a speed: it is the change in `Alt` over the \
3250                 step, within 1 % or 1 ft/s. That holds in only 0 of 2 rows after the first, under \
3251                 the 90 % the reader asks"
3252            ),
3253            "{notes}"
3254        );
3255        assert!(!notes.contains("`Veloc` read in"), "{notes}");
3256        assert!(notes.contains("the file has no raw velocity, `Veloc`, read as a speed"));
3257
3258        // 9 of 10 rows match: read; 8 of 10: kept as written.
3259        let rows = |misses: usize| -> String {
3260            (0..=10)
3261                .map(|i| {
3262                    let speed = if i > 0 && i <= misses {
3263                        99
3264                    } else {
3265                        10 * usize::from(i > 0)
3266                    };
3267                    format!("{i},{},{speed},0\n", 10 * i)
3268                })
3269                .collect()
3270        };
3271        let nine = read(&format!("T,Alt,Veloc,LDA\n{}", rows(1))).unwrap();
3272        assert_eq!(nine.channels[1].quantity, Quantity::Speed);
3273        assert!(
3274            nine.notes
3275                .iter()
3276                .any(|note| note.contains("in 9 of 10 rows after the first"))
3277        );
3278        let eight = read(&format!("T,Alt,Veloc,LDA\n{}", rows(2))).unwrap();
3279        assert_eq!(eight.channels[1].quantity, Quantity::Unrecognized);
3280        assert!(eight.vertical_speed_m_s.is_none());
3281    }
3282
3283    /// A header repeating a name gets that name's unit note once.
3284    #[test]
3285    fn a_repeated_name_is_noted_once() {
3286        let log = read(
3287            "T,Alt,Veloc,Veloc,LDA
32880,0,0,0,0
32890.1,1,10,10,0
3290",
3291        )
3292        .unwrap();
3293        let veloc = log
3294            .notes
3295            .iter()
3296            .filter(|note| note.starts_with("`Veloc` read in"))
3297            .count();
3298        assert_eq!(veloc, 1, "{:?}", log.notes);
3299        assert_eq!(log.channels[2].quantity, Quantity::Speed);
3300    }
3301
3302    /// A marker column with a very long name rising on every other row gives at most
3303    /// [`MAX_EVENTS_PER_MARKER`] events, each naming it cut short, and one note counting the rest:
3304    /// the record stays near the file's size.
3305    #[test]
3306    fn a_long_marker_name_rising_often_is_bounded() {
3307        let name = "X".repeat(100_000);
3308        let rows: String = (0..4000).map(|i| format!("{i},0,0,{}\n", i % 2)).collect();
3309        let text = format!("T,Alt,LDA,{name}\n{rows}");
3310        let log = read(&text).unwrap();
3311        assert_eq!(log.events.len(), MAX_EVENTS_PER_MARKER);
3312        assert!(
3313            log.events
3314                .iter()
3315                .all(|event| event.name.chars().count() <= 80)
3316        );
3317        assert!(log.events[0].name.ends_with('…'));
3318        assert_eq!(log.events[15].time_s, 31.0);
3319        let notes = log.notes.join("\n");
3320        assert!(
3321            notes.contains(&format!(
3322                "rises {} more times than the 16 kept as events",
3323                2000 - MAX_EVENTS_PER_MARKER
3324            )),
3325            "{}",
3326            short(&notes)
3327        );
3328        let bytes: usize = log.notes.iter().map(String::len).sum::<usize>()
3329            + log
3330                .events
3331                .iter()
3332                .map(|event| event.name.len())
3333                .sum::<usize>();
3334        assert!(bytes < 10_000, "{bytes} bytes of notes and event names");
3335        // The channel keeps the name as written.
3336        assert_eq!(log.channels[2].column.len(), 100_000);
3337    }
3338
3339    /// The marker note lists at most a few columns, and counts the rest.
3340    #[test]
3341    fn the_marker_note_stays_short() {
3342        let markers: String = (1..=40).map(|i| format!(",CH{i}")).collect();
3343        let text = format!(
3344            "T,Alt,LDA{markers}
33450,0{}
3346",
3347            ",0".repeat(41)
3348        );
3349        let log = read(&text).unwrap();
3350        let note = log
3351            .notes
3352            .iter()
3353            .find(|note| note.starts_with("the marker columns, kept as written: "))
3354            .unwrap();
3355        assert!(
3356            note.starts_with(
3357                "the marker columns, kept as written: `LDA`, `CH1`, `CH2`, `CH3`, `CH4` and 36 more \
3358                 columns. "
3359            ),
3360            "{note}"
3361        );
3362        assert!(
3363            read(
3364                "T,Alt,Veloc
33650,0,0
3366"
3367            )
3368            .unwrap()
3369            .notes
3370            .iter()
3371            .all(|note| !note.contains("marker columns"))
3372        );
3373    }
3374
3375    /// A marker held over several samples, or to the end, is one event; two runs are two.
3376    #[test]
3377    fn each_run_of_a_marker_is_one_event() {
3378        let text = "T,Alt,Veloc,Apogee,Main\n\
3379                    0,100,0,0,0\n0.5,101,2,101,0\n1,100,-2,101,0\n1.5,99,-2,0,0\n\
3380                    2,98,-2,98,98\n2.5,97,-2,0,98\n";
3381        let log = read(text).unwrap();
3382        let events: Vec<(f64, &str)> = log
3383            .events
3384            .iter()
3385            .map(|event| (event.time_s, event.name.as_str()))
3386            .collect();
3387        assert_eq!(events, [(0.5, "Apogee"), (2.0, "Apogee"), (2.0, "Main")]);
3388    }
3389
3390    /// Without a raw velocity, the filtered one is the vertical speed, with a note; without a
3391    /// filtered altitude, its unit is the manual's.
3392    #[test]
3393    fn the_filtered_velocity_stands_in_for_the_raw_one() {
3394        let log = read("T,Alt,FAlt,FVeloc,LDA\n0,0,0,0,0\n0.05,2,1,20,0\n").unwrap();
3395        assert_eq!(
3396            log.vertical_speed_m_s.as_deref(),
3397            Some(&[0.0, 20.0 * 0.3048][..])
3398        );
3399        assert!(
3400            log.notes
3401                .iter()
3402                .any(|note| note
3403                    .contains("the vertical speed is its filtered barometric \"FVeloc\""))
3404        );
3405        let old = read("T, Alt, VRaw, VFilt\n0, 0, 0, 0\n50, 1, 20, 4\n100, 3, 40, 12\n").unwrap();
3406        assert_eq!(old.time_s, [0.0, 0.05, 0.1]);
3407        assert_eq!(
3408            old.vertical_speed_m_s.as_deref(),
3409            Some(&[0.0, 20.0 * 0.3048, 40.0 * 0.3048][..])
3410        );
3411        assert!(old.notes[2].starts_with("`VRaw` read in feet per second, from the manual: "));
3412        assert!(
3413            old.notes[3].ends_with("The file has no filtered altitude to check it against"),
3414            "{}",
3415            old.notes[3]
3416        );
3417        assert!(old.notes[3].starts_with("`VFilt` read in feet per second, from the manual: "));
3418        assert!(
3419            read("T,Alt,LDA\n0,0,0\n")
3420                .unwrap()
3421                .vertical_speed_m_s
3422                .is_none()
3423        );
3424    }
3425
3426    /// A flight in the TRS's `Filt_Alt` layout, each row's cells joined by `separator`, the
3427    /// filtered altitude and its speed written `filtered_scale` times their values and every
3428    /// number by `mark` (to change its decimal mark).
3429    fn filtered_flight(
3430        separator: &str,
3431        filtered_scale: f64,
3432        mark: impl Fn(String) -> String,
3433    ) -> String {
3434        let mut text = ["T", "Alt", "Veloc", "Filt_Alt", "FVeloc", "LDA", "Apogee"].join(separator);
3435        text.push('\n');
3436        let (mut altitude, mut filtered) = (0.0_f64, 0.0_f64);
3437        for row in 0..60_u32 {
3438            let t = f64::from(row) * 0.05;
3439            // Up at a falling speed, then down: a whole-foot altitude, as the logger writes it.
3440            let next = (t * (200.0 - 30.0 * t)).max(0.0).round();
3441            let speed = if row == 0 {
3442                0.0
3443            } else {
3444                (next - altitude) / 0.05
3445            };
3446            let next_filtered = filtered + 0.2 * (next - filtered);
3447            let filtered_speed = if row == 0 {
3448                0.0
3449            } else {
3450                (next_filtered - filtered) / 0.05
3451            };
3452            altitude = next;
3453            filtered = next_filtered;
3454            let cells = [
3455                plain(t, 2),
3456                plain(altitude, 0),
3457                format!("{speed:.2}"),
3458                format!("{:.2}", filtered * filtered_scale),
3459                format!("{:.2}", filtered_speed * filtered_scale),
3460                "0".to_owned(),
3461                "0".to_owned(),
3462            ];
3463            let cells: Vec<String> = cells.into_iter().map(&mark).collect();
3464            text.push_str(&cells.join(separator));
3465            text.push('\n');
3466        }
3467        text
3468    }
3469
3470    fn channel<'a>(log: &'a FlightLog, name: &str) -> &'a Channel {
3471        log.channels.iter().find(|c| c.column == name).unwrap()
3472    }
3473
3474    #[test]
3475    fn semicolons_read_as_commas_do_with_either_decimal_mark() {
3476        let commas = read(&filtered_flight(",", 1.0, |cell| cell)).unwrap();
3477        let points = read(&filtered_flight(";", 1.0, |cell| cell)).unwrap();
3478        let decimal_commas =
3479            read(&filtered_flight(";", 1.0, |cell| cell.replace('.', ","))).unwrap();
3480        for log in [&points, &decimal_commas] {
3481            assert_eq!(log.time_s, commas.time_s);
3482            assert_eq!(log.altitude_m, commas.altitude_m);
3483            assert_eq!(log.vertical_speed_m_s, commas.vertical_speed_m_s);
3484            assert_eq!(log.channels, commas.channels);
3485            assert_eq!(log.notes[..commas.notes.len()], commas.notes[..]);
3486        }
3487        assert_eq!(
3488            channel(&points, "Filt_Alt").quantity,
3489            Quantity::AltitudeAboveGround
3490        );
3491        assert_eq!(channel(&points, "FVeloc").quantity, Quantity::Speed);
3492        assert!(!commas.notes.iter().any(|n| n.contains("semicolons")));
3493        assert!(points.notes.iter().any(|n| n.ends_with(
3494            "separated by semicolons, as a European locale's export writes them; a number's \
3495             decimal mark is a point"
3496        )));
3497        assert!(decimal_commas.notes.iter().any(|n| n.ends_with(
3498            "separated by semicolons, as a European locale's export writes them; a number's \
3499             decimal mark is a comma"
3500        )));
3501        // A comma-separated file never reads a decimal comma, and a semicolon one never mixes the
3502        // marks: a cell in the other is refused, naming its line.
3503        let mixed = filtered_flight(";", 1.0, |cell| cell).replacen("0.25;", "0,25;", 1);
3504        assert!(matches!(
3505            read(&mixed),
3506            Err(LogError::Syntax { line: 7, ref message, .. }) if message.starts_with("\"0,25\"")
3507        ));
3508        // A point among decimal commas, as `1.250`, settles the file on points, so its first
3509        // decimal comma is refused: the marks are never mixed.
3510        let thousands = filtered_flight(";", 1.0, |cell| cell.replace('.', ",")).replacen(
3511            ";0;0\n",
3512            ";1.250;0\n",
3513            1,
3514        );
3515        assert!(matches!(read(&thousands), Err(LogError::Syntax { .. })));
3516    }
3517
3518    #[test]
3519    fn a_filtered_altitude_off_the_altitudes_scale_refuses_the_file() {
3520        // Written a hundred times its value, as a file whose decimal points were taken out: the
3521        // filter lags `Alt` at 0.923 times it, so the fit gives 92.319.
3522        let refused = read(&filtered_flight(";", 100.0, |cell| cell));
3523        assert!(
3524            matches!(
3525                &refused,
3526                Err(LogError::Unit { line: 1, message, .. }) if message.starts_with(
3527                    "`Filt_Alt` isn't a filter of `Alt`: it is 92.319 times `Alt` by a \
3528                     least-squares fit. That is outside the 0.1 to 2"
3529                )
3530            ),
3531            "{refused:?}"
3532        );
3533        // The band's edges: written 2.1 and 0.11 times, 1.939 and 0.102 times `Alt` by the fit,
3534        // the filtered altitude is read; at 2.2 and 0.105 times, 2.031 and 0.097, the file is
3535        // refused.
3536        for (scale, reads) in [(2.1, true), (0.11, true), (2.2, false), (0.105, false)] {
3537            match read(&filtered_flight(",", scale, |cell| cell)) {
3538                Ok(log) => {
3539                    assert!(reads, "{scale}");
3540                    assert_eq!(
3541                        channel(&log, "Filt_Alt").quantity,
3542                        Quantity::AltitudeAboveGround
3543                    );
3544                }
3545                Err(error) => assert!(
3546                    !reads && matches!(error, LogError::Unit { .. }),
3547                    "{scale}: {error}"
3548                ),
3549            }
3550        }
3551        // A factor that isn't a number refuses the file too.
3552        let huge = "T,Alt,FAlt\n0,1e200,1e200\n0.05,1e200,1e200\n";
3553        assert!(matches!(
3554            read(huge),
3555            Err(LogError::Unit { ref message, .. }) if message.contains("isn't a finite number")
3556        ));
3557        // An altitude of zero throughout has nothing to check against.
3558        let flat = "T,Alt,FAlt\n0,0,0\n0.05,0,5\n0.1,0,9\n";
3559        assert_eq!(
3560            channel(&read(flat).unwrap(), "FAlt").quantity,
3561            Quantity::AltitudeAboveGround
3562        );
3563    }
3564
3565    #[test]
3566    fn a_step_neither_seconds_nor_milliseconds_refuses_the_file() {
3567        // A seconds clock written without its decimal points: 0.05 s as 5.
3568        let stripped = "T,Alt,Veloc\n0,0,0\n5,10,200\n10,25,300\n15,40,300\n";
3569        assert!(matches!(
3570            read(stripped),
3571            Err(LogError::Unit { line: 1, ref message, .. })
3572                if message.starts_with("the median step between rows of `T` is 5. That")
3573        ));
3574        // The ends are each a unit's: a step of 1 is seconds, one of 30 milliseconds.
3575        let one = read("T,Alt,Veloc\n0,0,0\n1,10,10\n2,25,15\n").unwrap();
3576        assert_eq!(one.time_s, [0.0, 1.0, 2.0]);
3577        let thirty = read("T,Alt,Veloc\n0,0,0\n30,1,33\n60,2,33\n").unwrap();
3578        assert_eq!(thirty.time_s, [0.0, 0.03, 0.06]);
3579        let over = "T,Alt,Veloc\n0,0,0\n1.01,10,10\n2.02,25,15\n";
3580        assert!(matches!(read(over), Err(LogError::Unit { .. })));
3581        let under = "T,Alt,Veloc\n0,0,0\n29.9,1,33\n59.8,2,33\n";
3582        assert!(matches!(read(under), Err(LogError::Unit { .. })));
3583    }
3584
3585    #[test]
3586    fn a_semicolon_in_a_channel_name_keeps_a_comma_file_a_comma_file() {
3587        let log = read("T,Alt,Veloc,LDA,Apogee,Dr;1\n0,0,0,0,0,0\n0.05,1,20,0,0,0\n").unwrap();
3588        assert_eq!(log.channels.last().unwrap().column, "Dr;1");
3589        assert!(!log.notes.iter().any(|n| n.contains("semicolons")));
3590    }
3591
3592    /// An unknown column before `LDA` is kept as written; after it, it is a marker with events.
3593    #[test]
3594    fn unknown_columns_are_kept_and_named_channels_are_markers() {
3595        let log = read("T,Alt,Veloc,Baro,LDA,Apogee,Drogue.1\n0,0,0,7,0,0,0\n0.05,4,80,8,4,0,4\n")
3596            .unwrap();
3597        assert_eq!(log.channels[2].quantity, Quantity::Unrecognized);
3598        assert_eq!(log.channels[2].values, [7.0, 8.0]);
3599        let names: Vec<&str> = log.events.iter().map(|event| event.name.as_str()).collect();
3600        assert_eq!(names, ["LDA", "Drogue.1"]);
3601        let notes = log.notes.join("\n");
3602        assert!(notes.contains("\"Baro\" isn't one this reader knows, and was kept as written"));
3603        assert!(notes.contains("\"Drogue.1\" isn't one this reader knows; it comes after `LDA`"));
3604    }
3605
3606    /// Rows of empty cells are skipped and counted; an empty cell and a short row leave gaps.
3607    #[test]
3608    fn empty_rows_are_skipped_and_empty_cells_are_gaps() {
3609        let text = format!(
3610            "{TRS}\r\n0,0,0,0,0,0,0,0,0,0,0\r\n0.05,2,,1,20,0,0,0,0,0,0\r\n0.1,5,60\r\n\
3611             ,,,,,,,,,,\r\n,,,,,,,,,,\r\n , ,\r\n"
3612        );
3613        let log = read(&text).unwrap();
3614        assert_eq!(log.time_s, [0.0, 0.05, 0.1]);
3615        assert!(log.channels[1].values[1].is_nan());
3616        assert!(log.channels[2].values[2].is_nan());
3617        let notes = log.notes.join("\n");
3618        assert!(
3619            notes.contains("3 rows hold only empty cells, and were skipped"),
3620            "{notes}"
3621        );
3622        assert!(notes.contains("the column \"Veloc\" leaves 1 cell empty: it is a gap"));
3623        assert!(notes.contains("the column \"Main\" leaves 1 cell empty: it is a gap"));
3624    }
3625
3626    /// Each refusal names its line and what is wrong.
3627    #[test]
3628    fn malformed_files_are_refused_where_they_go_wrong() {
3629        let cases = [
3630            (String::new(), "the file is empty"),
3631            ("\r\n\r\n".to_owned(), "the file is empty"),
3632            (
3633                "Time,Altitude\n0,0\n".to_owned(),
3634                "isn't an Eggtimer header row",
3635            ),
3636            (format!("{TRS}\n"), "no data rows"),
3637            (format!("{TRS}\n,,,,,,,,,,\n"), "no data rows"),
3638            (
3639                "T,Alt,,LDA\n".to_owned(),
3640                "line 1: the header's column 3 has no name",
3641            ),
3642            (
3643                "T,Alt,LDA\n0,0,0,0\n".to_owned(),
3644                "line 2: the row has 4 cells and the header names 3",
3645            ),
3646            (
3647                "T,Alt,LDA\n0,0,0\n0.05,x,0\n".to_owned(),
3648                "line 3: \"x\" in cell 2, under \"Alt\", isn't a number",
3649            ),
3650            (
3651                "T,Alt,LDA\n0,0,0\n0.05,1,NaN\n".to_owned(),
3652                "line 3: \"NaN\" in cell 3, under \"LDA\"",
3653            ),
3654            (
3655                "T,Alt,LDA\nx,0,0\n".to_owned(),
3656                "line 2: \"x\" in cell 1, under \"T\"",
3657            ),
3658            (
3659                "T,Alt,LDA\n,0,0\n".to_owned(),
3660                "line 2: the time, the row's first cell, is empty",
3661            ),
3662            (
3663                "T,Alt,LDA\n0,0,0\n0,1,0\n".to_owned(),
3664                "line 3: the time 0 comes at or before the one above it, 0",
3665            ),
3666            (
3667                "T,Alt,LDA\n\n1,0,0\n\n0.5,1,0\n".to_owned(),
3668                "line 5: the time 0.5 comes at or before",
3669            ),
3670        ];
3671        for (text, expected) in cases {
3672            let error = read(&text).unwrap_err().to_string();
3673            assert!(error.contains(expected), "{text:?}: {error}");
3674        }
3675    }
3676
3677    /// A value in g near the largest `f64` is finite as written and infinite in m/s²: refused on
3678    /// its line, in the CSV and in the terminal download, whose table is the same (ADR-258 §3).
3679    #[test]
3680    fn a_value_its_conversion_makes_infinite_is_refused() {
3681        let csv = "T,Alt,AccelG,LDA\n0,0,1,0\n0.05,1,-1.7e308,0\n";
3682        assert_eq!(
3683            read(csv).unwrap_err().to_string(),
3684            "Eggtimer CSV line 3: the column AccelG holds a value too large for its unit's \
3685             conversion to SI"
3686        );
3687        // The download's table: the invented flight's `T` and `Alt`, with `AccelG` beside them.
3688        let rows: String = flight(1000.0, 0.05, G_FT, None, 15.0)
3689            .lines()
3690            .enumerate()
3691            .map(|(row, line)| {
3692                let cells: Vec<&str> = line.split(',').take(2).collect();
3693                let g = if row == 1 { "-1.7e308" } else { "1" };
3694                format!("{},{g},0\n", cells.join(","))
3695            })
3696            .collect();
3697        let text =
3698            format!("Eggtimer TRS 2.07 Flight Settings\n...Units...Feet\nT,Alt,AccelG,LDA\n{rows}");
3699        assert_eq!(
3700            read_text(&text).unwrap_err().to_string(),
3701            "Eggtimer text line 5: the column AccelG holds a value too large for its unit's \
3702             conversion to SI"
3703        );
3704        // The largest value that stays finite in m/s² is read.
3705        let largest = f64::MAX / 9.806_65;
3706        let log = read(&format!("T,Alt,AccelG\n0,0,{largest:e}\n")).unwrap();
3707        assert!(log.channels[1].values[0].is_finite());
3708    }
3709
3710    /// A wide header over short rows is refused before its columns are allocated.
3711    #[test]
3712    fn a_wide_header_over_short_rows_is_refused() {
3713        let names: String = (0..2000).map(|i| format!(",u{i}")).collect();
3714        let rows = "0\n".repeat(200);
3715        let text = format!("T,Alt,LDA{names}\n{rows}");
3716        let error = read(&text).unwrap_err().to_string();
3717        assert!(
3718            error.contains("too few for the header to be this file's"),
3719            "{error}"
3720        );
3721    }
3722
3723    /// CR, LF, CR LF and CR CR LF line ends read the same.
3724    #[test]
3725    fn line_ends() {
3726        let rows = ["T,Alt,Veloc,LDA", "0,0,0,0", "0.05,2,40,0", "0.1,6,80,6"];
3727        let reference = read(&rows.join("\n")).unwrap();
3728        for end in ["\r", "\n", "\r\n", "\r\r\n"] {
3729            let text = format!("{}{end}", rows.join(end));
3730            assert_eq!(read(&text).unwrap(), reference, "{end:?}");
3731        }
3732        assert_eq!(reference.events.len(), 1);
3733    }
3734
3735    /// A header of many unknown columns keeps a short list of notes and counts the rest; the unit
3736    /// notes stay outside the cap.
3737    #[test]
3738    fn notes_stay_few() {
3739        let unknown: String = (0..100).map(|i| format!(",u{i}")).collect();
3740        let text = format!("T,Alt,Veloc{unknown}\n0,0,0{}\n", ",1".repeat(100));
3741        let log = read(&text).unwrap();
3742        assert_eq!(log.channels.len(), 102);
3743        // `T`, `Alt` and `Veloc`'s unit notes, 20 notes about columns, and one counting the rest.
3744        assert_eq!(log.notes.len(), 3 + 20 + 1, "{:?}", log.notes);
3745        assert!(
3746            log.notes[23].starts_with("and 80 more notes"),
3747            "{:?}",
3748            log.notes[23]
3749        );
3750    }
3751
3752    /// A file that isn't text is refused with a short quote of it.
3753    #[test]
3754    fn a_long_line_is_quoted_short() {
3755        let junk = "\u{fffd}".repeat(100_000);
3756        let error = read(&junk).unwrap_err().to_string();
3757        assert!(error.len() < 400, "{} bytes", error.len());
3758    }
3759
3760    #[test]
3761    fn numbers_are_written_plainly() {
3762        assert_eq!(plain(0.050_000_000_000_000_71, 4), "0.05");
3763        assert_eq!(plain(50.0, 4), "50");
3764        assert_eq!(plain(32.166, 2), "32.17");
3765        assert_eq!(plain(-0.0, 2), "-0");
3766    }
3767
3768    /// Feet's standard gravity, ft/s².
3769    const G_FT: f64 = 32.174;
3770
3771    /// A charge before the top: when it fires, s, and its canopy's descent rate, the table's unit
3772    /// a second.
3773    type Drogue = Option<(f64, f64)>;
3774
3775    /// An invented flight's table rows, in the TRS layout (`TRS`): a boost of 1 s, then a coast
3776    /// slowing at `slowing` the table's unit a second squared (`G_FT` for 1 g in feet), topping
3777    /// out at 10 s; or, if `drogue` fires first, a canopy's drag `slowing (v / v_t)²` added from
3778    /// then on, `v_t` its descent rate, closed-form; then a descent at 40 a second to `end_s`. A
3779    /// row every `step_s`, `T` written `per_second` to the second, `Alt` in whole units, `Veloc`
3780    /// and `FVeloc` its change over the step, `FAlt` equal to it; `LDA` at 0.1 s, `LowV` at 5 s,
3781    /// `Apogee` at the top, `N-O` and `Drogue` at the drogue's time or 10.5 s.
3782    fn flight(per_second: f64, step_s: f64, slowing: f64, drogue: Drogue, end_s: f64) -> String {
3783        let boost = 9.0 * slowing;
3784        let coast = |t: f64| boost / 2.0 + boost * (t - 1.0) - slowing * (t - 1.0).powi(2) / 2.0;
3785        let altitude = |t: f64| -> f64 {
3786            if t <= 1.0 {
3787                return boost * t * t / 2.0;
3788            }
3789            match drogue {
3790                Some((at, rate)) if t > at => {
3791                    let angle = (slowing * (10.0 - at) / rate).atan();
3792                    let stop = at + rate * angle / slowing;
3793                    let rise = |t: f64| {
3794                        coast(at)
3795                            + rate * rate / slowing
3796                                * ((angle - slowing * (t - at) / rate).cos() / angle.cos()).ln()
3797                    };
3798                    if t <= stop {
3799                        rise(t)
3800                    } else {
3801                        rise(stop) - 40.0 * (t - stop)
3802                    }
3803                }
3804                _ if t <= 10.0 => coast(t),
3805                _ => coast(10.0) - 40.0 * (t - 10.0),
3806            }
3807        };
3808        let count = (end_s / step_s).round() as usize;
3809        let times: Vec<f64> = (0..=count).map(|row| row as f64 * step_s).collect();
3810        let heights: Vec<f64> = times.iter().map(|t| altitude(*t).round()).collect();
3811        let at = |time: f64| (time / step_s).round() as usize;
3812        let top = at(match drogue {
3813            Some((time, rate)) if time < 10.0 => {
3814                time + rate * (slowing * (10.0 - time) / rate).atan() / slowing
3815            }
3816            _ => 10.0,
3817        });
3818        let deploy = at(drogue.map_or(10.5, |(time, _)| time));
3819        let mut text = String::new();
3820        for (row, (t, h)) in times.iter().zip(&heights).enumerate() {
3821            let speed = row
3822                .checked_sub(1)
3823                .map_or(0.0, |up| (h - heights[up]) / step_s);
3824            let mark = |on: bool| if on { *h } else { 0.0 };
3825            text.push_str(&format!(
3826                "{},{h},{speed:.2},{h:.2},{speed:.2},{},{},{},{},{},0\n",
3827                (t * per_second * 1000.0).round() / 1000.0,
3828                mark(row == at(0.1)),
3829                mark(row == at(5.0)),
3830                mark(row == top),
3831                mark(row == deploy),
3832                mark(row == deploy),
3833            ));
3834        }
3835        text
3836    }
3837
3838    /// The invented flight's table in milliseconds, a row every 50 ms, with no charge before its
3839    /// top and its header.
3840    fn table() -> String {
3841        format!("{TRS}\n{}", flight(1000.0, 0.05, G_FT, None, 15.0))
3842    }
3843
3844    /// An invented terminal download: firmware 2.07's spellings, the table in milliseconds.
3845    fn download() -> String {
3846        format!(
3847            "Flight Summary:\n\
3848             \n\
3849             Eggtimer TRS 2.07    Flight Settings\n\
3850             ...Drogue <1=Normal,2=Backup,0=OFF>...1\n\
3851             ...Main Altitude <50-2000 by 50, 0=OFF>...300\n\
3852             ...Frequency (Ctrl-F to change)...915\n\
3853             ...ID Code...4\n\
3854             ...SECRET NAME\n\
3855             ASL Alt.: 1000 ft\n\
3856             Base Temp: 20.5 C\n\
3857             Last Flight Phase: 9\n\
3858             Apogee: 1448 ft\n\
3859             T @ Apogee: 10.000\n\
3860             Max Velocity: 290 ft/sec\n\
3861             T @ Max Velocity: 1.000\n\
3862             Time @ LDA:0.100\n\
3863             Altitude @ Main Deploy: 0 ft\n\
3864             T @ Main Deploy: 0.000\n\
3865             {}",
3866            table()
3867        )
3868    }
3869
3870    #[test]
3871    fn recognizes_the_terminal_download_and_no_other_layout() {
3872        let table = table();
3873        for text in [
3874            download(),
3875            format!("Eggtimer TRS 2.10    Flight Settings\r{table}"),
3876            format!("\u{feff}Eggtimer TRS 2.07\nFlight Settings\n...ID Code...0\n{table}"),
3877            format!("Flight Summary:\nEggtimer Flight Settings\n{table}"),
3878            format!("Saved Flight Summary\nEggtimer TRS 2.07 Flight Settings\n{table}"),
3879        ] {
3880            assert!(recognizes_text(&text), "{text:?}");
3881            assert!(read_text(&text).is_ok(), "{text:?}");
3882        }
3883        for text in [
3884            String::new(),
3885            table.clone(),
3886            download().replace("Flight Settings", "Settings"),
3887            format!("Eggtimer TRS 2.07\nFlight Summary:\n{table}"),
3888            format!("{table}Eggtimer TRS 2.07 Flight Settings\n{table}"),
3889            "Eggtimer TRS 2.07 Flight Settings\nTime,Altitude,Velocity\n0,0,0\n".to_owned(),
3890            "Eggtimer TRS 2.07 Flight Settings\nT,Alt\n0,0\n".to_owned(),
3891            format!(
3892                "Eggtimer TRS 2.07 Flight Settings\n{}{table}",
3893                "Beep Code: 0\n".repeat(MAX_PREAMBLE_LINES)
3894            ),
3895            "PerfectFlite Pnut\nEggtimer TRS 2.07 Flight Settings\n".to_owned(),
3896        ] {
3897            assert!(!recognizes_text(&text), "{text:?}");
3898            assert!(
3899                matches!(
3900                    read_text(&text),
3901                    Err(LogError::NotThisFormat {
3902                        format: TEXT_FORMAT,
3903                        ..
3904                    })
3905                ),
3906                "{text:?}"
3907            );
3908        }
3909        // The preamble may fill all but the header's line of those looked through.
3910        let full = format!(
3911            "Eggtimer TRS 2.07 Flight Settings\n{}{table}",
3912            "Beep Code: 0\n".repeat(MAX_PREAMBLE_LINES - 2)
3913        );
3914        assert!(recognizes_text(&full));
3915        // The CSV download isn't this layout, nor this one the CSV's.
3916        assert!(recognizes(&table) && !recognizes(&download()));
3917    }
3918
3919    /// The title, the settings, the summary's heights and times, and the table, as the module's
3920    /// documentation says each is read.
3921    #[test]
3922    fn reads_the_settings_the_summary_and_the_table() {
3923        let log = read_text(&download()).unwrap();
3924        assert_eq!(log.format, LogFormat::EggtimerText);
3925        assert_eq!(log.logger, "Eggtimer TRS");
3926        assert_eq!(log.firmware.as_deref(), Some("2.07"));
3927        assert_eq!(log.time_s.len(), 301);
3928        assert_eq!(log.time_s[..3], [0.0, 0.05, 0.1]);
3929        assert!(close(log.stated.apogee_m.unwrap(), 1448.0 * 0.3048));
3930        assert!(close(
3931            log.stated.ground_elevation_msl_m.unwrap(),
3932            1000.0 * 0.3048
3933        ));
3934        assert_eq!(log.stated.samples, None);
3935        // The table's markers, and the summary's `Max Velocity`, which no marker marks, in time
3936        // order; `Apogee` and `LDA` are their markers', and `Main Deploy` at 0 is no event.
3937        let events: Vec<(f64, &str)> = log
3938            .events
3939            .iter()
3940            .map(|event| (event.time_s, event.name.as_str()))
3941            .collect();
3942        assert_eq!(
3943            events,
3944            [
3945                (0.1, "LDA"),
3946                (1.0, "Max Velocity"),
3947                (5.0, "LowV"),
3948                (10.0, "Apogee"),
3949                (10.5, "N-O"),
3950                (10.5, "Drogue")
3951            ]
3952        );
3953        let notes = &log.notes[6..];
3954        assert_eq!(
3955            notes,
3956            [
3957                "`ASL Alt.` read in feet, from its unit mark: the flight summary writes 1000 ft; \
3958                 the launch site's elevation above sea level, as the logger measured it (TRS \
3959                 manual p36)",
3960                "`Apogee` read in feet, from its unit mark: the flight summary writes 1448 ft; \
3961                 the logger's apogee above its zero, kept beside the table's altitudes (TRS \
3962                 manual p36)",
3963                "`T @` and `Time @` read in seconds, from the manual: the TRS manual's download \
3964                 writes the flight summary's times in `secs.` (p36). The same download writes its LDA \
3965                 at 0.700 secs. as \"700ms into the flight\" (p37)",
3966                "the flight summary's times are its table markers' to the millisecond, one event \
3967                 each, the marker's: `Apogee` at `Apogee`, `LDA` at `LDA`",
3968                "the flight summary's times of no marker in the table, each an event of its own: \
3969                 `Max Velocity`",
3970                "the flight summary's times of 0, no event, as the TRS manual writes zeroes for a \
3971                 channel that didn't fire (p25): `Main Deploy`",
3972                "the flight settings, as the file writes them: `Drogue <1=Normal,2=Backup,0=OFF>` \
3973                 1; `Main Altitude <50-2000 by 50, 0=OFF>` 300; `Frequency (Ctrl-F to change)` \
3974                 915; `ID Code` 4",
3975                "1 line of the flight settings holds no setting: the name its owner gave the \
3976                 flight computer (TRS manual p24). The name is left out of the record as free text \
3977                 that may name a person",
3978                "the flight summary's other lines, as the file writes them: `Base Temp: 20.5 C`; \
3979                 `Last Flight Phase: 9` (landing detected, TRS manual p37); `Max Velocity: 290 \
3980                 ft/sec`; `Altitude @ Main Deploy: 0 ft`",
3981            ]
3982        );
3983        assert!(
3984            log.notes[0].starts_with("`T` read in milliseconds, from the step and the coast: ")
3985        );
3986        assert!(log.notes[1].starts_with("`Alt` read in feet, from the manual and the coast: "));
3987        assert!(log.notes[3].starts_with("`FAlt` read in feet, from the manual and the coast: "));
3988        // The owner's name for the flight computer is nowhere in the record.
3989        let json = serde_json::to_string(&log).unwrap();
3990        assert!(!json.contains("SECRET"));
3991    }
3992
3993    /// A time with its unit mark, a time that isn't its marker's, a height in meters, one with no
3994    /// unit mark, a repeated one, and lines before the title.
3995    #[test]
3996    fn summary_lines_read_by_what_they_state() {
3997        let text = format!(
3998            "Captured with a terminal\n\
3999             Eggtimer TRS 2.07    Flight Settings\n\
4000             Apogee: 9 m\n\
4001             Apogee: 30 ft\n\
4002             ASL Alt.: 1000\n\
4003             T @ Apogee: 10.100 secs.\n\
4004             T @ Nose-Over: 10.5 s\n\
4005             T @ Unlock: soon\n\
4006             a line with no colon\n\
4007             {}",
4008            table()
4009        );
4010        let log = read_text(&text).unwrap();
4011        assert_eq!(log.stated.apogee_m, Some(9.0));
4012        assert_eq!(log.stated.ground_elevation_msl_m, None);
4013        let names: Vec<(f64, &str)> = log
4014            .events
4015            .iter()
4016            .map(|event| (event.time_s, event.name.as_str()))
4017            .collect();
4018        assert_eq!(
4019            names,
4020            [
4021                (0.1, "LDA"),
4022                (5.0, "LowV"),
4023                (10.0, "Apogee"),
4024                (10.1, "Apogee"),
4025                (10.5, "N-O"),
4026                (10.5, "Drogue")
4027            ]
4028        );
4029        let has = |wanted: &str| log.notes.iter().any(|note| note == wanted);
4030        assert!(has(
4031            "`Apogee` read in meters, from its unit mark: the flight summary writes 9 m; the \
4032             logger's apogee above its zero, kept beside the table's altitudes (TRS manual p36)"
4033        ));
4034        assert!(has(
4035            "`ASL Alt.` kept as written, with no unit mark the reader knows: the flight summary \
4036             writes \"1000\", where the TRS manual's writes `ft` (p36)"
4037        ));
4038        assert!(has(
4039            "`T @` and `Time @` read in seconds, from their unit mark: the flight summary writes \
4040             `secs.` after each, as the TRS manual's download does (p36)"
4041        ));
4042        assert!(has(
4043            "the flight summary's times that differ from their markers' in the table, both kept \
4044             as events: `Apogee` at 10.1 s, the marker `Apogee` at 10 s"
4045        ));
4046        assert!(has(
4047            "the flight summary's times are its table markers' to the millisecond, one event \
4048             each, the marker's: `Nose-Over` at `N-O`"
4049        ));
4050        assert!(has(
4051            "the flight summary's other lines, as the file writes them: `Apogee: 30 ft`; `ASL \
4052             Alt.: 1000`; `T @ Unlock: soon`; `a line with no colon`"
4053        ));
4054        assert!(has(
4055            "1 lines before the title `Eggtimer … Flight Settings` weren't read"
4056        ));
4057    }
4058
4059    /// What the table refuses is refused naming the file's line, and the download's format.
4060    #[test]
4061    fn the_tables_errors_name_the_files_line() {
4062        let bad = download().replacen("\n100,1,", "\n100,x,", 1);
4063        assert_eq!(
4064            read_text(&bad).unwrap_err(),
4065            LogError::Syntax {
4066                format: TEXT_FORMAT,
4067                line: 22,
4068                message: "\"x\" in cell 2, under \"Alt\", isn't a number".to_owned(),
4069            }
4070        );
4071        let cr = bad.replace('\n', "\r");
4072        assert!(matches!(
4073            read_text(&cr),
4074            Err(LogError::Syntax { line: 22, .. })
4075        ));
4076        let download = download();
4077        let headless = download
4078            .split_once("0,0,0.00")
4079            .map(|(head, _)| head)
4080            .unwrap();
4081        assert_eq!(
4082            read_text(headless).unwrap_err(),
4083            LogError::NoData {
4084                format: TEXT_FORMAT
4085            }
4086        );
4087    }
4088
4089    /// A long preamble's notes list at most [`MAX_PREAMBLE_ITEMS`] lines, each cut short.
4090    #[test]
4091    fn the_preamble_notes_stay_short() {
4092        let settings: String = (0..150)
4093            .map(|index| format!("...Setting {index} {}...1\n", "y".repeat(500)))
4094            .collect();
4095        let times: String = (0..30)
4096            .map(|index| format!("T @ Thing {index}: {}.5\n", index + 1))
4097            .collect();
4098        // A table in seconds out to 40 s, past the last time, so every time is an event.
4099        let rows = flight(1.0, 0.05, G_FT, None, 40.0);
4100        let text = format!(
4101            "Eggtimer {} 9.99 Flight Settings\n{settings}{times}{TRS}\n{rows}",
4102            "Z".repeat(500)
4103        );
4104        let log = read_text(&text).unwrap();
4105        assert!(log.logger.chars().count() < 100);
4106        assert_eq!(log.firmware.as_deref(), Some("9.99"));
4107        // The 30 times, and the table's 5 markers.
4108        assert_eq!(log.events.len(), 35);
4109        let settings = log
4110            .notes
4111            .iter()
4112            .find(|note| note.starts_with("the flight settings"))
4113            .unwrap();
4114        assert!(settings.ends_with("; and 110 more"), "{settings}");
4115        assert!(settings.len() < 40 * 100 + 200, "{} bytes", settings.len());
4116        for note in &log.notes {
4117            assert!(note.len() < 5_000, "{} bytes", note.len());
4118        }
4119    }
4120
4121    /// The invented flight as a terminal download, its table changed row by row by `change`, which
4122    /// gets each row's index and cells.
4123    fn coast_download(table: &str, change: impl Fn(usize, &mut Vec<String>)) -> String {
4124        let rows: String = table
4125            .lines()
4126            .enumerate()
4127            .map(|(row, line)| {
4128                let mut cells: Vec<String> = line.split(',').map(str::to_owned).collect();
4129                change(row, &mut cells);
4130                format!("{}\n", cells.join(","))
4131            })
4132            .collect();
4133        format!("Eggtimer TRS 2.07 Flight Settings\n{TRS}\n{rows}")
4134    }
4135
4136    /// The note that opens with `prefix`, or a panic listing the notes.
4137    fn note_from<'a>(log: &'a FlightLog, prefix: &str) -> &'a str {
4138        log.notes
4139            .iter()
4140            .find(|note| note.starts_with(prefix))
4141            .unwrap_or_else(|| panic!("no note opens with {prefix:?}: {:#?}", log.notes))
4142    }
4143
4144    /// The slowing, in g, a note gives after `slows at`, for `unit`, `feet` or `meters`.
4145    fn slowing_g(note: &str, unit: &str) -> f64 {
4146        let after = note.split("slows at ").nth(1).unwrap_or_default();
4147        let (number, rest) = after.split_once(" g in ").unwrap_or_default();
4148        if rest.starts_with(unit) {
4149            return number.parse().unwrap();
4150        }
4151        // The other unit follows: `… g in feet and … g in meters`.
4152        let other = rest.split(" and ").nth(1).unwrap_or_default();
4153        let (number, rest) = other.split_once(" g in ").unwrap_or_default();
4154        assert!(rest.starts_with(unit), "{note}");
4155        number.parse().unwrap()
4156    }
4157
4158    /// A clock in milliseconds or in seconds, and an altitude in feet, each pass both of their
4159    /// checks: the coast slows at 1 g in feet on the step's clock.
4160    #[test]
4161    fn the_coast_bears_out_the_clock_and_feet() {
4162        for (per_second, unit) in [(1000.0, "milliseconds"), (1.0, "seconds")] {
4163            let text = coast_download(&flight(per_second, 0.05, G_FT, None, 15.0), |_, _| {});
4164            let log = read_text(&text).unwrap();
4165            assert_eq!(log.time_s.len(), 301);
4166            assert!(close(log.time_s[200], 10.0));
4167            let clock = note_from(&log, "`T` read in ");
4168            assert!(
4169                clock.starts_with(&format!(
4170                    "`T` read in {unit}, from the step and the coast: the median step between \
4171                     rows is "
4172                )),
4173                "{clock}"
4174            );
4175            // The window ends at the top: the first row of the highest whole foot, 9.9 s.
4176            assert!(
4177                clock.contains(
4178                    " g in feet over the rows from 6.9 s to 9.9 s, up to the altitude's top. \
4179                     The reader takes 0.7 to 1.3 g in feet or in meters, and a clock 1,000 \
4180                     times off would put that slowing 10⁶ times off"
4181                ),
4182                "{clock}"
4183            );
4184            assert!((slowing_g(clock, "feet") - 1.0).abs() < 0.01, "{clock}");
4185            let alt = note_from(&log, "`Alt` ");
4186            assert!(
4187                alt.starts_with(
4188                    "`Alt` read in feet, from the manual and the coast: the Classic and TRS \
4189                     manuals (p37) state feet. The Quantum and Proton manuals give every height \
4190                     in feet, and no Eggtimer manual offers meters. Over the rows from 6.9 s to \
4191                     9.9 s, up to the altitude's top, it slows at "
4192                ),
4193                "{alt}"
4194            );
4195            assert!(alt.contains(" g in feet, within the 0.7 to 1.3 g the reader takes. In"));
4196            assert!((slowing_g(alt, "feet") - 1.0).abs() < 0.01, "{alt}");
4197            assert!(note_from(&log, "`FAlt` ").starts_with("`FAlt` read in feet, from the "));
4198            assert!(note_from(&log, "`Veloc` ").starts_with("`Veloc` read in feet per second"));
4199            assert_eq!(log.channels[0].quantity, Quantity::AltitudeAboveGround);
4200            assert_eq!(log.channels[2].quantity, Quantity::AltitudeAboveGround);
4201            assert!(close(log.altitude_m[200], 1448.0 * FOOT_M));
4202            assert!(log.vertical_speed_m_s.is_some());
4203        }
4204    }
4205
4206    /// A table in meters slows at 1 g in meters: the clock is borne out, as a clock 1,000 times
4207    /// off would put the slowing 10⁶ times off, but the manuals' feet aren't, so `Alt` and
4208    /// `FAlt`, and the speeds that are their change, are kept as written.
4209    #[test]
4210    fn an_altitude_in_meters_is_kept_as_written() {
4211        let text = coast_download(
4212            &flight(1000.0, 0.05, STANDARD_GRAVITY_MPS2, None, 15.0),
4213            |_, _| {},
4214        );
4215        let log = read_text(&text).unwrap();
4216        let clock = note_from(&log, "`T` ");
4217        assert!(clock.starts_with("`T` read in milliseconds, from the step and the coast"));
4218        assert!(
4219            clock.contains(" g in meters over the rows from "),
4220            "{clock}"
4221        );
4222        assert!((slowing_g(clock, "meters") - 1.0).abs() < 0.02, "{clock}");
4223        let alt = note_from(&log, "`Alt` ");
4224        assert!(
4225            alt.starts_with(
4226                "`Alt` kept as written: the manuals give feet, but over the rows from "
4227            ),
4228            "{alt}"
4229        );
4230        assert!(alt.ends_with(
4231            " g in meters. The reader takes 0.7 to 1.3 g in feet. The record holds no \
4232             barometric altitude"
4233        ));
4234        assert!((slowing_g(alt, "feet") - FOOT_M).abs() < 0.01, "{alt}");
4235        assert!((slowing_g(alt, "meters") - 1.0).abs() < 0.02, "{alt}");
4236        let falt = note_from(&log, "`FAlt` ");
4237        assert!(
4238            falt.starts_with(
4239                "`FAlt` kept as written: the manuals give it in feet, as the logger's filtered \
4240                 `Alt` (Quantum p38, Proton p45). But over the rows from "
4241            ),
4242            "{falt}"
4243        );
4244        assert!(falt.ends_with(" g in feet, outside the 0.7 to 1.3 g the reader takes"));
4245        assert_eq!(
4246            note_from(&log, "`Veloc` "),
4247            "`Veloc` kept as written: it is the change in `Alt` over the step, and `Alt` is kept \
4248             as written"
4249        );
4250        assert_eq!(
4251            note_from(&log, "`FVeloc` "),
4252            "`FVeloc` kept as written: it is the change in `FAlt` over the step, and `FAlt` is \
4253             kept as written"
4254        );
4255        for channel in &log.channels[..4] {
4256            assert_eq!(
4257                channel.quantity,
4258                Quantity::Unrecognized,
4259                "{}",
4260                channel.column
4261            );
4262        }
4263        // As written: whole meters.
4264        assert_eq!(log.channels[0].values[200], 441.0);
4265        assert!(log.altitude_m.is_empty());
4266        assert_eq!(log.vertical_speed_m_s, None);
4267    }
4268
4269    /// A filtered altitude in another unit than `Alt`'s is kept as written on its own check, with
4270    /// its speed; `Alt` is still read in feet.
4271    #[test]
4272    fn a_filtered_altitude_the_coast_doesnt_bear_out_is_kept() {
4273        let table = flight(1000.0, 0.05, G_FT, None, 15.0);
4274        let text = coast_download(&table, |row, cells| {
4275            let meters = |cells: &[String]| cells[1].parse::<f64>().unwrap() * FOOT_M;
4276            let up: Option<f64> = row
4277                .checked_sub(1)
4278                .and_then(|up| table.lines().nth(up))
4279                .map(|line| line.split(',').map(str::to_owned).collect::<Vec<_>>())
4280                .map(|cells| meters(&cells));
4281            let here = meters(cells);
4282            cells[3] = format!("{here:.2}");
4283            cells[4] = format!("{:.2}", up.map_or(0.0, |up| (here - up) / 0.05));
4284        });
4285        let log = read_text(&text).unwrap();
4286        assert!(note_from(&log, "`Alt` ").starts_with("`Alt` read in feet, from the manual and"));
4287        assert!(note_from(&log, "`FAlt` ").starts_with("`FAlt` kept as written: "));
4288        let falt = note_from(&log, "`FAlt` ");
4289        assert!(falt.ends_with(" g in feet, outside the 0.7 to 1.3 g the reader takes"));
4290        assert!((slowing_g(falt, "feet") - FOOT_M).abs() < 0.01, "{falt}");
4291        assert!(note_from(&log, "`FVeloc` ").starts_with("`FVeloc` kept as written: "));
4292        assert_eq!(log.channels[0].quantity, Quantity::AltitudeAboveGround);
4293        assert_eq!(log.channels[2].quantity, Quantity::Unrecognized);
4294        assert_eq!(log.channels[3].quantity, Quantity::Unrecognized);
4295        assert!(close(log.altitude_m[200], 1448.0 * FOOT_M));
4296    }
4297
4298    /// A coast window cut short at more than `COAST_CUTS` jumps is refused, in a bounded search.
4299    #[test]
4300    fn a_coast_cut_at_every_few_rows_is_refused_after_a_bounded_search() {
4301        // A spike on every third row of a long climb, one row a second: each cut ends the window
4302        // a few rows earlier, and with no bound the cuts would run back to the first row, each
4303        // costing a search of the rows before it, quadratic in the rows.
4304        let mut text = String::from("Eggtimer TRS 2.07 Flight Settings\nT,Alt,Apogee\n");
4305        for row in 0..20_000 {
4306            let spike = if row % 3 == 1 { 100_000 } else { 0 };
4307            text.push_str(&format!("{row},{},0\n", row + spike));
4308        }
4309        let error = read_text(&text).unwrap_err().to_string();
4310        assert!(
4311            error.contains(&format!(
4312                "the coast window is cut short more than {COAST_CUTS} times by jumps or motor \
4313                 markers before the top"
4314            )),
4315            "{error}"
4316        );
4317    }
4318
4319    /// A clock in milliseconds written 250 times a second, a step of 4, reads as seconds by its
4320    /// step; on that clock the coast's 3 s hold one row, and the file is refused. So is a coast
4321    /// that slows at g in neither feet nor meters, and a table with no coast.
4322    #[test]
4323    fn a_clock_the_coast_doesnt_bear_out_is_refused() {
4324        let text = coast_download(&flight(1000.0, 0.004, G_FT, None, 12.0), |_, _| {});
4325        let error = read_text(&text).unwrap_err();
4326        let LogError::Unit {
4327            format: TEXT_FORMAT,
4328            line: 2,
4329            message,
4330        } = &error
4331        else {
4332            panic!("{error:?}");
4333        };
4334        assert!(
4335            message.starts_with(
4336                "the clock `T` is in seconds by its step, but no coast bears that out: "
4337            ),
4338            "{message}"
4339        );
4340        // A coast slowing at 3 g in feet, 9.84 g in meters, is gravity in neither unit.
4341        let text = coast_download(&flight(1000.0, 0.05, 3.0 * G_FT, None, 15.0), |_, _| {});
4342        let error = read_text(&text).unwrap_err().to_string();
4343        assert!(
4344            error.starts_with(
4345                "Eggtimer text line 2: the clock `T` is in milliseconds by its step. But on that \
4346                 clock `Alt` slows at 3 g in feet and 9.841 g in meters over the rows from "
4347            ),
4348            "{error}"
4349        );
4350        assert!(error.ends_with(". Neither is in the 0.7 to 1.3 g the reader takes"));
4351        // A table of one row has neither a step nor a coast.
4352        let one = coast_download("0,0,0,0,0,0,0,0,0,0,0", |_, _| {});
4353        assert!(matches!(
4354            read_text(&one),
4355            Err(LogError::Unit { message, .. }) if message.starts_with(
4356                "the clock `T` can't be settled: the table holds one row"
4357            )
4358        ));
4359        // A table that stops before its top has no coast up to it.
4360        let short = coast_download(&flight(1000.0, 0.05, G_FT, None, 1.5), |_, _| {});
4361        let error = read_text(&short).unwrap_err().to_string();
4362        assert!(
4363            error.contains("is in milliseconds by its step, but no coast bears that out: "),
4364            "{error}"
4365        );
4366    }
4367
4368    /// A charge before the top, a drogue out at 9.5 s: the coast ends at the row before its
4369    /// marker, and its canopy's drag is left out; without the marker, the window would run on
4370    /// through the canopy to the top at 9.7 s.
4371    #[test]
4372    fn a_charge_before_the_top_ends_the_coast() {
4373        let text = coast_download(
4374            &flight(1000.0, 0.05, G_FT, Some((9.5, 10.0)), 15.0),
4375            |_, _| {},
4376        );
4377        let log = read_text(&text).unwrap();
4378        let alt = note_from(&log, "`Alt` ");
4379        assert!(
4380            alt.starts_with(
4381                "`Alt` read in feet, from the manual and the coast: the Classic and TRS manuals"
4382            ),
4383            "{alt}"
4384        );
4385        assert!(
4386            alt.contains(
4387                "Over the rows from 6.45 s to 9.45 s, up to the row before the marker `N-O` at \
4388                 9.5 s, it slows at 1 g in feet"
4389            ),
4390            "{alt}"
4391        );
4392    }
4393
4394    /// A table in meters whose drogue is out at 80 m/s, 1.85 s into the flight, and slows the
4395    /// rocket to its top before 4 s: fitted up to the top, the canopy's drag makes the 3 s before
4396    /// it slow at 1.27 g read in feet, and the meters would pass for feet. The coast ends before
4397    /// the charge, where too little of the table is left, and the clock is refused.
4398    #[test]
4399    fn a_canopy_that_would_pass_meters_for_feet_is_left_out() {
4400        let text = coast_download(
4401            &flight(
4402                1000.0,
4403                0.05,
4404                STANDARD_GRAVITY_MPS2,
4405                Some((1.85, 15.0)),
4406                15.0,
4407            ),
4408            |_, _| {},
4409        );
4410        let error = read_text(&text).unwrap_err().to_string();
4411        assert_eq!(
4412            error,
4413            "Eggtimer text line 2: the clock `T` is in milliseconds by its step, but no coast \
4414             bears that out: the table starts 1.8 s before the coast's end, up to the row before \
4415             the marker `N-O` at 1.85 s, short of the 3 s window"
4416        );
4417    }
4418
4419    /// A jump in the altitude, an ejection's pressure on one row, ends the coast at the row
4420    /// before it; one far from the window's end is no matter.
4421    #[test]
4422    fn a_jump_ends_the_coast() {
4423        let jumped = |at: usize| {
4424            coast_download(
4425                &flight(1000.0, 0.05, G_FT, None, 15.0),
4426                move |row, cells| {
4427                    if row == at {
4428                        cells[1] = "900".to_owned();
4429                    }
4430                },
4431            )
4432        };
4433        let log = read_text(&jumped(190)).unwrap();
4434        assert!(
4435            note_from(&log, "`Alt` ").contains(
4436                "Over the rows from 6.45 s to 9.45 s, up to the row before `Alt` jumps at 9.5 s, \
4437                 it slows at 1 g in feet"
4438            ),
4439            "{}",
4440            note_from(&log, "`Alt` ")
4441        );
4442        // At 5 s, the jump is before the search's 4 s: the window ends at the top.
4443        let log = read_text(&jumped(100)).unwrap();
4444        assert!(
4445            note_from(&log, "`Alt` ").contains("from 6.9 s to 9.9 s, up to the altitude's top")
4446        );
4447        // At 8 s, the window ends 2 s before the coast's top, further than 1 s: no coast.
4448        let error = read_text(&jumped(160)).unwrap_err().to_string();
4449        assert!(
4450            error.contains(
4451                "up to the row before `Alt` jumps at 8 s, the parabola fitted to `Alt` tops out \
4452                 2.05 s from the window's end, further than the 1 s the reader asks"
4453            ),
4454            "{error}"
4455        );
4456    }
4457
4458    #[test]
4459    fn markers_are_detections_motors_or_charges() {
4460        for name in ["LDA", "LowV", "MaxV", "MaxA"] {
4461            assert_eq!(marker_role(name), MarkerRole::Detection, "{name}");
4462        }
4463        for name in ["BurnT", "BO#1", "Boost#2"] {
4464            assert_eq!(marker_role(name), MarkerRole::Motor, "{name}");
4465        }
4466        for name in [
4467            "Apogee", "N-O", "Drogue", "Main", "AUX", "CHA", "CH3", "Boost#", "Sustain",
4468        ] {
4469            assert_eq!(marker_role(name), MarkerRole::Charge, "{name}");
4470        }
4471    }
4472
4473    #[test]
4474    fn a_parabola_and_a_level_are_fitted_exactly() {
4475        let points: Vec<(f64, f64)> = (0..10)
4476            .map(|step| {
4477                let x = f64::from(step) * 0.25 - 2.0;
4478                (x, 5.0 + 3.0 * x - 16.0 * x * x)
4479            })
4480            .collect();
4481        let (slope, curvature) = parabola(&points).unwrap();
4482        assert!((slope - 3.0).abs() < 1e-9 && (curvature + 32.0).abs() < 1e-9);
4483        assert_eq!(parabola(&points[..2]), None);
4484        // A spike of one row is passed over; at the ends the median narrows to the row.
4485        let values = [1.0, 2.0, 300.0, 4.0, 5.0, f64::NAN, 7.0];
4486        assert_eq!(level(&values, 0, 6, 2), 4.0);
4487        assert_eq!(level(&values, 0, 6, 0), 1.0);
4488        assert_eq!(level(&values, 0, 6, 5), 6.0);
4489        assert_eq!(level(&values, 2, 3, 3), 4.0);
4490    }
4491
4492    #[test]
4493    fn the_title_names_the_model_and_firmware() {
4494        assert_eq!(
4495            title_words("TRS 2.07"),
4496            ("TRS".to_owned(), Some("2.07".to_owned()))
4497        );
4498        assert_eq!(title_words("TRS"), ("TRS".to_owned(), None));
4499        assert_eq!(title_words(""), (String::new(), None));
4500        assert_eq!(
4501            title_words("2.10"),
4502            (String::new(), Some("2.10".to_owned()))
4503        );
4504        assert_eq!(height("12 ft"), Some((12.0 * 0.3048, "feet")));
4505        assert_eq!(height("12"), None);
4506        assert_eq!(height("12 ft extra"), None);
4507        assert_eq!(summary_time("1.5 secs."), Some((1.5, true)));
4508        assert_eq!(summary_time("1.5"), Some((1.5, false)));
4509        assert_eq!(summary_time("1.5 hours"), None);
4510    }
4511
4512    proptest::proptest! {
4513        /// Any preamble is read or refused, never a panic; what is read has increasing times and
4514        /// its events in time order.
4515        #[test]
4516        fn any_preamble_is_read_or_refused(
4517            lines in proptest::collection::vec("[.:@ A-Za-z0-9<>=,-]{0,30}", 0..12)
4518        ) {
4519            let text = format!(
4520                "Eggtimer TRS 2.07 Flight Settings\n{}\n{}",
4521                lines.join("\n"),
4522                table()
4523            );
4524            if let Ok(log) = read_text(&text) {
4525                proptest::prop_assert!(log.time_s.windows(2).all(|pair| pair[1] > pair[0]));
4526                proptest::prop_assert!(
4527                    log.events.windows(2).all(|pair| pair[0].time_s <= pair[1].time_s)
4528                );
4529            }
4530        }
4531    }
4532
4533    proptest::proptest! {
4534        /// Any text is read or refused, never a panic; what is read has increasing times and every
4535        /// channel a value for each.
4536        #[test]
4537        fn any_text_is_read_or_refused(
4538            rows in proptest::collection::vec("[-0-9.,x \r]{0,30}", 0..12)
4539        ) {
4540            let text = format!("{TRS}\n{}", rows.join("\n"));
4541            if let Ok(log) = read(&text) {
4542                proptest::prop_assert!(log.time_s.windows(2).all(|pair| pair[1] > pair[0]));
4543                proptest::prop_assert_eq!(log.time_s.len(), log.altitude_m.len());
4544                for channel in &log.channels {
4545                    proptest::prop_assert_eq!(channel.time_s.len(), channel.values.len());
4546                }
4547                for event in &log.events {
4548                    proptest::prop_assert!(log.time_s.contains(&event.time_s));
4549                }
4550            }
4551        }
4552    }
4553
4554    /// The RTF document's text: groups, control words with their delimiter, control symbols,
4555    /// escapes in Windows 1252, Unicode characters with their fallback, and the destinations
4556    /// skipped.
4557    #[test]
4558    fn rtf_unwraps_to_its_text() {
4559        let document = "{\\rtf1\\ansi{\\fonttbl\\f0 Helvetica;}{\\colortbl;\\red0;}\
4560                        {\\stylesheet{\\s0 Normal;}}{\\info{\\title Hidden}}{\\*\\generator X;}\
4561                        a\\\\b\\{c\\}\\'85\\'41\\tab d\\par e\\line f\\~g\\_h\\-i\\u8364?j\
4562                        {\\uc0\\u955 k}\\emdash\\b0\\par}";
4563        let text = unwrap_rtf(document).unwrap().text;
4564        assert_eq!(
4565            text,
4566            "a\\b{c}\u{2026}A\td\ne\nf\u{a0}g-hi\u{20ac}j\u{3bb}k\u{2014}\n"
4567        );
4568    }
4569
4570    /// Each of the text's lines maps to the document's line it starts on; raw line ends aren't
4571    /// text, and `\` at a line's end is a paragraph.
4572    #[test]
4573    fn rtf_lines_map_to_the_documents() {
4574        let unwrapped = unwrap_rtf("{\\rtf1\n\\f0 a\\\r\nb\\par\n\nc}").unwrap();
4575        assert_eq!(unwrapped.text, "a\nb\nc");
4576        assert_eq!(unwrapped.starts, [2, 3, 5]);
4577        assert_eq!(unwrapped.file_line(3), 5);
4578        assert_eq!(unwrapped.file_line(9), 5);
4579        assert_eq!(unwrapped.file_line(0), 5);
4580    }
4581
4582    /// Numbers of any size are read without overflow; `\bin`'s data is skipped, to the end at
4583    /// most; a byte outside Windows 1252, or undefined in it, is counted.
4584    #[test]
4585    fn rtf_numbers_binary_and_code_pages_are_bounded() {
4586        let huge = "9".repeat(400);
4587        let text = unwrap_rtf(&format!(
4588            "{{\\rtf1\\fs{huge} a\\u{huge}?\\u-3913?{{\\uc{huge}\\u65 bc}} d\\fs-{huge} e}}"
4589        ))
4590        .unwrap()
4591        .text;
4592        assert_eq!(text, "a\u{fffd}\u{f0b7}A de");
4593        assert_eq!(unwrap_rtf("{\\rtf1 a\\bin3 {}}b}").unwrap().text, "ab");
4594        let error = unwrap_rtf(&format!("{{\\rtf1 a\\bin{huge} b}}"))
4595            .unwrap_err()
4596            .to_string();
4597        assert_eq!(
4598            error,
4599            "Eggtimer RTF line 1: the document ends with 1 groups open: its braces don't balance"
4600        );
4601        let other = unwrap_rtf("{\\rtf1\\ansi\\ansicpg1251 \\'e0\\'41\\'81}").unwrap();
4602        assert_eq!(other.text, "\u{fffd}A\u{fffd}");
4603        assert_eq!(other.unmapped, 2);
4604        let undefined = unwrap_rtf("{\\rtf1\\ansi \\'81\\'e9\\'9f}").unwrap();
4605        assert_eq!(undefined.text, "\u{fffd}\u{e9}\u{178}");
4606        assert_eq!(undefined.unmapped, 1);
4607        let after = unwrap_rtf("{\\rtf1 a}\r\n x}").unwrap();
4608        assert_eq!((after.text.as_str(), after.after_end), ("a", 2));
4609    }
4610
4611    /// Markup the reader refuses, each at its line: unbalanced braces, groups nested past the
4612    /// cap, a broken escape, text outside the document's group.
4613    #[test]
4614    fn rtf_markup_is_refused_where_it_goes_wrong() {
4615        let deep = "{".repeat(MAX_RTF_DEPTH + 1);
4616        let cases = [
4617            (
4618                "}{\\rtf1 a}",
4619                "line 1: a `}` closes a group that was never opened",
4620            ),
4621            (
4622                "{\\rtf1\n{a}\n",
4623                "line 3: the document ends with 1 groups open",
4624            ),
4625            (
4626                deep.as_str(),
4627                "line 1: the document's groups nest deeper than 64",
4628            ),
4629            (
4630                "{\\rtf1\n\\'4g}",
4631                "line 2: a `\\'` escape isn't followed by two hexadecimal digits",
4632            ),
4633            (
4634                "x{\\rtf1 a}",
4635                "line 1: text comes before the document's opening `{`",
4636            ),
4637            ("", "the file holds no RTF group"),
4638        ];
4639        for (document, expected) in cases {
4640            let error = unwrap_rtf(document).unwrap_err().to_string();
4641            assert!(error.contains(expected), "{document:?}: {error}");
4642        }
4643        // A deep document that stays under the cap is read.
4644        let nested = format!(
4645            "{}a{}",
4646            "{".repeat(MAX_RTF_DEPTH),
4647            "}".repeat(MAX_RTF_DEPTH)
4648        );
4649        assert_eq!(unwrap_rtf(&nested).unwrap().text, "a");
4650    }
4651
4652    /// A file that isn't RTF, or whose text holds no download, is refused by name.
4653    #[test]
4654    fn rtf_without_a_download_is_refused_by_name() {
4655        for (text, expected) in [
4656            ("T,Alt\n0,0\n", "doesn't open with `{\\rtf`"),
4657            (
4658                "{\\rtf1 Eggtimer notes\\par T,Alt\\par 0,0}",
4659                "the RTF document's text holds no Eggtimer terminal download",
4660            ),
4661        ] {
4662            let error = read_rtf(text).unwrap_err();
4663            assert!(
4664                matches!(&error, LogError::NotThisFormat { format: "Eggtimer RTF", message }
4665                    if message.contains(expected)),
4666                "{error}"
4667            );
4668        }
4669    }
4670
4671    proptest::proptest! {
4672        /// Any markup is unwrapped or refused, never a panic; the text is never longer than the
4673        /// document, and each of its lines has the document's line it starts on.
4674        #[test]
4675        fn any_rtf_is_unwrapped_or_refused(
4676            body in "[{}\\\\a-z0-9 '\\-*~_?\r\n]{0,80}"
4677        ) {
4678            let document = format!("{{\\rtf1 {body}}}");
4679            if let Ok(unwrapped) = unwrap_rtf(&document) {
4680                proptest::prop_assert!(unwrapped.text.len() <= document.len());
4681                let text = &unwrapped.text;
4682                let lines = text.matches('\n').count()
4683                    + usize::from(!text.is_empty() && !text.ends_with('\n'));
4684                proptest::prop_assert_eq!(lines, unwrapped.starts.len());
4685            }
4686            let _ = read_rtf(&document);
4687        }
4688    }
4689}