rsspice 0.1.0

Pure Rust port of the SPICE Toolkit for space geometry
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
//
// GENERATED FILE
//

use super::*;
use crate::SpiceContext;
use f2rust_std::*;

const CTRSIZ: i32 = 2;
const NDELIM: i32 = 5;
const DELIMS: &[u8; NDELIM as usize] = &fstr::extend_const::<{ NDELIM as usize }>(b".:-, ");
const TDB: i32 = 1;
const TDT: i32 = 2;
const MXPART: i32 = 9999;
const MXCOEF: i32 = 100000;
const MXNFLD: i32 = 10;
const DPLEN: i32 = 30;
const IXNFLD: i32 = 1;
const IXDLIM: i32 = (IXNFLD + 1);
const IXTSYS: i32 = (IXDLIM + 1);
const IXNCOF: i32 = (IXTSYS + 1);
const IXNPRT: i32 = (IXNCOF + 1);
const IXBCOF: i32 = (IXNPRT + 1);
const IXBSTR: i32 = (IXBCOF + 1);
const IXBEND: i32 = (IXBSTR + 1);
const IXBMOD: i32 = (IXBEND + 1);
const IXBOFF: i32 = (IXBMOD + 1);
const NIVALS: i32 = IXBOFF;
const MXNCLK: i32 = 100;
const DBUFSZ: i32 = (((3 * MXCOEF) + (2 * MXPART)) + (2 * MXNFLD));
const IBUFSZ: i32 = (NIVALS * MXNCLK);
const LBSNGL: i32 = -5;
const CPLSIZ: i32 = ((MXNCLK - LBSNGL) + 1);
const ERRLEN: i32 = 240;
const MSGLEN: i32 = 320;
const INITSC: i32 = 0;
const KVNMLN: i32 = 32;

struct SaveVars {
    HDSCLK: StackArray<i32, 100>,
    SCPOOL: StackArray<i32, 106>,
    CLKLST: StackArray<i32, 100>,
    SCBASE: StackArray<i32, 100>,
    BVLMSG: Vec<u8>,
    CMP: ActualCharArray,
    DEL: ActualCharArray,
    DPCHAR: Vec<u8>,
    ERROR: Vec<u8>,
    KVNAME: Vec<u8>,
    CMPTKS: StackArray<f64, 10>,
    CMPVAL: StackArray<f64, 10>,
    CONST: f64,
    DPBUFF: ActualArray<f64>,
    DVAL: f64,
    MAXWID: f64,
    MXTICK: f64,
    PARTIM: f64,
    RATE: f64,
    REM: f64,
    SAVCMP: f64,
    TIKDIF: f64,
    TIKMSC: f64,
    TIMDIF: f64,
    CMPWID: StackArray<i32, 10>,
    COFBAS: i32,
    DELCDE: i32,
    DPFREE: i32,
    END: i32,
    ENDBAS: i32,
    I: i32,
    IFREE: i32,
    INTBUF: ActualArray<i32>,
    J: i32,
    LENGTH: StackArray<i32, 10>,
    LOWER: i32,
    MIDDLE: i32,
    MODBAS: i32,
    N: i32,
    NCOEFF: i32,
    NEEDED: i32,
    NFIELD: i32,
    NPART: i32,
    OFFBAS: i32,
    PAD: i32,
    PNTR: i32,
    POLCTR: StackArray<i32, 2>,
    PRVSC: i32,
    STRBAS: i32,
    TIMSYS: i32,
    UPPER: i32,
    FOUND: bool,
    PASS1: bool,
    SAMCLK: bool,
    UPDATE: bool,
}

impl SaveInit for SaveVars {
    fn new() -> Self {
        let mut HDSCLK = StackArray::<i32, 100>::new(1..=MXNCLK);
        let mut SCPOOL = StackArray::<i32, 106>::new(LBSNGL..=MXNCLK);
        let mut CLKLST = StackArray::<i32, 100>::new(1..=MXNCLK);
        let mut SCBASE = StackArray::<i32, 100>::new(1..=MXNCLK);
        let mut BVLMSG = vec![b' '; MSGLEN as usize];
        let mut CMP = ActualCharArray::new(DPLEN, 1..=MXNFLD);
        let mut DEL = ActualCharArray::new(1, 1..=NDELIM);
        let mut DPCHAR = vec![b' '; DPLEN as usize];
        let mut ERROR = vec![b' '; ERRLEN as usize];
        let mut KVNAME = vec![b' '; KVNMLN as usize];
        let mut CMPTKS = StackArray::<f64, 10>::new(1..=MXNFLD);
        let mut CMPVAL = StackArray::<f64, 10>::new(1..=MXNFLD);
        let mut CONST: f64 = 0.0;
        let mut DPBUFF = ActualArray::<f64>::new(1..=DBUFSZ);
        let mut DVAL: f64 = 0.0;
        let mut MAXWID: f64 = 0.0;
        let mut MXTICK: f64 = 0.0;
        let mut PARTIM: f64 = 0.0;
        let mut RATE: f64 = 0.0;
        let mut REM: f64 = 0.0;
        let mut SAVCMP: f64 = 0.0;
        let mut TIKDIF: f64 = 0.0;
        let mut TIKMSC: f64 = 0.0;
        let mut TIMDIF: f64 = 0.0;
        let mut CMPWID = StackArray::<i32, 10>::new(1..=MXNFLD);
        let mut COFBAS: i32 = 0;
        let mut DELCDE: i32 = 0;
        let mut DPFREE: i32 = 0;
        let mut END: i32 = 0;
        let mut ENDBAS: i32 = 0;
        let mut I: i32 = 0;
        let mut IFREE: i32 = 0;
        let mut INTBUF = ActualArray::<i32>::new(1..=IBUFSZ);
        let mut J: i32 = 0;
        let mut LENGTH = StackArray::<i32, 10>::new(1..=MXNFLD);
        let mut LOWER: i32 = 0;
        let mut MIDDLE: i32 = 0;
        let mut MODBAS: i32 = 0;
        let mut N: i32 = 0;
        let mut NCOEFF: i32 = 0;
        let mut NEEDED: i32 = 0;
        let mut NFIELD: i32 = 0;
        let mut NPART: i32 = 0;
        let mut OFFBAS: i32 = 0;
        let mut PAD: i32 = 0;
        let mut PNTR: i32 = 0;
        let mut POLCTR = StackArray::<i32, 2>::new(1..=CTRSIZ);
        let mut PRVSC: i32 = 0;
        let mut STRBAS: i32 = 0;
        let mut TIMSYS: i32 = 0;
        let mut UPPER: i32 = 0;
        let mut FOUND: bool = false;
        let mut PASS1: bool = false;
        let mut SAMCLK: bool = false;
        let mut UPDATE: bool = false;

        fstr::assign(&mut BVLMSG, b"Invalid value of #. Value was #.");
        {
            use f2rust_std::data::Val;

            let mut clist = [
                Val::C(b"."),
                Val::C(b":"),
                Val::C(b"-"),
                Val::C(b","),
                Val::C(b" "),
            ]
            .into_iter();
            DEL.iter_mut()
                .for_each(|n| fstr::assign(n, clist.next().unwrap().into_str()));

            debug_assert!(clist.next().is_none(), "DATA not fully initialised");
        }
        PASS1 = true;
        PRVSC = INITSC;
        COFBAS = 0;
        STRBAS = 0;
        ENDBAS = 0;
        MODBAS = 0;
        OFFBAS = 0;
        DPFREE = 1;
        IFREE = 1;

        Self {
            HDSCLK,
            SCPOOL,
            CLKLST,
            SCBASE,
            BVLMSG,
            CMP,
            DEL,
            DPCHAR,
            ERROR,
            KVNAME,
            CMPTKS,
            CMPVAL,
            CONST,
            DPBUFF,
            DVAL,
            MAXWID,
            MXTICK,
            PARTIM,
            RATE,
            REM,
            SAVCMP,
            TIKDIF,
            TIKMSC,
            TIMDIF,
            CMPWID,
            COFBAS,
            DELCDE,
            DPFREE,
            END,
            ENDBAS,
            I,
            IFREE,
            INTBUF,
            J,
            LENGTH,
            LOWER,
            MIDDLE,
            MODBAS,
            N,
            NCOEFF,
            NEEDED,
            NFIELD,
            NPART,
            OFFBAS,
            PAD,
            PNTR,
            POLCTR,
            PRVSC,
            STRBAS,
            TIMSYS,
            UPPER,
            FOUND,
            PASS1,
            SAMCLK,
            UPDATE,
        }
    }
}

fn COEFFS(I: i32, J: i32, DPBUFF: &[f64], COFBAS: i32) -> f64 {
    let DPBUFF = DummyArray::new(DPBUFF, 1..=DBUFSZ);
    DPBUFF[((COFBAS + I) + ((J - 1) * 3))]
}

fn PREND(I: i32, DPBUFF: &[f64], ENDBAS: i32) -> f64 {
    let DPBUFF = DummyArray::new(DPBUFF, 1..=DBUFSZ);
    DPBUFF[(ENDBAS + I)]
}

fn PRSTRT(I: i32, DPBUFF: &[f64], STRBAS: i32) -> f64 {
    let DPBUFF = DummyArray::new(DPBUFF, 1..=DBUFSZ);
    DPBUFF[(STRBAS + I)]
}

fn MODULI(I: i32, DPBUFF: &[f64], MODBAS: i32) -> f64 {
    let DPBUFF = DummyArray::new(DPBUFF, 1..=DBUFSZ);
    DPBUFF[(MODBAS + I)]
}

fn OFFSET(I: i32, DPBUFF: &[f64], OFFBAS: i32) -> f64 {
    let DPBUFF = DummyArray::new(DPBUFF, 1..=DBUFSZ);
    DPBUFF[(OFFBAS + I)]
}

/// Spacecraft clock, type 1
///
/// Perform time conversions between different representations of
/// type 1 spacecraft clock.
///
/// # Required Reading
///
/// * [SCLK](crate::required_reading::sclk)
/// * [TIME](crate::required_reading::time)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  ENTRY POINTS
///  --------  ---  --------------------------------------------------
///  SC         I   (All)
///  CLKSTR    I-O  SCTK01, SCFM01
///  TICKS     I-O  SCTK01, SCFM01
///  SCLKDP    I-O  SCTE01, SCET01, SCEC01
///  ET        I-O  SCTE01, SCET01, SCEC01
///  NPARTN     O   SCPR01
///  PARBEG     O   SCPR01
///  PAREND     O   SCPR01
///  CLKTYP     O   SCTY01
///  MXCOEF     P   SCTE01, SCET01
///  MXPART     P   (All)
///  DELIMS     P   SCTK01, SCFM01
///  MXNFLD     P   SCTK01, SCFM01
///  DPLEN      P   SCTK01, SCFM01
/// ```
///
/// # Detailed Input
///
/// ```text
///  See the entry points SCTK01, SCFM01, SCET01, SCTE01, SCEC01.
/// ```
///
/// # Detailed Output
///
/// ```text
///  See the entry points SCTK01, SCFM01, SCET01, SCTE01, SCEC01.
/// ```
///
/// # Parameters
///
/// ```text
///  MXCOEF   is the maximum number of coefficient sets in the
///           array COEFFS that defines the mapping between
///           encoded type 1 SCLK and a parallel time system,
///           such as TDB or TDT. This array has dimension
///           3 x MXCOEF. The value of MXCOEF may be increased
///           as required.
///
///  MXPART   is the maximum number of partitions for any type 1
///           spacecraft clock. Type 1 SCLK kernels contain
///           start and stop times for each partition. The value
///           of MXPART may be increased as required.
///
///  MXNFLD   is an upper bound on the number of components in
///           the clock string.
///
///  DPLEN    is an upper bound on the width of the individual
///           components of the clock string.
///
///  DELIMS   are the characters that are accepted delimiters of
///           the clock components in the input SCLK string.
/// ```
///
/// # Exceptions
///
/// ```text
///  1)  If SC01 is called directly, the error SPICE(BOGUSENTRY)
///      is signaled.
///
///  2)  See the entry points SCTK01, SCFM01, SCET01, SCTE01 for a
///      description of the exceptions specific to those routines.
/// ```
///
/// # Files
///
/// ```text
///  An SCLK kernel appropriate to the spacecraft clock identified
///  by SC must be loaded at the time any entry point of this
///  routine is called.
///
///  If the SCLK kernel used with this routine does not map SCLK
///  directly to barycentric dynamical time, a leapseconds kernel
///  must be loaded at the time any entry point of this routine is
///  called.
///
///  Normally kernels are loaded by user applications once at the
///  start of execution. It is not necessary to load them repeatedly.
/// ```
///
/// # Particulars
///
/// ```text
///  SC01 serves as an umbrella routine under which the shared
///  variables of its entry points are declared.  SC01 should
///  never be called directly.
///
///  The entry points of SC01 are
///
///     SCTK01 ( SCLK to ticks,          type 1 )
///     SCFM01 ( Format,                 type 1 )
///     SCET01 ( ET to ticks,            type 1 )
///     SCEC01 ( ET to continuous ticks, type 1 )
///     SCTE01 ( Ticks to ET,            type 1 )
///     SCTY01 ( Return type of SCLK )
///     SCPR01 ( Return partition start and stop times, type 1 )
/// ```
///
/// # Examples
///
/// ```text
///  See the entry points.
/// ```
///
/// # Restrictions
///
/// ```text
///  1)  Efficiency of the conversion routines in this package
///      depends on the assumption that the kernel pool is updated
///      relatively infrequently. Any modification of kernel pool data,
///      including setting watches, will cause entry points of this
///      package to re-buffer saved SCLK data.
/// ```
///
/// # Author and Institution
///
/// ```text
///  N.J. Bachman       (JPL)
///  J. Diaz del Rio    (ODC Space)
///  J.M. Lynch         (JPL)
///  B.V. Semenov       (JPL)
///  E.D. Wright        (JPL)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 4.0.0, 01-DEC-2021 (NJB) (JDR)
///
///         Added entry points SCPR01 (return partition data) and
///         SCTY01 (indicate whether clock is type 1).
///
///         Updated all entry points to support buffering of data for
///         multiple clocks.
///
///         Added error checks for invalid time system codes.
///
///         Edited headers of umbrella routine and all entry points to
///         comply with NAIF standard.
///
/// -    SPICELIB Version 3.4.0, 09-SEP-2013 (BVS)
///
///         Updated to keep track of the POOL counter and call ZZCVPOOL.
///
/// -    SPICELIB Version 3.3.0, 05-MAR-2009 (NJB)
///
///         Bug fix: the entry points of this routine now keep track of
///         whether their kernel pool look-ups succeeded. If not, a kernel
///         pool lookup is attempted on the next call to any entry point
///         of this routine.
///
/// -    SPICELIB Version 3.2.0, 17-FEB-2008 (NJB)
///
///         Bug fix: changed maximum value arguments to 1 in
///         calls to SCLI01 to fetch NFIELD and DELCDE values.
///
///         Bug fix: spaces between fields are now inserted
///         correctly when the output field delimiter is blank.
///
/// -    SPICELIB Version 3.1.1, 22-AUG-2006 (EDW)
///
///         Replaced references to LDPOOL with references
///         to FURNSH.
///
/// -    SPICELIB Version 3.1.0, 24-JAN-2003 (BVS)
///
///         Increased MXCOEF to 10000.
///
/// -    SPICELIB Version 3.0.0, 09-MAR-1999 (NJB)
///
///         Added new entry point SCEC01. Removed some extraneous
///         C's from column 1; these had been added by a wayward
///         preprocessor.
///
///         Removed local variable RNDCLK; entry point SCTE01 no longer
///         creates a rounded version of its input argument.
///
///         Updated/fixed various comments here and in entry SCET01.
///
/// -    SPICELIB Version 2.1.0, 07-JUL-1996 (NJB)
///
///         Removed declaration, DATA and SAVE statements for unused
///         variables NFDMSG and OLDID.
///
/// -    SPICELIB Version 2.0.0, 17-APR-1992 (NJB)
///
///         All entry points were updated to handle SCLK kernels that
///         map between SCLK and a variety of time systems; formerly
///         only TDB was supported. All entry points have had corrections
///         and additions made to their headers. Comment section for
///         permuted index source lines was added following the header.
///
/// -    SPICELIB Version 1.0.0, 03-SEP-1990 (NJB) (JML)
/// ```
///
/// # Revisions
///
/// ```text
/// -    SPICELIB Version 3.3.0, 05-MAR-2009 (NJB)
///
///         Bug fix: the entry points of this routine now keep track of
///         whether their kernel pool look-ups succeeded. If not, a kernel
///         pool lookup is attempted on the next call to any entry point
///         of this routine.
///
///         All entry points of this routine look up the same kernel
///         variables, and use the saved variable UPDATE to indicate that
///         a kernel pool look-up is needed. A look-up failure occurring
///         in any entry point will now prevent all entry points from
///         relying on stored kernel data.
///
///
/// -    SPICELIB Version 3.2.0, 17-FEB-2008 (NJB)
///
///         Bug fix: changed maximum value arguments to 1 in
///         calls to SCLI01 to fetch NFIELD and DELCDE values.
///
///         Bug fix: spaces between fields are now inserted
///         correctly when the output field delimiter is blank.
///
///         Unused parameter INITID was removed.
///
/// -    SPICELIB Version 3.1.0, 24-JAN-2003 (BVS)
///
///         Increased MXCOEF to 10000.
///
/// -    SPICELIB Version 3.0.0, 09-MAR-1999 (NJB)
///
///         Added new entry point SCEC01. Removed some extraneous
///         C's from column 1; these had been added by a wayward
///         preprocessor.
///
///         Removed local variable RNDCLK; entry point SCTE01 no longer
///         creates a rounded version of its input argument.
///
///         Updated/fixed various comments here and in entry SCET01.
///
/// -    SPICELIB Version 2.1.0, 07-JUL-1996 (NJB)
///
///         Removed declaration, DATA and SAVE statements for unused
///         variables NFDMSG and OLDID.
///
/// -    SPICELIB Version 2.0.0, 17-APR-1992 (NJB)
///
///         Entry points SCET01 and SCTE01 were updated to handle a time
///         system specification for the `parallel' time system
///         in the SCLK kernel. Formerly, the only time system that
///         an SCLK kernel could map SCLK to was TDB. Now TDT is
///         supported, and the mechanism for allowing other parallel
///         time systems is in place.
///
///         To support a new parallel time system, it is necessary
///         to
///
///            -- Update SCTE01 so that after the routine converts an input
///               tick value to a value in the parallel system, the
///               resulting value is converted to TDB. See the current
///               treatment of TDT in that routine for an example of how
///               this is done.
///
///            -- Update SCET01 so that the input TDB value can be
///               converted to a value in the new parallel system when
///               required. This converted value is then used as an input
///               to the interpolation algorithm performed in SCET01. See
///               the current treatment of TDT in that routine for an
///               example of how this is done.
///
///            -- Update the parameter MXTSYS in SCLU01 to indicate the
///               new number of supported parallel time systems.
///
///            -- Update the SCLK Required Reading to document the
///               description of the currently supported parallel time
///               systems.
///
///         See the named entry points for further details.
///
///         The kernel pool routines SWPOOL and CVPOOL are now used
///         to determine when it is necessary to look up kernel pool
///         constants. The variable UPDATE is now used to indicate
///         when it is necessary to look up the kernel variables used by
///         this suite of routines. All of the entry points SCFM01,
///         SCTK01, SCET01, and SCTE01 were affected by this update.
///
///         All of the entry points have had their headers updated to
///         discuss the fact that a leapseconds kernel will now need to be
///         loaded in order to use SCLK kernels that map between SCLK and
///         a parallel time system other than TDB.
///
///         In this routine, a comment section for permuted index
///         source lines was added following the header.
/// ```
pub fn sc01(
    ctx: &mut SpiceContext,
    sc: i32,
    clkstr: &str,
    ticks: f64,
    sclkdp: f64,
    et: f64,
    npartn: i32,
    parbeg: &[f64],
    parend: &[f64],
    clktyp: i32,
) -> crate::Result<()> {
    SC01(
        sc,
        clkstr.as_bytes(),
        ticks,
        sclkdp,
        et,
        npartn,
        parbeg,
        parend,
        clktyp,
        ctx.raw_context(),
    )?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SC01 ( Spacecraft clock, type 1 )
pub fn SC01(
    SC: i32,
    CLKSTR: &[u8],
    TICKS: f64,
    SCLKDP: f64,
    ET: f64,
    NPARTN: i32,
    PARBEG: &[f64],
    PAREND: &[f64],
    CLKTYP: i32,
    ctx: &mut Context,
) -> f2rust_std::Result<()> {
    //
    // SPICELIB functions
    //

    //
    // Local parameters
    //

    //
    // Local variables
    //

    //
    // SCLK pool:
    //

    //
    // Other local variables
    //

    //
    // Declarations of statement functions
    //

    //
    // Saved variables
    //

    //
    // There are at least a half dozen distinct items to save. We're
    // safer just saving everything.
    //
    // Maintenance programming note: the coefficient buffer
    // should be saved in any event to prevent memory problems
    // on some platforms.
    //

    //
    // Initial values
    //

    //
    // NEW: Statement functions
    //

    //
    // Function COEFFS returns the Ith element of the Jth coefficient
    // record for the record set starting at index COFBAS+1 in the
    // double precision SCLK data buffer.

    //
    // Function PREND returns the Ith partition end time for the
    // partition end time set starting at index ENDBAS+1 in the double
    // precision SCLK data buffer.
    //

    //
    // Function PRSTRT returns the Ith partition start time for the
    // partition start time set starting at index STRBAS+1 in the double
    // precision SCLK data buffer.
    //

    //
    // Function MODULI returns the Ith field modulus for the modulus
    // array starting at index MODBAS+1 in the double
    // precision SCLK data buffer.
    //

    //
    // Function OFFSET returns the Ith field offset for the offset
    // array starting at index OFFBAS+1 in the double
    // precision SCLK data buffer.
    //

    //
    // For later implementation:
    //
    // Function CMPWID returns the width in characters required to
    // represent as a string the maximum count of the Ith field.
    //
    //  CMPWID( I ) = INTBUF( OFFCMP + I )

    //
    // Standard SPICE error handling.
    //
    if RETURN(ctx) {
        return Ok(());
    }

    CHKIN(b"SC01", ctx)?;

    SIGERR(b"SPICE(BOGUSENTRY)", ctx)?;

    CHKOUT(b"SC01", ctx)?;
    Ok(())
}

/// Convert type 1 SCLK string to ticks
///
/// Convert a character representation of a type 1 spacecraft clock
/// count to ticks.
///
/// # Required Reading
///
/// * [SCLK](crate::required_reading::sclk)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  DESCRIPTION
///  --------  ---  --------------------------------------------------
///  SC         I   NAIF spacecraft ID code.
///  CLKSTR     I   Character representation of a clock count.
///  TICKS      O   Number of ticks represented by the clock count.
/// ```
///
/// # Detailed Input
///
/// ```text
///  SC       is a NAIF spacecraft identification code. See the
///           $Examples section below, and also the NAIF_IDS
///           required reading file for a complete list of body ID
///           codes.
///
///
///  CLKSTR   on input is the character representation of a
///           spacecraft clock count (SCLK), without a partition
///           number.
///
///           Using Galileo as an example, a SCLK string without
///           a partition number has the form
///
///                          wwwwwwww:xx:y:z
///
///           where z is a mod-8 counter (values 0-7) which
///           increments approximately once every 8 1/3 ms., y is a
///           mod-10 counter (values 0-9) which increments once
///           every time z turns over, i.e., approximately once every
///           66 2/3 ms., xx is a mod-91 (values 0-90) counter
///           which increments once every time y turns over, i.e.,
///           once every 2/3 seconds. wwwwwwww is the Real-Time
///           Image Count (RIM), which increments once every time
///           xx turns over, i.e., once every 60 2/3 seconds. The
///           roll-over expression for the RIM is 16777215, which
///           corresponds to approximately 32 years.
///
///           wwwwwwww, xx, y, and z are referred to interchangeably
///           as the fields or components of the spacecraft count.
///           SCLK components may be separated by any of the
///           single character delimiters in the string DELIMS, with
///           any number of spaces separating the components and
///           the delimiters. The presence of the RIM component
///           is required. Successive components may be omitted, and
///           in such cases are assumed to represent zero values.
///
///           Values for the individual components may exceed the
///           maximum expected values. For instance, '0:0:0:9' is
///           an acceptable Galileo clock string, and indicates the
///           same time interval as '0:0:1:1'.
///
///           Consecutive delimiters containing no intervening digits
///           are treated as if they delimit zero components, except
///           in the case of blanks.  Consecutive blanks are treated
///           as a single blank.
///
///           Trailing zeros should always be included to match the
///           length of the counter.  For example, a Galileo clock
///           count of '25684.90' should not be represented as
///           '25684.9'.
///
///           Some spacecraft clock components have offset, or
///           starting, values different from zero. For example,
///           with an offset value of 1, a mod 20 counter would
///           cycle from 1 to 20 instead of from 0 to 19.
///
///           See the SCLK required reading for a detailed
///           description of the Galileo, Mars Observer, and Voyager
///           clock formats.
///
///           See the $Examples section in SCTK01, below.
/// ```
///
/// # Detailed Output
///
/// ```text
///  TICKS    is the number of "ticks" corresponding to the input
///           spacecraft clock string CLKSTR.  "Ticks" are the units
///           in which encoded SCLK strings are represented.
///
///           A typical Galileo SCLK string looks like
///
///                        'wwwwwwww xx y z',
///
///           as described above. Since z is the mod-8 (one tick)
///           counter, the number of ticks represented by y is 8*y.
///           And since y is the mod-10 counter, the number of ticks
///           represented by xx is 10*8*xx. The total number of
///           ticks represented by the above string is
///
///                         wwwwwwww( 7280 ) +
///                               xx(   80 ) +
///                                y(    8 ) +
///                                z
///
///           Clock strings for other spacecraft are converted in
///           a similar manner.
///
///           See $Examples below.
/// ```
///
/// # Exceptions
///
/// ```text
///  1)  This routine assumes that that an SCLK kernel appropriate to
///      the spacecraft clock identified by the input argument SC has
///      been loaded. If an SCLK kernel has not been loaded, does not
///      contain all of the required data, or contains invalid data, an
///      error is signaled by a routine in the call tree of this
///      routine. The output argument TICKS will not be modified.
///
///      The variables that must be set by the SCLK kernel are:
///
///         -  The number of fields in an (unabridged) SCLK string
///         -  The output delimiter code
///         -  The parallel time system code
///         -  The moduli of the fields of an SCLK string
///         -  The offsets for each clock field.
///         -  The SCLK coefficients array
///         -  The partition start times
///         -  The partition end times
///
///  2)  When using SCLK kernels that map SCLK to a time system other
///      than ET (also called barycentric dynamical time---`TDB'), it
///      is necessary to have a leapseconds kernel loaded at the time
///      this routine is called. If a leapseconds kernel is required
///      for conversion between SCLK and ET but is not loaded, an error
///      is signaled by a routine in the call tree of this routine. The
///      output argument TICKS will not be modified.
///
///      The time system that an SCLK kernel maps SCLK to is indicated
///      by the variable SCLK_TIME_SYSTEM_nn in the kernel, where nn
///      is the negative of the NAIF integer code for the spacecraft.
///      The time system used in a kernel is TDB if and only if the
///      variable is assigned the value 1.
///
///
///  3)  If any of the following kernel variables have invalid values,
///      the error will be diagnosed by routines called by this
///      routine:
///
///         -  The time system code
///         -  The number of SCLK coefficients
///         -  The number of partition start times
///         -  The number of partition end times
///         -  The number of fields of a SCLK string
///         -  The number of moduli for a SCLK string
///
///      If the number of values for any item read from the kernel
///      pool exceeds the maximum allowed value, it is may not be
///      possible to diagnose the error correctly, since overwriting
///      of memory may occur. This particular type of error is not
///      diagnosed by this routine.
///
///
///  4)  The input argument CLKSTR may be invalid for a variety of
///      reasons:
///
///         -- One of the extracted clock components cannot be parsed
///            as an integer
///
///         -- CLKSTR contains too many components
///
///         -- the value  of one of the components is less than the
///            offset value
///
///      If any of these conditions is detected, the error
///      SPICE(INVALIDSCLKSTRING) is signaled. The output argument
///      TICKS will not be modified.
/// ```
///
/// # Particulars
///
/// ```text
///  This routine converts a character string representation of a
///  spacecraft clock count into the number of ticks represented
///  by the clock count. An important distinction between this type
///  of conversion and that carried out by SCENCD is that this routine
///  treats spacecraft clock times as representations of time
///  intervals, not absolute times.
///
///  This routine does not make use of any partition information.
///  See SCENCD for details on how to make use of partition numbers.
/// ```
///
/// # Examples
///
/// ```text
///  1)  Below are some examples illustrating various inputs and the
///      resulting outputs for the Galileo spacecraft.
///
///      CLKSTR                TICKS
///      ----------------      --------------------
///      '0:0:0:1'             1
///      '0:0:1'               8
///      '0:1'                 80
///      '1'                   7280
///      '1 0 0 0'             7280
///      '1,0,0,0'             7280
///      '1:90'                14480
///      '1:9'                 8000
///      '1:09'                8000
///      '0-0-10'              80   |--  Third component is supposed
///      '0-1-0'               80   |    to be a mod-10 count.
///      '0/1/0'               Error: '/' is not an accepted delimiter.
///      '1: 00 : 0 : 1'       7281
///      '1:::1'               7281
///      '1.1.1.1.1'           Error: Too many components
///      '1.1.1.1.'            Error: The last delimiter signals that
///                                   a fifth component will follow.
///
///
///      The following examples are for the Voyager 2 spacecraft. Note
///      that the last component of the Voyager clock has an offset
///      value of 1.
///
///      CLKSTR                TICKS
///      ----------------      --------------------
///      '0.0.001'             0
///      '0:0:002'             1
///      '0:01'                800
///      '1'                   48000
///      '1.0'                 48000
///      '1.0.0'               Error: The 3rd component is never 0.
///      '0.0:100'             99
///      '0-60-1'              48000
///      '1-1-1'               48800
///      '1-1-2'               48801
/// ```
///
/// # Restrictions
///
/// ```text
///  1)  An SCLK kernel appropriate to the spacecraft clock identified
///      by SC must be loaded at the time this routine is called.
///
///  2)  If the SCLK kernel used with this routine does not map SCLK
///      directly to barycentric dynamical time, a leapseconds kernel
///      must be loaded at the time this routine is called.
/// ```
///
/// # Author and Institution
///
/// ```text
///  N.J. Bachman       (JPL)
///  J. Diaz del Rio    (ODC Space)
///  J.M. Lynch         (JPL)
///  B.V. Semenov       (JPL)
///  R.E. Thurman       (JPL)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 3.0.0, 01-DEC-2021 (NJB) (JDR)
///
///         Updated to support buffering of data for multiple clocks.
///         This entry point tracks kernel pool changes but no longer
///         sets or uses watches.
///
///         Updated long error message.
///
///         Edited the header to comply with NAIF standard.
///
/// -    SPICELIB Version 2.3.0, 09-SEP-2013 (BVS)
///
///         Updated to keep track of the POOL counter and call ZZCVPOOL.
///
/// -    SPICELIB Version 2.2.0, 05-MAR-2009 (NJB)
///
///         Bug fix: this routine now keeps track of whether its
///         kernel pool look-up succeeded. If not, a kernel pool
///         lookup is attempted on the next call to this routine.
///
/// -    SPICELIB Version 2.1.0, 09-NOV-2007 (NJB)
///
///         Bug fix: changed maximum value arguments to 1 in
///         calls to SCLI01 to fetch NFIELD and DELCDE values.
///
/// -    SPICELIB Version 2.0.0, 17-APR-1992 (NJB)
///
///         Header was updated, particularly $Exceptions and $Restrictions
///         sections. Kernel pool watch is now set on required kernel
///         variables. Comment section for permuted index source lines
///         was added following the header.
///
/// -    SPICELIB Version 1.0.0, 04-SEP-1990 (NJB) (JML) (RET)
/// ```
///
/// # Revisions
///
/// ```text
/// -    SPICELIB Version 2.1.0, 09-NOV-2007 (NJB)
///
///         Bug fix: changed maximum value arguments to 1 in
///         calls to SCLI01 to fetch NFIELD and DELCDE values.
///
/// -    SPICELIB Version 2.0.0, 17-APR-1992 (NJB)
///
///         This routine now uses the new kernel pool watch capability
///         to determine when it is necessary to look up SCLK variables.
///         This method of checking for kernel pool updates replaces the
///         previously used once-per-call lookup of the SCLK_KERNEL_ID
///         kernel variable.
///
///         The header was updated to discuss the fact that a leapseconds
///         kernel will now need to be loaded in order to use SCLK kernels
///         that map between SCLK and a parallel time system other than
///         TDB. The $Exceptions and $Restrictions sections were affected.
///
///         A comment section for permuted index source lines was added
///         following the header.
/// ```
pub fn sctk01(ctx: &mut SpiceContext, sc: i32, clkstr: &str, ticks: &mut f64) -> crate::Result<()> {
    SCTK01(sc, clkstr.as_bytes(), ticks, ctx.raw_context())?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SCTK01 ( Convert type 1 SCLK string to ticks )
pub fn SCTK01(
    SC: i32,
    CLKSTR: &[u8],
    TICKS: &mut f64,
    ctx: &mut Context,
) -> f2rust_std::Result<()> {
    let save = ctx.get_vars::<SaveVars>();
    let save = &mut *save.borrow_mut();

    //
    // Standard SPICE error handling.
    //
    if RETURN(ctx) {
        return Ok(());
    }

    CHKIN(b"SCTK01", ctx)?;

    if save.PASS1 {
        //
        // Initialize local data structures. This routine is error-free.
        //
        ZZSCIN01(
            save.HDSCLK.as_slice_mut(),
            save.SCPOOL.as_slice_mut(),
            save.CLKLST.as_slice_mut(),
            &mut save.DPFREE,
            &mut save.IFREE,
            &mut save.PRVSC,
            ctx,
        )?;
        ZZCTRUIN(save.POLCTR.as_slice_mut(), ctx);

        save.PASS1 = false;
    }

    //
    // Get parameters and data for this clock from the type 1 database.
    // Update the database if necessary.
    //
    ZZSCUP01(
        SC,
        save.POLCTR.as_slice_mut(),
        save.HDSCLK.as_slice_mut(),
        save.SCPOOL.as_slice_mut(),
        save.CLKLST.as_slice_mut(),
        &mut save.DPFREE,
        save.DPBUFF.as_slice_mut(),
        &mut save.IFREE,
        save.INTBUF.as_slice_mut(),
        save.SCBASE.as_slice_mut(),
        &mut save.PRVSC,
        &mut save.NFIELD,
        &mut save.DELCDE,
        &mut save.TIMSYS,
        &mut save.NCOEFF,
        &mut save.NPART,
        &mut save.COFBAS,
        &mut save.STRBAS,
        &mut save.ENDBAS,
        &mut save.MODBAS,
        &mut save.OFFBAS,
        ctx,
    )?;

    if FAILED(ctx) {
        //
        // For safety, initialize the database on the next call to
        // any entry point of SC01. Setting PASS1 to .TRUE.
        // accomplishes this.
        //
        save.PASS1 = true;

        CHKOUT(b"SCTK01", ctx)?;
        return Ok(());
    }

    //
    // If our clock string is blank, we can stop now.
    //
    if fstr::eq(CLKSTR, b" ") {
        save.PASS1 = true;

        SETMSG(b"CLKSTR is blank.", ctx);
        SIGERR(b"SPICE(INVALIDSCLKSTRING)", ctx)?;
        CHKOUT(b"SCTK01", ctx)?;
        return Ok(());
    }

    //
    // Determine how many ticks is each field is worth.
    //
    save.CMPTKS[save.NFIELD] = 1.0;

    {
        let m1__: i32 = (save.NFIELD - 1);
        let m2__: i32 = 1;
        let m3__: i32 = -1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            save.CMPTKS[save.I] = (save.CMPTKS[(save.I + 1)]
                * MODULI((save.I + 1), save.DPBUFF.as_slice(), save.MODBAS));
            save.I += m3__;
        }
    }

    //
    // Parse the clock components from the input string. There should
    // be at most NFIELD of them, but, in order to check for too long
    // a clock string, we'll let LPARSM take up to MXNFLD components and
    // then test for an error.
    //
    // NOTE: LPARSM is error-free.
    //
    LPARSM(CLKSTR, DELIMS, MXNFLD, &mut save.N, save.CMP.as_arg_mut());

    //
    // If the string has too many fields for the specified spacecraft
    // then signal an error.
    //
    if (save.N > save.NFIELD) {
        save.PASS1 = true;

        SETMSG(b"CLKSTR has # fields, which is too many.", ctx);
        ERRINT(b"#", save.N, ctx);
        SIGERR(b"SPICE(INVALIDSCLKSTRING)", ctx)?;
        CHKOUT(b"SCTK01", ctx)?;
        return Ok(());
    }

    //
    // Convert each of the components into numbers.  Error if any
    // of the conversions screw up.  NPARSD doesn't assign a value
    // to ' ', so assign the numeric value of the blank components
    // to be equal to the offset value.
    //
    {
        let m1__: i32 = 1;
        let m2__: i32 = save.N;
        let m3__: i32 = 1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            if fstr::eq(save.CMP.get(save.I), b" ") {
                save.CMPVAL[save.I] = OFFSET(save.I, save.DPBUFF.as_slice(), save.OFFBAS);
            } else {
                NPARSD(
                    &save.CMP[save.I],
                    &mut save.CMPVAL[save.I],
                    &mut save.ERROR,
                    &mut save.PNTR,
                    ctx,
                );
            }

            if fstr::ne(&save.ERROR, b" ") {
                save.PASS1 = true;

                SETMSG(b"Could not parse SCLK component # from # as a number.", ctx);
                ERRCH(b"#", &save.CMP[save.I], ctx);
                ERRCH(b"#", CLKSTR, ctx);
                SIGERR(b"SPICE(INVALIDSCLKSTRING)", ctx)?;
                CHKOUT(b"SCTK01", ctx)?;
                return Ok(());
            }

            //
            // Subtract off the offset value so that we can do base ten
            // arithmetic.  Also, if any of the components become negative
            // as a result of the subtraction, then that component must
            // have been invalid.
            //
            save.SAVCMP = save.CMPVAL[save.I];
            save.CMPVAL[save.I] =
                (save.CMPVAL[save.I] - OFFSET(save.I, save.DPBUFF.as_slice(), save.OFFBAS));

            if (f64::round(save.CMPVAL[save.I]) < 0.0) {
                save.PASS1 = true;

                SETMSG(b"Component number # in the SCLK string, counting left to right, is invalid: component # is less than field offset #.", ctx);
                ERRINT(b"#", save.I, ctx);
                ERRDP(b"#", save.SAVCMP, ctx);
                ERRDP(
                    b"#",
                    OFFSET(save.I, save.DPBUFF.as_slice(), save.OFFBAS),
                    ctx,
                );
                SIGERR(b"SPICE(INVALIDSCLKSTRING)", ctx)?;
                CHKOUT(b"SCTK01", ctx)?;
                return Ok(());
            }

            save.I += m3__;
        }
    }

    //
    // Convert to ticks by multiplying the value of each component by
    // the number of ticks each component count represents, and then
    // add up the results.
    //
    *TICKS = 0.0;

    {
        let m1__: i32 = 1;
        let m2__: i32 = save.N;
        let m3__: i32 = 1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            *TICKS = (*TICKS + (save.CMPVAL[save.I] * save.CMPTKS[save.I]));
            save.I += m3__;
        }
    }

    //
    // Keep track of the last spacecraft clock ID encountered.
    //
    save.PRVSC = SC;

    CHKOUT(b"SCTK01", ctx)?;
    Ok(())
}

/// Convert ticks to a type 1 SCLK string.
///
/// Convert a number of ticks to an equivalent type 1 spacecraft clock
/// string.
///
/// # Required Reading
///
/// * [SCLK](crate::required_reading::sclk)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  DESCRIPTION
///  --------  ---  --------------------------------------------------
///  SC         I   NAIF spacecraft identification code.
///  TICKS      I   Number of ticks represented by a clock count.
///  CLKSTR     O   Character string representation of the clock count.
/// ```
///
/// # Detailed Input
///
/// ```text
///  SC       is a NAIF spacecraft identification code. See the
///           $Examples section below, and also the KERNEL required
///           reading file for a complete list of body ID codes.
///
///
///  TICKS    is the number of ticks to be converted to a spacecraft
///           clock string, where a tick is defined to be
///           the smallest time increment expressible by the
///           spacecraft clock.
///
///           If TICKS contains a fractional part, the string that
///           results is the same as if TICKS had been rounded to
///           the nearest whole number.
///
///           See $Examples below.
/// ```
///
/// # Detailed Output
///
/// ```text
///  CLKSTR   on output is the character string representation of
///           the spacecraft clock count. The returned string has
///           the form
///
///                            'wwwwwwww:xx:y:z',
///
///           where the number of components and the width of each
///           one are different for each spacecraft. The delimiter
///           used is determined by a kernel pool variable and is
///           one of the five specified by the parameter DELIMS.
///           See $Examples below.
///
///           If CLKSTR is not long enough to accommodate the
///           formatted tick value, the result will be truncated on
///           the right.
/// ```
///
/// # Exceptions
///
/// ```text
///  1)  This routine assumes that that an SCLK kernel appropriate to
///      the spacecraft clock identified by the input argument SC has
///      been loaded. If an SCLK kernel has not been loaded, does not
///      contain all of the required data, or contains invalid data, an
///      error is signaled by a routine in the call tree of this
///      routine. The output argument CLKSTR will not be modified.
///
///      The variables that must be set by the SCLK kernel are:
///
///         -  The number of fields in an (unabridged) SCLK string
///         -  The output delimiter code
///         -  The parallel time system code
///         -  The moduli of the fields of an SCLK string
///         -  The offsets for each clock field.
///         -  The SCLK coefficients array
///         -  The partition start times
///         -  The partition end times
///
///  2)  When using SCLK kernels that map SCLK to a time system other
///      than ET (also called barycentric dynamical time---`TDB'), it
///      is necessary to have a leapseconds kernel loaded at the time
///      this routine is called. If a leapseconds kernel is required
///      for conversion between SCLK and ET but is not loaded, an error
///      is signaled by a routine in the call tree of this routine. The
///      output argument CLKSTR will not be modified.
///
///      The time system that an SCLK kernel maps SCLK to is indicated
///      by the variable SCLK_TIME_SYSTEM_nn in the kernel, where nn
///      is the negative of the NAIF integer code for the spacecraft.
///      The time system used in a kernel is TDB if and only if the
///      variable is assigned the value 1.
///
///  3)  If any of the following kernel variables have invalid values,
///      the error will be diagnosed by routines called by this
///      routine:
///
///         -  The time system code
///         -  The number of SCLK coefficients
///         -  The number of partition start times
///         -  The number of partition end times
///         -  The number of fields of a SCLK string
///         -  The number of moduli for a SCLK string
///
///      If the number of values for any item read from the kernel
///      pool exceeds the maximum allowed value, it is may not be
///      possible to diagnose the error correctly, since overwriting
///      of memory may occur. This particular type of error is not
///      diagnosed by this routine.
///
///  4)  If the input value for TICKS is negative, the error
///      SPICE(VALUEOUTOFRANGE) is signaled. The output argument
///      CLKSTR will not be modified.
///
///  5)  If the output argument CLKSTR is too short to accommodate
///      the output string produced by this routine, the error
///      SPICE(SCLKTRUNCATED) is signaled. The output string
///      CLKSTR will not be modified.
/// ```
///
/// # Particulars
///
/// ```text
///  The routine determines the values of the components of the
///  spacecraft clock count that is equivalent to the number TICKS.
///  The information needed to perform this operation, such as the
///  number of clock components and their moduli, is provided by
///  an SCLK kernel file. Normally, your program should load this
///  file during initialization.
///
///  This routine does not make use of any partition information.
///  See SCDECD for details on how to make use of partition numbers.
/// ```
///
/// # Examples
///
/// ```text
///  Below are some examples illustrating various inputs and the
///   resulting outputs for the Galileo spacecraft.
///
///      TICKS                 CLKSTR
///      ----------------      --------------------
///      -1                    Error: Ticks must be a positive number
///      0                     '0:00:0:0'
///      1                     '0:00:0:1'
///      1.3                   '0:00:0:1'
///      1.5                   '0:00:0:2'
///      2                     '0:00:0:2'
///      7                     '0:00:0:7'
///      8                     '0:00:1:0'
///      80                    '0:01:0:0'
///      88                    '0:01:1:0'
///      7279                  '0:90:9:7'
///      7280                  '1:00:0:0'
///      1234567890            '169583:45:6:2'
///
///
///  The following examples are for the Voyager 2 spacecraft.
///  Note that the third component of the Voyager clock has an
///  offset value of one.
///
///      TICKS                 CLKSTR
///      ----------------      --------------------
///      -1                    Error: Ticks must be a positive number
///      0                     '00000 00 001'
///      1                     '00000 00 002'
///      1.3                   '00000:00:002'
///      1.5                   '00000.00.003'
///      2                     '00000-00-003'
///      799                   '00000,00,800'
///      800                   '00000 01 001'
///      47999                 '00000 59 800'
///      48000                 '00001 00 001'
///      3145727999            '65535 59 800'
/// ```
///
/// # Restrictions
///
/// ```text
///  1)  An SCLK kernel appropriate to the spacecraft clock identified
///      by SC must be loaded at the time this routine is called.
///
///  2)  If the SCLK kernel used with this routine does not map SCLK
///      directly to barycentric dynamical time, a leapseconds kernel
///      must be loaded at the time this routine is called.
/// ```
///
/// # Author and Institution
///
/// ```text
///  N.J. Bachman       (JPL)
///  J. Diaz del Rio    (ODC Space)
///  J.M. Lynch         (JPL)
///  B.V. Semenov       (JPL)
///  R.E. Thurman       (JPL)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 3.0.0, 01-DEC-2021 (NJB) (JDR)
///
///         Updated to support buffering of data for multiple clocks.
///         This entry point tracks kernel pool changes but no longer
///         sets or uses watches.
///
///         Edited the header to comply with NAIF standard.
///
/// -    SPICELIB Version 2.3.0, 09-SEP-2013 (BVS)
///
///         Updated to keep track of the POOL counter and call ZZCVPOOL.
///
/// -    SPICELIB Version 2.2.0, 05-MAR-2009 (NJB)
///
///         Bug fix: this routine now keeps track of whether its
///         kernel pool look-up succeeded. If not, a kernel pool
///         lookup is attempted on the next call to this routine.
///
/// -    SPICELIB Version 2.1.0, 17-FEB-2008 (NJB)
///
///         Bug fix: changed maximum value arguments to 1 in
///         calls to SCLI01 to fetch NFIELD and DELCDE values.
///
///         Bug fix: spaces between fields are now inserted
///         correctly when the output field delimiter is blank.
///
/// -    SPICELIB Version 2.0.1, 18-JUL-1996 (NJB)
///
///         Misspelling in header fixed.
///
/// -    SPICELIB Version 2.0.0, 17-APR-1992 (NJB)
///
///         Error is now signaled if truncation of output string occurs.
///         Header was updated, particularly $Exceptions and $Restrictions
///         sections. Kernel pool watch is now set on required kernel
///         variables. Comment section for permuted index source lines
///         was added following the header.
///
/// -    SPICELIB Version 1.0.0, 06-SEP-1990 (NJB) (JML) (RET)
/// ```
///
/// # Revisions
///
/// ```text
/// -    SPICELIB Version 2.1.0, 17-FEB-2008 (NJB)
///
///         Bug fix: changed maximum value arguments to 1 in
///         calls to SCLI01 to fetch NFIELD and DELCDE values.
///
///         Bug fix: spaces between fields are now inserted
///         correctly when the output field delimiter is blank.
///
/// -    SPICELIB Version 2.0.0, 17-APR-1992 (NJB) (WLT)
///
///         An error is now signaled if truncation of output string
///         occurs.
///
///         The header was updated to discuss exception handling when
///         the output string is truncated. The header was also expanded
///         to discuss the fact that a leapseconds kernel will now need to
///         be loaded in order to use SCLK kernels that map between SCLK
///         and a parallel time system other than TDB. The $Exceptions
///         and $Restrictions sections were affected.
///
///         This routine now uses the new kernel pool watch capability
///         to determine when it is necessary to look up SCLK variables.
///         This method of checking for kernel pool updates replaces the
///         previously used once-per-call lookup of the SCLK_KERNEL_ID
///         kernel variable.
///
///         A comment section for permuted index source lines was added
///         following the header.
/// ```
pub fn scfm01(ctx: &mut SpiceContext, sc: i32, ticks: f64, clkstr: &mut str) -> crate::Result<()> {
    SCFM01(
        sc,
        ticks,
        fstr::StrBytes::new(clkstr).as_mut(),
        ctx.raw_context(),
    )?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SCFM01 ( Convert ticks to a type 1 SCLK string. )
pub fn SCFM01(SC: i32, TICKS: f64, CLKSTR: &mut [u8], ctx: &mut Context) -> f2rust_std::Result<()> {
    let save = ctx.get_vars::<SaveVars>();
    let save = &mut *save.borrow_mut();

    //
    // Standard SPICE error handling.
    //
    if RETURN(ctx) {
        return Ok(());
    }

    CHKIN(b"SCFM01", ctx)?;

    //
    // On the first pass through the subroutine, or if the spacecraft
    // clock ID changes, we will set watches on the SCLK kernel
    // variables for the current clock.
    //
    if save.PASS1 {
        //
        // Initialize local data structures. This routine is error-free.
        //
        ZZSCIN01(
            save.HDSCLK.as_slice_mut(),
            save.SCPOOL.as_slice_mut(),
            save.CLKLST.as_slice_mut(),
            &mut save.DPFREE,
            &mut save.IFREE,
            &mut save.PRVSC,
            ctx,
        )?;
        ZZCTRUIN(save.POLCTR.as_slice_mut(), ctx);

        save.PASS1 = false;
    }

    //
    // Get parameters and data for this clock from the type 1 database.
    // Update the database if necessary.
    //
    ZZSCUP01(
        SC,
        save.POLCTR.as_slice_mut(),
        save.HDSCLK.as_slice_mut(),
        save.SCPOOL.as_slice_mut(),
        save.CLKLST.as_slice_mut(),
        &mut save.DPFREE,
        save.DPBUFF.as_slice_mut(),
        &mut save.IFREE,
        save.INTBUF.as_slice_mut(),
        save.SCBASE.as_slice_mut(),
        &mut save.PRVSC,
        &mut save.NFIELD,
        &mut save.DELCDE,
        &mut save.TIMSYS,
        &mut save.NCOEFF,
        &mut save.NPART,
        &mut save.COFBAS,
        &mut save.STRBAS,
        &mut save.ENDBAS,
        &mut save.MODBAS,
        &mut save.OFFBAS,
        ctx,
    )?;

    if FAILED(ctx) {
        //
        // For safety, initialize the database on the next call to
        // any entry point of SC01. Setting PASS1 to .TRUE.
        // accomplishes this.
        //
        save.PASS1 = true;

        CHKOUT(b"SCFM01", ctx)?;
        return Ok(());
    }
    //
    // Determine how many ticks each field is worth.
    //
    save.CMPTKS[save.NFIELD] = 1.0;

    {
        let m1__: i32 = (save.NFIELD - 1);
        let m2__: i32 = 1;
        let m3__: i32 = -1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            save.CMPTKS[save.I] = (save.CMPTKS[(save.I + 1)]
                * MODULI((save.I + 1), save.DPBUFF.as_slice(), save.MODBAS));
            save.I += m3__;
        }
    }

    //
    // Determine the width of each field.
    //
    {
        let m1__: i32 = 1;
        let m2__: i32 = save.NFIELD;
        let m3__: i32 = 1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            save.MAXWID = ((MODULI(save.I, save.DPBUFF.as_slice(), save.MODBAS)
                + OFFSET(save.I, save.DPBUFF.as_slice(), save.OFFBAS))
                - 1.0);

            save.CMPWID[save.I] = (1 + (f64::log10((save.MAXWID + 0.5)) as i32));

            save.I += m3__;
        }
    }

    //
    // Check whether the output string is long enough to contain the
    // string we're about to assemble.  We need room for (NFIELD - 1)
    // delimiters as well as for the numeric fields.
    //
    save.NEEDED = ((save.NFIELD - 1) + SUMAI(save.CMPWID.as_slice(), save.NFIELD));

    if (intrinsics::LEN(CLKSTR) < save.NEEDED) {
        save.PASS1 = true;

        SETMSG(
            b"Output argument has declared length #; required length is #. Input tick value was #.",
            ctx,
        );
        ERRINT(b"#", intrinsics::LEN(CLKSTR), ctx);
        ERRINT(b"#", save.NEEDED, ctx);
        ERRDP(b"#", TICKS, ctx);
        SIGERR(b"SPICE(SCLKTRUNCATED)", ctx)?;
        CHKOUT(b"SCFM01", ctx)?;
        return Ok(());
    }

    //
    // Need to check that TICKS is a positive number.
    //
    if (f64::round(TICKS) < 0 as f64) {
        save.PASS1 = true;

        SETMSG(b"Negative value for SCLK ticks: #", ctx);
        ERRDP(b"#", TICKS, ctx);
        SIGERR(b"SPICE(VALUEOUTOFRANGE)", ctx)?;
        CHKOUT(b"SCFM01", ctx)?;
        return Ok(());
    }

    //
    // Determine the value of each of the components. This is done by
    // successively dividing by the number of ticks each component value
    // is worth.
    //
    save.REM = f64::round(TICKS);

    {
        let m1__: i32 = 1;
        let m2__: i32 = (save.NFIELD - 1);
        let m3__: i32 = 1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            save.CMPVAL[save.I] = (f64::trunc((save.REM / save.CMPTKS[save.I]))
                + OFFSET(save.I, save.DPBUFF.as_slice(), save.OFFBAS));
            save.REM = intrinsics::DMOD(save.REM, save.CMPTKS[save.I]);

            save.I += m3__;
        }
    }

    save.CMPVAL[save.NFIELD] =
        (save.REM + OFFSET(save.NFIELD, save.DPBUFF.as_slice(), save.OFFBAS));

    //
    // Convert the values of each component from double precision
    // numbers to character strings.
    //
    {
        let m1__: i32 = 1;
        let m2__: i32 = save.NFIELD;
        let m3__: i32 = 1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            //
            // NOTE: DPSTRF is error-free.
            //
            DPSTRF(save.CMPVAL[save.I], DPLEN, b"F", &mut save.DPCHAR, ctx);

            save.END = (intrinsics::INDEX(&save.DPCHAR, b".") - 1);
            save.LENGTH[save.I] = (save.END - 1);
            fstr::assign(
                save.CMP.get_mut(save.I),
                fstr::substr(&save.DPCHAR, 2..=save.END),
            );

            save.I += m3__;
        }
    }

    //
    // Pad on the left with zeros if necessary.
    //
    {
        let m1__: i32 = 1;
        let m2__: i32 = save.NFIELD;
        let m3__: i32 = 1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            save.PAD = (save.CMPWID[save.I] - save.LENGTH[save.I]);

            if (save.PAD > 0) {
                {
                    let m1__: i32 = 1;
                    let m2__: i32 = save.PAD;
                    let m3__: i32 = 1;
                    save.J = m1__;
                    for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
                        PREFIX(b"0", 0, &mut save.CMP[save.I]);
                        save.J += m3__;
                    }
                }
            }

            save.I += m3__;
        }
    }

    //
    // Construct the clock string with a delimiter separating
    // each field.
    //
    fstr::assign(CLKSTR, save.CMP.get(1));

    {
        let m1__: i32 = 2;
        let m2__: i32 = save.NFIELD;
        let m3__: i32 = 1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            if fstr::ne(save.DEL.get(save.DELCDE), b" ") {
                PREFIX(&save.DEL[save.DELCDE], 0, &mut save.CMP[save.I]);
                SUFFIX(&save.CMP[save.I], 0, CLKSTR);
            } else {
                SUFFIX(&save.CMP[save.I], 1, CLKSTR);
            }

            save.I += m3__;
        }
    }

    //
    // Keep track of the last spacecraft clock ID encountered.
    //
    save.PRVSC = SC;

    CHKOUT(b"SCFM01", ctx)?;
    Ok(())
}

/// Ticks to ET, type 01
///
/// Convert encoded type 1 spacecraft clock (`ticks') to ephemeris
/// seconds past J2000 (ET).
///
/// # Required Reading
///
/// * [SCLK](crate::required_reading::sclk)
/// * [TIME](crate::required_reading::time)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  DESCRIPTION
///  --------  ---  --------------------------------------------------
///  SC         I   NAIF spacecraft ID code.
///  SCLKDP     I   Type 1 SCLK, encoded as ticks since clock start.
///  ET         I   Ephemeris time, seconds past J2000.
/// ```
///
/// # Detailed Input
///
/// ```text
///  SC       is a NAIF ID code for a spacecraft, one of whose
///           clock values is represented by SCLKDP.
///
///  SCLKDP   is an encoded type 1 spacecraft clock value
///           produced by the routine SCENCD. SCLKDP is a
///           count of ticks since spacecraft clock start:
///           partition information IS included in the encoded
///           value.
/// ```
///
/// # Detailed Output
///
/// ```text
///  ET       is the ephemeris time, seconds past J2000, that
///           corresponds to SCLKDP.
/// ```
///
/// # Exceptions
///
/// ```text
///  1)  This routine assumes that that an SCLK kernel appropriate to
///      the spacecraft clock identified by the input argument SC has
///      been loaded. If an SCLK kernel has not been loaded, does not
///      contain all of the required data, or contains invalid data, an
///      error is signaled by a routine in the call tree of this
///      routine. The output argument ET will not be modified.
///
///      The variables that must be set by the SCLK kernel are:
///
///         -  The number of fields in an (unabridged) SCLK string
///         -  The output delimiter code
///         -  The parallel time system code
///         -  The moduli of the fields of an SCLK string
///         -  The offsets for each clock field.
///         -  The SCLK coefficients array
///         -  The partition start times
///         -  The partition end times
///
///  2)  When using SCLK kernels that map SCLK to a time system other
///      than ET (also called barycentric dynamical time---`TDB'), it
///      is necessary to have a leapseconds kernel loaded at the time
///      this routine is called. If a leapseconds kernel is required
///      for conversion between SCLK and ET but is not loaded, an error
///      is signaled by a routine in the call tree of this routine. The
///      output argument ET will not be modified.
///
///      The time system that an SCLK kernel maps SCLK to is indicated
///      by the variable SCLK_TIME_SYSTEM_nn in the kernel, where nn
///      is the negative of the NAIF integer code for the spacecraft.
///      The time system used in a kernel is TDB if and only if the
///      variable is assigned the value 1.
///
///
///  3)  If any of the following kernel variables have invalid values,
///      the error will be diagnosed by routines called by this
///      routine:
///
///         -  The number of SCLK coefficients
///         -  The number of partition start times
///         -  The number of partition end times
///         -  The number of fields of a SCLK string
///         -  The number of moduli for a SCLK string
///
///      If the number of values for any item read from the kernel
///      pool exceeds the maximum allowed value, it is may not be
///      possible to diagnose the error correctly, since overwriting
///      of memory may occur. This particular type of error is not
///      diagnosed by this routine.
///
///  4)  If the time system code is not recognized, the error
///      SPICE(VALUEOUTOFRANGE) is signaled.
///
///  5)  If the input SCLK value SCLKDP is out of range, the error
///      SPICE(VALUEOUTOFRANGE) is signaled. The output argument ET
///      will not be modified.
///
///  6)  If the SCLK rate used to interpolate SCLK values is
///      nonpositive, the error SPICE(VALUEOUTOFRANGE) is signaled.
///      The output argument SCLKDP will not be modified.
///
///  7)  If the partition times or SCLK coefficients themselves
///      are invalid, this routine will almost certainly give
///      incorrect results. This routine cannot diagnose errors
///      in the partition times or SCLK coefficients, except possibly
///      by crashing.
/// ```
///
/// # Particulars
///
/// ```text
///  SCTE01 is not usually called by routines external to SPICELIB.
///  The conversion routine SCT2E converts any type of encoded
///  spacecraft clock value produced by SCENCD to ephemeris seconds
///  past J2000.  SCT2E is the preferred user interface routine
///  because its interface specification does not refer to spacecraft
///  clock types. However, direct use of SCTE01 by user routines is
///  not prohibited.
/// ```
///
/// # Examples
///
/// ```text
///  1)  Convert an encoded type 1 SCLK value to ET:
///
///      During program initialization, load the leapseconds and SCLK
///      kernels. We will assume that these files are named
///      "LEAPSECONDS.KER" and "SCLK.KER".  You must substitute the
///      actual names of these files in your code.
///
///         CALL CLPOOL
///         CALL FURNSH ( 'LEAPSECONDS.KER' )
///         CALL FURNSH ( 'SCLK.KER'        )
///
///      If SCLKDP is an encoded spacecraft clock value, if SC
///      is the NAIF integer code for the spacecraft whose
///      SCLK <--> ET mapping is defined by the data in SCLK.KER,
///      then the call
///
///         CALL SCTE01 ( SC, SCLKDP, ET )
///
///      will return the ET value corresponding to SCLKDP.
///
///      For example, if SC is -77, indicating the Galileo spacecraft,
///      and if a Galileo SCLK kernel is loaded, then if SCLKDP
///      is set to
///
///         7.2800000000000E+05
///
///      the call
///
///         CALL SCTE01 ( SC, SCLKDP, ET )
///
///      returns ET as
///
///         -3.2286984854565E+08
///
///      on a VAX 11/780 running VMS 5.3, Fortran 5.5.
/// ```
///
/// # Restrictions
///
/// ```text
///  1)  An SCLK kernel appropriate to the spacecraft clock identified
///      by SC must be loaded at the time this routine is called.
///
///  2)  If the SCLK kernel used with this routine does not map SCLK
///      directly to barycentric dynamical time, a leapseconds kernel
///      must be loaded at the time this routine is called.
/// ```
///
/// # Author and Institution
///
/// ```text
///  N.J. Bachman       (JPL)
///  J. Diaz del Rio    (ODC Space)
///  B.V. Semenov       (JPL)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 4.0.0, 01-DEC-2021 (NJB) (JDR)
///
///         Updated to support buffering of data for multiple clocks.
///         This entry point tracks kernel pool changes but no longer
///         sets or uses watches.
///
///         A check for invalid time system code was added.
///
///         A check for nonpositive clock rate was added.
///
///         Edited the header to comply with NAIF standard.
///
/// -    SPICELIB Version 3.3.0, 09-SEP-2013 (BVS)
///
///         Updated to keep track of the POOL counter and call ZZCVPOOL.
///
/// -    SPICELIB Version 3.2.0, 05-MAR-2009 (NJB)
///
///         Bug fix: this routine now keeps track of whether its
///         kernel pool look-up succeeded. If not, a kernel pool
///         lookup is attempted on the next call to this routine.
///
/// -    SPICELIB Version 3.1.0, 09-NOV-2007 (NJB)
///
///         Bug fix: changed maximum value arguments to 1 in
///         calls to SCLI01 to fetch NFIELD and DELCDE values.
///
/// -    SPICELIB Version 3.0.0, 06-JAN-1998 (NJB)
///
///         Removed local variable RNDCLK; this entry point no longer
///         creates a rounded version of its input argument. Use of
///         ANINT to round coefficients has been discontinued.
///
/// -    SPICELIB Version 2.0.0, 17-APR-1992 (NJB)
///
///         This routine was updated to handle SCLK kernels that use
///         TDT as their `parallel' time system. Header was updated,
///         particularly $Exceptions and $Restrictions. Watch is now
///         set on required kernel variables. Comment section for
///         permuted index source lines was added following the header.
///
/// -    SPICELIB Version 1.0.0, 21-AUG-1990 (NJB)
/// ```
///
/// # Revisions
///
/// ```text
/// -    SPICELIB Version 3.1.0, 09-NOV-2007 (NJB)
///
///         Bug fix: changed maximum value arguments to 1 in
///         calls to SCLI01 to fetch NFIELD and DELCDE values.
///
/// -    SPICELIB Version 3.0.0, 06-JAN-1998 (NJB)
///
///         Removed local variable RNDCLK; this entry point no longer
///         creates a rounded version of its input argument. Use of
///         ANINT to round coefficients has been discontinued.
///
/// -    SPICELIB Version 2.0.0, 17-APR-1992 (NJB) (WLT)
///
///         This routine was updated to handle a time system specification
///         for the `parallel' time system used in the SCLK kernel.
///
///         Specific changes include:
///
///            -- The time system code is looked up along with the
///               other SCLK specification parameters.
///
///            -- The time value arrived at by interpolation of the
///               SCLK-to-parallel time mapping is converted to TDB
///               if the parallel time system is TDT.
///
///         The header was expanded to discuss the fact that a leapseconds
///         kernel will now need to be loaded in order to use SCLK kernels
///         that map between SCLK and a parallel time system other than
///         TDB. The $Exceptions and $Restrictions sections were affected.
///
///         This routine now uses the new kernel pool watch capability
///         to determine when it is necessary to look up SCLK variables.
///         This method of checking for kernel pool updates replaces the
///         previously used once-per-call lookup of the SCLK_KERNEL_ID
///         kernel variable.
///
///         A comment section for permuted index source lines was added
///         following the header.
/// ```
pub fn scte01(ctx: &mut SpiceContext, sc: i32, sclkdp: f64, et: &mut f64) -> crate::Result<()> {
    SCTE01(sc, sclkdp, et, ctx.raw_context())?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SCTE01 ( Ticks to ET, type 01 )
pub fn SCTE01(SC: i32, SCLKDP: f64, ET: &mut f64, ctx: &mut Context) -> f2rust_std::Result<()> {
    let save = ctx.get_vars::<SaveVars>();
    let save = &mut *save.borrow_mut();

    //
    // Standard SPICE error handling.
    //
    if RETURN(ctx) {
        return Ok(());
    }

    CHKIN(b"SCTE01", ctx)?;

    if save.PASS1 {
        //
        // Initialize local data structures. This routine is error-free.
        //
        ZZSCIN01(
            save.HDSCLK.as_slice_mut(),
            save.SCPOOL.as_slice_mut(),
            save.CLKLST.as_slice_mut(),
            &mut save.DPFREE,
            &mut save.IFREE,
            &mut save.PRVSC,
            ctx,
        )?;
        ZZCTRUIN(save.POLCTR.as_slice_mut(), ctx);

        save.PASS1 = false;
    }

    //
    // Get parameters and data for this clock from the type 1 database.
    // Update the database if necessary.
    //
    ZZSCUP01(
        SC,
        save.POLCTR.as_slice_mut(),
        save.HDSCLK.as_slice_mut(),
        save.SCPOOL.as_slice_mut(),
        save.CLKLST.as_slice_mut(),
        &mut save.DPFREE,
        save.DPBUFF.as_slice_mut(),
        &mut save.IFREE,
        save.INTBUF.as_slice_mut(),
        save.SCBASE.as_slice_mut(),
        &mut save.PRVSC,
        &mut save.NFIELD,
        &mut save.DELCDE,
        &mut save.TIMSYS,
        &mut save.NCOEFF,
        &mut save.NPART,
        &mut save.COFBAS,
        &mut save.STRBAS,
        &mut save.ENDBAS,
        &mut save.MODBAS,
        &mut save.OFFBAS,
        ctx,
    )?;

    if FAILED(ctx) {
        save.PASS1 = true;

        CHKOUT(b"SCTE01", ctx)?;
        return Ok(());
    }

    //
    // To check whether SCLKDP is in range, we must find the end time
    // of the last partition, in total ticks since spacecraft clock
    // start.
    //
    save.MXTICK = 0.0;

    {
        let m1__: i32 = 1;
        let m2__: i32 = save.NPART;
        let m3__: i32 = 1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            save.MXTICK = f64::round(
                ((PREND(save.I, save.DPBUFF.as_slice(), save.ENDBAS)
                    - PRSTRT(save.I, save.DPBUFF.as_slice(), save.STRBAS))
                    + save.MXTICK),
            );
            save.I += m3__;
        }
    }

    //
    // We now check that SCLKDP is in range.  COEFFS(1,1) and
    // MXTICK are, respectively, the first and last absolute
    // tick values of the clock.
    //
    if ((SCLKDP < COEFFS(1, 1, save.DPBUFF.as_slice(), save.COFBAS)) || (SCLKDP > save.MXTICK)) {
        save.PASS1 = true;

        SETMSG(&save.BVLMSG, ctx);
        ERRCH(b"#", b"SCLKDP", ctx);
        ERRDP(b"#", SCLKDP, ctx);
        SIGERR(b"SPICE(VALUEOUTOFRANGE)", ctx)?;
        CHKOUT(b"SCTE01", ctx)?;
        return Ok(());
    }

    //
    // Ok, if we made it this far, we can actually interpret the tick
    // value.  But by this time, we're not in very good mood.
    //

    //
    // Find the tick value in COEFFS closest to the rounded input tick
    // value.  The tick values in COEFFS are monotone increasing, so we
    // can do a binary search to find index of the greatest tick value
    // in the coefficient array that is less than or equal to SCLKDP.
    //
    // There are two cases:
    //
    //    1) SCLKDP is bounded by the least and greatest SCLK
    //       coefficients in the array.  In this case, we must search
    //       the array for a consecutive pair of records whose SCLK
    //       values bound SCLKDP.
    //
    //    2) SCLKDP is greater than or equal to all of the SCLK
    //       coefficients.  In that case, we don't need to search:  the
    //       last SCLK value in the array is the one we want.
    //

    if (SCLKDP < COEFFS(1, (save.NCOEFF / 3), save.DPBUFF.as_slice(), save.COFBAS)) {
        save.LOWER = 1;
        save.UPPER = (save.NCOEFF / 3);

        //
        // In the following loop, we maintain an invariant:
        //
        //    COEFFS( 1, LOWER )  <  SCLKDP  <  COEFFS( 1, UPPER )
        //                        -
        //
        // At each step, we decrease the distance between LOWER and
        // UPPER, while keeping the above statement true.  The loop
        // terminates when LOWER = UPPER - 1.
        //
        // Note that we start out with if LOWER < UPPER, since we've
        // already made sure that the invariant expression above is true.
        //
        while (save.LOWER < (save.UPPER - 1)) {
            save.MIDDLE = ((save.LOWER + save.UPPER) / 2);

            if (SCLKDP < COEFFS(1, save.MIDDLE, save.DPBUFF.as_slice(), save.COFBAS)) {
                save.UPPER = save.MIDDLE;
            } else {
                save.LOWER = save.MIDDLE;
            }
        }

    //
    // We've got SCLKDP trapped between two tick values that are
    // `adjacent' in the list:
    //
    //    COEFFS ( 1, LOWER )  and
    //    COEFFS ( 1, UPPER )
    //
    // since the second value must be greater than the first.  So
    //
    //    COEFFS( 1, LOWER )
    //
    // is the last tick value in the coefficients array less than or
    // equal to SCLKDP.
    //
    } else {
        //
        // SCLKDP is greater than or equal to all of the SCLK
        // coefficients in the coefficients array.
        //
        save.LOWER = (save.NCOEFF / 3);
    }

    //
    // Now we evaluate a linear polynomial to find the time value that
    // corresponds to SCLKDP.  The coefficients of the polynomial are
    // the time and rate (in units of seconds per tick) that correspond
    // to the tick value
    //
    //    COEFFS( 1, LOWER )
    //
    // We call these coefficients CONST and RATE.  The rates in the
    // coefficients array are in units of seconds per most significant
    // SCLK count, so we use the conversion factor TIKMSC to change the
    // rate to seconds per tick.
    //
    save.TIKMSC = 1.0;

    {
        let m1__: i32 = save.NFIELD;
        let m2__: i32 = 2;
        let m3__: i32 = -1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            save.TIKMSC = (save.TIKMSC * MODULI(save.I, save.DPBUFF.as_slice(), save.MODBAS));
            save.I += m3__;
        }
    }

    if (COEFFS(3, save.LOWER, save.DPBUFF.as_slice(), save.COFBAS) <= 0.0) {
        save.PASS1 = true;

        SETMSG(b"Invalid SCLK rate.", ctx);
        SIGERR(b"SPICE(VALUEOUTOFRANGE)", ctx)?;
        CHKOUT(b"SCTE01", ctx)?;
        return Ok(());
    }

    save.TIKDIF = (SCLKDP - COEFFS(1, save.LOWER, save.DPBUFF.as_slice(), save.COFBAS));
    save.CONST = COEFFS(2, save.LOWER, save.DPBUFF.as_slice(), save.COFBAS);
    save.RATE = (COEFFS(3, save.LOWER, save.DPBUFF.as_slice(), save.COFBAS) / save.TIKMSC);

    save.PARTIM = (save.CONST + (save.RATE * save.TIKDIF));

    //
    // Convert the parallel time to TDB, if the system is not TDB.
    // We don't need to check the validity of TIMSYS, because SCLI01
    // already made this check.
    //
    if (save.TIMSYS == TDB) {
        *ET = save.PARTIM;
    } else if (save.TIMSYS == TDT) {
        *ET = UNITIM(save.PARTIM, b"TDT", b"TDB", ctx)?;

        if FAILED(ctx) {
            CHKOUT(b"SCTE01", ctx)?;
            return Ok(());
        }
    } else {
        //
        // This code should be unreachable. It's present for safety.
        //
        save.PASS1 = true;

        SETMSG(b"Invalid time system code # was found for SCLK #.", ctx);
        ERRINT(b"#", save.TIMSYS, ctx);
        ERRINT(b"#", SC, ctx);
        SIGERR(b"SPICE(VALUEOUTOFRANGE)", ctx)?;
        CHKOUT(b"SCTE01", ctx)?;
        return Ok(());
    }

    //
    // Keep track of the last spacecraft clock ID encountered.
    //
    save.PRVSC = SC;

    CHKOUT(b"SCTE01", ctx)?;
    Ok(())
}

/// ET to discrete ticks, type 1
///
/// Convert ephemeris seconds past J2000 (ET) to discrete encoded
/// type 1 spacecraft clock (`ticks').
///
/// # Required Reading
///
/// * [SCLK](crate::required_reading::sclk)
/// * [TIME](crate::required_reading::time)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  DESCRIPTION
///  --------  ---  --------------------------------------------------
///  SC         I   NAIF spacecraft ID code.
///  ET         I   Ephemeris time, seconds past J2000.
///  SCLKDP     O   Type 1 SCLK, encoded as ticks since clock start.
/// ```
///
/// # Detailed Input
///
/// ```text
///  SC       is a NAIF ID code for a spacecraft, one of whose
///           clock values is represented by SCLKDP.
///
///  ET       is an ephemeris time, specified in seconds past
///           J2000, whose equivalent encoded SCLK value is
///           desired.
/// ```
///
/// # Detailed Output
///
/// ```text
///  SCLKDP   is the encoded type 1 spacecraft clock value
///           that corresponds to ET. The value is obtained
///           by mapping ET, using the piecewise linear mapping
///           defined by the SCLK kernel, to a value that may
///           have a non-zero fractional part, and then
///           rounding this value to the nearest double precision
///           whole number.
///
///           SCLKDP represents total time since spacecraft
///           clock start and hence does reflect partition
///           information.
/// ```
///
/// # Exceptions
///
/// ```text
///  1)  This routine assumes that that an SCLK kernel appropriate to
///      the spacecraft clock identified by the input argument SC has
///      been loaded. If an SCLK kernel has not been loaded, does not
///      contain all of the required data, or contains invalid data, an
///      error is signaled by a routine in the call tree of this
///      routine. The output argument SCLKDP will not be modified.
///
///      The variables that must be set by the SCLK kernel are:
///
///         -  The number of fields in an (unabridged) SCLK string
///         -  The output delimiter code
///         -  The parallel time system code
///         -  The moduli of the fields of an SCLK string
///         -  The offsets for each clock field.
///         -  The SCLK coefficients array
///         -  The partition start times
///         -  The partition end times
///
///  2)  When using SCLK kernels that map SCLK to a time system other
///      than ET (also called barycentric dynamical time---`TDB'), it
///      is necessary to have a leapseconds kernel loaded at the time
///      this routine is called. If a leapseconds kernel is required
///      for conversion between SCLK and ET but is not loaded, an error
///      is signaled by a routine in the call tree of this routine. The
///      output argument SCLKDP will not be modified.
///
///      The time system that an SCLK kernel maps SCLK to is indicated
///      by the variable SCLK_TIME_SYSTEM_nn in the kernel, where nn
///      is the negative of the NAIF integer code for the spacecraft.
///      The time system used in a kernel is TDB if and only if the
///      variable is assigned the value 1.
///
///  3)  If any of the following kernel variables have invalid values,
///      the error will be diagnosed by routines called by this
///      routine:
///
///         -  The number of SCLK coefficients
///         -  The number of partition start times
///         -  The number of partition end times
///         -  The number of fields of a SCLK string
///         -  The number of moduli for a SCLK string
///
///      If the number of values for any item read from the kernel
///      pool exceeds the maximum allowed value, it is may not be
///      possible to diagnose the error correctly, since overwriting
///      of memory may occur. This particular type of error is not
///      diagnosed by this routine.
///
///  4)  If the time system code is not recognized, the error
///      SPICE(VALUEOUTOFRANGE) is signaled.
///
///  5)  If the input ephemeris time value ET is out of range, the
///      error SPICE(VALUEOUTOFRANGE) is signaled. The output argument
///      SCLKDP will not be modified.
///
///  6)  If the SCLK rate used to interpolate SCLK values is
///      nonpositive, the error SPICE(VALUEOUTOFRANGE) is signaled.
///      The output argument SCLKDP will not be modified.
///
///  7)  If the partition times or SCLK coefficients themselves
///      are invalid, this routine will almost certainly give
///      incorrect results. This routine cannot diagnose errors
///      in the partition times or SCLK coefficients, except possibly
///      by crashing.
/// ```
///
/// # Particulars
///
/// ```text
///  Normally, the newer entry point SCEC01 (ET to continuous ticks,
///  type 1) should be used in place of this routine.
///
///  SCET01 is not usually called by routines external to SPICELIB.
///  The conversion routine SCE2T converts ephemeris seconds past J2000
///  to any type of discrete, encoded type 1 spacecraft clock value.
///  For conversion to continuous, encoded SCLK, SCE2C is the preferred
///  user interface routine because its interface specification does
///  not refer to spacecraft clock types. For conversion to discrete,
///  encoded SCLK, SCE2T is the preferred interface routine.
///
///  However, direct use of SCET01 by user routines is not prohibited.
/// ```
///
/// # Examples
///
/// ```text
///  1)  Converting ET to encoded type 1 SCLK:
///
///      During program initialization, load the leapseconds and SCLK
///      kernels. We will assume that these files are named
///      "LEAPSECONDS.KER" and "SCLK.KER".  You must substitute the
///      actual names of these files in your code.
///
///         CALL CLPOOL
///         CALL FURNSH ( 'LEAPSECONDS.KER' )
///         CALL FURNSH ( 'SCLK.KER'        )
///
///      If SC is -77, indicating the Galileo spacecraft, and
///      ET is set to
///
///         -3.2286984854565E+08
///
///      then the call
///
///         CALL SCET01 ( SC, ET, SCLKDP )
///
///      returns SCLKDP as
///
///         7.2800000000000E+05
///
///      on a VAX 11/780 running VMS 5.3, Fortran 5.5. Note that
///      the result should be the same (except for the output format)
///      on most computers, since the result is a double precision
///      whole number.
/// ```
///
/// # Restrictions
///
/// ```text
///  1)  An SCLK kernel appropriate to the spacecraft clock identified
///      by SC must be loaded at the time this routine is called.
///
///  2)  If the SCLK kernel used with this routine does not map SCLK
///      directly to barycentric dynamical time, a leapseconds kernel
///      must be loaded at the time this routine is called.
/// ```
///
/// # Author and Institution
///
/// ```text
///  N.J. Bachman       (JPL)
///  J. Diaz del Rio    (ODC Space)
///  B.V. Semenov       (JPL)
///  E.D. Wright        (JPL)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 3.0.0, 01-DEC-2021 (NJB) (JDR)
///
///         Updated to support buffering of data for multiple clocks.
///         This entry point tracks kernel pool changes but no longer
///         sets or uses watches.
///
///         A check for invalid time system code was added.
///
///         Edited the header to comply with NAIF standard.
///
///         Corrected description of invalid clock rate exception.
///
/// -    SPICELIB Version 2.3.0, 09-SEP-2013 (BVS)
///
///         Updated to keep track of the POOL counter and call ZZCVPOOL.
///
/// -    SPICELIB Version 2.2.0, 05-MAR-2009 (NJB)
///
///         Bug fix: this routine now keeps track of whether its
///         kernel pool look-up succeeded. If not, a kernel pool
///         lookup is attempted on the next call to this routine.
///
/// -    SPICELIB Version 2.1.0, 09-NOV-2007 (NJB)
///
///         Bug fix: changed maximum value arguments to 1 in
///         calls to SCLI01 to fetch NFIELD and DELCDE values.
///
/// -    SPICELIB Version 2.0.3, 22-AUG-2006 (EDW)
///
///         Replaced references to LDPOOL with references
///         to FURNSH.
///
/// -    SPICELIB Version 2.0.2, 09-MAR-1999 (NJB)
///
///         Comments were updated; references to SCE2C and SCEC01 were
///         added.
///
/// -    SPICELIB Version 2.0.1, 18-JUL-1996 (NJB)
///
///         Typo in comment fixed.
///
/// -    SPICELIB Version 2.0.0, 17-APR-1992 (NJB)
///
///         This routine was updated to handle SCLK kernels that use
///         TDT as their `parallel' time system. Header was updated,
///         particularly $Exceptions and $Restrictions. Watch is now
///         set on required kernel variables. Comment section for
///         permuted index source lines was added following the header.
///
/// -    SPICELIB Version 1.0.0, 04-SEP-1990 (NJB)
/// ```
///
/// # Revisions
///
/// ```text
/// -    SPICELIB Version 2.1.0, 09-NOV-2007 (NJB)
///
///         Bug fix: changed maximum value arguments to 1 in
///         calls to SCLI01 to fetch NFIELD and DELCDE values.
///
/// -    SPICELIB Version 2.0.0, 17-APR-1992 (NJB)
///
///         This routine was updated to handle a time system specification
///         for the `parallel' time system used in the SCLK kernel.
///
///         Specific changes include:
///
///            -- The time system code is looked up along with the
///               other SCLK specification parameters.
///
///            -- The input TDB value is converted, if necessary, to the
///               time system used in the parallel-time-to-SCLK mapping
///               defined by the current SCLK coefficients for the
///               specified spacecraft clock. This conversion is performed
///               prior to determination by interpolation of the
///               corresponding encoded SCLK value.
///
///         The header was expanded to discuss the fact that a leapseconds
///         kernel will now need to be loaded in order to use SCLK kernels
///         that map between SCLK and a parallel time system other than
///         TDB. The $Exceptions and $Restrictions sections were affected.
///
///         This routine now uses the new kernel pool watch capability
///         to determine when it is necessary to look up SCLK variables.
///         This method of checking for kernel pool updates replaces the
///         previously used once-per-call lookup of the SCLK_KERNEL_ID
///         kernel variable.
///
///         A comment section for permuted index source lines was added
///         following the header.
/// ```
pub fn scet01(ctx: &mut SpiceContext, sc: i32, et: f64, sclkdp: &mut f64) -> crate::Result<()> {
    SCET01(sc, et, sclkdp, ctx.raw_context())?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SCET01 ( ET to discrete ticks, type 1 )
pub fn SCET01(SC: i32, ET: f64, SCLKDP: &mut f64, ctx: &mut Context) -> f2rust_std::Result<()> {
    let save = ctx.get_vars::<SaveVars>();
    let save = &mut *save.borrow_mut();

    //
    // Standard SPICE error handling.
    //
    if RETURN(ctx) {
        return Ok(());
    }

    CHKIN(b"SCET01", ctx)?;

    if save.PASS1 {
        //
        // Initialize local data structures. This routine is error-free.
        //
        ZZSCIN01(
            save.HDSCLK.as_slice_mut(),
            save.SCPOOL.as_slice_mut(),
            save.CLKLST.as_slice_mut(),
            &mut save.DPFREE,
            &mut save.IFREE,
            &mut save.PRVSC,
            ctx,
        )?;
        ZZCTRUIN(save.POLCTR.as_slice_mut(), ctx);

        save.PASS1 = false;
    }

    //
    // Get parameters and data for this clock from the type 1 database.
    // Update the database if necessary.
    //
    ZZSCUP01(
        SC,
        save.POLCTR.as_slice_mut(),
        save.HDSCLK.as_slice_mut(),
        save.SCPOOL.as_slice_mut(),
        save.CLKLST.as_slice_mut(),
        &mut save.DPFREE,
        save.DPBUFF.as_slice_mut(),
        &mut save.IFREE,
        save.INTBUF.as_slice_mut(),
        save.SCBASE.as_slice_mut(),
        &mut save.PRVSC,
        &mut save.NFIELD,
        &mut save.DELCDE,
        &mut save.TIMSYS,
        &mut save.NCOEFF,
        &mut save.NPART,
        &mut save.COFBAS,
        &mut save.STRBAS,
        &mut save.ENDBAS,
        &mut save.MODBAS,
        &mut save.OFFBAS,
        ctx,
    )?;

    if FAILED(ctx) {
        save.PASS1 = true;

        CHKOUT(b"SCET01", ctx)?;
        return Ok(());
    }

    //
    // Convert the input TDB time to the parallel time system, if the
    // parallel system is not TDB.
    //
    // We don't need to check the validity of TIMSYS, because SCLI01
    // already made this check.
    //
    if (save.TIMSYS == TDB) {
        save.PARTIM = ET;
    } else if (save.TIMSYS == TDT) {
        save.PARTIM = UNITIM(ET, b"TDB", b"TDT", ctx)?;

        if FAILED(ctx) {
            CHKOUT(b"SCET01", ctx)?;
            return Ok(());
        }
    } else {
        //
        // This code should be unreachable. It's present for safety.
        //
        save.PASS1 = true;

        SETMSG(b"Invalid time system code # was found for SCLK #.", ctx);
        ERRINT(b"#", save.TIMSYS, ctx);
        ERRINT(b"#", SC, ctx);
        SIGERR(b"SPICE(VALUEOUTOFRANGE)", ctx)?;
        CHKOUT(b"SCET01", ctx)?;
        return Ok(());
    }
    //
    // We'd like to ascertain whether PARTIM is between the minimum
    // time value in the coefficients array and the end time
    // corresponding to the number of ticks since spacecraft clock
    // start at the end of the last partition.
    //
    // Checking the time value is a special case; we'll convert the time
    // value to ticks, and then check whether the resulting value is
    // less than the total number of ticks since spacecraft clock start
    // at the end of the last partition.  So, this check is performed
    // at the end of the routine.
    //
    // Find the time value in COEFFS closest to the input time value.
    // The time values are ordered, so we can do a binary search for the
    // closest one.  When the search is done, we will have found the
    // index of the greatest time value in the coefficient array that
    // is less than or equal to PARTIM.
    //
    //
    // There are three cases:
    //
    //    1) PARTIM is less than the least time coefficient in the array.
    //       In this case, we'll use the first coefficient set in the
    //       kernel to extrapolate from.  We don't automatically treat
    //       this case as an error because PARTIM could round up to the
    //       minimum tick value when converted to ticks.
    //
    //    2) PARTIM is bounded by the least and greatest time
    //       coefficients in the array.  In this case, we must search
    //       the array for a consecutive pair of records whose time
    //       values bound PARTIM.
    //
    //    3) PARTIM is greater than or equal to all of the time
    //       coefficients.  In that case, we don't need to search:  the
    //       last time value in the array is the one we want.
    //
    //
    if (save.PARTIM < COEFFS(2, 1, save.DPBUFF.as_slice(), save.COFBAS)) {
        //
        // The coefficient set to use for extrapolation is the first.
        //
        save.LOWER = 1;
    } else if (save.PARTIM < COEFFS(2, (save.NCOEFF / 3), save.DPBUFF.as_slice(), save.COFBAS)) {
        //
        // In the following loop, we maintain an invariant:
        //
        //    COEFFS( 2, LOWER )  <   PARTIM   <   COEFFS( 2, UPPER )
        //                        -
        //
        // At each step, we decrease the distance between LOWER and
        // UPPER, while keeping the above statement true.  The loop
        // terminates when LOWER = UPPER - 1.
        //
        // Note that we start out with if LOWER < UPPER, since we've
        // already made sure that the invariant expression above is true.
        //

        save.LOWER = 1;
        save.UPPER = (save.NCOEFF / 3);

        while (save.LOWER < (save.UPPER - 1)) {
            save.MIDDLE = ((save.LOWER + save.UPPER) / 2);

            if (save.PARTIM < COEFFS(2, save.MIDDLE, save.DPBUFF.as_slice(), save.COFBAS)) {
                save.UPPER = save.MIDDLE;
            } else {
                save.LOWER = save.MIDDLE;
            }
        }

    //
    // We've got PARTIM trapped between two time values that are
    // `adjacent' in the list:
    //
    //    COEFFS ( 2, LOWER )  and
    //    COEFFS ( 2, UPPER )
    //
    // since the second value must be greater than the first.  So
    //
    //    COEFFS( 2, LOWER )
    //
    // is the last time value in the coefficients array less than or
    // equal to PARTIM.
    //
    } else {
        //
        // PARTIM is greater than or equal to all of the time values in
        // the coefficients array.
        //
        save.LOWER = (save.NCOEFF / 3);
    }

    //
    // Now we evaluate a linear polynomial to find the tick value that
    // corresponds to PARTIM.  The coefficients of the polynomial are
    // the tick value and rate (in units of ticks per second) that
    // correspond to the time value
    //
    //    COEFFS( 2, LOWER )
    //
    // We call these coefficients CONST and RATE.  The rates in the
    // coefficients array are in units of seconds per most significant
    // clock count, so we use the conversion factor TIKMSC (`ticks per
    // most significant count') to change the rate to seconds per tick.
    //
    // One other thing:  SCLKDP should be an integral number of ticks.
    // We use the generic `nearest whole number' function ANINT to
    // ensure this.
    //
    save.TIMDIF = (save.PARTIM - COEFFS(2, save.LOWER, save.DPBUFF.as_slice(), save.COFBAS));
    save.CONST = COEFFS(1, save.LOWER, save.DPBUFF.as_slice(), save.COFBAS);

    if (COEFFS(3, save.LOWER, save.DPBUFF.as_slice(), save.COFBAS) <= 0.0) {
        save.PASS1 = true;

        SETMSG(b"Invalid SCLK rate.", ctx);
        SIGERR(b"SPICE(VALUEOUTOFRANGE)", ctx)?;
        CHKOUT(b"SCET01", ctx)?;
        return Ok(());
    }

    save.TIKMSC = 1.0;

    {
        let m1__: i32 = save.NFIELD;
        let m2__: i32 = 2;
        let m3__: i32 = -1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            save.TIKMSC = (save.TIKMSC * MODULI(save.I, save.DPBUFF.as_slice(), save.MODBAS));
            save.I += m3__;
        }
    }

    save.RATE = (1.0 / (COEFFS(3, save.LOWER, save.DPBUFF.as_slice(), save.COFBAS) / save.TIKMSC));

    *SCLKDP = f64::round((save.CONST + (save.RATE * save.TIMDIF)));

    //
    // Now, we'll see whether the SCLK value we've found is meaningful.
    // If it's too large, that's because the input PARTIM was beyond the
    // maximum value we can handle.  To check whether PARTIM is in
    // range, we must find the end time of the last partition, in total
    // ticks since spacecraft clock start.
    //
    save.MXTICK = f64::round(
        (PREND(1, save.DPBUFF.as_slice(), save.ENDBAS)
            - PRSTRT(1, save.DPBUFF.as_slice(), save.STRBAS)),
    );

    {
        let m1__: i32 = 2;
        let m2__: i32 = save.NPART;
        let m3__: i32 = 1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            save.MXTICK = f64::round(
                ((PREND(save.I, save.DPBUFF.as_slice(), save.ENDBAS)
                    - PRSTRT(save.I, save.DPBUFF.as_slice(), save.STRBAS))
                    + save.MXTICK),
            );
            save.I += m3__;
        }
    }

    //
    // Make sure that ET does not precede the ET corresponding to
    // the clock's minimum tick value or exceed the ET corresponding to
    // the clock's maximum tick value.  We'll do the comparison
    // using the tick value that ET mapped to and the minimum and
    // maximum tick values of the spacecraft clock.
    //
    // Convert SCLKDP and COEFFS(1,1) to whole numbers, so that
    // direct comparisons without tolerances are possible.
    //
    *SCLKDP = f64::round(*SCLKDP);
    save.DVAL = f64::round(COEFFS(1, 1, save.DPBUFF.as_slice(), save.COFBAS));

    if ((*SCLKDP < save.DVAL) || (*SCLKDP > save.MXTICK)) {
        save.PASS1 = true;

        SETMSG(&save.BVLMSG, ctx);
        ERRCH(b"#", b"ET", ctx);
        ERRDP(b"#", ET, ctx);
        SIGERR(b"SPICE(VALUEOUTOFRANGE)", ctx)?;
        CHKOUT(b"SCET01", ctx)?;
        return Ok(());
    }

    //
    // Keep track of the last spacecraft clock ID encountered.
    //
    save.PRVSC = SC;

    CHKOUT(b"SCET01", ctx)?;
    Ok(())
}

/// ET to continuous ticks, type 1
///
/// Convert ephemeris seconds past J2000 (ET) to continuous encoded
/// type 1 spacecraft clock (`ticks').  The output value need not be
/// integral.
///
/// # Required Reading
///
/// * [SCLK](crate::required_reading::sclk)
/// * [TIME](crate::required_reading::time)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  DESCRIPTION
///  --------  ---  --------------------------------------------------
///  SC         I   NAIF spacecraft ID code.
///  ET         I   Ephemeris time, seconds past J2000.
///  SCLKDP     O   Type 1 SCLK, encoded as continuous ticks since
///                 clock start.
/// ```
///
/// # Detailed Input
///
/// ```text
///  SC       is a NAIF ID code for a spacecraft, one of whose
///           clock values is represented by SCLKDP.
///
///  ET       is an ephemeris time, specified in seconds past
///           J2000, whose equivalent encoded SCLK value is
///           desired.
/// ```
///
/// # Detailed Output
///
/// ```text
///  SCLKDP   is the continuous encoded type 1 spacecraft clock
///           value corresponding to ET. The value is obtained
///           by mapping ET, using the piecewise linear mapping
///           defined by the SCLK kernel, to a value that may
///           have a non-zero fractional part. Unlike the output
///           of SCET01, SCLKDP is not rounded by this routine.
///
///           SCLKDP represents total time since spacecraft
///           clock start and hence does reflect partition
///           information.
/// ```
///
/// # Exceptions
///
/// ```text
///  1)  This routine assumes that that an SCLK kernel appropriate to
///      the spacecraft clock identified by the input argument SC has
///      been loaded. If an SCLK kernel has not been loaded, does not
///      contain all of the required data, or contains invalid data, an
///      error is signaled by a routine in the call tree of this
///      routine. The output argument SCLKDP will not be modified.
///
///      The variables that must be set by the SCLK kernel are:
///
///         -  The number of fields in an (unabridged) SCLK string
///         -  The output delimiter code
///         -  The parallel time system code
///         -  The moduli of the fields of an SCLK string
///         -  The offsets for each clock field.
///         -  The SCLK coefficients array
///         -  The partition start times
///         -  The partition end times
///
///  2)  When using SCLK kernels that map SCLK to a time system other
///      than ET (also called barycentric dynamical time---`TDB'), it
///      is necessary to have a leapseconds kernel loaded at the time
///      this routine is called. If a leapseconds kernel is required
///      for conversion between SCLK and ET but is not loaded, an error
///      is signaled by a routine in the call tree of this routine. The
///      output argument SCLKDP will not be modified.
///
///      The time system that an SCLK kernel maps SCLK to is indicated
///      by the variable SCLK_TIME_SYSTEM_nn in the kernel, where nn
///      is the negative of the NAIF integer code for the spacecraft.
///      The time system used in a kernel is TDB if and only if the
///      variable is assigned the value 1.
///
///  3)  If any of the following kernel variables have invalid values,
///      the error will be diagnosed by routines called by this
///      routine:
///
///         -  The number of SCLK coefficients
///         -  The number of partition start times
///         -  The number of partition end times
///         -  The number of fields of a SCLK string
///         -  The number of moduli for a SCLK string
///
///      If the number of values for any item read from the kernel
///      pool exceeds the maximum allowed value, it is may not be
///      possible to diagnose the error correctly, since overwriting
///      of memory may occur. This particular type of error is not
///      diagnosed by this routine.
///
///  4)  If the time system code is not recognized, the error
///      SPICE(VALUEOUTOFRANGE) is signaled.
///
///  5)  If the input ephemeris time value ET is out of range, the
///      error SPICE(VALUEOUTOFRANGE) is signaled. The output argument
///      SCLKDP will not be modified.
///
///  6)  If the SCLK rate used to interpolate SCLK values is
///      nonpositive, the error SPICE(VALUEOUTOFRANGE) is signaled.
///      The output argument SCLKDP will not be modified.
///
///  7)  If the partition times or SCLK coefficients themselves
///      are invalid, this routine will almost certainly give
///      incorrect results. This routine cannot diagnose errors
///      in the partition times or SCLK coefficients, except possibly
///      by crashing.
/// ```
///
/// # Particulars
///
/// ```text
///  SCEC01 is not usually called by routines external to SPICELIB.
///  The conversion routine SCE2C converts ephemeris seconds
///  past J2000 to any type of encoded spacecraft clock value.
///  SCE2C is the preferred user interface routine because its
///  interface specification does not refer to spacecraft clock types.
///  However, direct use of SCEC01 by user routines is not prohibited.
/// ```
///
/// # Examples
///
/// ```text
///  1)  Converting ET to encoded type 1 SCLK:
///
///      During program initialization, load the leapseconds and SCLK
///      kernels. We will assume that these files are named
///      "LEAPSECONDS.KER" and "SCLK.KER".  You must substitute the
///      actual names of these files in your code.
///
///         CALL CLPOOL
///         CALL FURNSH ( 'LEAPSECONDS.KER' )
///         CALL FURNSH ( 'SCLK.KER'        )
///
///      If SC is -77, indicating the Galileo spacecraft, and
///      ET is set to
///
///         -27848635.8149248
///
///      then the call
///
///         CALL SCEC01 ( SC, ET, SCLKDP )
///
///      returns SCLKDP as
///
///         35425287435.8554
///
///      on a NeXT workstation running NEXTSTEP 3.3.
/// ```
///
/// # Restrictions
///
/// ```text
///  1)  An SCLK kernel appropriate to the spacecraft clock identified
///      by SC must be loaded at the time this routine is called.
///
///  2)  If the SCLK kernel used with this routine does not map SCLK
///      directly to barycentric dynamical time, a leapseconds kernel
///      must be loaded at the time this routine is called.
/// ```
///
/// # Author and Institution
///
/// ```text
///  N.J. Bachman       (JPL)
///  J. Diaz del Rio    (ODC Space)
///  B.V. Semenov       (JPL)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 2.0.0, 01-DEC-2021 (NJB) (JDR)
///
///         Updated to support buffering of data for multiple clocks.
///         This entry point tracks kernel pool changes but no longer
///         sets or uses watches.
///
///         A check for invalid time system code was added.
///
///         Edited the header to comply with NAIF standard.
///
///         Corrected description of invalid clock rate exception.
///
/// -    SPICELIB Version 1.4.0, 09-SEP-2013 (BVS)
///
///         Updated to keep track of the POOL counter and call ZZCVPOOL.
///
/// -    SPICELIB Version 1.3.0, 05-MAR-2009 (NJB)
///
///         Bug fix: this routine now keeps track of whether its
///         kernel pool look-up succeeded. If not, a kernel pool
///         lookup is attempted on the next call to this routine.
///
/// -    SPICELIB Version 1.2.0, 09-NOV-2007 (NJB)
///
///         Bug fix: this routine now keeps track of whether its
///         kernel pool look-up succeeded. If not, a kernel pool
///         lookup is attempted on the next call to this routine.
///
/// -    SPICELIB Version 1.1.0, 09-NOV-2007 (NJB)
///
///         Bug fix: changed maximum value arguments to 1 in
///         calls to SCLI01 to fetch NFIELD and DELCDE values.
///
/// -    SPICELIB Version 1.0.0, 13-FEB-1999 (NJB)
/// ```
///
/// # Revisions
///
/// ```text
/// -    SPICELIB Version 1.1.0, 09-NOV-2007 (NJB)
///
///         Bug fix: changed maximum value arguments to 1 in
///         calls to SCLI01 to fetch NFIELD and DELCDE values.
/// ```
pub fn scec01(ctx: &mut SpiceContext, sc: i32, et: f64, sclkdp: &mut f64) -> crate::Result<()> {
    SCEC01(sc, et, sclkdp, ctx.raw_context())?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SCEC01 ( ET to continuous ticks, type 1 )
pub fn SCEC01(SC: i32, ET: f64, SCLKDP: &mut f64, ctx: &mut Context) -> f2rust_std::Result<()> {
    let save = ctx.get_vars::<SaveVars>();
    let save = &mut *save.borrow_mut();

    //
    // Standard SPICE error handling.
    //
    if RETURN(ctx) {
        return Ok(());
    }

    CHKIN(b"SCEC01", ctx)?;

    if save.PASS1 {
        //
        // Initialize local data structures. This routine is error-free.
        //
        ZZSCIN01(
            save.HDSCLK.as_slice_mut(),
            save.SCPOOL.as_slice_mut(),
            save.CLKLST.as_slice_mut(),
            &mut save.DPFREE,
            &mut save.IFREE,
            &mut save.PRVSC,
            ctx,
        )?;
        ZZCTRUIN(save.POLCTR.as_slice_mut(), ctx);

        save.PASS1 = false;
    }

    //
    // Get parameters and data for this clock from the type 1 database.
    // Update the database if necessary.
    //
    ZZSCUP01(
        SC,
        save.POLCTR.as_slice_mut(),
        save.HDSCLK.as_slice_mut(),
        save.SCPOOL.as_slice_mut(),
        save.CLKLST.as_slice_mut(),
        &mut save.DPFREE,
        save.DPBUFF.as_slice_mut(),
        &mut save.IFREE,
        save.INTBUF.as_slice_mut(),
        save.SCBASE.as_slice_mut(),
        &mut save.PRVSC,
        &mut save.NFIELD,
        &mut save.DELCDE,
        &mut save.TIMSYS,
        &mut save.NCOEFF,
        &mut save.NPART,
        &mut save.COFBAS,
        &mut save.STRBAS,
        &mut save.ENDBAS,
        &mut save.MODBAS,
        &mut save.OFFBAS,
        ctx,
    )?;

    if FAILED(ctx) {
        save.PASS1 = true;

        CHKOUT(b"SCEC01", ctx)?;
        return Ok(());
    }

    //
    // Convert the input TDB time to the parallel time system, if the
    // parallel system is not TDB.
    //
    // We don't need to check the validity of TIMSYS, because SCLI01
    // already made this check.
    //
    if (save.TIMSYS == TDB) {
        save.PARTIM = ET;
    } else if (save.TIMSYS == TDT) {
        save.PARTIM = UNITIM(ET, b"TDB", b"TDT", ctx)?;

        if FAILED(ctx) {
            CHKOUT(b"SCEC01", ctx)?;
            return Ok(());
        }
    } else {
        //
        // This code should be unreachable. It's present for safety.
        //
        save.PASS1 = true;

        SETMSG(b"Invalid time system code # was found for SCLK #.", ctx);
        ERRINT(b"#", save.TIMSYS, ctx);
        ERRINT(b"#", SC, ctx);
        SIGERR(b"SPICE(VALUEOUTOFRANGE)", ctx)?;
        CHKOUT(b"SCEC01", ctx)?;
        return Ok(());
    }

    //
    // We'd like to ascertain whether PARTIM is between the minimum
    // time value in the coefficients array and the end time
    // corresponding to the number of ticks since spacecraft clock
    // start at the end of the last partition.
    //
    // Checking the time value is a special case; we'll convert the time
    // value to ticks, and then check whether the resulting value is
    // less than the total number of ticks since spacecraft clock start
    // at the end of the last partition.  So, this check is performed
    // at the end of the routine.
    //
    // Find the time value in COEFFS closest to the input time value.
    // The time values are ordered, so we can do a binary search for the
    // closest one.  When the search is done, we will have found the
    // index of the greatest time value in the coefficient array that
    // is less than or equal to PARTIM.
    //
    //
    // There are two cases:
    //
    //    1) PARTIM is bounded by the least and greatest time
    //       coefficients in the array.  In this case, we must search
    //       the array for a consecutive pair of records whose time
    //       values bound PARTIM.
    //
    //    2) PARTIM is greater than or equal to all of the time
    //       coefficients.  In that case, we don't need to search:  the
    //       last time value in the array is the one we want.
    //
    //
    if (save.PARTIM < COEFFS(2, 1, save.DPBUFF.as_slice(), save.COFBAS)) {
        //
        // PARTIM precedes the coverage of the kernel.
        //
        save.PASS1 = true;

        SETMSG(&save.BVLMSG, ctx);
        ERRCH(b"#", b"ET", ctx);
        ERRDP(b"#", ET, ctx);
        SIGERR(b"SPICE(VALUEOUTOFRANGE)", ctx)?;
        CHKOUT(b"SCEC01", ctx)?;
        return Ok(());
    } else if (save.PARTIM < COEFFS(2, (save.NCOEFF / 3), save.DPBUFF.as_slice(), save.COFBAS)) {
        //
        // In the following loop, we maintain an invariant:
        //
        //    COEFFS( 2, LOWER )  <   PARTIM   <   COEFFS( 2, UPPER )
        //                        -
        //
        // At each step, we decrease the distance between LOWER and
        // UPPER, while keeping the above statement true.  The loop
        // terminates when LOWER = UPPER - 1.
        //
        // Note that we start out with if LOWER < UPPER, since we've
        // already made sure that the invariant expression above is true.
        //

        save.LOWER = 1;
        save.UPPER = (save.NCOEFF / 3);

        while (save.LOWER < (save.UPPER - 1)) {
            save.MIDDLE = ((save.LOWER + save.UPPER) / 2);

            if (save.PARTIM < COEFFS(2, save.MIDDLE, save.DPBUFF.as_slice(), save.COFBAS)) {
                save.UPPER = save.MIDDLE;
            } else {
                save.LOWER = save.MIDDLE;
            }
        }

    //
    // We've got PARTIM trapped between two time values that are
    // `adjacent' in the list:
    //
    //    COEFFS ( 2, LOWER )  and
    //    COEFFS ( 2, UPPER )
    //
    // since the second value must be greater than the first.  So
    //
    //    COEFFS( 2, LOWER )
    //
    // is the last time value in the coefficients array less than or
    // equal to PARTIM.
    //
    } else {
        //
        // PARTIM is greater than or equal to all of the time values in
        // the coefficients array.
        //
        save.LOWER = (save.NCOEFF / 3);
    }

    //
    // Now we evaluate a linear polynomial to find the tick value that
    // corresponds to PARTIM.  The coefficients of the polynomial are
    // the tick value and rate (in units of ticks per second) that
    // correspond to the time value
    //
    //    COEFFS( 2, LOWER )
    //
    // We call these coefficients CONST and RATE.  The rates in the
    // coefficients array are in units of seconds per most significant
    // clock count, so we use the conversion factor TIKMSC (`ticks per
    // most significant count') to change the rate to seconds per tick.
    //
    save.TIMDIF = (save.PARTIM - COEFFS(2, save.LOWER, save.DPBUFF.as_slice(), save.COFBAS));
    save.CONST = COEFFS(1, save.LOWER, save.DPBUFF.as_slice(), save.COFBAS);

    if (COEFFS(3, save.LOWER, save.DPBUFF.as_slice(), save.COFBAS) <= 0.0) {
        save.PASS1 = true;

        SETMSG(b"Invalid SCLK rate #.", ctx);
        ERRDP(
            b"#",
            COEFFS(3, save.LOWER, save.DPBUFF.as_slice(), save.COFBAS),
            ctx,
        );
        SIGERR(b"SPICE(VALUEOUTOFRANGE)", ctx)?;
        CHKOUT(b"SCEC01", ctx)?;
        return Ok(());
    }

    save.TIKMSC = 1.0;

    {
        let m1__: i32 = save.NFIELD;
        let m2__: i32 = 2;
        let m3__: i32 = -1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            save.TIKMSC = (save.TIKMSC * MODULI(save.I, save.DPBUFF.as_slice(), save.MODBAS));
            save.I += m3__;
        }
    }

    save.RATE = (1.0 / (COEFFS(3, save.LOWER, save.DPBUFF.as_slice(), save.COFBAS) / save.TIKMSC));

    *SCLKDP = (save.CONST + (save.RATE * save.TIMDIF));

    //
    // Now, we'll see whether the SCLK value we've found is meaningful.
    // If it's too large, that's because the input PARTIM was beyond the
    // maximum value we can handle.  To check whether PARTIM is in
    // range, we must find the end time of the last partition, in total
    // ticks since spacecraft clock start.
    //
    save.MXTICK = f64::round(
        (PREND(1, save.DPBUFF.as_slice(), save.ENDBAS)
            - PRSTRT(1, save.DPBUFF.as_slice(), save.STRBAS)),
    );

    {
        let m1__: i32 = 2;
        let m2__: i32 = save.NPART;
        let m3__: i32 = 1;
        save.I = m1__;
        for _ in 0..((m2__ - m1__ + m3__) / m3__) as i32 {
            save.MXTICK = f64::round(
                ((PREND(save.I, save.DPBUFF.as_slice(), save.ENDBAS)
                    - PRSTRT(save.I, save.DPBUFF.as_slice(), save.STRBAS))
                    + save.MXTICK),
            );
            save.I += m3__;
        }
    }

    //
    // Make sure that ET does not exceed the ET corresponding to
    // the clock's maximum tick value.  We'll do the comparison
    // using the tick value that ET mapped to and the maximum tick
    // value of the spacecraft clock.
    //
    if (*SCLKDP > save.MXTICK) {
        save.PASS1 = true;

        SETMSG(&save.BVLMSG, ctx);
        ERRCH(b"#", b"ET", ctx);
        ERRDP(b"#", ET, ctx);
        SIGERR(b"SPICE(VALUEOUTOFRANGE)", ctx)?;
        CHKOUT(b"SCEC01", ctx)?;
        return Ok(());
    }

    //
    // Keep track of the last spacecraft clock ID encountered.
    //
    save.PRVSC = SC;

    CHKOUT(b"SCEC01", ctx)?;
    Ok(())
}

/// SCLK type, using type 1 SCLK database
///
/// Return the type of a specified clock. The clock need not be
/// type 1.
///
/// # Required Reading
///
/// * [SCLK](crate::required_reading::sclk)
/// * [TIME](crate::required_reading::time)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  DESCRIPTION
///  --------  ---  --------------------------------------------------
///  SC         I   NAIF spacecraft clock ID code.
///  CLKTYP     O   NAIF spacecraft clock type.
/// ```
///
/// # Detailed Input
///
/// ```text
///  SC       is a NAIF ID code for a spacecraft clock.
/// ```
///
/// # Detailed Output
///
/// ```text
///  CLKTYP   is the integer spacecraft clock type. The type
///           need not be 1.
/// ```
///
/// # Exceptions
///
/// ```text
///  1)  If a kernel variable identifying requested SCLK type is not
///      found, the error SPICE(KERNELVARNOTFOUND) is signaled.
///
///  2)  If an error occurs in the course of updating the type 1 SCLK
///      database, the error is signaled by a routine in the call tree
///      of this routine.
///
///  3)  It is not an error to request the type of a clock that is not
///      type 1.
/// ```
///
/// # Files
///
/// ```text
///  Appropriate kernels must be loaded by the calling program before
///  this routine is called.
///
///  The following data are required:
///
///  -  An SCLK kernel providing data for the SCLK designated by
///     the input ID code SC.
///
///  In all cases, kernel data are normally loaded once per program
///  run, NOT every time this routine is called.
/// ```
///
/// # Particulars
///
/// ```text
///  SCLK "type" is a SPICE-specific concept. It indicates which
///  mechanism is used by SPICE for representing time as measured
///  by a specified clock, and for converting those time measurements
///  to standard time systems such as TDB.
///
///  This routine speeds up determination of a spacecraft clock's type
///  by querying the type 1 SCLK database for information about that
///  clock. If the clock is not found, the kernel pool is searched,
///  and if the clock is determined to be type 1, information about it
///  is stored in the type 1 database. If the clock is not type 1,
///  the type is returned, but the type 1 database is not modified.
///
///  This is the only entry point of SC01 for which it is valid to
///  supply the ID of a clock not of type 1.
/// ```
///
/// # Examples
///
/// ```text
///  See usage in the SPICELIB function SCTYPE.
/// ```
///
/// # Restrictions
///
/// ```text
///  1)  This is essentially a SPICE-private routine. It should not
///      be called directly by user application code.
/// ```
///
/// # Author and Institution
///
/// ```text
///  N.J. Bachman       (JPL)
///  J. Diaz del Rio    (ODC Space)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 1.0.0, 01-DEC-2021 (NJB) (JDR)
///
///         New entry point.
/// ```
pub fn scty01(ctx: &mut SpiceContext, sc: i32, clktyp: &mut i32) -> crate::Result<()> {
    SCTY01(sc, clktyp, ctx.raw_context())?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SCTY01 ( SCLK type, using type 1 SCLK database )
pub fn SCTY01(SC: i32, CLKTYP: &mut i32, ctx: &mut Context) -> f2rust_std::Result<()> {
    let save = ctx.get_vars::<SaveVars>();
    let save = &mut *save.borrow_mut();

    if RETURN(ctx) {
        return Ok(());
    }

    CHKIN(b"SCTY01", ctx)?;

    //
    // At this point, PRVSC is either 0 or the ID of the last type 1
    // clock for which a successful call to an entry point of SC01
    // was made. PRVSC is never assigned the code of a clock that isn't
    // type 1.
    //
    if save.PASS1 {
        //
        // Initialize local data structures.
        //
        ZZSCIN01(
            save.HDSCLK.as_slice_mut(),
            save.SCPOOL.as_slice_mut(),
            save.CLKLST.as_slice_mut(),
            &mut save.DPFREE,
            &mut save.IFREE,
            &mut save.PRVSC,
            ctx,
        )?;
        ZZCTRUIN(save.POLCTR.as_slice_mut(), ctx);

        save.PASS1 = false;
    }

    //
    // The clock type is unknown at this point.
    //
    *CLKTYP = 0;

    //
    // Reinitialize the SC01 database if the kernel pool has been
    // updated. The call below syncs POLCTR.
    //
    ZZPCTRCK(save.POLCTR.as_slice_mut(), &mut save.UPDATE, ctx);

    if save.UPDATE {
        //
        // Initialize local data structures.
        //
        ZZSCIN01(
            save.HDSCLK.as_slice_mut(),
            save.SCPOOL.as_slice_mut(),
            save.CLKLST.as_slice_mut(),
            &mut save.DPFREE,
            &mut save.IFREE,
            &mut save.PRVSC,
            ctx,
        )?;

        save.SAMCLK = false;
    } else {
        //
        // We never indicate the clock is the "same" as the previous
        // one unless the clock is type 1.
        //
        save.SAMCLK = ((SC != 0) && (SC == save.PRVSC));
    }

    if !save.SAMCLK {
        //
        // Get the SCLK type of the input SCLK.
        //
        fstr::assign(&mut save.KVNAME, b"SCLK_DATA_TYPE_#");
        REPMI(&save.KVNAME.to_vec(), b"#", -SC, &mut save.KVNAME, ctx);

        GIPOOL(
            &save.KVNAME,
            1,
            1,
            &mut save.N,
            std::slice::from_mut(CLKTYP),
            &mut save.FOUND,
            ctx,
        )?;

        if (FAILED(ctx) || !save.FOUND) {
            if FAILED(ctx) {
                save.PASS1 = true;

                CHKOUT(b"SCTY01", ctx)?;
                return Ok(());
            }

            if !save.FOUND {
                //
                // The GIPOOL call succeeded but the kernel variable was
                // not found.
                //
                save.PASS1 = true;

                SETMSG(b"Kernel variable # was not found in the kernel pool.", ctx);
                ERRCH(b"#", &save.KVNAME, ctx);
                SIGERR(b"SPICE(KERNELVARNOTFOUND)", ctx)?;

                CHKOUT(b"SCTY01", ctx)?;
                return Ok(());
            }
        }

        //
        // At this point, the clock type is set.
        //
        if (*CLKTYP != 1) {
            //
            // The clock is not type 1, so we don't add it to the
            // SC01 database.
            //
            save.PRVSC = 0;

            CHKOUT(b"SCTY01", ctx)?;
            return Ok(());
        }

        //
        // The SCLK is type 1 but may not be in the SC01 database, and
        // in any case is not the last type 1 clock seen on a successful
        // call to any SC01 entry point. Update the SCLK parameters and,
        // if necessary, the database.
        //
        ZZSCUP01(
            SC,
            save.POLCTR.as_slice_mut(),
            save.HDSCLK.as_slice_mut(),
            save.SCPOOL.as_slice_mut(),
            save.CLKLST.as_slice_mut(),
            &mut save.DPFREE,
            save.DPBUFF.as_slice_mut(),
            &mut save.IFREE,
            save.INTBUF.as_slice_mut(),
            save.SCBASE.as_slice_mut(),
            &mut save.PRVSC,
            &mut save.NFIELD,
            &mut save.DELCDE,
            &mut save.TIMSYS,
            &mut save.NCOEFF,
            &mut save.NPART,
            &mut save.COFBAS,
            &mut save.STRBAS,
            &mut save.ENDBAS,
            &mut save.MODBAS,
            &mut save.OFFBAS,
            ctx,
        )?;

        if FAILED(ctx) {
            save.PASS1 = true;

            CHKOUT(b"SCTY01", ctx)?;
            return Ok(());
        }
    }

    //
    // We can arrive here only if the clock type is 1.
    //
    *CLKTYP = 1;
    save.PRVSC = SC;

    CHKOUT(b"SCTY01", ctx)?;
    Ok(())
}

/// SCLK partition bounds, type 1
///
/// Return partition data for a specified type 1 clock.
///
/// # Required Reading
///
/// * [SCLK](crate::required_reading::sclk)
/// * [TIME](crate::required_reading::time)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  DESCRIPTION
///  --------  ---  --------------------------------------------------
///  SC         I   NAIF spacecraft clock ID code.
///  NPARTN     O   Number of partitions.
///  PARBEG     O   Partition begin times.
///  PAREND     O   Partition end times.
/// ```
///
/// # Detailed Input
///
/// ```text
///  SC       is a NAIF ID code for a spacecraft clock.
/// ```
///
/// # Detailed Output
///
/// ```text
///  NPARTN   is the number of partitions for the clock
///           designated by SC.
///
///  PARBEG,
///  PAREND   are, respectively, arrays of partition begin and
///           end times for the clock designated by SC. The
///           times are expressed as encoded SCLK.
/// ```
///
/// # Exceptions
///
/// ```text
///  1)  If an error occurs in the course of updating the type 1 SCLK
///      database, the error is signaled by a
///      routine in the call tree of this routine.
/// ```
///
/// # Files
///
/// ```text
///  Appropriate kernels must be loaded by the calling program before
///  this routine is called.
///
///  The following data are required:
///
///  -  An SCLK kernel providing data for the SCLK designated by
///     the input ID code SC.
///
///  In all cases, kernel data are normally loaded once per program
///  run, NOT every time this routine is called.
/// ```
///
/// # Examples
///
/// ```text
///  See usage in the SPICELIB function SCPART.
/// ```
///
/// # Restrictions
///
/// ```text
///  1)  This is essentially a SPICE-private routine. It should not
///      be called directly by user application code.
/// ```
///
/// # Author and Institution
///
/// ```text
///  N.J. Bachman       (JPL)
///  J. Diaz del Rio    (ODC Space)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 1.0.0, 01-DEC-2021 (NJB) (JDR)
///
///         New entry point.
/// ```
pub fn scpr01(
    ctx: &mut SpiceContext,
    sc: i32,
    npartn: &mut i32,
    parbeg: &mut [f64],
    parend: &mut [f64],
) -> crate::Result<()> {
    SCPR01(sc, npartn, parbeg, parend, ctx.raw_context())?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SCPR01 ( SCLK partition bounds, type 1  )
pub fn SCPR01(
    SC: i32,
    NPARTN: &mut i32,
    PARBEG: &mut [f64],
    PAREND: &mut [f64],
    ctx: &mut Context,
) -> f2rust_std::Result<()> {
    let save = ctx.get_vars::<SaveVars>();
    let save = &mut *save.borrow_mut();

    let mut PARBEG = DummyArrayMut::new(PARBEG, 1..);
    let mut PAREND = DummyArrayMut::new(PAREND, 1..);

    if RETURN(ctx) {
        return Ok(());
    }

    CHKIN(b"SCPR01", ctx)?;

    if save.PASS1 {
        //
        // Initialize local data structures. This routine is error-free.
        //
        ZZSCIN01(
            save.HDSCLK.as_slice_mut(),
            save.SCPOOL.as_slice_mut(),
            save.CLKLST.as_slice_mut(),
            &mut save.DPFREE,
            &mut save.IFREE,
            &mut save.PRVSC,
            ctx,
        )?;
        ZZCTRUIN(save.POLCTR.as_slice_mut(), ctx);

        save.PASS1 = false;
    }

    //
    // Get partition data for this clock. Update the type 1 database
    // if necessary.
    //
    ZZSCUP01(
        SC,
        save.POLCTR.as_slice_mut(),
        save.HDSCLK.as_slice_mut(),
        save.SCPOOL.as_slice_mut(),
        save.CLKLST.as_slice_mut(),
        &mut save.DPFREE,
        save.DPBUFF.as_slice_mut(),
        &mut save.IFREE,
        save.INTBUF.as_slice_mut(),
        save.SCBASE.as_slice_mut(),
        &mut save.PRVSC,
        &mut save.NFIELD,
        &mut save.DELCDE,
        &mut save.TIMSYS,
        &mut save.NCOEFF,
        &mut save.NPART,
        &mut save.COFBAS,
        &mut save.STRBAS,
        &mut save.ENDBAS,
        &mut save.MODBAS,
        &mut save.OFFBAS,
        ctx,
    )?;

    if FAILED(ctx) {
        save.PASS1 = true;

        CHKOUT(b"SCPR01", ctx)?;
        return Ok(());
    }

    //
    // Set the output partition arguments.
    //
    MOVED(
        save.DPBUFF.subarray((save.STRBAS + 1)),
        save.NPART,
        PARBEG.as_slice_mut(),
    );
    MOVED(
        save.DPBUFF.subarray((save.ENDBAS + 1)),
        save.NPART,
        PAREND.as_slice_mut(),
    );

    *NPARTN = save.NPART;

    save.PRVSC = SC;

    CHKOUT(b"SCPR01", ctx)?;
    Ok(())
}