mako-sgp4 0.2.0

Theory-based SGP4 propagator for TLEs and OMMs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
//! Module to handle the input and processing of GP (General Perturbation)
//! elements. Element sets can be parsed from TLE (including Alpha-5 catalog
//! numbers) and OMM formats, and written back to TLE and OMM KVN, XML, JSON,
//! and CSV.

// ------------------
// External Libraries
// ------------------
use std::fs;

#[cfg(any(feature = "xml", feature = "json", feature = "csv"))]
use std::collections::HashMap;

#[cfg(feature = "xml")]
use roxmltree::{Document, Node};

#[cfg(feature = "json")]
use serde_json::Value;

#[cfg(feature = "csv")]
use csv::{ReaderBuilder, WriterBuilder};

// ------------------
// Internal Libraries
// ------------------
use crate::sgp4::{Sgp4, Sgp4Error, init_sgp4};
use crate::time::{DateTime, Timezone, dayofyr2utc, validate_datetime};

// -------
// Structs
// -------

/// General Perturbation Element Set for an Earth-orbiting satellite.
///
/// This struct represents the parsed contents of a standard General Perturbation Element Set.
/// The General Perturbation Element Set is the standard set of orbital elements used with the
/// SGP4 propagator. Elements are commonly distributed as Two-Line Elements (TLEs) or Orbit
/// Mean-Elements Messages (OMMs).
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_tle_lines;
///
/// // Parse a TLE; the GP element set is stored on the SGP4 struct
/// let line0 = "ISS (ZARYA)";
/// let line1 = "1 25544U 98067A   08264.51782528 -.00002182 -00100-2 -11606-4 0  2921";
/// let line2 = "2 25544  51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537";
/// let sgp4 = from_tle_lines(line1, line2, Some(line0)).unwrap();
///
/// assert_eq!(sgp4.gp.satellite_catalog_number, 25544);
/// assert_eq!(sgp4.gp.common_name, "ISS (ZARYA)");
/// assert!((sgp4.gp.inclination - 51.6416).abs() < 1e-4);
/// ```
///
/// # References
/// - [Celestrak TLE Format](https://celestrak.org/columns/v04n03/#FAQ01)
#[derive(Default, Clone)]
pub struct GenPerturbElementSet {
    /// Common name of the satellite (e.g., "ISS (ZARYA)")
    pub common_name: String,

    /// NORAD satellite catalog number
    pub satellite_catalog_number: i32,

    /// Classification (`U` = Unclassified, `C` = Classified, `S` = Secret)
    pub classification: char,

    /// International designator in `Y-NP` form (launch year (4+ digits), launch number (3+ digits), piece (1+ characters))
    pub international_designator: String,

    /// Epoch UTC datetime
    pub epoch_datetime: DateTime,

    /// First time derivative of mean motion \[revs/day^2\]
    pub first_derivative_of_mean_motion: f64,

    /// Second time derivative of mean motion \[revs/day^3\]
    pub second_derivative_of_mean_motion: f64,

    /// B* drag term \[1/Earth radii\]
    pub bstar: f64,

    /// Ephemeris type (always zero)
    pub ephemeris_type: i32,

    /// Element set number
    pub element_set_number: i32,

    /// Orbital inclination \[degrees\]
    pub inclination: f64,

    /// Right ascension of the ascending node (RAAN) \[degrees\]
    pub right_ascension_of_ascending_node: f64,

    /// Orbital eccentricity \[\]
    pub eccentricity: f64,

    /// Argument of perigee \[degrees\]
    pub argument_of_perigee: f64,

    /// Mean anomaly \[degrees\]
    pub mean_anomaly: f64,

    /// Mean motion \[revs/day\]
    pub mean_motion: f64,

    /// Revolution number at epoch \[revs\]
    pub revolution_number_at_epoch: i64,

    /// TLE checksum result
    pub tle_checksum_valid: Option<bool>,
}

// -----
// Enums
// -----

/// GP errors
#[derive(Debug, Clone, PartialEq)]
pub enum GpError {
    /// TLE line 0 is invalid
    InvalidTleLine0,

    /// TLE line 1 is invalid
    InvalidTleLine1,

    /// TLE line 2 is invalid
    InvalidTleLine2,

    /// TLE epoch is invalid
    InvalidTleEpoch,

    /// TLE line 1 and line 2 have different NORAD catalog numbers
    MismatchedTleCatalog,

    /// A TLE file could not be read
    Io(String),

    /// TLE catalog number is negative or outside the Alpha-5 range
    InvalidTLECatalogNumber,

    /// TLE epoch datetime is before 1957 or after 2056
    InvalidTLEDateTime,

    /// A TLE data line is not 68 characters before the checksum
    InvalidTLELine,

    /// TLE international designator launch number or piece exceeds 3 characters
    InvalidTLEInternationalDesignator,

    /// An OMM field cannot be parsed as the requested type
    InvalidOmmField,

    /// OMM EPOCH cannot be parsed as a UTC datetime
    InvalidOmmEpoch,

    /// OMM XML document cannot be parsed
    InvalidOmmXml,

    /// OMM JSON cannot be parsed or is not an object or array of objects
    InvalidOmmJson,

    /// OMM CSV cannot be parsed
    InvalidOmmCsv,

    /// SGP4 initialization failed
    Sgp4(Sgp4Error),
}

// ------
// Traits
// ------

/// Convert an OMM field value into a typed GP field
///
/// Used by KVN and XML OMM parsing to turn a present field string into String,
/// char, integer, floating-point, or DateTime values, and to supply defaults
/// when a field is missing or empty.
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_omm_kvn_string;
///
/// // OMM numbers may use Fortran D exponents; missing classification is U
/// let omm = "\
/// CCSDS_OMM_VERS = 2.0
/// EPOCH          = 2026-06-14T15:07:48.259488
/// MEAN_MOTION    = 15.11169557
/// INCLINATION    = 97.5103
/// NORAD_CAT_ID   = 69097
/// BSTAR          = .39221734D-3
/// ";
/// let sgp4 = &from_omm_kvn_string(omm).unwrap()[0];
///
/// // Assert typed field conversion and the unclassified default
/// assert_eq!(sgp4.gp.satellite_catalog_number, 69097);
/// assert_eq!(sgp4.gp.classification, 'U');
/// assert!((sgp4.gp.bstar - 0.00039221734).abs() < 1e-12);
/// ```
trait FromOmm: Sized {
    /// Default used when the OMM field is missing or empty
    fn omm_default() -> Self;

    /// Parse a present, non-empty OMM field value
    fn from_omm(field: &str, value: &str) -> Result<Self, GpError>;
}

impl FromOmm for String {
    fn omm_default() -> Self {
        String::new()
    }

    fn from_omm(_field: &str, value: &str) -> Result<Self, GpError> {
        Ok(value.to_string())
    }
}

impl FromOmm for char {
    fn omm_default() -> Self {
        'U'
    }

    fn from_omm(_field: &str, value: &str) -> Result<Self, GpError> {
        Ok(value.chars().next().unwrap_or('U'))
    }
}

impl FromOmm for f64 {
    fn omm_default() -> Self {
        0.0
    }

    fn from_omm(_field: &str, value: &str) -> Result<Self, GpError> {
        let normalized = value.replace(['D', 'd'], "E");
        normalized
            .parse::<f64>()
            .map_err(|_| GpError::InvalidOmmField)
    }
}

impl FromOmm for i32 {
    fn omm_default() -> Self {
        0
    }

    fn from_omm(_field: &str, value: &str) -> Result<Self, GpError> {
        value.parse::<i32>().map_err(|_| GpError::InvalidOmmField)
    }
}

impl FromOmm for i64 {
    fn omm_default() -> Self {
        0
    }

    fn from_omm(_field: &str, value: &str) -> Result<Self, GpError> {
        value.parse::<i64>().map_err(|_| GpError::InvalidOmmField)
    }
}

impl FromOmm for DateTime {
    fn omm_default() -> Self {
        DateTime::default()
    }

    fn from_omm(_field: &str, value: &str) -> Result<Self, GpError> {
        parse_omm_epoch(value)
    }
}

// ---------
// Constants
// ---------

/// Celestrak GP CSV column order
///
/// Header names written by [`to_omm_csv_string`] and [`to_omm_csv_file`],
/// matching Celestrak GP CSV.
///
/// # References
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
#[cfg(feature = "csv")]
const OMM_CSV_HEADERS: [&str; 17] = [
    "OBJECT_NAME",
    "OBJECT_ID",
    "EPOCH",
    "MEAN_MOTION",
    "ECCENTRICITY",
    "INCLINATION",
    "RA_OF_ASC_NODE",
    "ARG_OF_PERICENTER",
    "MEAN_ANOMALY",
    "EPHEMERIS_TYPE",
    "CLASSIFICATION_TYPE",
    "NORAD_CAT_ID",
    "ELEMENT_SET_NO",
    "REV_AT_EPOCH",
    "BSTAR",
    "MEAN_MOTION_DOT",
    "MEAN_MOTION_DDOT",
];

// ---------
// Functions
// ---------

/// Builds a [`Sgp4`] struct from the lines of a Two-Line Element (TLE) set.
///
/// Given the two required TLE lines (line 1 and line 2), and an optional
/// name line (line 0), this function parses the input into a [`Sgp4`] struct.
///
/// # Arguments
/// * `line1` - The first TLE data line (TLE line 1)
/// * `line2` - The second TLE data line (TLE line 2)
/// * `line0` - Optional name line (TLE line 0)
///
/// # Returns
/// * `Ok(Sgp4)` - Struct containing the parsed SGP4 parameters
/// * `Err(GpError)` - If a TLE line or field cannot be parsed, or SGP4 initialization fails
///
/// # Errors
/// * [`GpError::InvalidTleLine0`] - If the optional name line is empty or longer than 24 characters
/// * [`GpError::InvalidTleLine1`] - If line 1 is not 69 ASCII characters, does not start with `1 `, or a field cannot be parsed
/// * [`GpError::InvalidTleLine2`] - If line 2 is not 69 ASCII characters, does not start with `2 `, or a field cannot be parsed
/// * [`GpError::InvalidTleEpoch`] - If the epoch cannot be converted to a UTC datetime
/// * [`GpError::MismatchedTleCatalog`] - If line 1 and line 2 have different NORAD catalog numbers
/// * [`GpError::Sgp4`] - If SGP4 initialization fails
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_tle_lines;
///
/// // Define a 3-line TLE (optional name, then line 1 and line 2)
/// let line0 = "ISS (ZARYA)";
/// let line1 = "1 25544U 98067A   08264.51782528 -.00002182 -00100-2 -11606-4 0  2921";
/// let line2 = "2 25544  51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537";
///
/// // Parse the TLE lines into an SGP4 propagator
/// let sgp4 = from_tle_lines(line1, line2, Some(line0)).unwrap();
///
/// // Assert the catalog number and name
/// assert_eq!(sgp4.gp.satellite_catalog_number, 25544);
/// assert_eq!(sgp4.gp.common_name, "ISS (ZARYA)");
/// ```
///
/// # References
/// - [Celestrak TLE Format](https://celestrak.org/columns/v04n03/#FAQ01)
pub fn from_tle_lines(line1: &str, line2: &str, line0: Option<&str>) -> Result<Sgp4, GpError> {
    // Create mutable General Perturbation Element Set struct
    let mut gp = GenPerturbElementSet::default();

    // Extract the common name of the satellite from line 0
    if let Some(name_line) = line0 {
        if name_line.is_empty() || name_line.len() > 24 {
            return Err(GpError::InvalidTleLine0);
        }
        gp.common_name = name_line.to_string();
    }

    // Line 1 must be 69 ASCII characters, starting with '1 ', before field slices or checksum
    if line1.len() != 69 || !line1.is_ascii() || !line1.starts_with("1 ") {
        return Err(GpError::InvalidTleLine1);
    }

    // Line 2 must be 69 ASCII characters, starting with '2 ', before field slices or checksum
    if line2.len() != 69 || !line2.is_ascii() || !line2.starts_with("2 ") {
        return Err(GpError::InvalidTleLine2);
    }

    // Validate the TLE checksum. A mismatch is a warning, not an error, and is reported
    // through `tle_checksum_valid`
    gp.tle_checksum_valid = Some(tle_checksum(line1) && tle_checksum(line2));

    // Satellite catalog number from line 1
    gp.satellite_catalog_number =
        parse_tle_catalog(&line1[2..7]).ok_or(GpError::InvalidTleLine1)?;

    // Line 2 must carry the same NORAD catalog number
    let catalog2 = parse_tle_catalog(&line2[2..7]).ok_or(GpError::InvalidTleLine2)?;
    if catalog2 != gp.satellite_catalog_number {
        return Err(GpError::MismatchedTleCatalog);
    }

    // Classification
    gp.classification = line1[7..8]
        .trim()
        .parse::<char>()
        .map_err(|_| GpError::InvalidTleLine1)?;

    // International designator (COSPAR YYYY-NNNP)
    let intl_des = line1[9..17].trim();
    if intl_des.is_empty() {
        // Handle case where international designator is not present
        gp.international_designator = String::new();
    } else if intl_des.len() < 2 {
        return Err(GpError::InvalidTleLine1);
    } else {
        // Expand two-digit launch year and insert the COSPAR dash
        let launch_year = tle_full_year(
            intl_des[..2]
                .parse::<i32>()
                .map_err(|_| GpError::InvalidTleLine1)?,
        );
        gp.international_designator = format!("{}-{}", launch_year, &intl_des[2..]);
    }

    // Epoch year (last two numbers)
    let yr_two_digit: i32 = line1[18..20]
        .trim()
        .parse()
        .map_err(|_| GpError::InvalidTleLine1)?;
    let epoch_year = tle_full_year(yr_two_digit);

    // Epoch day of year
    let epoch_day: f64 = line1[20..32]
        .trim()
        .parse()
        .map_err(|_| GpError::InvalidTleLine1)?;

    // Epoch UTC datetime
    gp.epoch_datetime = dayofyr2utc(epoch_year, epoch_day).map_err(|_| GpError::InvalidTleEpoch)?;

    // 1st derivative of mean motion [revs/day^2]
    gp.first_derivative_of_mean_motion = line1[33..43]
        .trim()
        .parse::<f64>()
        .map_err(|_| GpError::InvalidTleLine1)?
        * 2.0;

    // 2nd derivative of mean motion [revs/days^3]
    // Sign is a single column (space, +, or -) and must not be trimmed
    let nddot_mantissa: f64 = if line1.as_bytes()[44] == b'-' {
        format!("-0.{}", line1[45..50].trim())
            .parse()
            .map_err(|_| GpError::InvalidTleLine1)?
    } else {
        format!("0.{}", line1[45..50].trim())
            .parse()
            .map_err(|_| GpError::InvalidTleLine1)?
    };
    let nddot_exp: i32 = line1[50..52]
        .parse()
        .map_err(|_| GpError::InvalidTleLine1)?;
    gp.second_derivative_of_mean_motion = nddot_mantissa * 10.0_f64.powi(nddot_exp) * 6.0;

    // B* [1/Earth Radii]
    // Sign is a single column (space, +, or -) and must not be trimmed
    let bstar_mantissa: f64 = if line1.as_bytes()[53] == b'-' {
        format!("-0.{}", line1[54..59].trim())
            .parse()
            .map_err(|_| GpError::InvalidTleLine1)?
    } else {
        format!("0.{}", line1[54..59].trim())
            .parse()
            .map_err(|_| GpError::InvalidTleLine1)?
    };
    let bstar_exp: i32 = line1[59..61]
        .parse()
        .map_err(|_| GpError::InvalidTleLine1)?;
    gp.bstar = bstar_mantissa * 10.0_f64.powi(bstar_exp);

    // Ephemeris type
    if line1[62..63].trim().is_empty() {
        // Handle case where ephemeris type is not present
        gp.ephemeris_type = 0;
    } else {
        gp.ephemeris_type = line1[62..63]
            .parse()
            .map_err(|_| GpError::InvalidTleLine1)?;
    }

    // Element set number
    gp.element_set_number = line1[64..68]
        .trim()
        .parse()
        .map_err(|_| GpError::InvalidTleLine1)?;

    // Inclination [degs]
    gp.inclination = line2[8..16]
        .trim()
        .parse()
        .map_err(|_| GpError::InvalidTleLine2)?;

    // Right ascension of ascending node [degs]
    gp.right_ascension_of_ascending_node = line2[17..25]
        .trim()
        .parse()
        .map_err(|_| GpError::InvalidTleLine2)?;

    // Eccentricity
    gp.eccentricity = format!("0.{}", line2[26..33].trim())
        .parse()
        .map_err(|_| GpError::InvalidTleLine2)?;

    // Argument of perigee [degs]
    gp.argument_of_perigee = line2[34..42]
        .trim()
        .parse()
        .map_err(|_| GpError::InvalidTleLine2)?;

    // Mean anomaly [degs]
    gp.mean_anomaly = line2[43..51]
        .trim()
        .parse()
        .map_err(|_| GpError::InvalidTleLine2)?;

    // Mean motion [revs/day]
    gp.mean_motion = line2[52..63]
        .trim()
        .parse()
        .map_err(|_| GpError::InvalidTleLine2)?;

    // Revolution number at epoch
    gp.revolution_number_at_epoch = line2[63..68]
        .trim()
        .parse()
        .map_err(|_| GpError::InvalidTleLine2)?;

    // Initialize the SGP4 parameters
    init_sgp4(&gp, None).map_err(GpError::Sgp4)
}

/// Builds a vector of [`Sgp4`] structs from a string containing Two-Line Element (TLE) sets.
///
/// This function parses a string containing one or more TLEs in either
/// 2-line or 3-line (name + 2 lines) format and returns all successfully
/// parsed entries.
///
/// # Arguments
/// * `tle_string` - A string containing one or more Two-Line Element (TLE) sets
///
/// # Returns
/// * `Ok(Vec<Sgp4>)` - All successfully parsed SGP4 parameters
/// * `Err(GpError)` - If a TLE in the string cannot be parsed or SGP4 initialization fails
///
/// # Errors
/// * [`GpError::InvalidTleLine0`] - If an optional name line is empty or longer than 24 characters
/// * [`GpError::InvalidTleLine1`] - If a line 1 is not 69 characters or a field cannot be parsed
/// * [`GpError::InvalidTleLine2`] - If a line 2 is not 69 characters or a field cannot be parsed
/// * [`GpError::InvalidTleEpoch`] - If an epoch cannot be converted to a UTC datetime
/// * [`GpError::MismatchedTleCatalog`] - If a TLE has different NORAD catalog numbers on line 1 and line 2
/// * [`GpError::Sgp4`] - If SGP4 initialization fails
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_tle_string;
///
/// // Define one or more 2-line or 3-line TLEs, separated by newlines
/// let tle = "\
/// ISS (ZARYA)
/// 1 25544U 98067A   08264.51782528 -.00002182 -00100-2 -11606-4 0  2921
/// 2 25544  51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537
/// ";
///
/// // Parse the TLE string into SGP4 propagators
/// let sgp4s = from_tle_string(tle).unwrap();
///
/// // Assert the catalog number and name
/// assert_eq!(sgp4s.len(), 1);
/// assert_eq!(sgp4s[0].gp.satellite_catalog_number, 25544);
/// assert_eq!(sgp4s[0].gp.common_name, "ISS (ZARYA)");
/// ```
///
/// # References
/// - [Celestrak TLE Format](https://celestrak.org/columns/v04n03/#FAQ01)
pub fn from_tle_string(tle_string: &str) -> Result<Vec<Sgp4>, GpError> {
    // Parse the string into lines, removing spaces
    let lines: Vec<&str> = tle_string
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .collect();

    // Create the tles vector
    let mut sgp4s = Vec::new();
    let mut i = 0;

    // Iterate through the lines building TLE structs when possible
    while i < lines.len() {
        // Find TLEs within the string, either 2 or 3 line entries
        if lines[i].starts_with('1') {
            // This is likely a 2 line entry, check length
            if i + 1 >= lines.len() {
                break;
            }
            // Check that next line starts with '2'
            if lines[i + 1].starts_with('2') {
                let sgp4 = from_tle_lines(lines[i], lines[i + 1], None)?;
                sgp4s.push(sgp4);
                i += 2;
            } else {
                i += 1;
            }
        } else {
            // This is likely a 3 line entry, check length
            if i + 2 >= lines.len() {
                break;
            }
            // Check that next line 2 lines starts with '1' and '2'
            if lines[i + 1].starts_with('1') && lines[i + 2].starts_with('2') {
                let sgp4 = from_tle_lines(lines[i + 1], lines[i + 2], Some(lines[i]))?;
                sgp4s.push(sgp4);
                i += 3;
            } else {
                i += 1;
            }
        }
    }
    // Return vector of SGP4 structs
    Ok(sgp4s)
}

/// Builds a vector of [`Sgp4`] structs from a file containing Two-Line Element (TLE) sets.
///
/// This function parses a file containing one or more TLEs in either
/// 2-line or 3-line (name + 2 lines) format and returns all successfully
/// parsed entries.
///
/// # Arguments
/// * `file_path` - A path to a file containing one or more Two-Line Element (TLE) sets
///
/// # Returns
/// * `Ok(Vec<Sgp4>)` - All successfully parsed SGP4 structs
/// * `Err(GpError)` - If the file cannot be read, a TLE cannot be parsed, or SGP4 initialization fails
///
/// # Errors
/// * [`GpError::Io`] - If the file cannot be read
/// * [`GpError::InvalidTleLine0`] - If an optional name line is empty or longer than 24 characters
/// * [`GpError::InvalidTleLine1`] - If a line 1 is not 69 characters or a field cannot be parsed
/// * [`GpError::InvalidTleLine2`] - If a line 2 is not 69 characters or a field cannot be parsed
/// * [`GpError::InvalidTleEpoch`] - If an epoch cannot be converted to a UTC datetime
/// * [`GpError::MismatchedTleCatalog`] - If a TLE has different NORAD catalog numbers on line 1 and line 2
/// * [`GpError::Sgp4`] - If SGP4 initialization fails
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_tle_file;
///
/// // Define a 3-line TLE
/// let tle = "\
/// ISS (ZARYA)
/// 1 25544U 98067A   08264.51782528 -.00002182 -00100-2 -11606-4 0  2921
/// 2 25544  51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537
/// ";
///
/// // Write the TLE to a temporary file
/// let path = std::env::temp_dir().join("mako_sgp4_from_tle_file.tle");
/// std::fs::write(&path, tle).unwrap();
///
/// // Parse the TLE file into SGP4 propagators
/// let sgp4s = from_tle_file(path.to_str().unwrap()).unwrap();
///
/// // Remove the temporary file
/// let _ = std::fs::remove_file(&path);
///
/// // Assert the catalog number and name
/// assert_eq!(sgp4s.len(), 1);
/// assert_eq!(sgp4s[0].gp.satellite_catalog_number, 25544);
/// assert_eq!(sgp4s[0].gp.common_name, "ISS (ZARYA)");
/// ```
///
/// # References
/// - [Celestrak TLE Format](https://celestrak.org/columns/v04n03/#FAQ01)
pub fn from_tle_file(file_path: &str) -> Result<Vec<Sgp4>, GpError> {
    // Open the TLE file
    let tle_string = fs::read_to_string(file_path).map_err(|err| GpError::Io(err.to_string()))?;

    // Parse tle string into a vector of SGP4 structs
    from_tle_string(&tle_string)
}

/// Calculate the checksum of the Two-Line Element (TLE) line.
///
/// Given a TLE line, calculate the checksum of that line. Follow the following rules:
/// - Ignore alpha characters
/// - Sum digits 0-9 as integer values
/// - '-' is treated as 1
/// - Return checksum % 10
///
/// # Arguments
/// * `line` - The TLE line to calculate the checksum of
///
/// # Returns
/// * `checksum` - The checksum of the TLE line (integer 0-9)
fn calc_checksum(line: &str) -> i32 {
    // Initialize checksum to 0
    let mut checksum = 0;

    // Loop through the line and calculate the checksum
    for c in line.chars().take(68) {
        match c {
            '0'..='9' => checksum += (c as u8 - b'0') as i32,
            '-' => checksum += 1,
            _ => {}
        }
    }

    // Calculate the checksum
    checksum %= 10;

    checksum
}

/// Check if the TLE line has been corrupted by running a checksum test.
///
/// Given a TLE line, check if the checksum of that line is valid.
///
/// # Arguments
/// * `line` - The TLE line to check the checksum of
///
/// # Returns
/// * `bool` - True if the checksum of the line is valid, false if otherwise
fn tle_checksum(line: &str) -> bool {
    // The checksum digit is the 69th character
    if line.len() < 69 {
        return false;
    }

    // Compare the checksum to the last character of the line
    let Ok(digit) = line[68..69].parse::<i32>() else {
        return false;
    };
    calc_checksum(line) == digit
}

/// Convert a two-digit TLE year to a four-digit Gregorian year.
///
/// TLE years follow the convention that 57-99 map to 1957-1999 and 00-56 map
/// to 2000-2056, matching the original SGP4 epoch encoding.
///
/// # Arguments
/// * `two_digit_year` - Year modulo 100 as stored in a TLE
///
/// # Returns
/// * Four-digit year in the range 1957-2056
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_tle_lines;
///
/// // Two-digit TLE year 08 maps to 2008 (00-56 -> 2000-2056)
/// let tle_line1 = "1 25544U 98067A   08264.51782528 -.00002182 -00100-2 -11606-4 0  2921";
/// let tle_line2 = "2 25544  51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537";
/// let sgp4 = from_tle_lines(tle_line1, tle_line2, None).unwrap();
///
/// // Assert the epoch year is the four-digit Gregorian year
/// assert_eq!(sgp4.gp.epoch_datetime.year, 2008);
/// ```
fn tle_full_year(two_digit_year: i32) -> i32 {
    if two_digit_year < 57 {
        2000 + two_digit_year
    } else {
        1900 + two_digit_year
    }
}

/// Parse a TLE NORAD catalog field (numeric or Alpha-5).
///
/// # Arguments
/// * `field` - Five-character catalog substring from TLE line 1 or line 2
///
/// # Returns
/// * `Some(n)` - The catalog number
/// * `None` - If the field is empty or not a valid catalog number
fn parse_tle_catalog(field: &str) -> Option<i32> {
    let catalog = field.trim();
    let first_char = catalog.chars().next()?;
    if first_char.is_ascii_digit() {
        // This is a classic numeric catalog number
        catalog.parse().ok()
    } else if first_char.is_ascii_alphabetic() {
        // This is an Alpha-5 catalog number
        let alpha = alpha5_digit(first_char)?;
        let rest: i32 = catalog[1..].parse().ok()?;
        Some(alpha * 10000 + rest)
    } else {
        None
    }
}

/// Converts an Alpha-5 digit to an integer
///
/// Given a character, map it to the corresponding integer value as defined in the Alpha-5 standard.
///
/// # Arguments
/// * `c` - The character to convert
///
/// # Returns
/// * `Some(i)` - The integer value of the character
/// * `None` - If the character is not a valid Alpha-5 digit
///
/// # References
/// - [Alpha-5 Standard](https://www.space-track.org/documentation#tle-alpha5)
fn alpha5_digit(c: char) -> Option<i32> {
    // Convert the character to uppercase to match the standard
    let c_upper = c.to_ascii_uppercase();

    // Match the character to the corresponding integer value
    match c_upper {
        'A'..='H' => Some((c_upper as i32) - ('A' as i32) + 10),
        'J'..='N' => Some((c_upper as i32) - ('J' as i32) + 18),
        'P'..='Z' => Some((c_upper as i32) - ('P' as i32) + 23),
        _ => None, // Standard skips 'I' and 'O'
    }
}

/// Converts an integer to an Alpha-5 digit
///
/// Inverse of [`alpha5_digit`]. Integers 10-17 map to A-H, 18-22 to J-N,
/// and 23-33 to P-Z. The letters I and O are skipped.
///
/// # Arguments
/// * `digit` - The integer value to convert
///
/// # Returns
/// * `Some(c)` - The Alpha-5 character
/// * `None` - If the integer is outside 10-33 or would map to I or O
///
/// # References
/// - [Alpha-5 Standard](https://www.space-track.org/documentation#tle-alpha5)
fn alpha5_letter(digit: i32) -> Option<char> {
    // Match the integer to the corresponding Alpha-5 character
    match digit {
        10..=17 => Some((b'A' + (digit as u8 - 10)) as char),
        18..=22 => Some((b'J' + (digit as u8 - 18)) as char),
        23..=33 => Some((b'P' + (digit as u8 - 23)) as char),
        _ => None, // Standard skips 'I' and 'O'
    }
}

/// Format a NORAD catalog number for a TLE
///
/// Numbers below 100000 are written as a 5-character right-justified
/// field. Numbers 100000-339999 use Alpha-5 encoding.
///
/// # Arguments
/// * `catalog` - The NORAD catalog number
///
/// # Returns
/// * `Ok(String)` - A 5-character catalog field
/// * `Err(GpError)` - If the catalog number cannot be written as a TLE field
///
/// # Errors
/// * [`GpError::InvalidTLECatalogNumber`] - If the catalog number is negative or greater than 339999
///
/// # References
/// - [Alpha-5 Standard](https://www.space-track.org/documentation#tle-alpha5)
fn format_tle_catalog_number(catalog: i32) -> Result<String, GpError> {
    // Reject negative catalog numbers
    if catalog < 0 {
        return Err(GpError::InvalidTLECatalogNumber);
    }

    if catalog < 100000 {
        // This is a classic numeric catalog number
        return Ok(format!("{:>5}", catalog));
    }

    // This is an Alpha-5 catalog number
    let first = catalog / 10000;
    let rest = catalog % 10000;
    let Some(letter) = alpha5_letter(first) else {
        return Err(GpError::InvalidTLECatalogNumber);
    };
    Ok(format!("{}{:04}", letter, rest))
}

/// Format an international designator for a TLE
///
/// Converts YYYY-NNNP form back to the 8-character TLE field YYNNNPPP.
/// Missing designators are written as eight spaces. The TLE field allows
/// a 3-digit launch number and a 3-character piece; longer values stored
/// on the GP cannot be written as a TLE.
///
/// # Arguments
/// * `intl` - The international designator stored on the GP
///
/// # Returns
/// * `Ok(String)` - An 8-character international designator field
/// * `Err(GpError)` - If the designator cannot be written as a TLE field
///
/// # Errors
/// * [`GpError::InvalidTLEInternationalDesignator`] - If the launch number or piece exceeds 3 characters
fn format_tle_intl_des(intl: &str) -> Result<String, GpError> {
    let intl = intl.trim();
    if intl.is_empty() {
        // Handle case where international designator is not present
        return Ok("        ".to_string());
    }

    // Collapse YYYY-NNNP back to the two-digit TLE year plus the launch piece
    let field = if let Some((year_str, rest)) = intl.split_once('-') {
        // TLE allows 3 launch-number digits and 3 piece characters
        let launch_len = rest.bytes().take_while(u8::is_ascii_digit).count();
        let part_code = &rest[launch_len..];
        if launch_len > 3 || part_code.len() > 3 {
            return Err(GpError::InvalidTLEInternationalDesignator);
        }

        let year = year_str.parse::<i32>().unwrap_or(0);
        let yy = ((year % 100) + 100) % 100;
        format!("{:02}{}", yy, rest)
    } else if intl.len() > 8 {
        return Err(GpError::InvalidTLEInternationalDesignator);
    } else {
        intl.to_string()
    };

    // TLE international designator field is 8 characters, left-justified
    Ok(format!("{:<8}", field))
}

/// Format a TLE epoch from a UTC datetime
///
/// Writes YYDDD.DDDDDDDD: two-digit year and day of year with eight
/// fractional digits.
///
/// # Arguments
/// * `epoch` - The epoch datetime
///
/// # Returns
/// * `Ok(String)` - A 14-character TLE epoch field
/// * `Err(GpError)` - If the datetime cannot be written as a TLE epoch
///
/// # Errors
/// * [`GpError::InvalidTLEDateTime`] - If the year is before 1957 or after 2056
fn format_tle_epoch(epoch: &DateTime) -> Result<String, GpError> {
    // TLE two-digit years cover 1957-2056
    if !(1957..=2056).contains(&epoch.year) {
        return Err(GpError::InvalidTLEDateTime);
    }

    // TLE years are stored modulo 100
    let two_digit_year = ((epoch.year % 100) + 100) % 100;

    // Check for leap year
    let is_leap = (epoch.year % 4 == 0 && epoch.year % 100 != 0) || (epoch.year % 400 == 0);

    // Days per month (non-leap year)
    let days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    // Sum complete months to get the integer day of year
    let mut day_int = epoch.day;
    for m in 1..epoch.month {
        let days_this_month = if m == 2 && is_leap {
            29 // February in leap year
        } else {
            days_per_month[(m - 1) as usize]
        };
        day_int += days_this_month;
    }

    // Convert clock time to a fractional day
    let mut second = epoch.second;
    if second < 0.0 {
        second = 0.0;
    }
    let day_frac = (epoch.hour as f64 * 3600.0 + epoch.minute as f64 * 60.0 + second) / 86400.0;
    let dayofyr = day_int as f64 + day_frac;

    Ok(format!("{:02}{:012.8}", two_digit_year, dayofyr))
}

/// Format the TLE-printed first derivative of mean motion
///
/// Writes the 10-character field as a signed decimal without a leading
/// zero, for example `-.00002182` or ` .00000234`.
///
/// # Arguments
/// * `value` - The TLE-printed first derivative (stored value divided by 2) \[revs/day^2\]
///
/// # Returns
/// * A 10-character mean-motion-dot field
fn format_tle_ndot(value: f64) -> String {
    // Eight digits after the implied 0. prefix
    let mut digits = (value.abs() * 1e8).round() as i64;
    if digits > 99999999 {
        digits = 99999999;
    }

    // Negative values use '-', positive values use a leading space
    if value < 0.0 && digits != 0 {
        return format!("-.{:08}", digits);
    }
    format!(" .{:08}", digits)
}

/// Format a TLE exponential field (second derivative of mean motion or BSTAR)
///
/// Writes the 8-character assumed-decimal form, for example `-11606-4`
/// meaning -0.11606 times 10 to the -4. Zero is written as ` 00000+0`.
///
/// # Arguments
/// * `value` - The TLE-printed value
///
/// # Returns
/// * An 8-character TLE exponential field
fn format_tle_exp(value: f64) -> String {
    if !value.is_finite() || value == 0.0 {
        return " 00000+0".to_string();
    }

    let sign = if value < 0.0 { '-' } else { ' ' };
    let abs = value.abs();

    // Mantissa in [0.1, 1) so the five digits sit after an implied decimal
    let mut exp = abs.log10().floor() as i32 + 1;
    let mantissa = abs / 10f64.powi(exp);
    let mut digits = (mantissa * 100000.0).round() as i32;

    if digits >= 100000 {
        digits = 10000;
        exp += 1;
    }
    if digits == 0 {
        return " 00000+0".to_string();
    }

    // TLE exponent is a single digit
    if exp > 9 {
        exp = 9;
        digits = 99999;
    } else if exp < -9 {
        return " 00000+0".to_string();
    }

    let exp_sign = if exp >= 0 { '+' } else { '-' };
    format!("{}{:05}{}{}", sign, digits, exp_sign, exp.abs())
}

/// Format eccentricity for a TLE
///
/// Writes seven digits with the decimal point assumed. For example,
/// 0.0006703 becomes `0006703`.
///
/// # Arguments
/// * `eccentricity` - Orbital eccentricity
///
/// # Returns
/// * A 7-character eccentricity field
fn format_tle_eccentricity(eccentricity: f64) -> String {
    // Seven digits after the implied 0. prefix
    let mut digits = (eccentricity.abs() * 1e7).round() as i64;
    digits = digits.clamp(0, 9999999);
    format!("{:07}", digits)
}

/// Append a TLE checksum digit to a 68-character line
///
/// Computes the checksum of the first 68 characters with [`calc_checksum`]
/// and appends it so the returned line is 69 characters.
///
/// # Arguments
/// * `line68` - The first 68 characters of a TLE data line
///
/// # Returns
/// * `Ok(String)` - A 69-character TLE line including checksum
/// * `Err(GpError)` - If `line68` is not exactly 68 characters
///
/// # Errors
/// * [`GpError::InvalidTLELine`] - If `line68` is not exactly 68 characters
fn tle_line_with_checksum(line68: &str) -> Result<String, GpError> {
    if line68.len() != 68 {
        return Err(GpError::InvalidTLELine);
    }

    // Append checksum as the 69th character
    Ok(format!("{}{}", line68, calc_checksum(line68)))
}

/// Build TLE line 1 from a general perturbation element set
///
/// MEAN_MOTION_DOT and MEAN_MOTION_DDOT are written as the TLE-printed
/// values (stored derivatives divided by 2 and 6).
///
/// # Arguments
/// * `gp` - The element set to serialize
///
/// # Returns
/// * `Ok(String)` - TLE line 1, including checksum
/// * `Err(GpError)` - If a TLE field cannot be written
fn format_tle_line1(gp: &GenPerturbElementSet) -> Result<String, GpError> {
    // Line 1
    // Satellite catalog number
    let catalog = format_tle_catalog_number(gp.satellite_catalog_number)?;

    // Classification
    let classification = if gp.classification.is_ascii_graphic() {
        gp.classification
    } else {
        'U'
    };

    // International designator
    let intl_des = format_tle_intl_des(&gp.international_designator)?;

    // Epoch year and day of year
    let epoch = format_tle_epoch(&gp.epoch_datetime)?;

    // 1st derivative of mean motion (TLE prints the stored value divided by 2)
    let ndot = format_tle_ndot(gp.first_derivative_of_mean_motion / 2.0);

    // 2nd derivative of mean motion (TLE prints the stored value divided by 6)
    let nddot = format_tle_exp(gp.second_derivative_of_mean_motion / 6.0);

    // BSTAR drag term
    let bstar = format_tle_exp(gp.bstar);

    // Ephemeris type
    let ephem_type = if (0..=9).contains(&gp.ephemeris_type) {
        gp.ephemeris_type
    } else {
        0
    };

    // Element set number (4 digits)
    let elset = gp.element_set_number.rem_euclid(10000);

    let line68 = format!(
        "1 {}{} {} {} {} {} {} {} {:>4}",
        catalog, classification, intl_des, epoch, ndot, nddot, bstar, ephem_type, elset
    );
    tle_line_with_checksum(&line68)
}

/// Build TLE line 2 from a general perturbation element set
///
/// Writes inclination, RAAN, eccentricity, argument of perigee, mean
/// anomaly, mean motion, and revolution number in TLE column layout.
///
/// # Arguments
/// * `gp` - The element set to serialize
///
/// # Returns
/// * `Ok(String)` - TLE line 2, including checksum
/// * `Err(GpError)` - If a TLE field cannot be written
fn format_tle_line2(gp: &GenPerturbElementSet) -> Result<String, GpError> {
    // Line 2
    // Satellite catalog number
    let catalog = format_tle_catalog_number(gp.satellite_catalog_number)?;

    // Inclination [degs]
    let inclination = format!("{:8.4}", gp.inclination);

    // Right ascension of ascending node [degs]
    let right_ascension_of_ascending_node = format!("{:8.4}", gp.right_ascension_of_ascending_node);

    // Eccentricity (decimal point assumed)
    let ecc = format_tle_eccentricity(gp.eccentricity);

    // Argument of perigee [degs]
    let argument_of_perigee = format!("{:8.4}", gp.argument_of_perigee);

    // Mean anomaly [degs]
    let mean_anomaly = format!("{:8.4}", gp.mean_anomaly);

    // Mean motion [revs/day]
    let mean_motion = format!("{:11.8}", gp.mean_motion);

    // Revolution number at epoch (5 digits)
    let rev = format!("{:>5}", gp.revolution_number_at_epoch.rem_euclid(100000));

    let line68 = format!(
        "2 {} {} {} {} {} {} {}{}",
        catalog,
        inclination,
        right_ascension_of_ascending_node,
        ecc,
        argument_of_perigee,
        mean_anomaly,
        mean_motion,
        rev
    );
    tle_line_with_checksum(&line68)
}

/// Build one TLE from a general perturbation element set
///
/// A name line (line 0) is written when [`GenPerturbElementSet::common_name`]
/// is non-empty. Names longer than 24 characters are truncated. MEAN_MOTION
/// derivatives are written as the TLE-printed values (stored derivatives
/// divided by 2 and 6).
///
/// # Arguments
/// * `gp` - The element set to serialize
///
/// # Returns
/// * `Ok(String)` - One TLE in 2-line or 3-line format, including a trailing newline
/// * `Err(GpError)` - If a TLE field cannot be written
fn gp_to_tle(gp: &GenPerturbElementSet) -> Result<String, GpError> {
    let mut tle = String::new();

    // Optional name line (TLE line 0)
    let name = gp.common_name.trim();
    if !name.is_empty() {
        let mut name = name.to_string();
        if name.len() > 24 {
            name.truncate(24);
        }
        tle.push_str(&name);
        tle.push('\n');
    }

    // TLE line 1 and line 2
    tle.push_str(&format_tle_line1(gp)?);
    tle.push('\n');
    tle.push_str(&format_tle_line2(gp)?);
    tle.push('\n');
    Ok(tle)
}

/// Builds a Two-Line Element (TLE) string from a slice of [`Sgp4`] structs.
///
/// Each element set is written as a 2-line TLE, or a 3-line TLE when a
/// common name is present. Catalog numbers of 100000 and above use
/// Alpha-5 encoding. MEAN_MOTION_DOT and MEAN_MOTION_DDOT are the
/// TLE-printed values (the stored derivatives divided by 2 and 6).
///
/// An empty slice produces an empty string.
///
/// # Arguments
/// * `sgp4s` - The SGP4 structs to export
///
/// # Returns
/// * `Ok(String)` - One or more TLEs
/// * `Err(GpError)` - If a TLE field cannot be written
///
/// # Errors
/// * [`GpError::InvalidTLECatalogNumber`] - If a catalog number is negative or greater than 339999
/// * [`GpError::InvalidTLEDateTime`] - If an epoch year is before 1957 or after 2056
/// * [`GpError::InvalidTLEInternationalDesignator`] - If a launch number or piece exceeds 3 characters
/// * [`GpError::InvalidTLELine`] - If a formatted TLE data line is not 68 characters before the checksum
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::{from_tle_string, to_tle_string};
///
/// // Define a 3-line TLE
/// let tle = "\
/// ISS (ZARYA)
/// 1 25544U 98067A   08264.51782528 -.00002182 -00100-2 -11606-4 0  2921
/// 2 25544  51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537
/// ";
///
/// // Parse, export, and parse again
/// let sgp4s = from_tle_string(tle).unwrap();
/// let exported = to_tle_string(&sgp4s).unwrap();
/// let reparsed = from_tle_string(&exported).unwrap();
///
/// // Assert the round-trip catalog number and name
/// assert_eq!(reparsed.len(), 1);
/// assert_eq!(reparsed[0].gp.satellite_catalog_number, 25544);
/// assert_eq!(reparsed[0].gp.common_name, "ISS (ZARYA)");
/// ```
///
/// # References
/// - [Celestrak TLE Format](https://celestrak.org/columns/v04n03/#FAQ01)
/// - [Alpha-5 Standard](https://www.space-track.org/documentation#tle-alpha5)
pub fn to_tle_string(sgp4s: &[Sgp4]) -> Result<String, GpError> {
    // Serialize each element set as one TLE
    let mut records = String::new();
    for sgp4 in sgp4s {
        records.push_str(&gp_to_tle(&sgp4.gp)?);
    }

    Ok(records)
}

/// Writes a Two-Line Element (TLE) file from a slice of [`Sgp4`] structs.
///
/// This function serializes the provided element sets with
/// [`to_tle_string`] and writes the result to `tle_file_path`.
///
/// # Arguments
/// * `sgp4s` - The SGP4 structs to export
/// * `tle_file_path` - Destination path for the TLE file
///
/// # Returns
/// * `Ok(())` - If the file was written
/// * `Err(GpError)` - If a TLE field cannot be written or the file cannot be written
///
/// # Errors
/// * [`GpError::InvalidTLECatalogNumber`] - If a catalog number is negative or greater than 339999
/// * [`GpError::InvalidTLEDateTime`] - If an epoch year is before 1957 or after 2056
/// * [`GpError::InvalidTLEInternationalDesignator`] - If a launch number or piece exceeds 3 characters
/// * [`GpError::InvalidTLELine`] - If a formatted TLE data line is not 68 characters before the checksum
/// * [`GpError::Io`] - If the file cannot be written
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::{from_tle_file, from_tle_string, to_tle_file};
///
/// // Define a 3-line TLE and parse it
/// let tle = "\
/// ISS (ZARYA)
/// 1 25544U 98067A   08264.51782528 -.00002182 -00100-2 -11606-4 0  2921
/// 2 25544  51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537
/// ";
/// let sgp4s = from_tle_string(tle).unwrap();
///
/// // Write the element sets to a temporary TLE file
/// let path = std::env::temp_dir().join("mako_sgp4_to_tle_file.tle");
/// let path_str = path.to_str().unwrap();
/// to_tle_file(&sgp4s, path_str).unwrap();
///
/// // Parse the written file
/// let reparsed = from_tle_file(path_str).unwrap();
///
/// // Remove the temporary file
/// let _ = std::fs::remove_file(&path);
///
/// // Assert the round-trip catalog number and name
/// assert_eq!(reparsed.len(), 1);
/// assert_eq!(reparsed[0].gp.satellite_catalog_number, 25544);
/// assert_eq!(reparsed[0].gp.common_name, "ISS (ZARYA)");
/// ```
///
/// # References
/// - [Celestrak TLE Format](https://celestrak.org/columns/v04n03/#FAQ01)
/// - [Alpha-5 Standard](https://www.space-track.org/documentation#tle-alpha5)
pub fn to_tle_file(sgp4s: &[Sgp4], tle_file_path: &str) -> Result<(), GpError> {
    // Serialize the element sets and write the TLE file
    let tle_string = to_tle_string(sgp4s)?;
    fs::write(tle_file_path, tle_string).map_err(|err| GpError::Io(err.to_string()))?;
    Ok(())
}

/// Builds a [`Sgp4`] struct from the lines of a single OMM KVN record.
///
/// Given the key-value lines of one Orbit Mean-Elements Message, this function
/// parses the input into a [`GenPerturbElementSet`] and initializes SGP4,
/// matching [`from_tle_lines`]. Missing numeric fields default to 0 and missing
/// string fields default to an empty string.
///
/// # Arguments
/// * `lines` - The KVN key-value lines of one OMM record
///
/// # Returns
/// * `Ok(Sgp4)` - Struct containing the parsed SGP4 parameters
/// * `Err(GpError)` - If a field cannot be parsed or SGP4 initialization fails
///
/// # Errors
/// * [`GpError::InvalidOmmField`] - If a present field cannot be parsed as the requested type
/// * [`GpError::InvalidOmmEpoch`] - If EPOCH cannot be parsed as a UTC datetime
/// * [`GpError::Sgp4`] - If SGP4 initialization fails
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_omm_kvn_lines;
///
/// // Define one OMM record as key-value lines (missing fields use defaults)
/// let omm = "\
/// OBJECT_NAME    = 2026-106A
/// OBJECT_ID      = 2026-106A
/// EPOCH          = 2026-06-14T15:07:48.259488
/// MEAN_MOTION    = 15.11169557
/// ECCENTRICITY   = .00147468
/// INCLINATION    = 97.5103
/// RA_OF_ASC_NODE = 247.7605
/// ARG_OF_PERICENTER = 169.6213
/// MEAN_ANOMALY   = 190.5325
/// NORAD_CAT_ID   = 69097
/// BSTAR          = .39221734E-3
/// MEAN_MOTION_DOT = .6535E-4
/// MEAN_MOTION_DDOT = 0
/// ";
///
/// // Split the record into trimmed, non-empty lines
/// let lines: Vec<&str> = omm.lines().map(str::trim).filter(|l| !l.is_empty()).collect();
///
/// // Parse the OMM lines into an SGP4 propagator
/// let sgp4 = from_omm_kvn_lines(&lines).unwrap();
///
/// // Assert the catalog number and name
/// assert_eq!(sgp4.gp.satellite_catalog_number, 69097);
/// assert_eq!(sgp4.gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
pub fn from_omm_kvn_lines(lines: &[&str]) -> Result<Sgp4, GpError> {
    sgp4_from_omm_lookup(|field| kvn_lookup(lines, field))
}

/// Builds a vector of [`Sgp4`] structs from a string containing Orbit Mean-Elements Message
/// (OMM) sets in CCSDS KVN (key-value notation) format.
///
/// This function parses a string containing one or more OMM records. A new record
/// starts at each CCSDS_OMM_VERS line. Each record is parsed by
/// [`from_omm_kvn_lines`].
///
/// # Arguments
/// * `omm_kvn_string` - A string containing one or more OMM records in KVN format
///
/// # Returns
/// * `Ok(Vec<Sgp4>)` - All successfully parsed SGP4 parameters
/// * `Err(GpError)` - If a field cannot be parsed or SGP4 initialization fails
///
/// # Errors
/// * [`GpError::InvalidOmmField`] - If a present field cannot be parsed as the requested type
/// * [`GpError::InvalidOmmEpoch`] - If EPOCH cannot be parsed as a UTC datetime
/// * [`GpError::Sgp4`] - If SGP4 initialization fails
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_omm_kvn_string;
///
/// // Define an OMM KVN record. Concatenated records start at each CCSDS_OMM_VERS line
/// let omm = "\
/// CCSDS_OMM_VERS = 2.0
/// OBJECT_NAME    = 2026-106A
/// OBJECT_ID      = 2026-106A
/// EPOCH          = 2026-06-14T15:07:48.259488
/// MEAN_MOTION    = 15.11169557
/// ECCENTRICITY   = .00147468
/// INCLINATION    = 97.5103
/// RA_OF_ASC_NODE = 247.7605
/// ARG_OF_PERICENTER = 169.6213
/// MEAN_ANOMALY   = 190.5325
/// EPHEMERIS_TYPE = 0
/// CLASSIFICATION_TYPE = U
/// NORAD_CAT_ID   = 69097
/// ELEMENT_SET_NO = 999
/// REV_AT_EPOCH   = 459
/// BSTAR          = .39221734E-3
/// MEAN_MOTION_DOT = .6535E-4
/// MEAN_MOTION_DDOT = 0
/// ";
///
/// // Parse the OMM string into SGP4 propagators
/// let sgp4s = from_omm_kvn_string(omm).unwrap();
///
/// // Assert the catalog number and name
/// assert_eq!(sgp4s.len(), 1);
/// assert_eq!(sgp4s[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(sgp4s[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
pub fn from_omm_kvn_string(omm_kvn_string: &str) -> Result<Vec<Sgp4>, GpError> {
    // Split the string into individual OMM records
    let mut sgp4s = Vec::new();
    let mut current_lines: Vec<&str> = Vec::new();

    // Iterate through the lines, starting a new record at each CCSDS_OMM_VERS
    for line in omm_kvn_string.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        // A new CCSDS_OMM_VERS line starts the next concatenated record
        if trimmed.to_ascii_uppercase().starts_with("CCSDS_OMM_VERS") && !current_lines.is_empty() {
            let sgp4 = from_omm_kvn_lines(&current_lines)?;
            sgp4s.push(sgp4);
            current_lines.clear();
        }

        current_lines.push(trimmed);
    }

    // Parse the final record
    if !current_lines.is_empty() {
        let sgp4 = from_omm_kvn_lines(&current_lines)?;
        sgp4s.push(sgp4);
    }

    // Return vector of SGP4 structs
    Ok(sgp4s)
}

/// Builds a vector of [`Sgp4`] structs from a file containing Orbit Mean-Elements Message
/// (OMM) sets in CCSDS KVN format.
///
/// This function parses a file containing one or more OMM records in KVN
/// format and returns all successfully parsed entries.
///
/// # Arguments
/// * `omm_kvn_file_path` - A path to a file containing one or more OMM records in KVN format
///
/// # Returns
/// * `Ok(Vec<Sgp4>)` - All successfully parsed SGP4 structs
/// * `Err(GpError)` - If the file cannot be read or an OMM cannot be parsed
///
/// # Errors
/// * [`GpError::Io`] - If the file cannot be read
/// * [`GpError::InvalidOmmField`] - If a present field cannot be parsed as the requested type
/// * [`GpError::InvalidOmmEpoch`] - If EPOCH cannot be parsed as a UTC datetime
/// * [`GpError::Sgp4`] - If SGP4 initialization fails
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_omm_kvn_file;
///
/// // Define an OMM KVN record
/// let omm = "\
/// CCSDS_OMM_VERS = 2.0
/// OBJECT_NAME    = 2026-106A
/// OBJECT_ID      = 2026-106A
/// EPOCH          = 2026-06-14T15:07:48.259488
/// MEAN_MOTION    = 15.11169557
/// ECCENTRICITY   = .00147468
/// INCLINATION    = 97.5103
/// RA_OF_ASC_NODE = 247.7605
/// ARG_OF_PERICENTER = 169.6213
/// MEAN_ANOMALY   = 190.5325
/// NORAD_CAT_ID   = 69097
/// BSTAR          = .39221734E-3
/// MEAN_MOTION_DOT = .6535E-4
/// MEAN_MOTION_DDOT = 0
/// ";
///
/// // Write the OMM to a temporary file
/// let path = std::env::temp_dir().join("mako_sgp4_from_omm_kvn_file.txt");
/// std::fs::write(&path, omm).unwrap();
///
/// // Parse the OMM file into SGP4 propagators
/// let sgp4s = from_omm_kvn_file(path.to_str().unwrap()).unwrap();
///
/// // Remove the temporary file
/// let _ = std::fs::remove_file(&path);
///
/// // Assert the catalog number and name
/// assert_eq!(sgp4s.len(), 1);
/// assert_eq!(sgp4s[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(sgp4s[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
pub fn from_omm_kvn_file(omm_kvn_file_path: &str) -> Result<Vec<Sgp4>, GpError> {
    // Open the OMM KVN file
    let omm_kvn_string =
        fs::read_to_string(omm_kvn_file_path).map_err(|err| GpError::Io(err.to_string()))?;

    // Parse OMM string into a vector of SGP4 structs
    from_omm_kvn_string(&omm_kvn_string)
}

/// Parse a KVN field from OMM record lines
///
/// Search the provided lines for a key-value entry matching the given field
/// name. Missing or empty fields return a type-specific default: 0 for numbers
/// and an empty string for strings. Classification defaults to U.
///
/// # Arguments
/// * `lines` - The KVN lines of one OMM record
/// * `field` - The KVN keyword to look up
///
/// # Returns
/// * `Ok(T)` - The parsed value as the requested type
/// * `Err(GpError)` - If a present field cannot be parsed
#[cfg(test)]
fn kvn_parse<T: FromOmm>(lines: &[&str], field: &str) -> Result<T, GpError> {
    omm_typed_value(kvn_lookup(lines, field), field)
}

/// Look up a KVN keyword and return the cleaned value, if present
///
/// # Arguments
/// * `lines` - The KVN lines of one OMM record
/// * `field` - The KVN keyword to look up
///
/// # Returns
/// * `Some(value)` - The cleaned field value
/// * `None` - If the field is not present
fn kvn_lookup(lines: &[&str], field: &str) -> Option<String> {
    // Search each line for a matching KVN keyword
    for line in lines {
        let line = line.trim();

        // Skip empty lines and COMMENT lines
        if line.is_empty() || line.to_ascii_uppercase().starts_with("COMMENT") {
            continue;
        }

        // Split KEY = VALUE
        let Some((keyword, value)) = line.split_once('=') else {
            continue;
        };
        if !keyword.trim().eq_ignore_ascii_case(field) {
            continue;
        }

        return Some(clean_kvn_value(value));
    }

    None
}

/// Convert an optional OMM field string into type T
///
/// Missing or empty values use the type default.
///
/// # Arguments
/// * `value` - The raw field text, if the keyword was present
/// * `field` - The OMM keyword name, used in parse error messages
///
/// # Returns
/// * `Ok(T)` - The parsed value as the requested type
/// * `Err(GpError)` - If a present field cannot be parsed
fn omm_typed_value<T: FromOmm>(value: Option<String>, field: &str) -> Result<T, GpError> {
    match value {
        Some(v) if !v.is_empty() => T::from_omm(field, &v),
        _ => Ok(T::omm_default()),
    }
}

/// Build an [`Sgp4`] struct from an OMM field lookup
///
/// Shared by KVN and XML parsers. Missing numeric fields default to 0 and
/// missing string fields default to an empty string. OMM MEAN_MOTION_DOT and
/// MEAN_MOTION_DDOT are the TLE-printed values (already divided by 2 and 6)
/// and are scaled so [`GenPerturbElementSet`] stores the true derivatives.
///
/// # Arguments
/// * `lookup` - Returns the text of one OMM keyword, if present
///
/// # Returns
/// * `Ok(Sgp4)` - Struct containing the parsed SGP4 parameters
/// * `Err(GpError)` - If a field cannot be parsed or SGP4 initialization fails
fn sgp4_from_omm_lookup<F>(lookup: F) -> Result<Sgp4, GpError>
where
    F: Fn(&str) -> Option<String>,
{
    // Create a General Perturbation Element Set struct
    let gp = GenPerturbElementSet {
        common_name: omm_typed_value(lookup("OBJECT_NAME"), "OBJECT_NAME")?,
        satellite_catalog_number: omm_typed_value(lookup("NORAD_CAT_ID"), "NORAD_CAT_ID")?,
        classification: omm_typed_value(lookup("CLASSIFICATION_TYPE"), "CLASSIFICATION_TYPE")?,
        international_designator: omm_typed_value(lookup("OBJECT_ID"), "OBJECT_ID")?,
        epoch_datetime: omm_typed_value(lookup("EPOCH"), "EPOCH")?,
        first_derivative_of_mean_motion: omm_typed_value::<f64>(
            lookup("MEAN_MOTION_DOT"),
            "MEAN_MOTION_DOT",
        )? * 2.0,
        second_derivative_of_mean_motion: omm_typed_value::<f64>(
            lookup("MEAN_MOTION_DDOT"),
            "MEAN_MOTION_DDOT",
        )? * 6.0,
        bstar: omm_typed_value(lookup("BSTAR"), "BSTAR")?,
        ephemeris_type: omm_typed_value(lookup("EPHEMERIS_TYPE"), "EPHEMERIS_TYPE")?,
        element_set_number: omm_typed_value(lookup("ELEMENT_SET_NO"), "ELEMENT_SET_NO")?,
        inclination: omm_typed_value(lookup("INCLINATION"), "INCLINATION")?,
        right_ascension_of_ascending_node: omm_typed_value(
            lookup("RA_OF_ASC_NODE"),
            "RA_OF_ASC_NODE",
        )?,
        eccentricity: omm_typed_value(lookup("ECCENTRICITY"), "ECCENTRICITY")?,
        argument_of_perigee: omm_typed_value(lookup("ARG_OF_PERICENTER"), "ARG_OF_PERICENTER")?,
        mean_anomaly: omm_typed_value(lookup("MEAN_ANOMALY"), "MEAN_ANOMALY")?,
        mean_motion: omm_typed_value(lookup("MEAN_MOTION"), "MEAN_MOTION")?,
        revolution_number_at_epoch: omm_typed_value(lookup("REV_AT_EPOCH"), "REV_AT_EPOCH")?,
        tle_checksum_valid: None,
    };

    // Initialize the SGP4 parameters
    init_sgp4(&gp, None).map_err(GpError::Sgp4)
}

/// Clean a KVN value string
///
/// Trim whitespace, strip matching double quotes, and remove optional trailing
/// units written in square brackets.
///
/// # Arguments
/// * `value` - The raw value text to the right of the equals sign
///
/// # Returns
/// * The cleaned value string
fn clean_kvn_value(value: &str) -> String {
    let mut v = value.trim();

    // Strip matching double quotes
    if v.len() >= 2 && v.starts_with('"') && v.ends_with('"') {
        v = &v[1..v.len() - 1];
        v = v.trim();
    }

    // Strip optional units in square brackets
    if let Some(idx) = v.find('[') {
        v = v[..idx].trim();
    }

    v.to_string()
}

/// Format one CCSDS KVN keyword and value line
///
/// Keywords of 14 characters or fewer are padded so the equals sign aligns
/// with Celestrak OMM KVN files.
///
/// # Arguments
/// * `keyword` - The KVN keyword
/// * `value` - The KVN value
///
/// # Returns
/// * One `KEYWORD = VALUE` line
fn format_kvn_line(keyword: &str, value: &str) -> String {
    if keyword.len() >= 14 {
        format!("{} = {}", keyword, value)
    } else {
        format!("{:<14} = {}", keyword, value)
    }
}

/// Trim trailing zeros from a decimal string
///
/// # Arguments
/// * `value` - A decimal number already formatted as text
///
/// # Returns
/// * The number text without trailing fractional zeros
fn trim_decimal_zeros(value: &str) -> String {
    if !value.contains('.') {
        return value.to_string();
    }

    let trimmed = value.trim_end_matches('0');
    if trimmed.ends_with('.') {
        return trimmed.trim_end_matches('.').to_string();
    }
    trimmed.to_string()
}

/// Strip a leading zero before a decimal point
///
/// Celestrak OMM text uses `.00147468` rather than `0.00147468`. Whole
/// numbers such as `0` are left unchanged.
///
/// # Arguments
/// * `value` - A decimal number already formatted as text
///
/// # Returns
/// * The number text without a leading zero before the decimal point
fn strip_leading_decimal_zero(value: &str) -> String {
    if let Some(rest) = value.strip_prefix("-0.") {
        return format!("-.{}", rest);
    }
    if let Some(rest) = value.strip_prefix("0.") {
        return format!(".{}", rest);
    }
    value.to_string()
}

/// Format an OMM decimal number
///
/// Rounds to 12 decimal places to suppress binary float noise, then drops
/// trailing zeros. Values between -1 and 1 are written without a leading
/// zero (`.###`). Zero is written as `0`.
///
/// # Arguments
/// * `value` - The number to format
///
/// # Returns
/// * Decimal text suitable for a KVN, XML, or CSV value
fn format_omm_decimal(value: f64) -> String {
    if value == 0.0 {
        return "0".to_string();
    }

    let rounded = (value * 1e12).round() / 1e12;
    strip_leading_decimal_zero(&trim_decimal_zeros(&format!("{:.12}", rounded)))
}

/// Format an OMM scientific-notation number
///
/// Matches Celestrak style: a leading decimal mantissa and an explicit
/// exponent sign, for example `.39221734E-3`. Zero is written as `0`.
///
/// # Arguments
/// * `value` - The number to format
///
/// # Returns
/// * Scientific-notation text suitable for BSTAR, MEAN_MOTION_DOT, and
///   MEAN_MOTION_DDOT
fn format_omm_sci(value: f64) -> String {
    if value == 0.0 {
        return "0".to_string();
    }

    let sign = if value < 0.0 { "-" } else { "" };
    let abs = value.abs();

    // Mantissa in [0.1, 1) so the leading digit sits after the decimal point
    let mut exp = abs.log10().floor() as i32 + 1;
    let mut mantissa = abs / 10f64.powi(exp);

    if mantissa >= 1.0 {
        mantissa /= 10.0;
        exp += 1;
    } else if mantissa < 0.1 {
        mantissa *= 10.0;
        exp -= 1;
    }

    // 10 digits after the decimal, then drop trailing zeros
    const SCALE: f64 = 10_000_000_000.0;
    let mut digits = (mantissa * SCALE).round() as i64;
    if digits >= 10_000_000_000 {
        exp += 1;
        digits = 1_000_000_000;
    }

    let mut frac = format!("{:010}", digits);
    frac = frac.trim_end_matches('0').to_string();
    if frac.is_empty() {
        frac = "0".to_string();
    }

    let exp_sign = if exp >= 0 { "+" } else { "-" };
    format!("{}.{}E{}{}", sign, frac, exp_sign, exp.abs())
}

/// Format an OMM EPOCH string from a UTC datetime
///
/// Writes `YYYY-MM-DDTHH:MM:SS.ssssss` with six fractional-second digits.
///
/// # Arguments
/// * `epoch` - The epoch datetime
///
/// # Returns
/// * The EPOCH value in CCSDS calendar form
fn format_omm_epoch(epoch: &DateTime) -> String {
    let mut second = epoch.second;
    if second < 0.0 {
        second = 0.0;
    }
    if second >= 60.0 {
        second = 59.999999;
    }

    format!(
        "{:04}-{:02}-{:02}T{:02}:{:02}:{:09.6}",
        epoch.year, epoch.month, epoch.day, epoch.hour, epoch.minute, second
    )
}

/// Format a classification character for OMM export
///
/// Non-printable values default to unclassified (`U`).
///
/// # Arguments
/// * `classification` - The GP classification character
///
/// # Returns
/// * A single-character CLASSIFICATION_TYPE value
fn format_omm_classification(classification: char) -> String {
    if classification.is_ascii_graphic() {
        return classification.to_string();
    }
    "U".to_string()
}

/// Build one OMM KVN record from a general perturbation element set
///
/// Metadata that is not stored on [`GenPerturbElementSet`] is filled with
/// SGP4 defaults. MEAN_MOTION_DOT and MEAN_MOTION_DDOT are written as the
/// TLE-printed values (stored derivatives divided by 2 and 6).
///
/// # Arguments
/// * `gp` - The element set to serialize
///
/// # Returns
/// * One OMM record in KVN format, including a trailing newline
fn gp_to_omm_kvn(gp: &GenPerturbElementSet) -> String {
    // OMM MEAN_MOTION_DOT and MEAN_MOTION_DDOT are the TLE-printed values
    let mean_motion_dot = gp.first_derivative_of_mean_motion / 2.0;
    let mean_motion_ddot = gp.second_derivative_of_mean_motion / 6.0;

    vec![
        // Header
        format_kvn_line("CCSDS_OMM_VERS", "2.0"),
        format_kvn_line("CREATION_DATE", ""),
        format_kvn_line("ORIGINATOR", ""),
        String::new(),
        // Metadata
        format_kvn_line("OBJECT_NAME", &gp.common_name),
        format_kvn_line("OBJECT_ID", &gp.international_designator),
        format_kvn_line("CENTER_NAME", "EARTH"),
        format_kvn_line("REF_FRAME", "TEME"),
        format_kvn_line("TIME_SYSTEM", "UTC"),
        format_kvn_line("MEAN_ELEMENT_THEORY", "SGP/SGP4"),
        String::new(),
        // Mean elements
        format_kvn_line("EPOCH", &format_omm_epoch(&gp.epoch_datetime)),
        format_kvn_line("MEAN_MOTION", &format_omm_decimal(gp.mean_motion)),
        format_kvn_line("ECCENTRICITY", &format_omm_decimal(gp.eccentricity)),
        format_kvn_line("INCLINATION", &format_omm_decimal(gp.inclination)),
        format_kvn_line(
            "RA_OF_ASC_NODE",
            &format_omm_decimal(gp.right_ascension_of_ascending_node),
        ),
        format_kvn_line(
            "ARG_OF_PERICENTER",
            &format_omm_decimal(gp.argument_of_perigee),
        ),
        format_kvn_line("MEAN_ANOMALY", &format_omm_decimal(gp.mean_anomaly)),
        String::new(),
        // TLE / SGP4 parameters
        format_kvn_line("EPHEMERIS_TYPE", &gp.ephemeris_type.to_string()),
        format_kvn_line(
            "CLASSIFICATION_TYPE",
            &format_omm_classification(gp.classification),
        ),
        format_kvn_line("NORAD_CAT_ID", &gp.satellite_catalog_number.to_string()),
        format_kvn_line("ELEMENT_SET_NO", &gp.element_set_number.to_string()),
        format_kvn_line("REV_AT_EPOCH", &gp.revolution_number_at_epoch.to_string()),
        format_kvn_line("BSTAR", &format_omm_sci(gp.bstar)),
        format_kvn_line("MEAN_MOTION_DOT", &format_omm_sci(mean_motion_dot)),
        format_kvn_line("MEAN_MOTION_DDOT", &format_omm_sci(mean_motion_ddot)),
        // Trailing newline so concatenated records split on CCSDS_OMM_VERS
        String::new(),
    ]
    .join("\n")
}

/// Builds a CCSDS KVN OMM string from a slice of [`Sgp4`] structs.
///
/// Each element set is written as one OMM record starting with
/// `CCSDS_OMM_VERS`. Metadata fields that are not stored on
/// [`GenPerturbElementSet`] are filled with SGP4 defaults: Earth-centered,
/// TEME, UTC, and SGP/SGP4. CREATION_DATE and ORIGINATOR are left empty.
/// OMM MEAN_MOTION_DOT and MEAN_MOTION_DDOT are the TLE-printed values
/// (the stored derivatives divided by 2 and 6).
///
/// An empty slice produces an empty string.
///
/// # Arguments
/// * `sgp4s` - The SGP4 structs to export
///
/// # Returns
/// * `String` - One or more OMM records in KVN format
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::{from_omm_kvn_string, to_omm_kvn_string};
///
/// // Define an OMM KVN record
/// let omm = "\
/// CCSDS_OMM_VERS = 2.0
/// OBJECT_NAME    = 2026-106A
/// OBJECT_ID      = 2026-106A
/// EPOCH          = 2026-06-14T15:07:48.259488
/// MEAN_MOTION    = 15.11169557
/// ECCENTRICITY   = .00147468
/// INCLINATION    = 97.5103
/// RA_OF_ASC_NODE = 247.7605
/// ARG_OF_PERICENTER = 169.6213
/// MEAN_ANOMALY   = 190.5325
/// NORAD_CAT_ID   = 69097
/// BSTAR          = .39221734E-3
/// MEAN_MOTION_DOT = .6535E-4
/// MEAN_MOTION_DDOT = 0
/// ";
///
/// // Parse, export, and parse again
/// let sgp4s = from_omm_kvn_string(omm).unwrap();
/// let exported = to_omm_kvn_string(&sgp4s);
/// let reparsed = from_omm_kvn_string(&exported).unwrap();
///
/// // Assert the round-trip catalog number and name
/// assert_eq!(reparsed.len(), 1);
/// assert_eq!(reparsed[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(reparsed[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
pub fn to_omm_kvn_string(sgp4s: &[Sgp4]) -> String {
    // Serialize each element set as one KVN record
    let mut records = String::new();
    for sgp4 in sgp4s {
        records.push_str(&gp_to_omm_kvn(&sgp4.gp));
    }

    records
}

/// Writes a CCSDS KVN OMM file from a slice of [`Sgp4`] structs.
///
/// This function serializes the provided element sets with
/// [`to_omm_kvn_string`] and writes the result to `omm_kvn_file_path`.
///
/// # Arguments
/// * `sgp4s` - The SGP4 structs to export
/// * `omm_kvn_file_path` - Destination path for the KVN file
///
/// # Returns
/// * `Ok(())` - If the file is written
/// * `Err(GpError)` - If the file cannot be written
///
/// # Errors
/// * [`GpError::Io`] - If the file cannot be written
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::{from_omm_kvn_file, from_omm_kvn_string, to_omm_kvn_file};
///
/// // Define an OMM KVN record and parse it
/// let omm = "\
/// CCSDS_OMM_VERS = 2.0
/// OBJECT_NAME    = 2026-106A
/// OBJECT_ID      = 2026-106A
/// EPOCH          = 2026-06-14T15:07:48.259488
/// MEAN_MOTION    = 15.11169557
/// ECCENTRICITY   = .00147468
/// INCLINATION    = 97.5103
/// RA_OF_ASC_NODE = 247.7605
/// ARG_OF_PERICENTER = 169.6213
/// MEAN_ANOMALY   = 190.5325
/// NORAD_CAT_ID   = 69097
/// BSTAR          = .39221734E-3
/// MEAN_MOTION_DOT = .6535E-4
/// MEAN_MOTION_DDOT = 0
/// ";
/// let sgp4s = from_omm_kvn_string(omm).unwrap();
///
/// // Write the element sets to a temporary KVN file
/// let path = std::env::temp_dir().join("mako_sgp4_to_omm_kvn_file.txt");
/// let path_str = path.to_str().unwrap();
/// to_omm_kvn_file(&sgp4s, path_str).unwrap();
///
/// // Parse the written file
/// let reparsed = from_omm_kvn_file(path_str).unwrap();
///
/// // Remove the temporary file
/// let _ = std::fs::remove_file(&path);
///
/// // Assert the round-trip catalog number and name
/// assert_eq!(reparsed.len(), 1);
/// assert_eq!(reparsed[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(reparsed[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
pub fn to_omm_kvn_file(sgp4s: &[Sgp4], omm_kvn_file_path: &str) -> Result<(), GpError> {
    // Serialize the element sets and write the KVN file
    let omm_kvn_string = to_omm_kvn_string(sgp4s);
    fs::write(omm_kvn_file_path, omm_kvn_string).map_err(|err| GpError::Io(err.to_string()))?;
    Ok(())
}

/// Collect leaf OMM keyword values from one XML omm element
///
/// Wrapper tags (metadata, meanElements, tleParameters) and COMMENT elements
/// are skipped. Keys are stored in uppercase so lookup is case-insensitive.
///
/// # Arguments
/// * `omm` - The omm element to flatten
///
/// # Returns
/// * A map of OMM keyword to text value
#[cfg(feature = "xml")]
fn xml_omm_fields(omm: Node) -> HashMap<String, String> {
    let mut fields = HashMap::new();

    for node in omm.descendants() {
        if !node.is_element() {
            continue;
        }

        let name = node.tag_name().name();

        // Skip the record root, comments, and wrapper elements with children
        if name.eq_ignore_ascii_case("omm") || name.eq_ignore_ascii_case("COMMENT") {
            continue;
        }
        if node.children().any(|child| child.is_element()) {
            continue;
        }

        let text = node.text().unwrap_or("").trim();
        fields.insert(name.to_ascii_uppercase(), text.to_string());
    }

    fields
}

/// Builds a vector of [`Sgp4`] structs from a string containing Orbit Mean-Elements Message
/// (OMM) sets in CCSDS XML format.
///
/// This function parses a string containing one or more OMM records. Each
/// omm element is flattened to keyword and value pairs by local tag name, then
/// initialized with the same GP mapping as [`from_omm_kvn_lines`]. COMMENT
/// elements and wrapper tags are ignored. Empty tags use the same defaults
/// as missing KVN fields.
///
/// # Arguments
/// * `omm_xml_string` - A string containing one or more OMM records in XML format
///
/// # Returns
/// * `Ok(Vec<Sgp4>)` - All successfully parsed SGP4 parameters
/// * `Err(GpError)` - If the XML document or a field cannot be parsed
///
/// # Errors
/// * [`GpError::InvalidOmmXml`] - If the XML document cannot be parsed
/// * [`GpError::InvalidOmmField`] - If a present field cannot be parsed as the requested type
/// * [`GpError::InvalidOmmEpoch`] - If EPOCH cannot be parsed as a UTC datetime
/// * [`GpError::Sgp4`] - If SGP4 initialization fails
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_omm_xml_string;
///
/// // Define an OMM XML document with one omm record
/// let omm = r#"<ndm>
/// <omm id="CCSDS_OMM_VERS" version="2.0">
/// <body><segment>
/// <metadata>
/// <OBJECT_NAME>2026-106A</OBJECT_NAME>
/// <OBJECT_ID>2026-106A</OBJECT_ID>
/// </metadata>
/// <data><meanElements>
/// <EPOCH>2026-06-14T15:07:48.259488</EPOCH>
/// <MEAN_MOTION>15.11169557</MEAN_MOTION>
/// <ECCENTRICITY>.00147468</ECCENTRICITY>
/// <INCLINATION>97.5103</INCLINATION>
/// <RA_OF_ASC_NODE>247.7605</RA_OF_ASC_NODE>
/// <ARG_OF_PERICENTER>169.6213</ARG_OF_PERICENTER>
/// <MEAN_ANOMALY>190.5325</MEAN_ANOMALY>
/// </meanElements><tleParameters>
/// <EPHEMERIS_TYPE>0</EPHEMERIS_TYPE>
/// <CLASSIFICATION_TYPE>U</CLASSIFICATION_TYPE>
/// <NORAD_CAT_ID>69097</NORAD_CAT_ID>
/// <ELEMENT_SET_NO>999</ELEMENT_SET_NO>
/// <REV_AT_EPOCH>459</REV_AT_EPOCH>
/// <BSTAR>.39221734E-3</BSTAR>
/// <MEAN_MOTION_DOT>.6535E-4</MEAN_MOTION_DOT>
/// <MEAN_MOTION_DDOT>0</MEAN_MOTION_DDOT>
/// </tleParameters></data>
/// </segment></body></omm></ndm>"#;
///
/// // Parse the OMM XML into SGP4 propagators
/// let sgp4s = from_omm_xml_string(omm).unwrap();
///
/// // Assert the catalog number and name
/// assert_eq!(sgp4s.len(), 1);
/// assert_eq!(sgp4s[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(sgp4s[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
#[cfg(feature = "xml")]
pub fn from_omm_xml_string(omm_xml_string: &str) -> Result<Vec<Sgp4>, GpError> {
    // Parse the XML document
    let doc = Document::parse(omm_xml_string).map_err(|_| GpError::InvalidOmmXml)?;

    // Each omm element is one GP record
    let mut sgp4s = Vec::new();
    for node in doc.descendants() {
        if !node.is_element() {
            continue;
        }
        if !node.tag_name().name().eq_ignore_ascii_case("omm") {
            continue;
        }

        let fields = xml_omm_fields(node);
        let sgp4 = sgp4_from_omm_lookup(|field| fields.get(&field.to_ascii_uppercase()).cloned())?;
        sgp4s.push(sgp4);
    }

    // Return vector of SGP4 structs
    Ok(sgp4s)
}

/// Builds a vector of [`Sgp4`] structs from a file containing Orbit Mean-Elements Message
/// (OMM) sets in CCSDS XML format.
///
/// This function parses a file containing one or more OMM records in XML
/// format and returns all successfully parsed entries.
///
/// # Arguments
/// * `omm_xml_file_path` - A path to a file containing one or more OMM records in XML format
///
/// # Returns
/// * `Ok(Vec<Sgp4>)` - All successfully parsed SGP4 structs
/// * `Err(GpError)` - If the file cannot be read or the XML cannot be parsed
///
/// # Errors
/// * [`GpError::Io`] - If the file cannot be read
/// * [`GpError::InvalidOmmXml`] - If the XML document cannot be parsed
/// * [`GpError::InvalidOmmField`] - If a present field cannot be parsed as the requested type
/// * [`GpError::InvalidOmmEpoch`] - If EPOCH cannot be parsed as a UTC datetime
/// * [`GpError::Sgp4`] - If SGP4 initialization fails
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_omm_xml_file;
///
/// // Define an OMM XML document with one omm record
/// let omm = r#"<ndm>
/// <omm id="CCSDS_OMM_VERS" version="2.0">
/// <body><segment>
/// <metadata>
/// <OBJECT_NAME>2026-106A</OBJECT_NAME>
/// <OBJECT_ID>2026-106A</OBJECT_ID>
/// </metadata>
/// <data><meanElements>
/// <EPOCH>2026-06-14T15:07:48.259488</EPOCH>
/// <MEAN_MOTION>15.11169557</MEAN_MOTION>
/// <ECCENTRICITY>.00147468</ECCENTRICITY>
/// <INCLINATION>97.5103</INCLINATION>
/// <RA_OF_ASC_NODE>247.7605</RA_OF_ASC_NODE>
/// <ARG_OF_PERICENTER>169.6213</ARG_OF_PERICENTER>
/// <MEAN_ANOMALY>190.5325</MEAN_ANOMALY>
/// </meanElements><tleParameters>
/// <NORAD_CAT_ID>69097</NORAD_CAT_ID>
/// <BSTAR>.39221734E-3</BSTAR>
/// <MEAN_MOTION_DOT>.6535E-4</MEAN_MOTION_DOT>
/// <MEAN_MOTION_DDOT>0</MEAN_MOTION_DDOT>
/// </tleParameters></data>
/// </segment></body></omm></ndm>"#;
///
/// // Write the OMM to a temporary file
/// let path = std::env::temp_dir().join("mako_sgp4_from_omm_xml_file.xml");
/// std::fs::write(&path, omm).unwrap();
///
/// // Parse the OMM file into SGP4 propagators
/// let sgp4s = from_omm_xml_file(path.to_str().unwrap()).unwrap();
///
/// // Remove the temporary file
/// let _ = std::fs::remove_file(&path);
///
/// // Assert the catalog number and name
/// assert_eq!(sgp4s.len(), 1);
/// assert_eq!(sgp4s[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(sgp4s[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
#[cfg(feature = "xml")]
pub fn from_omm_xml_file(omm_xml_file_path: &str) -> Result<Vec<Sgp4>, GpError> {
    // Open the OMM XML file
    let omm_xml_string =
        fs::read_to_string(omm_xml_file_path).map_err(|err| GpError::Io(err.to_string()))?;

    // Parse OMM string into a vector of SGP4 structs
    from_omm_xml_string(&omm_xml_string)
}

/// Escape text for inclusion in an XML element
///
/// Replaces the five XML markup characters so satellite names and other
/// free-text fields remain well-formed.
///
/// # Arguments
/// * `value` - The raw text to escape
///
/// # Returns
/// * The escaped text
#[cfg(feature = "xml")]
fn escape_xml_text(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for c in value.chars() {
        match c {
            '&' => escaped.push_str("&amp;"),
            '<' => escaped.push_str("&lt;"),
            '>' => escaped.push_str("&gt;"),
            '"' => escaped.push_str("&quot;"),
            '\'' => escaped.push_str("&apos;"),
            _ => escaped.push(c),
        }
    }
    escaped
}

/// Format one XML element from a keyword and value
///
/// Empty values are written as a self-closing tag, matching Celestrak OMM XML.
///
/// # Arguments
/// * `name` - The XML element name
/// * `value` - The element text
///
/// # Returns
/// * One XML element
#[cfg(feature = "xml")]
fn format_xml_tag(name: &str, value: &str) -> String {
    if value.is_empty() {
        format!("<{} />", name)
    } else {
        format!("<{}>{}</{}>", name, escape_xml_text(value), name)
    }
}

/// Build one OMM XML record from a general perturbation element set
///
/// Metadata that is not stored on [`GenPerturbElementSet`] is filled with
/// SGP4 defaults. MEAN_MOTION_DOT and MEAN_MOTION_DDOT are written as the
/// TLE-printed values (stored derivatives divided by 2 and 6). Layout matches
/// Celestrak: the `omm` opening tag on its own line, then the record body
/// packed onto the next line.
///
/// # Arguments
/// * `gp` - The element set to serialize
///
/// # Returns
/// * One `omm` element, including a trailing newline
#[cfg(feature = "xml")]
fn gp_to_omm_xml(gp: &GenPerturbElementSet) -> String {
    // OMM MEAN_MOTION_DOT and MEAN_MOTION_DDOT are the TLE-printed values
    let mean_motion_dot = gp.first_derivative_of_mean_motion / 2.0;
    let mean_motion_ddot = gp.second_derivative_of_mean_motion / 6.0;

    let mut xml = String::from("<omm id=\"CCSDS_OMM_VERS\" version=\"2.0\">\n");
    xml.push_str("<header><CREATION_DATE /><ORIGINATOR /></header>");
    xml.push_str("<body><segment><metadata>");
    xml.push_str(&format_xml_tag("OBJECT_NAME", &gp.common_name));
    xml.push_str(&format_xml_tag("OBJECT_ID", &gp.international_designator));
    xml.push_str(&format_xml_tag("CENTER_NAME", "EARTH"));
    xml.push_str(&format_xml_tag("REF_FRAME", "TEME"));
    xml.push_str(&format_xml_tag("TIME_SYSTEM", "UTC"));
    xml.push_str(&format_xml_tag("MEAN_ELEMENT_THEORY", "SGP4"));
    xml.push_str("</metadata><data><meanElements>");
    xml.push_str(&format_xml_tag(
        "EPOCH",
        &format_omm_epoch(&gp.epoch_datetime),
    ));
    xml.push_str(&format_xml_tag(
        "MEAN_MOTION",
        &format_omm_decimal(gp.mean_motion),
    ));
    xml.push_str(&format_xml_tag(
        "ECCENTRICITY",
        &format_omm_decimal(gp.eccentricity),
    ));
    xml.push_str(&format_xml_tag(
        "INCLINATION",
        &format_omm_decimal(gp.inclination),
    ));
    xml.push_str(&format_xml_tag(
        "RA_OF_ASC_NODE",
        &format_omm_decimal(gp.right_ascension_of_ascending_node),
    ));
    xml.push_str(&format_xml_tag(
        "ARG_OF_PERICENTER",
        &format_omm_decimal(gp.argument_of_perigee),
    ));
    xml.push_str(&format_xml_tag(
        "MEAN_ANOMALY",
        &format_omm_decimal(gp.mean_anomaly),
    ));
    xml.push_str("</meanElements><tleParameters>");
    xml.push_str(&format_xml_tag(
        "EPHEMERIS_TYPE",
        &gp.ephemeris_type.to_string(),
    ));
    xml.push_str(&format_xml_tag(
        "CLASSIFICATION_TYPE",
        &format_omm_classification(gp.classification),
    ));
    xml.push_str(&format_xml_tag(
        "NORAD_CAT_ID",
        &gp.satellite_catalog_number.to_string(),
    ));
    xml.push_str(&format_xml_tag(
        "ELEMENT_SET_NO",
        &gp.element_set_number.to_string(),
    ));
    xml.push_str(&format_xml_tag(
        "REV_AT_EPOCH",
        &gp.revolution_number_at_epoch.to_string(),
    ));
    xml.push_str(&format_xml_tag("BSTAR", &format_omm_sci(gp.bstar)));
    xml.push_str(&format_xml_tag(
        "MEAN_MOTION_DOT",
        &format_omm_sci(mean_motion_dot),
    ));
    xml.push_str(&format_xml_tag(
        "MEAN_MOTION_DDOT",
        &format_omm_sci(mean_motion_ddot),
    ));
    xml.push_str("</tleParameters></data></segment></body></omm>\n");

    xml
}

/// Builds a CCSDS XML OMM string from a slice of [`Sgp4`] structs.
///
/// Each element set is written as one `omm` record inside an `ndm` document.
/// The `ndm` root includes the CCSDS NDM XML schema location used by
/// Celestrak. Metadata fields that are not stored on
/// [`GenPerturbElementSet`] are filled with SGP4 defaults: Earth-centered,
/// TEME, UTC, and SGP4. CREATION_DATE and ORIGINATOR are left empty.
/// OMM MEAN_MOTION_DOT and MEAN_MOTION_DDOT are the TLE-printed values
/// (the stored derivatives divided by 2 and 6).
///
/// An empty slice produces an `ndm` document with no `omm` records.
///
/// # Arguments
/// * `sgp4s` - The SGP4 structs to export
///
/// # Returns
/// * `String` - An NDM XML document containing one or more OMM records
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::{from_omm_xml_string, to_omm_xml_string};
///
/// // Define an OMM XML document with one omm record
/// let omm = r#"<ndm>
/// <omm id="CCSDS_OMM_VERS" version="2.0">
/// <body><segment>
/// <metadata>
/// <OBJECT_NAME>2026-106A</OBJECT_NAME>
/// <OBJECT_ID>2026-106A</OBJECT_ID>
/// </metadata>
/// <data><meanElements>
/// <EPOCH>2026-06-14T15:07:48.259488</EPOCH>
/// <MEAN_MOTION>15.11169557</MEAN_MOTION>
/// <ECCENTRICITY>.00147468</ECCENTRICITY>
/// <INCLINATION>97.5103</INCLINATION>
/// <RA_OF_ASC_NODE>247.7605</RA_OF_ASC_NODE>
/// <ARG_OF_PERICENTER>169.6213</ARG_OF_PERICENTER>
/// <MEAN_ANOMALY>190.5325</MEAN_ANOMALY>
/// </meanElements><tleParameters>
/// <NORAD_CAT_ID>69097</NORAD_CAT_ID>
/// <BSTAR>.39221734E-3</BSTAR>
/// <MEAN_MOTION_DOT>.6535E-4</MEAN_MOTION_DOT>
/// <MEAN_MOTION_DDOT>0</MEAN_MOTION_DDOT>
/// </tleParameters></data>
/// </segment></body></omm></ndm>"#;
///
/// // Parse, export, and parse again
/// let sgp4s = from_omm_xml_string(omm).unwrap();
/// let exported = to_omm_xml_string(&sgp4s);
/// let reparsed = from_omm_xml_string(&exported).unwrap();
///
/// // Assert the round-trip catalog number and name
/// assert_eq!(reparsed.len(), 1);
/// assert_eq!(reparsed[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(reparsed[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
#[cfg(feature = "xml")]
pub fn to_omm_xml_string(sgp4s: &[Sgp4]) -> String {
    // Wrap all records in an NDM document with the CCSDS schema location
    let mut xml = String::from(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
         <ndm xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \
         xsi:noNamespaceSchemaLocation=\"https://sanaregistry.org/r/ndmxml_unqualified/ndmxml-2.0.0-master-2.0.xsd\">\n",
    );
    for sgp4 in sgp4s {
        xml.push_str(&gp_to_omm_xml(&sgp4.gp));
    }
    xml.push_str("</ndm>\n");

    xml
}

/// Writes a CCSDS XML OMM file from a slice of [`Sgp4`] structs.
///
/// This function serializes the provided element sets with
/// [`to_omm_xml_string`] and writes the result to `omm_xml_file_path`.
///
/// # Arguments
/// * `sgp4s` - The SGP4 structs to export
/// * `omm_xml_file_path` - Destination path for the XML file
///
/// # Returns
/// * `Ok(())` - If the file is written
/// * `Err(GpError)` - If the file cannot be written
///
/// # Errors
/// * [`GpError::Io`] - If the file cannot be written
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::{from_omm_xml_file, from_omm_xml_string, to_omm_xml_file};
///
/// // Define an OMM XML document and parse it
/// let omm = r#"<ndm>
/// <omm id="CCSDS_OMM_VERS" version="2.0">
/// <body><segment>
/// <metadata>
/// <OBJECT_NAME>2026-106A</OBJECT_NAME>
/// <OBJECT_ID>2026-106A</OBJECT_ID>
/// </metadata>
/// <data><meanElements>
/// <EPOCH>2026-06-14T15:07:48.259488</EPOCH>
/// <MEAN_MOTION>15.11169557</MEAN_MOTION>
/// <ECCENTRICITY>.00147468</ECCENTRICITY>
/// <INCLINATION>97.5103</INCLINATION>
/// <RA_OF_ASC_NODE>247.7605</RA_OF_ASC_NODE>
/// <ARG_OF_PERICENTER>169.6213</ARG_OF_PERICENTER>
/// <MEAN_ANOMALY>190.5325</MEAN_ANOMALY>
/// </meanElements><tleParameters>
/// <NORAD_CAT_ID>69097</NORAD_CAT_ID>
/// <BSTAR>.39221734E-3</BSTAR>
/// <MEAN_MOTION_DOT>.6535E-4</MEAN_MOTION_DOT>
/// <MEAN_MOTION_DDOT>0</MEAN_MOTION_DDOT>
/// </tleParameters></data>
/// </segment></body></omm></ndm>"#;
/// let sgp4s = from_omm_xml_string(omm).unwrap();
///
/// // Write the element sets to a temporary XML file
/// let path = std::env::temp_dir().join("mako_sgp4_to_omm_xml_file.xml");
/// let path_str = path.to_str().unwrap();
/// to_omm_xml_file(&sgp4s, path_str).unwrap();
///
/// // Parse the written file
/// let reparsed = from_omm_xml_file(path_str).unwrap();
///
/// // Remove the temporary file
/// let _ = std::fs::remove_file(&path);
///
/// // Assert the round-trip catalog number and name
/// assert_eq!(reparsed.len(), 1);
/// assert_eq!(reparsed[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(reparsed[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
#[cfg(feature = "xml")]
pub fn to_omm_xml_file(sgp4s: &[Sgp4], omm_xml_file_path: &str) -> Result<(), GpError> {
    // Serialize the element sets and write the XML file
    let omm_xml_string = to_omm_xml_string(sgp4s);
    fs::write(omm_xml_file_path, omm_xml_string).map_err(|err| GpError::Io(err.to_string()))?;
    Ok(())
}

/// Build an [`Sgp4`] struct from one JSON OMM object
///
/// # Arguments
/// * `record` - One OMM record as a JSON object
///
/// # Returns
/// * `Ok(Sgp4)` - Struct containing the parsed SGP4 parameters
/// * `Err(GpError)` - If the JSON value is not an object or a field cannot be parsed
#[cfg(feature = "json")]
fn sgp4_from_json_record(record: &Value) -> Result<Sgp4, GpError> {
    let fields = json_omm_fields(record)?;
    sgp4_from_omm_lookup(|field| fields.get(&field.to_ascii_uppercase()).cloned())
}

/// Builds a vector of [`Sgp4`] structs from a string containing Orbit Mean-Elements Message
/// (OMM) sets in JSON format.
///
/// This function parses a string containing one OMM object or an array of OMM
/// objects. Each object is flattened to keyword and value pairs, then
/// initialized with the same GP mapping as [`from_omm_kvn_lines`]. JSON numbers
/// are converted to text. Null, missing, and empty string fields use the same
/// defaults as missing KVN fields.
///
/// # Arguments
/// * `omm_json_string` - A string containing one or more OMM records in JSON format
///
/// # Returns
/// * `Ok(Vec<Sgp4>)` - All successfully parsed SGP4 parameters
/// * `Err(GpError)` - If the JSON document or a field cannot be parsed
///
/// # Errors
/// * [`GpError::InvalidOmmJson`] - If the JSON cannot be parsed or is not an object or array of objects
/// * [`GpError::InvalidOmmField`] - If a present field cannot be parsed as the requested type
/// * [`GpError::InvalidOmmEpoch`] - If EPOCH cannot be parsed as a UTC datetime
/// * [`GpError::Sgp4`] - If SGP4 initialization fails
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_omm_json_string;
///
/// // Define OMM JSON as an array of objects (a single object is also accepted)
/// let omm = r#"[
/// {
/// "OBJECT_NAME": "2026-106A",
/// "OBJECT_ID": "2026-106A",
/// "EPOCH": "2026-06-14T15:07:48.259488",
/// "MEAN_MOTION": 15.11169557,
/// "ECCENTRICITY": 0.00147468,
/// "INCLINATION": 97.5103,
/// "RA_OF_ASC_NODE": 247.7605,
/// "ARG_OF_PERICENTER": 169.6213,
/// "MEAN_ANOMALY": 190.5325,
/// "EPHEMERIS_TYPE": 0,
/// "CLASSIFICATION_TYPE": "U",
/// "NORAD_CAT_ID": 69097,
/// "ELEMENT_SET_NO": 999,
/// "REV_AT_EPOCH": 459,
/// "BSTAR": 0.00039221734,
/// "MEAN_MOTION_DOT": 6.535e-05,
/// "MEAN_MOTION_DDOT": 0
/// }
/// ]"#;
///
/// // Parse the OMM JSON into SGP4 propagators
/// let sgp4s = from_omm_json_string(omm).unwrap();
///
/// // Assert the catalog number and name
/// assert_eq!(sgp4s.len(), 1);
/// assert_eq!(sgp4s[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(sgp4s[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
#[cfg(feature = "json")]
pub fn from_omm_json_string(omm_json_string: &str) -> Result<Vec<Sgp4>, GpError> {
    // Parse the JSON document
    let value: Value =
        serde_json::from_str(omm_json_string).map_err(|_| GpError::InvalidOmmJson)?;

    // A file may be one object or an array of objects
    let mut sgp4s = Vec::new();
    match &value {
        Value::Array(records) => {
            for record in records {
                sgp4s.push(sgp4_from_json_record(record)?);
            }
        }
        Value::Object(_) => {
            sgp4s.push(sgp4_from_json_record(&value)?);
        }
        _ => return Err(GpError::InvalidOmmJson),
    }

    // Return vector of SGP4 structs
    Ok(sgp4s)
}

/// Collect OMM keyword values from one JSON object
///
/// Keys are stored in uppercase so lookup is case-insensitive. Strings are
/// used as-is, numbers are converted to text, and null becomes an empty
/// string. Nested arrays and objects are ignored.
///
/// # Arguments
/// * `record` - The JSON object to flatten
///
/// # Returns
/// * `Ok(HashMap)` - A map of OMM keyword to text value
/// * `Err(GpError)` - If the JSON value is not an object
#[cfg(feature = "json")]
fn json_omm_fields(record: &Value) -> Result<HashMap<String, String>, GpError> {
    let Some(object) = record.as_object() else {
        return Err(GpError::InvalidOmmJson);
    };

    let mut fields = HashMap::new();
    for (key, value) in object {
        if key.eq_ignore_ascii_case("COMMENT") {
            continue;
        }

        // Convert JSON scalars to the same text form used by KVN and XML
        let text = match value {
            Value::Null => String::new(),
            Value::String(s) => s.trim().to_string(),
            Value::Number(n) => n.to_string(),
            Value::Bool(b) => b.to_string(),
            Value::Array(_) | Value::Object(_) => continue,
        };
        fields.insert(key.to_ascii_uppercase(), text);
    }

    Ok(fields)
}

/// Builds a vector of [`Sgp4`] structs from a file containing Orbit Mean-Elements Message
/// (OMM) sets in JSON format.
///
/// This function parses a file containing one OMM object or an array of OMM
/// objects in JSON format and returns all successfully parsed entries.
///
/// # Arguments
/// * `omm_json_file_path` - A path to a file containing one or more OMM records in JSON format
///
/// # Returns
/// * `Ok(Vec<Sgp4>)` - All successfully parsed SGP4 structs
/// * `Err(GpError)` - If the file cannot be read or the JSON cannot be parsed
///
/// # Errors
/// * [`GpError::Io`] - If the file cannot be read
/// * [`GpError::InvalidOmmJson`] - If the JSON cannot be parsed or is not an object or array of objects
/// * [`GpError::InvalidOmmField`] - If a present field cannot be parsed as the requested type
/// * [`GpError::InvalidOmmEpoch`] - If EPOCH cannot be parsed as a UTC datetime
/// * [`GpError::Sgp4`] - If SGP4 initialization fails
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_omm_json_file;
///
/// // Define OMM JSON as an array of objects
/// let omm = r#"[
/// {
/// "OBJECT_NAME": "2026-106A",
/// "OBJECT_ID": "2026-106A",
/// "EPOCH": "2026-06-14T15:07:48.259488",
/// "MEAN_MOTION": 15.11169557,
/// "ECCENTRICITY": 0.00147468,
/// "INCLINATION": 97.5103,
/// "RA_OF_ASC_NODE": 247.7605,
/// "ARG_OF_PERICENTER": 169.6213,
/// "MEAN_ANOMALY": 190.5325,
/// "NORAD_CAT_ID": 69097,
/// "BSTAR": 0.00039221734,
/// "MEAN_MOTION_DOT": 6.535e-05,
/// "MEAN_MOTION_DDOT": 0
/// }
/// ]"#;
///
/// // Write the OMM to a temporary file
/// let path = std::env::temp_dir().join("mako_sgp4_from_omm_json_file.json");
/// std::fs::write(&path, omm).unwrap();
///
/// // Parse the OMM file into SGP4 propagators
/// let sgp4s = from_omm_json_file(path.to_str().unwrap()).unwrap();
///
/// // Remove the temporary file
/// let _ = std::fs::remove_file(&path);
///
/// // Assert the catalog number and name
/// assert_eq!(sgp4s.len(), 1);
/// assert_eq!(sgp4s[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(sgp4s[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
#[cfg(feature = "json")]
pub fn from_omm_json_file(omm_json_file_path: &str) -> Result<Vec<Sgp4>, GpError> {
    // Open the OMM JSON file
    let omm_json_string =
        fs::read_to_string(omm_json_file_path).map_err(|err| GpError::Io(err.to_string()))?;

    // Parse OMM string into a vector of SGP4 structs
    from_omm_json_string(&omm_json_string)
}

/// Format an OMM number as a JSON numeric literal
///
/// JSON requires a digit before the decimal point, so this does not use
/// Celestrak KVN scientific notation or a leading-dot fraction. Zero is
/// written as `0`.
///
/// # Arguments
/// * `value` - The number to format
///
/// # Returns
/// * A JSON number literal
#[cfg(feature = "json")]
fn format_omm_json_number(value: f64) -> String {
    if value == 0.0 {
        return "0".to_string();
    }

    let rounded = (value * 1e12).round() / 1e12;
    match serde_json::Number::from_f64(rounded) {
        Some(n) => n.to_string(),
        None => "0".to_string(),
    }
}

/// Build one OMM JSON object from a general perturbation element set
///
/// Field names and types match Celestrak GP JSON: strings for names, epoch,
/// and classification; numbers for the remaining GP fields. MEAN_MOTION_DOT
/// and MEAN_MOTION_DDOT are the TLE-printed values (stored derivatives
/// divided by 2 and 6).
///
/// # Arguments
/// * `gp` - The element set to serialize
///
/// # Returns
/// * One pretty-printed JSON object
#[cfg(feature = "json")]
fn gp_to_omm_json(gp: &GenPerturbElementSet) -> String {
    // OMM MEAN_MOTION_DOT and MEAN_MOTION_DDOT are the TLE-printed values
    let mean_motion_dot = gp.first_derivative_of_mean_motion / 2.0;
    let mean_motion_ddot = gp.second_derivative_of_mean_motion / 6.0;

    let fields = [
        format!(
            "        \"OBJECT_NAME\": {}",
            serde_json::to_string(&gp.common_name).unwrap()
        ),
        format!(
            "        \"OBJECT_ID\": {}",
            serde_json::to_string(&gp.international_designator).unwrap()
        ),
        format!(
            "        \"EPOCH\": {}",
            serde_json::to_string(&format_omm_epoch(&gp.epoch_datetime)).unwrap()
        ),
        format!(
            "        \"MEAN_MOTION\": {}",
            format_omm_json_number(gp.mean_motion)
        ),
        format!(
            "        \"ECCENTRICITY\": {}",
            format_omm_json_number(gp.eccentricity)
        ),
        format!(
            "        \"INCLINATION\": {}",
            format_omm_json_number(gp.inclination)
        ),
        format!(
            "        \"RA_OF_ASC_NODE\": {}",
            format_omm_json_number(gp.right_ascension_of_ascending_node)
        ),
        format!(
            "        \"ARG_OF_PERICENTER\": {}",
            format_omm_json_number(gp.argument_of_perigee)
        ),
        format!(
            "        \"MEAN_ANOMALY\": {}",
            format_omm_json_number(gp.mean_anomaly)
        ),
        format!("        \"EPHEMERIS_TYPE\": {}", gp.ephemeris_type),
        format!(
            "        \"CLASSIFICATION_TYPE\": {}",
            serde_json::to_string(&format_omm_classification(gp.classification)).unwrap()
        ),
        format!("        \"NORAD_CAT_ID\": {}", gp.satellite_catalog_number),
        format!("        \"ELEMENT_SET_NO\": {}", gp.element_set_number),
        format!(
            "        \"REV_AT_EPOCH\": {}",
            gp.revolution_number_at_epoch
        ),
        format!("        \"BSTAR\": {}", format_omm_json_number(gp.bstar)),
        format!(
            "        \"MEAN_MOTION_DOT\": {}",
            format_omm_json_number(mean_motion_dot)
        ),
        format!(
            "        \"MEAN_MOTION_DDOT\": {}",
            format_omm_json_number(mean_motion_ddot)
        ),
    ];

    format!("    {{\n{}\n    }}", fields.join(",\n"))
}

/// Builds a Celestrak-style JSON OMM string from a slice of [`Sgp4`] structs.
///
/// Each element set is written as one JSON object in a top-level array.
/// Strings are used for OBJECT_NAME, OBJECT_ID, EPOCH, and
/// CLASSIFICATION_TYPE. Numeric GP fields are JSON numbers.
/// OMM MEAN_MOTION_DOT and MEAN_MOTION_DDOT are the TLE-printed values
/// (the stored derivatives divided by 2 and 6).
///
/// An empty slice produces `[]`.
///
/// # Arguments
/// * `sgp4s` - The SGP4 structs to export
///
/// # Returns
/// * `String` - A JSON array of OMM objects
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::{from_omm_json_string, to_omm_json_string};
///
/// // Define OMM JSON as an array of objects
/// let omm = r#"[
/// {
/// "OBJECT_NAME": "2026-106A",
/// "OBJECT_ID": "2026-106A",
/// "EPOCH": "2026-06-14T15:07:48.259488",
/// "MEAN_MOTION": 15.11169557,
/// "ECCENTRICITY": 0.00147468,
/// "INCLINATION": 97.5103,
/// "RA_OF_ASC_NODE": 247.7605,
/// "ARG_OF_PERICENTER": 169.6213,
/// "MEAN_ANOMALY": 190.5325,
/// "NORAD_CAT_ID": 69097,
/// "BSTAR": 0.00039221734,
/// "MEAN_MOTION_DOT": 6.535e-05,
/// "MEAN_MOTION_DDOT": 0
/// }
/// ]"#;
///
/// // Parse, export, and parse again
/// let sgp4s = from_omm_json_string(omm).unwrap();
/// let exported = to_omm_json_string(&sgp4s);
/// let reparsed = from_omm_json_string(&exported).unwrap();
///
/// // Assert the round-trip catalog number and name
/// assert_eq!(reparsed.len(), 1);
/// assert_eq!(reparsed[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(reparsed[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
#[cfg(feature = "json")]
pub fn to_omm_json_string(sgp4s: &[Sgp4]) -> String {
    // An empty slice is an empty JSON array
    if sgp4s.is_empty() {
        return "[]\n".to_string();
    }

    // Serialize each element set as one JSON object
    let mut objects = Vec::new();
    for sgp4 in sgp4s {
        objects.push(gp_to_omm_json(&sgp4.gp));
    }

    format!("[\n{}\n]\n", objects.join(",\n"))
}

/// Writes a Celestrak-style JSON OMM file from a slice of [`Sgp4`] structs.
///
/// This function serializes the provided element sets with
/// [`to_omm_json_string`] and writes the result to `omm_json_file_path`.
///
/// # Arguments
/// * `sgp4s` - The SGP4 structs to export
/// * `omm_json_file_path` - Destination path for the JSON file
///
/// # Returns
/// * `Ok(())` - If the file is written
/// * `Err(GpError)` - If the file cannot be written
///
/// # Errors
/// * [`GpError::Io`] - If the file cannot be written
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::{from_omm_json_file, from_omm_json_string, to_omm_json_file};
///
/// // Define OMM JSON and parse it
/// let omm = r#"[
/// {
/// "OBJECT_NAME": "2026-106A",
/// "OBJECT_ID": "2026-106A",
/// "EPOCH": "2026-06-14T15:07:48.259488",
/// "MEAN_MOTION": 15.11169557,
/// "ECCENTRICITY": 0.00147468,
/// "INCLINATION": 97.5103,
/// "RA_OF_ASC_NODE": 247.7605,
/// "ARG_OF_PERICENTER": 169.6213,
/// "MEAN_ANOMALY": 190.5325,
/// "NORAD_CAT_ID": 69097,
/// "BSTAR": 0.00039221734,
/// "MEAN_MOTION_DOT": 6.535e-05,
/// "MEAN_MOTION_DDOT": 0
/// }
/// ]"#;
/// let sgp4s = from_omm_json_string(omm).unwrap();
///
/// // Write the element sets to a temporary JSON file
/// let path = std::env::temp_dir().join("mako_sgp4_to_omm_json_file.json");
/// let path_str = path.to_str().unwrap();
/// to_omm_json_file(&sgp4s, path_str).unwrap();
///
/// // Parse the written file
/// let reparsed = from_omm_json_file(path_str).unwrap();
///
/// // Remove the temporary file
/// let _ = std::fs::remove_file(&path);
///
/// // Assert the round-trip catalog number and name
/// assert_eq!(reparsed.len(), 1);
/// assert_eq!(reparsed[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(reparsed[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
#[cfg(feature = "json")]
pub fn to_omm_json_file(sgp4s: &[Sgp4], omm_json_file_path: &str) -> Result<(), GpError> {
    // Serialize the element sets and write the JSON file
    let omm_json_string = to_omm_json_string(sgp4s);
    fs::write(omm_json_file_path, omm_json_string).map_err(|err| GpError::Io(err.to_string()))?;
    Ok(())
}

/// Build an [`Sgp4`] struct from one CSV OMM row
///
/// # Arguments
/// * `headers` - Uppercase OMM keywords from the CSV header row
/// * `record` - One OMM data row
///
/// # Returns
/// * `Ok(Sgp4)` - Struct containing the parsed SGP4 parameters
/// * `Err(GpError)` - If a field cannot be parsed
#[cfg(feature = "csv")]
fn sgp4_from_csv_record(headers: &[String], record: &csv::StringRecord) -> Result<Sgp4, GpError> {
    let fields = csv_omm_fields(headers, record);
    sgp4_from_omm_lookup(|field| fields.get(&field.to_ascii_uppercase()).cloned())
}

/// Builds a vector of [`Sgp4`] structs from a string containing Orbit Mean-Elements Message
/// (OMM) sets in CSV format.
///
/// This function parses a string containing a header row of OMM keywords and
/// one data row per record. Each row is flattened to keyword and value pairs,
/// then initialized with the same GP mapping as [`from_omm_kvn_lines`]. Empty
/// cells use the same defaults as missing KVN fields.
///
/// # Arguments
/// * `omm_csv_string` - A string containing one or more OMM records in CSV format
///
/// # Returns
/// * `Ok(Vec<Sgp4>)` - All successfully parsed SGP4 parameters
/// * `Err(GpError)` - If the CSV document or a field cannot be parsed
///
/// # Errors
/// * [`GpError::InvalidOmmCsv`] - If the CSV document cannot be parsed
/// * [`GpError::InvalidOmmField`] - If a present field cannot be parsed as the requested type
/// * [`GpError::InvalidOmmEpoch`] - If EPOCH cannot be parsed as a UTC datetime
/// * [`GpError::Sgp4`] - If SGP4 initialization fails
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_omm_csv_string;
///
/// // Define an OMM CSV with a header row and one data row
/// let omm = "\
/// OBJECT_NAME,OBJECT_ID,EPOCH,MEAN_MOTION,ECCENTRICITY,INCLINATION,RA_OF_ASC_NODE,ARG_OF_PERICENTER,MEAN_ANOMALY,EPHEMERIS_TYPE,CLASSIFICATION_TYPE,NORAD_CAT_ID,ELEMENT_SET_NO,REV_AT_EPOCH,BSTAR,MEAN_MOTION_DOT,MEAN_MOTION_DDOT
/// 2026-106A,2026-106A,2026-06-14T15:07:48.259488,15.11169557,.00147468,97.5103,247.7605,169.6213,190.5325,0,U,69097,999,459,.39221734E-3,.6535E-4,0
/// ";
///
/// // Parse the OMM CSV into SGP4 propagators
/// let sgp4s = from_omm_csv_string(omm).unwrap();
///
/// // Assert the catalog number and name
/// assert_eq!(sgp4s.len(), 1);
/// assert_eq!(sgp4s[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(sgp4s[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
#[cfg(feature = "csv")]
pub fn from_omm_csv_string(omm_csv_string: &str) -> Result<Vec<Sgp4>, GpError> {
    // Parse the CSV document, using the first row as OMM keywords
    let mut reader = ReaderBuilder::new()
        .has_headers(true)
        .from_reader(omm_csv_string.as_bytes());

    let headers: Vec<String> = reader
        .headers()
        .map_err(|_| GpError::InvalidOmmCsv)?
        .iter()
        .map(|header| header.trim().to_ascii_uppercase())
        .collect();

    // Each data row is one GP record
    let mut sgp4s = Vec::new();
    for result in reader.records() {
        let record = result.map_err(|_| GpError::InvalidOmmCsv)?;
        sgp4s.push(sgp4_from_csv_record(&headers, &record)?);
    }

    // Return vector of SGP4 structs
    Ok(sgp4s)
}

/// Collect OMM keyword values from one CSV row
///
/// Keys are stored in uppercase so lookup is case-insensitive. COMMENT columns
/// are skipped. Empty cells become empty strings so missing-field defaults apply.
///
/// # Arguments
/// * `headers` - Uppercase OMM keywords from the CSV header row
/// * `record` - One OMM data row
///
/// # Returns
/// * A map of OMM keyword to text value
#[cfg(feature = "csv")]
fn csv_omm_fields(headers: &[String], record: &csv::StringRecord) -> HashMap<String, String> {
    let mut fields = HashMap::new();

    for (index, header) in headers.iter().enumerate() {
        if header.is_empty() || header.eq_ignore_ascii_case("COMMENT") {
            continue;
        }

        let text = record.get(index).unwrap_or("").trim().to_string();
        fields.insert(header.clone(), text);
    }

    fields
}

/// Builds a vector of [`Sgp4`] structs from a file containing Orbit Mean-Elements Message
/// (OMM) sets in CSV format.
///
/// This function parses a file containing a header row of OMM keywords and
/// one data row per record and returns all successfully parsed entries.
///
/// # Arguments
/// * `omm_csv_file_path` - A path to a file containing one or more OMM records in CSV format
///
/// # Returns
/// * `Ok(Vec<Sgp4>)` - All successfully parsed SGP4 structs
/// * `Err(GpError)` - If the file cannot be read or the CSV cannot be parsed
///
/// # Errors
/// * [`GpError::Io`] - If the file cannot be read
/// * [`GpError::InvalidOmmCsv`] - If the CSV document cannot be parsed
/// * [`GpError::InvalidOmmField`] - If a present field cannot be parsed as the requested type
/// * [`GpError::InvalidOmmEpoch`] - If EPOCH cannot be parsed as a UTC datetime
/// * [`GpError::Sgp4`] - If SGP4 initialization fails
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::from_omm_csv_file;
///
/// // Define an OMM CSV with a header row and one data row
/// let omm = "\
/// OBJECT_NAME,OBJECT_ID,EPOCH,MEAN_MOTION,ECCENTRICITY,INCLINATION,RA_OF_ASC_NODE,ARG_OF_PERICENTER,MEAN_ANOMALY,NORAD_CAT_ID,BSTAR,MEAN_MOTION_DOT,MEAN_MOTION_DDOT
/// 2026-106A,2026-106A,2026-06-14T15:07:48.259488,15.11169557,.00147468,97.5103,247.7605,169.6213,190.5325,69097,.39221734E-3,.6535E-4,0
/// ";
///
/// // Write the OMM to a temporary file
/// let path = std::env::temp_dir().join("mako_sgp4_from_omm_csv_file.csv");
/// std::fs::write(&path, omm).unwrap();
///
/// // Parse the OMM file into SGP4 propagators
/// let sgp4s = from_omm_csv_file(path.to_str().unwrap()).unwrap();
///
/// // Remove the temporary file
/// let _ = std::fs::remove_file(&path);
///
/// // Assert the catalog number and name
/// assert_eq!(sgp4s.len(), 1);
/// assert_eq!(sgp4s[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(sgp4s[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
#[cfg(feature = "csv")]
pub fn from_omm_csv_file(omm_csv_file_path: &str) -> Result<Vec<Sgp4>, GpError> {
    // Open the OMM CSV file
    let omm_csv_string =
        fs::read_to_string(omm_csv_file_path).map_err(|err| GpError::Io(err.to_string()))?;

    // Parse OMM string into a vector of SGP4 structs
    from_omm_csv_string(&omm_csv_string)
}

/// Build one OMM CSV data row from a general perturbation element set
///
/// MEAN_MOTION_DOT and MEAN_MOTION_DDOT are the TLE-printed values (stored
/// derivatives divided by 2 and 6). BSTAR and the mean-motion derivatives
/// use Celestrak scientific notation.
///
/// # Arguments
/// * `gp` - The element set to serialize
///
/// # Returns
/// * One CSV data row, in [`OMM_CSV_HEADERS`] order
#[cfg(feature = "csv")]
fn gp_to_omm_csv_row(gp: &GenPerturbElementSet) -> [String; 17] {
    // OMM MEAN_MOTION_DOT and MEAN_MOTION_DDOT are the TLE-printed values
    let mean_motion_dot = gp.first_derivative_of_mean_motion / 2.0;
    let mean_motion_ddot = gp.second_derivative_of_mean_motion / 6.0;

    [
        gp.common_name.clone(),
        gp.international_designator.clone(),
        format_omm_epoch(&gp.epoch_datetime),
        format_omm_decimal(gp.mean_motion),
        format_omm_decimal(gp.eccentricity),
        format_omm_decimal(gp.inclination),
        format_omm_decimal(gp.right_ascension_of_ascending_node),
        format_omm_decimal(gp.argument_of_perigee),
        format_omm_decimal(gp.mean_anomaly),
        gp.ephemeris_type.to_string(),
        format_omm_classification(gp.classification),
        gp.satellite_catalog_number.to_string(),
        gp.element_set_number.to_string(),
        gp.revolution_number_at_epoch.to_string(),
        format_omm_sci(gp.bstar),
        format_omm_sci(mean_motion_dot),
        format_omm_sci(mean_motion_ddot),
    ]
}

/// Builds a Celestrak-style CSV OMM string from a slice of [`Sgp4`] structs.
///
/// The first row is the OMM keyword header. Each following row is one
/// element set. MEAN_MOTION_DOT and MEAN_MOTION_DDOT are the TLE-printed
/// values (the stored derivatives divided by 2 and 6).
///
/// An empty slice produces a header-only CSV.
///
/// # Arguments
/// * `sgp4s` - The SGP4 structs to export
///
/// # Returns
/// * `String` - A CSV document with a header row and one row per record
///
/// # Panics
/// * If the in-memory CSV writer fails
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::{from_omm_csv_string, to_omm_csv_string};
///
/// // Define an OMM CSV with a header row and one data row
/// let omm = "\
/// OBJECT_NAME,OBJECT_ID,EPOCH,MEAN_MOTION,ECCENTRICITY,INCLINATION,RA_OF_ASC_NODE,ARG_OF_PERICENTER,MEAN_ANOMALY,EPHEMERIS_TYPE,CLASSIFICATION_TYPE,NORAD_CAT_ID,ELEMENT_SET_NO,REV_AT_EPOCH,BSTAR,MEAN_MOTION_DOT,MEAN_MOTION_DDOT
/// 2026-106A,2026-106A,2026-06-14T15:07:48.259488,15.11169557,.00147468,97.5103,247.7605,169.6213,190.5325,0,U,69097,999,459,.39221734E-3,.6535E-4,0
/// ";
///
/// // Parse, export, and parse again
/// let sgp4s = from_omm_csv_string(omm).unwrap();
/// let exported = to_omm_csv_string(&sgp4s);
/// let reparsed = from_omm_csv_string(&exported).unwrap();
///
/// // Assert the round-trip catalog number and name
/// assert_eq!(reparsed.len(), 1);
/// assert_eq!(reparsed[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(reparsed[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
#[cfg(feature = "csv")]
pub fn to_omm_csv_string(sgp4s: &[Sgp4]) -> String {
    // Write the header row, then one data row per element set
    let mut writer = WriterBuilder::new().from_writer(Vec::new());
    writer
        .write_record(OMM_CSV_HEADERS)
        .expect("Cannot write OMM CSV");
    for sgp4 in sgp4s {
        writer
            .write_record(gp_to_omm_csv_row(&sgp4.gp))
            .expect("Cannot write OMM CSV");
    }

    let bytes = writer.into_inner().expect("Cannot write OMM CSV");
    String::from_utf8(bytes).expect("Cannot write OMM CSV")
}

/// Writes a Celestrak-style CSV OMM file from a slice of [`Sgp4`] structs.
///
/// This function serializes the provided element sets with
/// [`to_omm_csv_string`] and writes the result to `omm_csv_file_path`.
///
/// # Arguments
/// * `sgp4s` - The SGP4 structs to export
/// * `omm_csv_file_path` - Destination path for the CSV file
///
/// # Returns
/// * `Ok(())` - If the file is written
/// * `Err(GpError)` - If the file cannot be written
///
/// # Errors
/// * [`GpError::Io`] - If the file cannot be written
///
/// # Examples
/// ```rust
/// use mako_sgp4::gp::{from_omm_csv_file, from_omm_csv_string, to_omm_csv_file};
///
/// // Define an OMM CSV and parse it
/// let omm = "\
/// OBJECT_NAME,OBJECT_ID,EPOCH,MEAN_MOTION,ECCENTRICITY,INCLINATION,RA_OF_ASC_NODE,ARG_OF_PERICENTER,MEAN_ANOMALY,NORAD_CAT_ID,BSTAR,MEAN_MOTION_DOT,MEAN_MOTION_DDOT
/// 2026-106A,2026-106A,2026-06-14T15:07:48.259488,15.11169557,.00147468,97.5103,247.7605,169.6213,190.5325,69097,.39221734E-3,.6535E-4,0
/// ";
/// let sgp4s = from_omm_csv_string(omm).unwrap();
///
/// // Write the element sets to a temporary CSV file
/// let path = std::env::temp_dir().join("mako_sgp4_to_omm_csv_file.csv");
/// let path_str = path.to_str().unwrap();
/// to_omm_csv_file(&sgp4s, path_str).unwrap();
///
/// // Parse the written file
/// let reparsed = from_omm_csv_file(path_str).unwrap();
///
/// // Remove the temporary file
/// let _ = std::fs::remove_file(&path);
///
/// // Assert the round-trip catalog number and name
/// assert_eq!(reparsed.len(), 1);
/// assert_eq!(reparsed[0].gp.satellite_catalog_number, 69097);
/// assert_eq!(reparsed[0].gp.common_name, "2026-106A");
/// ```
///
/// # References
/// - [CCSDS Orbit Data Messages Specification](https://ccsds.org/Pubs/502x0b3e1.pdf)
/// - [CCSDS XML Specification for Navigation Data Messages](https://ccsds.org/Pubs/505x0b3e2.pdf)
/// - [Celestrak GP Data Formats](https://celestrak.org/NORAD/documentation/gp-data-formats.php)
#[cfg(feature = "csv")]
pub fn to_omm_csv_file(sgp4s: &[Sgp4], omm_csv_file_path: &str) -> Result<(), GpError> {
    // Serialize the element sets and write the CSV file
    let omm_csv_string = to_omm_csv_string(sgp4s);
    fs::write(omm_csv_file_path, omm_csv_string).map_err(|err| GpError::Io(err.to_string()))?;
    Ok(())
}

/// Parse an OMM EPOCH string into a UTC DateTime
///
/// Accepts an ISO-8601 date and time with optional fractional seconds and an
/// optional trailing Z. The date and time may be separated by T or a space.
///
/// # Arguments
/// * `epoch` - The EPOCH string from the OMM record
///
/// # Returns
/// * `Ok(DateTime)` - The epoch as a UTC datetime
/// * `Err(GpError)` - If the EPOCH string cannot be parsed
fn parse_omm_epoch(epoch: &str) -> Result<DateTime, GpError> {
    // Strip a trailing Z timezone marker
    let mut s = epoch.trim();
    if s.ends_with('Z') || s.ends_with('z') {
        s = &s[..s.len() - 1];
    }

    // Split date and time
    let (date, time) = if let Some((date, time)) = s.split_once('T') {
        (date, time)
    } else if let Some((date, time)) = s.split_once(' ') {
        (date, time)
    } else {
        return Err(GpError::InvalidOmmEpoch);
    };

    let date_parts: Vec<&str> = date.split('-').collect();
    let time_parts: Vec<&str> = time.split(':').collect();
    if date_parts.len() != 3 || time_parts.len() != 3 {
        return Err(GpError::InvalidOmmEpoch);
    }

    // Parse calendar date
    let year = date_parts[0]
        .parse::<i32>()
        .map_err(|_| GpError::InvalidOmmEpoch)?;
    let month = date_parts[1]
        .parse::<i32>()
        .map_err(|_| GpError::InvalidOmmEpoch)?;
    let day = date_parts[2]
        .parse::<i32>()
        .map_err(|_| GpError::InvalidOmmEpoch)?;

    // Parse clock time
    let hour = time_parts[0]
        .parse::<i32>()
        .map_err(|_| GpError::InvalidOmmEpoch)?;
    let minute = time_parts[1]
        .parse::<i32>()
        .map_err(|_| GpError::InvalidOmmEpoch)?;
    let second = time_parts[2]
        .parse::<f64>()
        .map_err(|_| GpError::InvalidOmmEpoch)?;

    let datetime = DateTime {
        year,
        month,
        day,
        hour,
        minute,
        second,
        timezone: Timezone::UTC,
    };

    // Reject out-of-range calendar or clock fields (e.g. month 13 or hour 25)
    validate_datetime(&datetime).map_err(|_| GpError::InvalidOmmEpoch)?;

    Ok(datetime)
}

// ----------
// Unit Tests
// ----------
#[cfg(test)]
mod tests {
    use super::*;
    use serde::Deserialize;
    use std::collections::HashMap;
    use toml::from_str;

    /// Reject a TLE whose two data lines name different catalog numbers
    ///
    /// # Panics
    /// * If parsing returns anything other than a catalog mismatch
    #[test]
    fn test_tle_catalog_mismatch() {
        let line1 = "1 25544U 98067A   08264.51782528 -.00002182 -00100-2 -11606-4 0  2921";
        let line2 = "2 25545  51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537";
        let err = match from_tle_lines(line1, line2, None) {
            Err(err) => err,
            Ok(_) => panic!("expected MismatchedTleCatalog"),
        };
        assert_eq!(err, GpError::MismatchedTleCatalog);
    }

    /// Reject a TLE path that cannot be read
    ///
    /// # Panics
    /// * If the missing file returns anything other than an I/O error
    #[test]
    fn test_tle_file_io_error() {
        let err = match from_tle_file("test/this_tle_file_does_not_exist.txt") {
            Err(err) => err,
            Ok(_) => panic!("expected GpError::Io"),
        };
        assert!(matches!(err, GpError::Io(_)));
    }

    /// Reject catalog numbers outside the TLE range
    ///
    /// # Panics
    /// * If a negative number or 340000 is accepted
    #[test]
    fn test_invalid_tle_catalog_number() {
        let err = match format_tle_catalog_number(-1) {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidTLECatalogNumber"),
        };
        assert_eq!(err, GpError::InvalidTLECatalogNumber);

        let err = match format_tle_catalog_number(340000) {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidTLECatalogNumber"),
        };
        assert_eq!(err, GpError::InvalidTLECatalogNumber);
    }

    /// Reject TLE epochs outside 1957 through 2056
    ///
    /// # Panics
    /// * If 1956 or 2057 is accepted
    #[test]
    fn test_invalid_tle_datetime() {
        let mut epoch = DateTime {
            year: 1956,
            month: 12,
            day: 31,
            hour: 0,
            minute: 0,
            second: 0.0,
            timezone: Timezone::UTC,
        };
        let err = match format_tle_epoch(&epoch) {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidTLEDateTime"),
        };
        assert_eq!(err, GpError::InvalidTLEDateTime);

        epoch.year = 2057;
        let err = match format_tle_epoch(&epoch) {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidTLEDateTime"),
        };
        assert_eq!(err, GpError::InvalidTLEDateTime);
    }

    /// Reject a TLE data line that is too short for a checksum
    ///
    /// # Panics
    /// * If the short line is accepted
    #[test]
    fn test_invalid_tle_line() {
        let err = match tle_line_with_checksum("1 25544U") {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidTLELine"),
        };
        assert_eq!(err, GpError::InvalidTLELine);
    }

    /// Check TLE international designator length limits
    ///
    /// Launch numbers and piece designators that do not fit the TLE columns are
    /// rejected. Designators that fit are formatted into the eight-character field.
    ///
    /// # Panics
    /// * If an overlong designator is accepted or a fitting one is formatted wrong
    #[test]
    fn test_invalid_tle_international_designator() {
        let err = match format_tle_intl_des("2026-1234A") {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidTLEInternationalDesignator"),
        };
        assert_eq!(err, GpError::InvalidTLEInternationalDesignator);

        let err = match format_tle_intl_des("2026-106ABCD") {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidTLEInternationalDesignator"),
        };
        assert_eq!(err, GpError::InvalidTLEInternationalDesignator);

        assert_eq!(format_tle_intl_des("1998-067A").unwrap(), "98067A  ");
        assert_eq!(format_tle_intl_des("2025-286AD").unwrap(), "25286AD ");
        assert_eq!(format_tle_intl_des("2025-001ABC").unwrap(), "25001ABC");
    }

    /// Reject OMM fields that are not the expected type
    ///
    /// # Panics
    /// * If a non-numeric mean motion or catalog id is accepted
    #[test]
    fn test_invalid_omm_field() {
        let err = match from_omm_kvn_string("MEAN_MOTION = not_a_number") {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidOmmField"),
        };
        assert_eq!(err, GpError::InvalidOmmField);

        let err = match from_omm_kvn_string("NORAD_CAT_ID = abc") {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidOmmField"),
        };
        assert_eq!(err, GpError::InvalidOmmField);
    }

    /// Reject OMM epochs that are not a full UTC timestamp
    ///
    /// # Panics
    /// * If a non-date, a date without a time, or a bad clock time is accepted
    #[test]
    fn test_invalid_omm_epoch() {
        let err = match from_omm_kvn_string("EPOCH = not-an-epoch") {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidOmmEpoch"),
        };
        assert_eq!(err, GpError::InvalidOmmEpoch);

        let err = match from_omm_kvn_string("EPOCH = 2026-06-14") {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidOmmEpoch"),
        };
        assert_eq!(err, GpError::InvalidOmmEpoch);

        let err = match from_omm_kvn_string("EPOCH = 2026-06-14Txx:00:00") {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidOmmEpoch"),
        };
        assert_eq!(err, GpError::InvalidOmmEpoch);

        // Out-of-range calendar and clock fields
        for epoch in [
            "2026-13-01T00:00:00",
            "2026-02-29T00:00:00",
            "2026-06-31T00:00:00",
            "2026-06-14T24:00:00",
            "2026-06-14T00:60:00",
            "2026-06-14T00:00:61.0",
        ] {
            let err = match from_omm_kvn_string(&format!("EPOCH = {epoch}\nMEAN_MOTION = 15.0")) {
                Err(err) => err,
                Ok(_) => panic!("expected InvalidOmmEpoch for {epoch}"),
            };
            assert_eq!(err, GpError::InvalidOmmEpoch, "{epoch}");
        }
    }

    /// Reject OMM XML that is not a document
    ///
    /// # Panics
    /// * If the bad text is accepted
    #[cfg(feature = "xml")]
    #[test]
    fn test_invalid_omm_xml() {
        let err = match from_omm_xml_string("<<<not xml") {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidOmmXml"),
        };
        assert_eq!(err, GpError::InvalidOmmXml);
    }

    /// Reject OMM JSON that is not an object or an array of objects
    ///
    /// # Panics
    /// * If invalid JSON, a number, or an array of numbers is accepted
    #[cfg(feature = "json")]
    #[test]
    fn test_invalid_omm_json() {
        let err = match from_omm_json_string("not json") {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidOmmJson"),
        };
        assert_eq!(err, GpError::InvalidOmmJson);

        let err = match from_omm_json_string("1") {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidOmmJson"),
        };
        assert_eq!(err, GpError::InvalidOmmJson);

        let err = match from_omm_json_string("[1]") {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidOmmJson"),
        };
        assert_eq!(err, GpError::InvalidOmmJson);
    }

    /// Reject OMM CSV whose rows do not match the header
    ///
    /// # Panics
    /// * If the short row is accepted
    #[cfg(feature = "csv")]
    #[test]
    fn test_invalid_omm_csv() {
        let err = match from_omm_csv_string("OBJECT_NAME,MEAN_MOTION\nonly_one_field") {
            Err(err) => err,
            Ok(_) => panic!("expected InvalidOmmCsv"),
        };
        assert_eq!(err, GpError::InvalidOmmCsv);
    }

    /// Reject an OMM path that cannot be read
    ///
    /// # Panics
    /// * If the missing file returns anything other than an I/O error
    #[test]
    fn test_omm_file_io_error() {
        let err = match from_omm_kvn_file("test/this_omm_file_does_not_exist.txt") {
            Err(err) => err,
            Ok(_) => panic!("expected GpError::Io"),
        };
        assert!(matches!(err, GpError::Io(_)));
    }

    /// Expand a two-digit TLE year into 1957 through 2056
    ///
    /// # Panics
    /// * If a year maps to the wrong century
    #[test]
    fn test_tle_full_year() {
        assert_eq!(tle_full_year(0), 2000);
        assert_eq!(tle_full_year(25), 2025);
        assert_eq!(tle_full_year(56), 2056);
        assert_eq!(tle_full_year(57), 1957);
        assert_eq!(tle_full_year(98), 1998);
        assert_eq!(tle_full_year(99), 1999);
    }

    /// Convert between Alpha-5 digits and their numeric values
    ///
    /// Letters I and O are skipped. Values outside 10 through 33 have no letter.
    ///
    /// # Panics
    /// * If a letter or value maps to the wrong digit
    #[test]
    fn test_alpha5_digit() {
        assert_eq!(alpha5_digit('A'), Some(10));
        assert_eq!(alpha5_digit('H'), Some(17));
        assert_eq!(alpha5_digit('J'), Some(18));
        assert_eq!(alpha5_digit('N'), Some(22));
        assert_eq!(alpha5_digit('P'), Some(23));
        assert_eq!(alpha5_digit('Z'), Some(33));
        assert_eq!(alpha5_digit('a'), Some(10));
        assert_eq!(alpha5_digit('I'), None);
        assert_eq!(alpha5_digit('O'), None);
        assert_eq!(alpha5_digit('0'), None);

        assert_eq!(alpha5_letter(10), Some('A'));
        assert_eq!(alpha5_letter(17), Some('H'));
        assert_eq!(alpha5_letter(18), Some('J'));
        assert_eq!(alpha5_letter(22), Some('N'));
        assert_eq!(alpha5_letter(23), Some('P'));
        assert_eq!(alpha5_letter(33), Some('Z'));
        assert_eq!(alpha5_letter(9), None);
        assert_eq!(alpha5_letter(34), None);
    }

    /// Compute the checksum of a known TLE line
    ///
    /// # Panics
    /// * If the checksum is not 1
    #[test]
    fn test_checksum_calculation() {
        // Define the TLE line
        let tle_line1 = "1 25544U 98067A   08264.51782528 -.00002182 -00100-2 -11606-4 0  2921";

        // Calculate the checksum of the TLE line
        let checksum = calc_checksum(tle_line1);

        // Assert the checksum is correct
        assert_eq!(checksum, 1);
    }

    /// Accept a TLE line with the right checksum and reject a wrong one
    ///
    /// # Panics
    /// * If the valid line fails or the altered line passes
    #[test]
    fn test_checksum_comparison() {
        // Define the TLE line
        let tle_line1 = "1 25544U 98067A   08264.51782528 -.00002182 -00100-2 -11606-4 0  2921";
        let tle_line2 = "1 25544U 98067A   08264.51782528 -.00002182 -00100-2 -11606-4 0  2922";

        // Calculate the checksum of the TLE line
        let checksum = tle_checksum(tle_line1);
        let checksum2 = tle_checksum(tle_line2);

        // Assert the checksum is correct
        assert!(checksum);
        assert!(!checksum2);
    }

    /// Report a TLE checksum mismatch as a warning, not an error
    ///
    /// # Panics
    /// * If a bad checksum fails the parse or is not flagged, or a good one is flagged
    #[test]
    fn test_tle_checksum_warning() {
        let line1 = "1 25544U 98067A   08264.51782528 -.00002182 -00100-2 -11606-4 0  2921";
        let line2 = "2 25544  51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537";
        let bad_line1 = "1 25544U 98067A   08264.51782528 -.00002182 -00100-2 -11606-4 0  2922";

        let sgp4 = from_tle_lines(line1, line2, None).expect("valid TLE should parse");
        assert_eq!(sgp4.gp.tle_checksum_valid, Some(true));

        let sgp4 = from_tle_lines(bad_line1, line2, None).expect("bad checksum should still parse");
        assert_eq!(sgp4.gp.tle_checksum_valid, Some(false));
    }

    /// Reject TLE data lines with the wrong line number or non-ASCII characters
    ///
    /// # Panics
    /// * If a bad line is accepted or slicing a non-ASCII line panics
    #[test]
    fn test_invalid_tle_line_prefix_and_ascii() {
        let line1 = "1 25544U 98067A   08264.51782528 -.00002182 -00100-2 -11606-4 0  2921";
        let line2 = "2 25544  51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537";

        // Wrong line number digits, swapped lines, and a missing separator space
        let bad_line1 = line1.replacen('1', "3", 1);
        let bad_line2 = line2.replacen('2', "3", 1);
        let no_space_line1 = format!("10{}", &line1[2..]);
        assert!(matches!(
            from_tle_lines(&bad_line1, line2, None),
            Err(GpError::InvalidTleLine1)
        ));
        assert!(matches!(
            from_tle_lines(line1, &bad_line2, None),
            Err(GpError::InvalidTleLine2)
        ));
        assert!(matches!(
            from_tle_lines(line2, line1, None),
            Err(GpError::InvalidTleLine1)
        ));
        assert!(matches!(
            from_tle_lines(&no_space_line1, line2, None),
            Err(GpError::InvalidTleLine1)
        ));

        // 69-byte lines with a multibyte character across a field boundary
        let utf8_line1 = format!("{}\u{e9}{}", &line1[..62], &line1[64..]);
        let utf8_line2 = format!("{}\u{e9}{}", &line2[..15], &line2[17..]);
        assert_eq!(utf8_line1.len(), 69);
        assert_eq!(utf8_line2.len(), 69);
        assert!(matches!(
            from_tle_lines(&utf8_line1, line2, None),
            Err(GpError::InvalidTleLine1)
        ));
        assert!(matches!(
            from_tle_lines(line1, &utf8_line2, None),
            Err(GpError::InvalidTleLine2)
        ));
    }

    // -------------------------------------------------------
    // Structs for deserializing the TLE / OMM parsing test TOML
    // -------------------------------------------------------

    #[derive(Deserialize)]
    struct ParsingCases {
        test: HashMap<String, ParsingCase>,
    }

    #[derive(Deserialize)]
    struct ParsingCase {
        name: String,
        #[serde(default)]
        tle: String,
        #[serde(default)]
        omm_kvn: String,
        #[serde(default)]
        exception: bool,
        #[serde(default)]
        common_name: String,
        #[serde(default)]
        satellite_catalog_number: i32,
        #[serde(default)]
        classification: String,
        #[serde(default)]
        international_designator: String,
        #[serde(default)]
        epoch_datetime_year: i32,
        #[serde(default)]
        epoch_datetime_month: i32,
        #[serde(default)]
        epoch_datetime_day: i32,
        #[serde(default)]
        epoch_datetime_hour: i32,
        #[serde(default)]
        epoch_datetime_minute: i32,
        #[serde(default)]
        epoch_datetime_second: f64,
        #[serde(default)]
        first_derivative_of_mean_motion: f64,
        #[serde(default)]
        second_derivative_of_mean_motion: f64,
        #[serde(default)]
        bstar: f64,
        #[serde(default)]
        ephemeris_type: i32,
        #[serde(default)]
        element_set_number: i32,
        #[serde(default)]
        inclination: f64,
        #[serde(default)]
        right_ascension_of_ascending_node: f64,
        #[serde(default)]
        eccentricity: f64,
        #[serde(default)]
        argument_of_perigee: f64,
        #[serde(default)]
        mean_anomaly: f64,
        #[serde(default)]
        mean_motion: f64,
        #[serde(default)]
        revolution_number_at_epoch: i64,
    }

    // Absolute tolerance for parsed GP numeric fields.
    const TLE_PARSE_TOL: f64 = 1e-9;

    /// Compare one parsed numeric field with its expected value
    ///
    /// # Arguments
    /// * `key` - TOML case key, included in the failure message
    /// * `name` - Case description, included in the failure message
    /// * `source` - Parser that produced the value, included in the failure message
    /// * `label` - Field name, included in the failure message
    /// * `value` - Parsed number
    /// * `expected` - Number stored in the test case
    ///
    /// # Panics
    /// * If the absolute difference is at least the parse tolerance
    fn assert_near(key: &str, name: &str, source: &str, label: &str, value: f64, expected: f64) {
        assert!(
            (value - expected).abs() < TLE_PARSE_TOL,
            "{key} ({name}) via {source}: {label} mismatch {value} vs {expected}"
        );
    }

    /// Compare a parsed element set with one TOML case
    ///
    /// # Arguments
    /// * `key` - TOML case key, included in the failure message
    /// * `name` - Case description, included in the failure message
    /// * `source` - Parser that produced the element set
    /// * `gp` - Parsed element set
    /// * `case` - Expected fields
    ///
    /// # Panics
    /// * If any field differs from the case
    fn assert_gp_matches(
        key: &str,
        name: &str,
        source: &str,
        gp: &GenPerturbElementSet,
        case: &ParsingCase,
    ) {
        assert_eq!(
            gp.common_name, case.common_name,
            "{key} ({name}) via {source}: common_name"
        );
        assert_eq!(
            gp.satellite_catalog_number, case.satellite_catalog_number,
            "{key} ({name}) via {source}: satellite_catalog_number"
        );
        assert_eq!(
            gp.classification.to_string(),
            case.classification,
            "{key} ({name}) via {source}: classification"
        );
        assert_eq!(
            gp.international_designator, case.international_designator,
            "{key} ({name}) via {source}: international_designator"
        );
        assert_eq!(
            gp.epoch_datetime.year, case.epoch_datetime_year,
            "{key} ({name}) via {source}: epoch year"
        );
        assert_eq!(
            gp.epoch_datetime.month, case.epoch_datetime_month,
            "{key} ({name}) via {source}: epoch month"
        );
        assert_eq!(
            gp.epoch_datetime.day, case.epoch_datetime_day,
            "{key} ({name}) via {source}: epoch day"
        );
        assert_eq!(
            gp.epoch_datetime.hour, case.epoch_datetime_hour,
            "{key} ({name}) via {source}: epoch hour"
        );
        assert_eq!(
            gp.epoch_datetime.minute, case.epoch_datetime_minute,
            "{key} ({name}) via {source}: epoch minute"
        );
        assert_near(
            key,
            name,
            source,
            "epoch second",
            gp.epoch_datetime.second,
            case.epoch_datetime_second,
        );
        assert_near(
            key,
            name,
            source,
            "n-dot",
            gp.first_derivative_of_mean_motion,
            case.first_derivative_of_mean_motion,
        );
        assert_near(
            key,
            name,
            source,
            "n-ddot",
            gp.second_derivative_of_mean_motion,
            case.second_derivative_of_mean_motion,
        );
        assert_near(key, name, source, "bstar", gp.bstar, case.bstar);
        assert_eq!(
            gp.ephemeris_type, case.ephemeris_type,
            "{key} ({name}) via {source}: ephemeris_type"
        );
        assert_eq!(
            gp.element_set_number, case.element_set_number,
            "{key} ({name}) via {source}: element_set_number"
        );
        assert_near(
            key,
            name,
            source,
            "inclination",
            gp.inclination,
            case.inclination,
        );
        assert_near(
            key,
            name,
            source,
            "raan",
            gp.right_ascension_of_ascending_node,
            case.right_ascension_of_ascending_node,
        );
        assert_near(
            key,
            name,
            source,
            "eccentricity",
            gp.eccentricity,
            case.eccentricity,
        );
        assert_near(
            key,
            name,
            source,
            "argp",
            gp.argument_of_perigee,
            case.argument_of_perigee,
        );
        assert_near(
            key,
            name,
            source,
            "mean anomaly",
            gp.mean_anomaly,
            case.mean_anomaly,
        );
        assert_near(
            key,
            name,
            source,
            "mean motion",
            gp.mean_motion,
            case.mean_motion,
        );
        assert_eq!(
            gp.revolution_number_at_epoch, case.revolution_number_at_epoch,
            "{key} ({name}) via {source}: revolution_number_at_epoch"
        );
    }

    /// Parse one TLE case, with or without a name line
    ///
    /// # Arguments
    /// * `tle` - TLE text from the test case
    ///
    /// # Returns
    /// * `Ok(Sgp4)` - Parsed propagator
    /// * `Err(GpError)` - If the TLE is invalid
    fn sgp4_from_case_tle(tle: &str) -> Result<Sgp4, GpError> {
        let lines: Vec<&str> = tle
            .lines()
            .map(str::trim)
            .filter(|l| !l.is_empty())
            .collect();
        if lines[0].starts_with('1') {
            from_tle_lines(lines[0], lines[1], None)
        } else {
            from_tle_lines(lines[1], lines[2], Some(lines[0]))
        }
    }

    /// Compare TLE parsing with the TOML cases and the fixture file
    ///
    /// Exception cases must fail. The other cases must match from lines, from a
    /// string, and from the fixture file.
    ///
    /// # Panics
    /// * If a case fails to parse or a field misses the expected value
    #[test]
    fn test_tle_parsing_cases() {
        let content = std::fs::read_to_string("test/tle_parsing_cases.toml")
            .expect("could not read test/tle_parsing_cases.toml");
        let cases: ParsingCases =
            from_str(&content).expect("could not parse test/tle_parsing_cases.toml");

        let from_file = from_tle_file("test/tle_parsing_cases.txt")
            .expect("could not read test/tle_parsing_cases.txt");
        let expected_file_count = cases.test.values().filter(|c| !c.exception).count();
        assert_eq!(
            from_file.len(),
            expected_file_count,
            "tle_parsing_cases.txt should contain one entry per non-error TOML case"
        );

        let mut keys: Vec<&String> = cases.test.keys().collect();
        keys.sort();

        for key in keys {
            let case = &cases.test[key];

            if case.exception {
                assert!(
                    sgp4_from_case_tle(&case.tle).is_err(),
                    "case {key} ({}): expected from_tle_lines to return Err",
                    case.name
                );
                assert!(
                    from_tle_string(&case.tle).is_err(),
                    "case {key} ({}): expected from_tle_string to return Err",
                    case.name
                );
                continue;
            }

            let from_lines = sgp4_from_case_tle(&case.tle).unwrap_or_else(|err| {
                panic!("case {key} ({}): from_tle_lines failed: {err:?}", case.name)
            });
            assert_gp_matches(key, &case.name, "from_tle_lines", &from_lines.gp, case);

            let from_string = from_tle_string(&case.tle).unwrap_or_else(|err| {
                panic!(
                    "case {key} ({}): from_tle_string failed: {err:?}",
                    case.name
                )
            });
            assert_eq!(
                from_string.len(),
                1,
                "case {key} ({}): expected one TLE from string",
                case.name
            );
            assert_gp_matches(key, &case.name, "from_tle_string", &from_string[0].gp, case);

            let file_match = from_file
                .iter()
                .find(|s| s.gp.satellite_catalog_number == case.satellite_catalog_number)
                .unwrap_or_else(|| {
                    panic!(
                        "case {key} ({}): catalog {} missing from tle_parsing_cases.txt parse",
                        case.name, case.satellite_catalog_number
                    )
                });
            assert_gp_matches(key, &case.name, "from_tle_file", &file_match.gp, case);
        }
    }

    /// Load the OMM parsing cases from TOML
    ///
    /// # Returns
    /// * `ParsingCases` - Parsed case file
    ///
    /// # Panics
    /// * If the file cannot be read or parsed
    fn load_omm_parsing_cases() -> ParsingCases {
        let content = std::fs::read_to_string("test/omm_parsing_cases.toml")
            .expect("could not read test/omm_parsing_cases.toml");
        from_str(&content).expect("could not parse test/omm_parsing_cases.toml")
    }

    /// Return OMM case keys in a stable order
    ///
    /// # Arguments
    /// * `cases` - Parsed OMM case file
    ///
    /// # Returns
    /// * `Vec<&String>` - Sorted case keys
    fn sorted_omm_keys(cases: &ParsingCases) -> Vec<&String> {
        let mut keys: Vec<&String> = cases.test.keys().collect();
        keys.sort();
        keys
    }

    /// Compare an OMM fixture parse with the non-error TOML cases
    ///
    /// # Arguments
    /// * `cases` - Parsed OMM case file
    /// * `from_file` - Propagators parsed from the fixture
    /// * `source` - Parser name, included in failure messages
    /// * `fixture` - Fixture file name, included in failure messages
    ///
    /// # Panics
    /// * If the record count differs or a catalog number is missing or mismatched
    #[cfg(any(feature = "xml", feature = "json", feature = "csv"))]
    fn assert_omm_file_matches_cases(
        cases: &ParsingCases,
        from_file: &[Sgp4],
        source: &str,
        fixture: &str,
    ) {
        let expected_file_count = cases.test.values().filter(|c| !c.exception).count();
        assert_eq!(
            from_file.len(),
            expected_file_count,
            "{fixture} should contain one entry per non-error TOML case"
        );

        for key in sorted_omm_keys(cases) {
            let case = &cases.test[key];
            if case.exception {
                continue;
            }

            let file_match = from_file
                .iter()
                .find(|s| s.gp.satellite_catalog_number == case.satellite_catalog_number)
                .unwrap_or_else(|| {
                    panic!(
                        "case {key} ({}): catalog {} missing from {fixture} parse",
                        case.name, case.satellite_catalog_number
                    )
                });
            assert_gp_matches(key, &case.name, source, &file_match.gp, case);
        }
    }

    /// Parse one KVN OMM case into a propagator
    ///
    /// # Arguments
    /// * `omm_kvn` - KVN text from the test case
    ///
    /// # Returns
    /// * `Ok(Sgp4)` - Parsed propagator
    /// * `Err(GpError)` - If the OMM is invalid
    fn sgp4_from_case_omm(omm_kvn: &str) -> Result<Sgp4, GpError> {
        let lines: Vec<&str> = omm_kvn
            .lines()
            .map(str::trim)
            .filter(|l| !l.is_empty())
            .collect();
        from_omm_kvn_lines(&lines)
    }

    /// Compare KVN OMM parsing with the TOML cases and the fixture file
    ///
    /// Exception cases must fail. The other cases must match from lines, from a
    /// string, and from the fixture file.
    ///
    /// # Panics
    /// * If a case fails to parse or a field misses the expected value
    #[test]
    fn test_omm_kvn_parsing_cases() {
        let cases = load_omm_parsing_cases();
        let from_file = from_omm_kvn_file("test/omm_parsing_cases.txt")
            .expect("could not parse test/omm_parsing_cases.txt");
        let expected_file_count = cases.test.values().filter(|c| !c.exception).count();
        assert_eq!(
            from_file.len(),
            expected_file_count,
            "omm_parsing_cases.txt should contain one entry per non-error TOML case"
        );

        for key in sorted_omm_keys(&cases) {
            let case = &cases.test[key];

            if case.exception {
                assert!(
                    sgp4_from_case_omm(&case.omm_kvn).is_err(),
                    "case {key} ({}): expected from_omm_kvn_lines to return Err",
                    case.name
                );
                assert!(
                    from_omm_kvn_string(&case.omm_kvn).is_err(),
                    "case {key} ({}): expected from_omm_kvn_string to return Err",
                    case.name
                );
                continue;
            }

            let from_lines = sgp4_from_case_omm(&case.omm_kvn).unwrap_or_else(|err| {
                panic!(
                    "case {key} ({}): from_omm_kvn_lines failed: {err:?}",
                    case.name
                )
            });
            assert_gp_matches(key, &case.name, "from_omm_kvn_lines", &from_lines.gp, case);

            let from_string = from_omm_kvn_string(&case.omm_kvn).unwrap_or_else(|err| {
                panic!(
                    "case {key} ({}): from_omm_kvn_string failed: {err:?}",
                    case.name
                )
            });
            assert_eq!(
                from_string.len(),
                1,
                "case {key} ({}): expected one OMM from string",
                case.name
            );
            assert_gp_matches(
                key,
                &case.name,
                "from_omm_kvn_string",
                &from_string[0].gp,
                case,
            );

            let file_match = from_file
                .iter()
                .find(|s| s.gp.satellite_catalog_number == case.satellite_catalog_number)
                .unwrap_or_else(|| {
                    panic!(
                        "case {key} ({}): catalog {} missing from omm_parsing_cases.txt parse",
                        case.name, case.satellite_catalog_number
                    )
                });
            assert_gp_matches(key, &case.name, "from_omm_kvn_file", &file_match.gp, case);
        }
    }

    /// Compare XML OMM parsing with the TOML cases and the fixture file
    ///
    /// # Panics
    /// * If the fixture fails to parse or a field misses the expected value
    #[cfg(feature = "xml")]
    #[test]
    fn test_omm_xml_parsing_cases() {
        let cases = load_omm_parsing_cases();
        let from_xml_file = from_omm_xml_file("test/omm_parsing_cases.xml")
            .expect("could not parse test/omm_parsing_cases.xml");
        assert_omm_file_matches_cases(
            &cases,
            &from_xml_file,
            "from_omm_xml_file",
            "omm_parsing_cases.xml",
        );
    }

    /// Compare JSON OMM parsing with the TOML cases and the fixture file
    ///
    /// # Panics
    /// * If the fixture fails to parse or a field misses the expected value
    #[cfg(feature = "json")]
    #[test]
    fn test_omm_json_parsing_cases() {
        let cases = load_omm_parsing_cases();
        let from_json_file = from_omm_json_file("test/omm_parsing_cases.json")
            .expect("could not parse test/omm_parsing_cases.json");
        assert_omm_file_matches_cases(
            &cases,
            &from_json_file,
            "from_omm_json_file",
            "omm_parsing_cases.json",
        );
    }

    /// Compare CSV OMM parsing with the TOML cases and the fixture file
    ///
    /// # Panics
    /// * If the fixture fails to parse or a field misses the expected value
    #[cfg(feature = "csv")]
    #[test]
    fn test_omm_csv_parsing_cases() {
        let cases = load_omm_parsing_cases();
        let from_csv_file = from_omm_csv_file("test/omm_parsing_cases.csv")
            .expect("could not parse test/omm_parsing_cases.csv");
        assert_omm_file_matches_cases(
            &cases,
            &from_csv_file,
            "from_omm_csv_file",
            "omm_parsing_cases.csv",
        );
    }

    /// Compare two element sets field by field
    ///
    /// # Arguments
    /// * `label` - Record label, included in the failure message
    /// * `original` - Element set before export
    /// * `exported` - Element set parsed from the export
    ///
    /// # Panics
    /// * If any field differs
    fn assert_gp_eq(label: &str, original: &GenPerturbElementSet, exported: &GenPerturbElementSet) {
        assert_eq!(
            original.common_name, exported.common_name,
            "{label}: common_name"
        );
        assert_eq!(
            original.satellite_catalog_number, exported.satellite_catalog_number,
            "{label}: satellite_catalog_number"
        );
        assert_eq!(
            original.classification, exported.classification,
            "{label}: classification"
        );
        assert_eq!(
            original.international_designator, exported.international_designator,
            "{label}: international_designator"
        );
        assert_eq!(
            original.epoch_datetime.year, exported.epoch_datetime.year,
            "{label}: epoch year"
        );
        assert_eq!(
            original.epoch_datetime.month, exported.epoch_datetime.month,
            "{label}: epoch month"
        );
        assert_eq!(
            original.epoch_datetime.day, exported.epoch_datetime.day,
            "{label}: epoch day"
        );
        assert_eq!(
            original.epoch_datetime.hour, exported.epoch_datetime.hour,
            "{label}: epoch hour"
        );
        assert_eq!(
            original.epoch_datetime.minute, exported.epoch_datetime.minute,
            "{label}: epoch minute"
        );
        assert!(
            (original.epoch_datetime.second - exported.epoch_datetime.second).abs() < TLE_PARSE_TOL,
            "{label}: epoch second {} vs {}",
            original.epoch_datetime.second,
            exported.epoch_datetime.second
        );
        assert!(
            (original.first_derivative_of_mean_motion - exported.first_derivative_of_mean_motion)
                .abs()
                < TLE_PARSE_TOL,
            "{label}: n-dot"
        );
        assert!(
            (original.second_derivative_of_mean_motion - exported.second_derivative_of_mean_motion)
                .abs()
                < TLE_PARSE_TOL,
            "{label}: n-ddot"
        );
        assert!(
            (original.bstar - exported.bstar).abs() < TLE_PARSE_TOL,
            "{label}: bstar"
        );
        assert_eq!(
            original.ephemeris_type, exported.ephemeris_type,
            "{label}: ephemeris_type"
        );
        assert_eq!(
            original.element_set_number, exported.element_set_number,
            "{label}: element_set_number"
        );
        assert!(
            (original.inclination - exported.inclination).abs() < TLE_PARSE_TOL,
            "{label}: inclination"
        );
        assert!(
            (original.right_ascension_of_ascending_node
                - exported.right_ascension_of_ascending_node)
                .abs()
                < TLE_PARSE_TOL,
            "{label}: raan"
        );
        assert!(
            (original.eccentricity - exported.eccentricity).abs() < TLE_PARSE_TOL,
            "{label}: eccentricity"
        );
        assert!(
            (original.argument_of_perigee - exported.argument_of_perigee).abs() < TLE_PARSE_TOL,
            "{label}: argp"
        );
        assert!(
            (original.mean_anomaly - exported.mean_anomaly).abs() < TLE_PARSE_TOL,
            "{label}: mean anomaly"
        );
        assert!(
            (original.mean_motion - exported.mean_motion).abs() < TLE_PARSE_TOL,
            "{label}: mean motion"
        );
        assert_eq!(
            original.revolution_number_at_epoch, exported.revolution_number_at_epoch,
            "{label}: revolution_number_at_epoch"
        );
    }

    /// Create the export directory and return a path inside it
    ///
    /// # Arguments
    /// * `file_name` - File name under test/export
    ///
    /// # Returns
    /// * `String` - Path of the export file
    ///
    /// # Panics
    /// * If the directory cannot be created or the path is not valid UTF-8
    fn export_test_path(file_name: &str) -> String {
        let dir = std::path::Path::new("test/export");
        std::fs::create_dir_all(dir).expect("could not create test/export");
        dir.join(file_name)
            .to_str()
            .expect("export path is valid UTF-8")
            .to_string()
    }

    /// Export no propagators as an empty KVN string
    ///
    /// # Panics
    /// * If the export is not empty
    #[test]
    fn test_omm_kvn_export_empty() {
        // An empty slice should produce an empty KVN string
        let exported = to_omm_kvn_string(&[]);
        assert_eq!(exported, "");
    }

    /// Export KVN text and parse it back to the same element sets
    ///
    /// # Panics
    /// * If a record count or field differs
    #[test]
    fn test_omm_kvn_export_string_roundtrip() {
        // Parse the KVN test file, export, and parse the export
        let original = from_omm_kvn_file("test/omm_parsing_cases.txt")
            .expect("could not parse test/omm_parsing_cases.txt");
        let exported = to_omm_kvn_string(&original);
        let reparsed = from_omm_kvn_string(&exported).unwrap();

        assert_eq!(original.len(), reparsed.len());
        for (i, (a, b)) in original.iter().zip(reparsed.iter()).enumerate() {
            assert_gp_eq(&format!("record {i}"), &a.gp, &b.gp);
        }
    }

    /// Write KVN to a file and parse it back to the same element sets
    ///
    /// # Panics
    /// * If the file cannot be written or a field differs
    #[test]
    fn test_omm_kvn_export_file_roundtrip() {
        // Parse the KVN test file and write it back out
        let original = from_omm_kvn_file("test/omm_parsing_cases.txt")
            .expect("could not parse test/omm_parsing_cases.txt");
        let out_path = export_test_path("omm_kvn.txt");
        to_omm_kvn_file(&original, &out_path).expect("could not write exported KVN file");

        // Parse the written file and compare GP fields
        let reparsed = from_omm_kvn_file(&out_path).expect("could not parse exported KVN file");

        assert_eq!(original.len(), reparsed.len());
        for (i, (a, b)) in original.iter().zip(reparsed.iter()).enumerate() {
            assert_gp_eq(&format!("record {i}"), &a.gp, &b.gp);
        }
    }

    /// Export no propagators as an XML document with no OMM records
    ///
    /// # Panics
    /// * If the exported document parses as a non-empty list
    #[cfg(feature = "xml")]
    #[test]
    fn test_omm_xml_export_empty() {
        // An empty slice should produce an NDM document with no OMM records
        let exported = to_omm_xml_string(&[]);
        let reparsed = from_omm_xml_string(&exported).unwrap();
        assert!(reparsed.is_empty());
    }

    /// Export XML text and parse it back to the same element sets
    ///
    /// # Panics
    /// * If a record count or field differs
    #[cfg(feature = "xml")]
    #[test]
    fn test_omm_xml_export_string_roundtrip() {
        // Parse the XML test file, export, and parse the export
        let original = from_omm_xml_file("test/omm_parsing_cases.xml")
            .expect("could not parse test/omm_parsing_cases.xml");
        let exported = to_omm_xml_string(&original);
        let reparsed = from_omm_xml_string(&exported).unwrap();

        assert_eq!(original.len(), reparsed.len());
        for (i, (a, b)) in original.iter().zip(reparsed.iter()).enumerate() {
            assert_gp_eq(&format!("record {i}"), &a.gp, &b.gp);
        }
    }

    /// Write XML to a file and parse it back to the same element sets
    ///
    /// # Panics
    /// * If the file cannot be written or a field differs
    #[cfg(feature = "xml")]
    #[test]
    fn test_omm_xml_export_file_roundtrip() {
        // Parse the XML test file and write it back out
        let original = from_omm_xml_file("test/omm_parsing_cases.xml")
            .expect("could not parse test/omm_parsing_cases.xml");
        let out_path = export_test_path("omm_xml.xml");
        to_omm_xml_file(&original, &out_path).expect("could not write exported XML file");

        // Parse the written file and compare GP fields
        let reparsed = from_omm_xml_file(&out_path).expect("could not parse exported XML file");

        assert_eq!(original.len(), reparsed.len());
        for (i, (a, b)) in original.iter().zip(reparsed.iter()).enumerate() {
            assert_gp_eq(&format!("record {i}"), &a.gp, &b.gp);
        }
    }

    /// Export no propagators as an empty JSON array
    ///
    /// # Panics
    /// * If the exported array parses as a non-empty list
    #[cfg(feature = "json")]
    #[test]
    fn test_omm_json_export_empty() {
        // An empty slice should produce an empty JSON array
        let exported = to_omm_json_string(&[]);
        let reparsed = from_omm_json_string(&exported).unwrap();
        assert!(reparsed.is_empty());
    }

    /// Export JSON text and parse it back to the same element sets
    ///
    /// # Panics
    /// * If a record count or field differs
    #[cfg(feature = "json")]
    #[test]
    fn test_omm_json_export_string_roundtrip() {
        // Parse the JSON test file, export, and parse the export
        let original = from_omm_json_file("test/omm_parsing_cases.json")
            .expect("could not parse test/omm_parsing_cases.json");
        let exported = to_omm_json_string(&original);
        let reparsed = from_omm_json_string(&exported).unwrap();

        assert_eq!(original.len(), reparsed.len());
        for (i, (a, b)) in original.iter().zip(reparsed.iter()).enumerate() {
            assert_gp_eq(&format!("record {i}"), &a.gp, &b.gp);
        }
    }

    /// Write JSON to a file and parse it back to the same element sets
    ///
    /// # Panics
    /// * If the file cannot be written or a field differs
    #[cfg(feature = "json")]
    #[test]
    fn test_omm_json_export_file_roundtrip() {
        // Parse the JSON test file and write it back out
        let original = from_omm_json_file("test/omm_parsing_cases.json")
            .expect("could not parse test/omm_parsing_cases.json");
        let out_path = export_test_path("omm_json.json");
        to_omm_json_file(&original, &out_path).expect("could not write exported JSON file");

        // Parse the written file and compare GP fields
        let reparsed = from_omm_json_file(&out_path).expect("could not parse exported JSON file");

        assert_eq!(original.len(), reparsed.len());
        for (i, (a, b)) in original.iter().zip(reparsed.iter()).enumerate() {
            assert_gp_eq(&format!("record {i}"), &a.gp, &b.gp);
        }
    }

    /// Export no propagators as a header-only CSV
    ///
    /// # Panics
    /// * If the exported CSV parses as a non-empty list
    #[cfg(feature = "csv")]
    #[test]
    fn test_omm_csv_export_empty() {
        // An empty slice should produce a header-only CSV
        let exported = to_omm_csv_string(&[]);
        let reparsed = from_omm_csv_string(&exported).unwrap();
        assert!(reparsed.is_empty());
    }

    /// Export CSV text and parse it back to the same element sets
    ///
    /// # Panics
    /// * If a record count or field differs
    #[cfg(feature = "csv")]
    #[test]
    fn test_omm_csv_export_string_roundtrip() {
        // Parse the CSV test file, export, and parse the export
        let original = from_omm_csv_file("test/omm_parsing_cases.csv")
            .expect("could not parse test/omm_parsing_cases.csv");
        let exported = to_omm_csv_string(&original);
        let reparsed = from_omm_csv_string(&exported).unwrap();

        assert_eq!(original.len(), reparsed.len());
        for (i, (a, b)) in original.iter().zip(reparsed.iter()).enumerate() {
            assert_gp_eq(&format!("record {i}"), &a.gp, &b.gp);
        }
    }

    /// Write CSV to a file and parse it back to the same element sets
    ///
    /// # Panics
    /// * If the file cannot be written or a field differs
    #[cfg(feature = "csv")]
    #[test]
    fn test_omm_csv_export_file_roundtrip() {
        // Parse the CSV test file and write it back out
        let original = from_omm_csv_file("test/omm_parsing_cases.csv")
            .expect("could not parse test/omm_parsing_cases.csv");
        let out_path = export_test_path("omm_csv.csv");
        to_omm_csv_file(&original, &out_path).expect("could not write exported CSV file");

        // Parse the written file and compare GP fields
        let reparsed = from_omm_csv_file(&out_path).expect("could not parse exported CSV file");

        assert_eq!(original.len(), reparsed.len());
        for (i, (a, b)) in original.iter().zip(reparsed.iter()).enumerate() {
            assert_gp_eq(&format!("record {i}"), &a.gp, &b.gp);
        }
    }

    /// Export no propagators as an empty TLE string
    ///
    /// # Panics
    /// * If the export fails or is not empty
    #[test]
    fn test_tle_export_empty() {
        // An empty slice should produce an empty TLE string
        let exported = to_tle_string(&[]).expect("empty TLE export should succeed");
        assert_eq!(exported, "");
    }

    /// Export TLE text and parse it back to the same element sets
    ///
    /// # Panics
    /// * If a record count or field differs
    #[test]
    fn test_tle_export_string_roundtrip() {
        // Parse the TLE test file, export, and parse the export
        let original = from_tle_file("test/tle_parsing_cases.txt")
            .expect("could not read test/tle_parsing_cases.txt");
        let exported = to_tle_string(&original).expect("TLE export should succeed");
        let reparsed = from_tle_string(&exported).expect("exported TLE string should parse");

        assert_eq!(original.len(), reparsed.len());
        for (i, (a, b)) in original.iter().zip(reparsed.iter()).enumerate() {
            assert_gp_eq(&format!("record {i}"), &a.gp, &b.gp);
        }
    }

    /// Write a TLE file and parse it back to the same element sets
    ///
    /// # Panics
    /// * If the file cannot be written or a field differs
    #[test]
    fn test_tle_export_file_roundtrip() {
        // Parse the TLE test file and write it back out
        let original = from_tle_file("test/tle_parsing_cases.txt")
            .expect("could not read test/tle_parsing_cases.txt");
        let out_path = export_test_path("tle.txt");
        to_tle_file(&original, &out_path).expect("TLE file export should succeed");

        // Parse the written file and compare GP fields
        let reparsed = from_tle_file(&out_path).expect("could not parse exported TLE file");

        assert_eq!(original.len(), reparsed.len());
        for (i, (a, b)) in original.iter().zip(reparsed.iter()).enumerate() {
            assert_gp_eq(&format!("record {i}"), &a.gp, &b.gp);
        }
    }

    /// Check exported TLE line length, checksum, and name length
    ///
    /// Data lines must be 69 characters and pass the checksum. Name lines must be
    /// non-empty and at most 24 characters.
    ///
    /// # Panics
    /// * If a line has the wrong length or a bad checksum
    #[test]
    fn test_tle_export_line_format() {
        // Exported data lines must be 69 characters and pass the checksum
        let original = from_tle_file("test/tle_parsing_cases.txt")
            .expect("could not read test/tle_parsing_cases.txt");
        let exported = to_tle_string(&original).expect("TLE export should succeed");

        for line in exported.lines() {
            if line.starts_with('1') || line.starts_with('2') {
                assert_eq!(line.len(), 69, "TLE data line length: {line}");
                assert!(tle_checksum(line), "TLE checksum: {line}");
            } else {
                assert!(!line.is_empty() && line.len() <= 24, "TLE name: {line}");
            }
        }
    }

    /// Use type defaults when a KVN field is missing
    ///
    /// Numbers default to 0, strings to empty, and classification to U.
    ///
    /// # Panics
    /// * If a missing field returns another default
    #[test]
    fn test_kvn_parse_defaults() {
        // Define an empty OMM record
        let lines: [&str; 0] = [];

        // Parse missing fields
        let name: String = kvn_parse(&lines, "OBJECT_NAME").unwrap();
        let catalog: i32 = kvn_parse(&lines, "NORAD_CAT_ID").unwrap();
        let rev: i64 = kvn_parse(&lines, "REV_AT_EPOCH").unwrap();
        let motion: f64 = kvn_parse(&lines, "MEAN_MOTION").unwrap();
        let class: char = kvn_parse(&lines, "CLASSIFICATION_TYPE").unwrap();

        // Assert numeric fields default to 0, strings to empty, classification to U
        assert_eq!(name, "");
        assert_eq!(catalog, 0);
        assert_eq!(rev, 0);
        assert_eq!(motion, 0.0);
        assert_eq!(class, 'U');
    }
}