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
//
// GENERATED FILE
//

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

const FPRINT: i32 = 32;
const LPRINT: i32 = 126;
const DIRSIZ: i32 = 100;
const IFNLEN: i32 = 60;
const FTSIZE: i32 = 20;
const IMPLE: i32 = 0;
const IMPCLS: i32 = 1;
const EXPLT: i32 = 2;
const EXPLE: i32 = 3;
const EXPCLS: i32 = 4;
const MNIDXT: i32 = 0;
const MXIDXT: i32 = 4;
const CONBAS: i32 = 1;
const NCON: i32 = (CONBAS + 1);
const RDRBAS: i32 = (NCON + 1);
const NRDR: i32 = (RDRBAS + 1);
const RDRTYP: i32 = (NRDR + 1);
const REFBAS: i32 = (RDRTYP + 1);
const NREF: i32 = (REFBAS + 1);
const PDRBAS: i32 = (NREF + 1);
const NPDR: i32 = (PDRBAS + 1);
const PDRTYP: i32 = (NPDR + 1);
const PKTBAS: i32 = (PDRTYP + 1);
const NPKT: i32 = (PKTBAS + 1);
const RSVBAS: i32 = (NPKT + 1);
const NRSV: i32 = (RSVBAS + 1);
const PKTSZ: i32 = (NRSV + 1);
const PKTOFF: i32 = (PKTSZ + 1);
const NMETA: i32 = (PKTOFF + 1);
const MXMETA: i32 = NMETA;
const MNMETA: i32 = 15;

struct SaveVars {
    INDEX: i32,
    LSTHAN: i32,
    NUMFXD: i32,
    NUMVAR: i32,
    EXPLCT: bool,
    FXDSEG: bool,
    FTREFS: StackArray2D<f64, 40>,
    FTBADR: StackArray<i32, 20>,
    FTHAN: StackArray<i32, 20>,
    FTITYP: StackArray<i32, 20>,
    FTMXSZ: StackArray<i32, 20>,
    FTNCON: StackArray<i32, 20>,
    FTNPKT: StackArray<i32, 20>,
    FTNREF: StackArray<i32, 20>,
    FTNRES: StackArray<i32, 20>,
    FTOFF: StackArray<i32, 20>,
    FTPKSZ: StackArray<i32, 20>,
    NFT: i32,
    FTFIXD: StackArray<bool, 20>,
    FTEXPL: StackArray<bool, 20>,
}

impl SaveInit for SaveVars {
    fn new() -> Self {
        let mut INDEX: i32 = 0;
        let mut LSTHAN: i32 = 0;
        let mut NUMFXD: i32 = 0;
        let mut NUMVAR: i32 = 0;
        let mut EXPLCT: bool = false;
        let mut FXDSEG: bool = false;
        let mut FTREFS = StackArray2D::<f64, 40>::new(1..=2, 1..=FTSIZE);
        let mut FTBADR = StackArray::<i32, 20>::new(1..=FTSIZE);
        let mut FTHAN = StackArray::<i32, 20>::new(1..=FTSIZE);
        let mut FTITYP = StackArray::<i32, 20>::new(1..=FTSIZE);
        let mut FTMXSZ = StackArray::<i32, 20>::new(1..=FTSIZE);
        let mut FTNCON = StackArray::<i32, 20>::new(1..=FTSIZE);
        let mut FTNPKT = StackArray::<i32, 20>::new(1..=FTSIZE);
        let mut FTNREF = StackArray::<i32, 20>::new(1..=FTSIZE);
        let mut FTNRES = StackArray::<i32, 20>::new(1..=FTSIZE);
        let mut FTOFF = StackArray::<i32, 20>::new(1..=FTSIZE);
        let mut FTPKSZ = StackArray::<i32, 20>::new(1..=FTSIZE);
        let mut NFT: i32 = 0;
        let mut FTFIXD = StackArray::<bool, 20>::new(1..=FTSIZE);
        let mut FTEXPL = StackArray::<bool, 20>::new(1..=FTSIZE);

        NUMFXD = 0;
        NUMVAR = 0;
        NFT = 0;

        Self {
            INDEX,
            LSTHAN,
            NUMFXD,
            NUMVAR,
            EXPLCT,
            FXDSEG,
            FTREFS,
            FTBADR,
            FTHAN,
            FTITYP,
            FTMXSZ,
            FTNCON,
            FTNPKT,
            FTNREF,
            FTNRES,
            FTOFF,
            FTPKSZ,
            NFT,
            FTFIXD,
            FTEXPL,
        }
    }
}

/// Generic segments: Sequential writer.
///
/// This is the umbrella routine for managing the sequential writing
/// of generic segments to DAF files. It should never be called
/// directly, it provides the mechanism whereby data are shared by
/// its entry points.
///
/// # Required Reading
///
/// * [DAF](crate::required_reading::daf)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  DESCRIPTION
///  --------  ---  --------------------------------------------------
///  HANDLE    I    Handle of a DAF file opened with write access.
///  DESCR     I    Descriptor for a generic segment.
///  SEGID     I    Identifier for a generic segment.
///  NCONST    I    Number of constant values in a generic segment.
///  CONST     I    Array of constant values for a generic segment.
///  NPKTS     I    Number of data packets to write to a segment.
///  PKTSIZ    I    Size of fixed size packets or sizes of variable
///                 size packets.
///  PKTDAT    I    Array of packet data.
///  NREFS     I    Number of reference values.
///  REFDAT    I    Reference data.
///  IDXTYP    I    Index type for the reference values.
/// ```
///
/// # Detailed Input
///
/// ```text
///  HANDLE   is the handle of a DAF file opened with write access.
///           This is the handle of the file in which a generic segment
///           will be started, or the handle of a file in which a
///           generic segment is currently being written.
///
///  DESCR    is the descriptor for the generic segment that is being
///           written. This is the packed form of the DAF double
///           precision and integer summaries which contains ND double
///           precision numbers and NI integers, respectively.
///
///  SEGID    is an identifier for the generic segment that is being
///           written. This is a character string containing at most
///           NC printing ASCII characters where
///
///                             /  ND + ( NI + 1 )  \
///                  NC =  8 *  | ----------------- |
///                             \         2         /
///
///            SEGID may be blank.
///
///  NCONST   is the number of constant values to be placed in the
///           generic segment.
///
///  CONST    is an array of NCONST constant values for the generic
///           segment.
///
///  NPKTS    is the number of data packets to write to a generic
///           segment.
///
///  PKTSIZ   is the size of fixed size packets or sizes of variable
///           size packets.
///
///           The size of a packet is the number of double precision
///           numbers it contains.
///
///           When writing a segment with fixed size packets, only
///           the first element of the array, PKTSIZ(1), is used, and
///           it should contain the size of the fixed size packets. In
///           this instance, the calling program need not declare this
///           variable as an array of one integer; it may be declared
///           as an integer variable.
///
///           When writing a segment with variable size packets,
///           there must be an element in the array PKTSIZ for each of
///           the data packets.
///
///  PKTDAT   is a singly dimensioned array containing the double
///           precision data for the fixed or variable size data
///           packets to be added to the generic segment associated
///           with HANDLE.
///
///           For fixed size data packets, PKTDAT will have the
///           following structure:
///
///              Packet #  Range of locations for the packet data.
///              --------  ------------------------------------------
///
///                 1      PKTDAT(1)              to PKTDAT(PS)
///                 2      PKTDAT(PS+1)           to PKTDAT(2*PS)
///                 3      PKTDAT(2*PS+1)         to PKTDAT(3*PS)
///                 4      PKTDAT(3*PS+1)         to PKTDAT(4*PS)
///
///                                         .
///                                         .
///                                         .
///
///                NPKTS   PKTDAT((NPKTS-1)*PS+1) to PKTDAT(NPKTS*PS)
///
///           where PS = PKTSIZ(1).
///
///           For variable size data packets, PKTDAT will have the
///           following structure:
///
///              Packet #  Range of locations for the packet data.
///              --------  ------------------------------------------
///
///                 1      PKTDAT(1)           to PKTDAT(P(1))
///                 2      PKTDAT(P(1)+1)      to PKTDAT(P(2))
///                 3      PKTDAT(P(2)+1)      to PKTDAT(P(3))
///                 4      PKTDAT(P(3)+1)      to PKTDAT(P(4))
///
///                                         .
///                                         .
///                                         .
///
///                NPKTS   PKTDAT(P(NPKTS-1)+1) to PKTDAT(P(NPKTS))
///
///                            I
///                           ---
///           where P(I) =    >   PKTSIZ(K).
///                           ---
///                          K = 1
///
///  NREFS    is the number of reference values.
///
///           For implicitly indexed packets, NREFS must have a value
///           of two (2).
///
///           When writing packets to a generic segment which uses an
///           implicit index type, the value specified by NREFS is
///           used only on the first call to SGWFPK or SGWVPK. On all
///           subsequent calls to these subroutines for a particular
///           implicitly indexed generic segment, the value of NREFS
///           is ignored.
///
///           For explicitly indexed packets, NREFS must be equal to
///           NPKTS; there should be a reference value for each data
///           packet being written to the generic segment.
///
///           When writing packets to a segment which uses an explicit
///           index type, the value specified by NREFS is used on
///           every call to SGWFPK or SGWVPK and it must always be
///           equal to NPKTS.
///
///  REFDAT   is the reference data values.
///
///           For implicitly indexed packets, there must be two (2)
///           values. The values represent a starting value, which
///           will have an index of 1, and a step size between
///           reference values, which are used to compute an index and
///           a reference value associated with a specified key value.
///
///           In order to avoid, or at least minimize, numerical
///           difficulties associated with computing index values for
///           generic segments with implicit index types, the value of
///           the step size must be an integer, i.e., DINT(REFDAT(2))
///           must equal REFDAT(2). In this case, we also recommend
///           that REFDAT(1) be an integer, although this is not
///           enforced.
///
///           When writing packets to a generic segment which uses an
///           implicit index type, the values specified by REFDAT are
///           used only on the first call to SGWFPK or SGWVPK. On all
///           subsequent calls to these subroutines for a particular
///           implicitly indexed generic segment REFDAT is ignored.
///
///           For explicitly indexed packets, there must be NPKTS
///           reference values and the values must be in increasing
///           order:
///
///              REFDAT(I) < REFDAT(I+1), I = 1, NPKTS-1
///
///           When writing packets to a segment which uses an explicit
///           index type, the values specified by REFDAT are used on
///           every call to SGWFPK or SGWVPK. On all calls to these
///           subroutines after the first, the value of REFDAT(1) must
///           be strictly greater than than the value of REFDAT(NPKTS)
///           from the previous call. This preserves the ordering of
///           the reference values for the entire segment.
///
///  IDXTYP   is the index type to use for the reference values.
///
///           Two forms of indexing are provided:
///
///              1) An implicit form of indexing based on using two
///                 values, a starting value, which will have an index
///                 of 1, and a step size between reference values,
///                 which are used to compute an index and a reference
///                 value associated with a specified key value. See
///                 the descriptions of the implicit types below for
///                 the particular formula used in each case.
///
///              2) An explicit form of indexing based on a reference
///                 value for each data packet.
///
///           See the chapter on Generic segments in the DAF required
///           or the include file 'sgparam.inc' for more details
///           about the index types that are available.
/// ```
///
/// # Detailed Output
///
/// ```text
///  None.
///
///  The data passed to the various entry points of this subroutine are
///  used to construct a generic segment in one or more DAF files, with
///  the current file specified by the input argument HANDLE.
/// ```
///
/// # Parameters
///
/// ```text
///  The entry points in this subroutine make use of parameters defined
///  in the file 'sgparam.inc'.
/// ```
///
/// # Exceptions
///
/// ```text
///  1)  If this subroutine is called directly rather than through one
///      of its entry points, the error SPICE(BOGUSENTRY) is signaled.
///
///  2)  See the individual entry points for descriptions of their
///      exceptions.
/// ```
///
/// # Files
///
/// ```text
///  See HANDLE in the $Detailed_Input section above.
/// ```
///
/// # Particulars
///
/// ```text
///  This is the umbrella routine for managing the sequential writing
///  of generic segments to DAF files. It should never be called
///  directly, but provides the mechanism whereby data are shared by
///  its entry points. The entry points included in this subroutine
///  are:
///
///  SGBWFS ( HANDLE, DESCR, SEGID, NCONST, CONST, PKTSIZ, IDXTYP )
///     Begin writing a generic segment with fixed size packets.
///
///  SGBWVS ( HANDLE, DESCR, SEGID, NCONST, CONST, IDXTYP )
///     Begin writing a generic segment with variable size packets.
///
///  SGWFPK ( HANDLE, NPKTS, PKTDAT, NREFS, REFDAT )
///     Write fixed size packets to a generic segment started by
///     calling SGBWFS.
///
///  SGWVPK ( HANDLE, NPKTS, PKTSIZ, PKTDAT, NREFS, REFDAT )
///     Write variable size packets to a generic segment started by
///     calling SGBWVS.
///
///  SGWES ( HANDLE )
///     End a generic segment.
///
///  A DAF generic segment contains several logical data partitions:
///
///     1) A partition for constant values to be associated with each
///        data packet in the segment.
///
///     2) A partition for the data packets.
///
///     3) A partition for reference values.
///
///     4) A partition for a packet directory, if the segment contains
///        variable sized packets.
///
///     5) A partition for a reference value directory.
///
///     6) A reserved partition that is not currently used. This
///        partition is only for the use of the NAIF group at the Jet
///        Propulsion Laboratory (JPL).
///
///     7) A partition for the meta data which describes the locations
///        and sizes of other partitions as well as providing some
///        additional descriptive information about the generic
///        segment.
///
///              +============================+
///              |         Constants          |
///              +============================+
///              |          Packet 1          |
///              |----------------------------|
///              |          Packet 2          |
///              |----------------------------|
///              |              .             |
///              |              .             |
///              |              .             |
///              |----------------------------|
///              |          Packet N          |
///              +============================+
///              |      Reference Values      |
///              +============================+
///              |      Packet Directory      |
///              +============================+
///              |    Reference  Directory    |
///              +============================+
///              |       Reserved  Area       |
///              +============================+
///              |     Segment Meta Data      |
///              +----------------------------+
///
///  Only the placement of the meta data at the end of a generic
///  segment is required. The other data partitions may occur in any
///  order in the generic segment because the meta data will contain
///  pointers to their appropriate locations within the generic
///  segment.
///
///  The meta data for a generic segment should only be obtained
///  through use of the subroutine SGMETA. The meta data should not be
///  written through any mechanism other than the ending of a generic
///  segment begun by SGBWFS or SGBWVS using SGWES.
///
///  The entry points of this subroutine when used together provide the
///  following capabilities:
///
///     1) The ability to write a generic segment with fixed size data
///        packets to a DAF.
///
///     2) the ability to write a generic segment with variable size
///        data packets to a DAF.
///
///     3) The ability to write generic segments to multiple files.
///        Only a single generic segment may be written to a particular
///        file at any time, but several files may each have a generic
///        segment being written to them at the same time.
///
///  Packets may be placed into a generic segment one at a time or N at
///  at time, depending upon the whim of the programmer, limitations
///  of the computing equipment (memory), or requirements placed upon
///  the software that will write a generic segment.
///
///  Packets are retrieved from a generic segment by an index which may
///  be obtained by using the subroutine SGFRVI (generic segments fetch
///  reference value and index).
/// ```
///
/// # Examples
///
/// ```text
///  In examples 1 and 3, we make use of the fictitious subroutines
///
///     GET_FIX_PKT ( PACKET, REF, DONE )
///
///  and
///
///     GET_VAR_PKT ( PACKET, SIZE, REF, DONE )
///
///  where
///
///     DONE   is a logical flag indicating whether there is more data
///            available. DONE = .TRUE. implies there is no more data.
///            DONE = .FALSE. implies there is more data available.
///
///     PACKET is a double precision array of an appropriate size to
///            hold all of the data returned.
///
///     REF    is a double precision reference value that will be used
///            to create an index for the data packets in the segment.
///            The values of this variable are always increasing, e.g.,
///            the value of REF on the second call to GET_FIX_PKT or
///            GET_VAR_PKT will be greater than the value on the first
///            call to the subroutine.
///
///     SIZE   is an integer for the size of the variable size data
///            packet that is returned.
///
///  These subroutines return a fixed size data packet and a variable
///  size data packet, respectively. We make use of these fictitious
///  subroutines in the examples to avoid adding unnecessary or
///  distracting complications.
///
///  You may think of these subroutines as methods for acquiring data
///  from a "black-box" process. In the first case, the data is always
///  returned in fixed size blocks from a black-box that fills a local
///  buffer with data and always returned the entire buffer when data
///  is requested, e.g., an instrument that measures the concentrations
///  of carbon dioxide, sulfur dioxide, ozone, and other constituents
///  of the air. In the second case, the data is returned in variably
///  sized blocks from a black-box, e.g., an algorithm which integrates
///  a function using polynomials of varying degree; different numbers
///  of coefficients are required for polynomials of differing degrees.
///
///  In examples 2 and 4, we make use of the fictitious subroutines
///
///     GET_FIX_PKTS ( NPKTS, PKTS, REFS, DONE )
///
///  and
///
///     GET_VAR_PKTS ( NPKTS, PKTS, SIZES, REFS, DONE )
///
///  where
///
///     DONE   is a logical flag indicating whether there is more data
///            available. DONE = .TRUE. implies there is no more data.
///            DONE = .FALSE. implies there is more data available;
///
///     NPKTS  is the number of data packets returned in the array
///            PKTS.
///
///     PKTS   is a double precision array containing NPKTS data
///            packets, either fixed size or variable size, and is of
///            an appropriate size to hold all of the data returned.
///            See the description of PKTDAT above for the exact manner
///            in which fixed size packets and variable size packets
///            are stored in an array.
///
///     REFS   is a double precision array which contains NPKTS
///            reference values that will be used to create an index
///            for the data packets in the segment. The values of this
///            variable are always increasing, e.g., the first value of
///            REFS on the second call to GET_FIX_PKTS or GET_VAR_PKTS
///            will be greater than the last value of REFS on the first
///            call to the subroutine.
///
///     SIZES  is an array of integers containing the sizes of each of
///            the variable size data packets that is returned in PKTS.
///
///  These subroutines return arrays containing one or more fixed size
///  data packets and one or more variable size data packets,
///  respectively. We make use of these fictitious subroutines in the
///  examples to avoid adding unnecessary or distracting complications.
///
///  For each example, we provide a simple code fragment that
///  demonstrates the use of the entry points to create generic
///  segments. We assume that all of the relevant variables are defined
///  at the time that the entry points are invoked. These code
///  fragments are for illustrative purposes; they do not necessarily
///  conform to what would be considered good programming practice.
///
///  Example 1-A: Adding fixed size packets one at a time.
///
///     For this example, we make no assumptions about the reference
///     values returned by GET_VAR_PKT other than they are increasing.
///     Having no other information about the reference values, we must
///     use an explicit indexing method to store the packets.
///
///                             .
///                             .
///                             .
///     C
///     C     First we begin a fixed size segment. To do this, we
///     C     need:
///     C
///     C        HANDLE -- The handle of a DAF opened with write
///     C                  access.
///     C        DESCR  -- The packed descriptor for the segment that
///     C                  we want to create.
///     C        SEGID  -- A short character string that provides an
///     C                  identifier for the segment.
///     C        NCONST -- The number of constant values to be
///     C                  associated with all of the packets in the
///     C                  segment.
///     C        CONST  -- An array of constant values to be associated
///     C                  with all of the packets in a segment.
///     C        PKTSIZ -- The size of the packets that will be stored
///     C                  in this segment, i.e., the number of double
///     C                  precision numbers necessary to store a
///     C                  complete data packet.
///     C        EXPCLS -- The type of indexing scheme that we will use
///     C                  for searching the segment to obtain a data
///     C                  packet. In this case, we are going to use an
///     C                  explicit index, which requires a reference
///     C                  value for each data packet, and when
///     C                  searching for a data packet we will choose
///     C                  the packet with a reference value closest to
///     C                  the requested value. See the include file
///     C                  'sgparam.inc' for the value of EXPCLS.
///     C
///           CALL SGBWFS ( HANDLE, DESCR,  SEGID,  NCONST,
///          .              CONST,  PKTSIZ, EXPCLS          )
///     C
///     C     We loop until done, obtaining a fixed size packet
///     C     and writing it to the generic segment in the file.
///     C
///           DONE = .FALSE.
///           DO WHILE ( .NOT. DONE )
///     C
///     C        Get a fixed size packet and a reference value.
///     C
///              CALL GET_FIX_PKT ( PACKET, REF, DONE )
///     C
///     C        Write the packet to the segment, unless we're done.
///     C
///              IF ( .NOT. DONE ) THEN
///
///                 CALL SGWFPK ( HANDLE, 1, PACKET, 1, REF )
///
///              END IF
///
///           END DO
///     C
///     C     End the segment and move on to other things.
///     C
///           CALL SGWES ( HANDLE )
///                             .
///                             .
///                             .
///
///  Example 1-B: Adding fixed size packets with uniformly spaced
///               reference values.
///
///     In the previous example, we made no assumptions about the
///     reference values other than that they were increasing. We now
///     will assume that the reference values are also equally spaced
///     and that we have a priori values for a beginning reference
///     value, BEGIN_REF, and a step size, STEP_SIZE, that is the
///     difference between two consecutive reference values. We have
///
///        BEGIN_REF <= REF <= BEGIN_REF + (N-1) * STEP_SIZE
///
///     where BEGIN_REF equals the first reference value returned by
///     GET_FIX_PKT and BEGIN_REF + (N-1) * STEP_SIZE equals the last
///     reference value returned. Under these assumptions we can use an
///     implicit index for the data packets which will provide a more
///     space efficient method for putting the data packets into a
///     generic segment. We repeat the example under these assumptions
///     using an implicit indexing method. Nothing else has changed.
///
///     The index for a data packet in the implicitly indexed generic
///     segment we create is computed from the formula:
///
///                       /          VALUE - REFDAT(1)    \
///         INDEX = IDINT | 1.5 + ----------------------- |
///                       \              REFDAT(2)        /
///
///     where the index for the data packet associated with VALUE is
///     desired.
///
///     The reference value associated with this index is:
///
///         REF   =  REFDAT(1) + REFDAT*(INDEX - 1)
///
///                             .
///                             .
///                             .
///     C
///     C     First we begin a fixed size segment. To do this, we
///     C     need:
///     C
///     C        HANDLE -- The handle of a DAF opened with write
///     C                  access.
///     C        DESCR  -- The packed descriptor for the segment that
///     C                  we want to create.
///     C        SEGID  -- A short character string that provides an
///     C                  identifier for the segment.
///     C        NCONST -- The number of constant values to be
///     C                  associated with all of the packets in the
///     C                  segment.
///     C        CONST  -- An array of constant values to be associated
///     C                  with all of the packets in a segment.
///     C        PKTSIZ -- The size of the packets that will be stored
///     C                  in this segment, i.e., the number of double
///     C                  precision numbers necessary to store a
///     C                  complete data packet.
///     C        IMPCLS -- The type of indexing scheme that we will use
///     C                  for searching the segment to obtain a data
///     C                  packet. In this case, we are going to use
///     C                  an implicit index, which requires beginning
///     C                  and ending times which bound all reference
///     C                  values, and when searching for a data packet
///     C                  we will choose the packet whose index is
///     C                  computed by the formula above. See the
///     C                  include file 'sgparam.inc' for the value
///     C                  of IMPCLS
///     C
///           CALL SGBWFS ( HANDLE, DESCR,  SEGID,  NCONST,
///          .              CONST,  PKTSIZ, IMPCLS          )
///     C
///     C     Set the beginning and ending reference values for the
///     C     implicit indexing method.
///     C
///           REFS(1) = BEGIN_REF
///           REFS(2) = STEP_SIZE
///     C
///     C     Get the first data packet and put it in the generic
///     C     segment. At the same time, we write the bounds used for
///     C     the implicit indexing. We ignore the value of REF since
///     C     the reference values are equally spaced and we are using
///     C     an implicit indexing method. We do not check DONE here
///     C     because we assume that there is at least one data packet.
///     C
///           CALL GET_FIX_PKT ( PACKET, REF, DONE )
///
///           CALL SGWFPK ( HANDLE, 1, PACKET, 2, REFS )
///     C
///     C     We loop until done, obtaining a fixed size packet
///     C     and writing it to the generic segment in the file.
///     C
///           DO WHILE ( .NOT. DONE )
///     C
///     C        Get a fixed size packet and a reference value.
///     C
///              CALL GET_FIX_PKT ( PACKET, REF, DONE )
///     C
///     C        Write the packet to the segment, unless we're done.
///     C        Because this segment is implicitly indexed, the last
///     C        two calling arguments are only used in the first call
///     C        to SGWFPK above. they are ignored in all subsequent
///     C        calls, so we may pass "dummy" arguments.
///     C
///              IF ( .NOT. DONE ) THEN
///
///                 CALL SGWFPK ( HANDLE, 1, PACKET, DUM1, DUM2 )
///
///              END IF
///
///           END DO
///     C
///     C     End the segment and move on to other things.
///     C
///           CALL SGWES ( HANDLE )
///                             .
///                             .
///                             .
///
///  Example 2: Adding fixed size packets more efficiently.
///
///     It is possible to add more than one fixed size data packet to a
///     generic segment at one time. Doing this will usually prove to
///     be a more efficient way of adding the data packets, provided
///     there is sufficient storage to hold more than one data packet
///     available. This example demonstrates this capability.
///
///     For this example, we make no assumptions about the reference
///     values returned by GET_FIX_PKTS other than they are increasing.
///     Having no other information about the reference values, we must
///     use an explicit indexing method to store the packets.
///
///                             .
///                             .
///                             .
///     C
///     C     First we begin a fixed size segment. To do this, we
///     C     need:
///     C
///     C        HANDLE -- The handle of a DAF opened with write
///     C                  access.
///     C        DESCR  -- The packed descriptor for the segment that
///     C                  we want to create.
///     C        SEGID  -- A short character string that provides an
///     C                  identifier for the segment.
///     C        NCONST -- The number of constant values to be
///     C                  associated with all of the packets in the
///     C                  segment.
///     C        CONST  -- An array of constant values to be associated
///     C                  with all of the packets in a segment.
///     C        PKTSIZ -- The size of the packets that will be stored
///     C                  in this segment, i.e., the number of double
///     C                  precision numbers necessary to store a
///     C                  complete data packet.
///     C        EXPCLS -- The type of indexing scheme that we will use
///     C                  for searching the segment to obtain a data
///     C                  packet. In this case, we are going to use an
///     C                  explicit index, which requires a reference
///     C                  value for each data packet, and when
///     C                  searching for a data packet we will choose
///     C                  the packet with a reference value closest to
///     C                  the requested value. See the include file
///     C                  'sgparam.inc' for the value of EXPCLS
///     C
///           CALL SGBWFS ( HANDLE, DESCR,  SEGID,  NCONST,
///          .              CONST,  PKTSIZ, EXPCLS          )
///     C
///     C     We loop until done, obtaining a fixed size packet
///     C     and writing it to the generic segment in the file.
///     C
///           DONE = .FALSE.
///           DO WHILE ( .NOT. DONE )
///     C
///     C        Get a collection of fixed size packet and associated
///     C        array of increasing reference values.
///     C
///              CALL GET_FIX_PKTS ( NPKTS, PKTS, REFS, DONE )
///     C
///     C        Write the packets to the segment if we have any. Since
///     C        we are using an explicit index, the number of
///     C        reference values is the same as the number of data
///     C        packets.
///     C
///              IF ( .NOT. DONE ) THEN
///
///                 CALL SGWFPK ( HANDLE, NPKTS, PKTS, NPKTS, REFS )
///
///              END IF
///
///           END DO
///     C
///     C     End the segment and move on to other things.
///     C
///           CALL SGWES ( HANDLE )
///                             .
///                             .
///                             .
///
///     If we are using an implicit indexing method, multiple data
///     packets may be added with one call to SGWFPK as in the above
///     example for an explicit index, with the exception that there
///     are only two reference values, and they are specified on the
///     first call to SGWFPK, as in Example 1-B.
///
///  Example 3-A: Adding variable size packets one at a time.
///
///     For this example, we make no assumptions about the reference
///     values returned by GET_VAR_PKT other than they are increasing.
///     Having no other information about the reference values, we must
///     use an explicit indexing method to store the packets.
///
///                             .
///                             .
///                             .
///     C
///     C     First we begin a variable size segment. To do this, we
///     C     need:
///     C
///     C        HANDLE -- The handle of a DAF opened with write
///     C                  access.
///     C        DESCR  -- The packed descriptor for the segment that
///     C                  we want to create.
///     C        SEGID  -- A short character string that provides an
///     C                  identifier for the segment.
///     C        NCONST -- The number of constant values to be
///     C                  associated with all of the packets in the
///     C                  segment.
///     C        CONST  -- An array of constant values to be associated
///     C                  with all of the packets in a segment.
///     C        EXPCLS -- The type of indexing scheme that we will use
///     C                  for searching the segment to obtain a data
///     C                  packet. In this case, we are going to use an
///     C                  explicit index, which requires a reference
///     C                  value for each data packet, and when
///     C                  searching for a data packet we will choose
///     C                  the packet with a reference value closest to
///     C                  the requested value. See the include file
///     C                  'sgparam.inc' for the value of EXPCLS.
///     C
///           CALL SGBVFS ( HANDLE, DESCR, SEGID,
///          .              NCONST, CONST, EXPCLS )
///     C
///     C     We loop until done, obtaining a variable size packet
///     C     and writing it to the generic segment in the file.
///     C
///           DONE = .FALSE.
///           DO WHILE ( .NOT. DONE )
///     C
///     C        Get a variable size packet and a reference value.
///     C
///              CALL GET_VAR_PKT ( PACKET, SIZE, REF, DONE )
///     C
///     C        Write the packet to the segment, unless we're done.
///     C
///              IF ( .NOT. DONE ) THEN
///
///                 CALL SGWVPK ( HANDLE, 1, SIZE, PACKET, 1, REF )
///
///              END IF
///
///           END DO
///     C
///     C     End the segment and move on to other things.
///     C
///           CALL SGWES ( HANDLE )
///                             .
///                             .
///                             .
///
///  Example 3-B: Adding variable size packets one at a time with
///               uniformly spaced reference values.
///
///     In the previous example, we made no assumptions about the
///     reference values other than that they were increasing. We now
///     will assume that the reference values are also equally spaced
///     and that we have a priori values for a beginning reference
///     value, BEGIN_REF, and a step size, STEP_SIZE, that is the
///     difference between two consecutive reference values. We have
///
///        BEGIN_REF <= REF <= BEGIN_REF + (N-1) * STEP_SIZE
///
///     where BEGIN_REF equals the first reference value returned by
///     GET_VAR_PKT and BEGIN_REF + (N-1) * STEP_SIZE equals the last
///     reference value returned. Putting all of this together means
///     that we can use an implicit index for the data packets which
///     will provide a more space efficient method for putting the data
///     packets into a generic segment. We repeat the example under
///     these assumptions using an implicit indexing method. Nothing
///     else has changed.
///
///     The index for a data packet in the implicitly indexed generic
///     segment we create is computed from the formula:
///
///                       /          VALUE - REFDAT(1)    \
///         INDEX = IDINT | 1.5 + ----------------------- |
///                       \              REFDAT(2)        /
///
///     where the index for the data packet associated with VALUE is
///     desired.
///
///     The reference value associated with this index is:
///
///         REF   =  REFDAT(1) + REFDAT*(INDEX - 1)
///
///                             .
///                             .
///                             .
///     C
///     C     First we begin a variable size segment. To do this, we
///     C     need:
///     C
///     C        HANDLE -- The handle of a DAF opened with write
///     C                  access.
///     C        DESCR  -- The packed descriptor for the segment that
///     C                  we want to create.
///     C        SEGID  -- A short character string that provides an
///     C                  identifier for the segment.
///     C        NCONST -- The number of constant values to be
///     C                  associated with all of the packets in the
///     C                  segment.
///     C        CONST  -- An array of constant values to be associated
///     C                  with all of the packets in a segment.
///     C        IMPCLS -- The type of indexing scheme that we will use
///     C                  for searching the segment to obtain a data
///     C                  packet. In this case, we are going to use
///     C                  an implicit index, which requires beginning
///     C                  and ending times which bound all reference
///     C                  values, and when searching for a data packet
///     C                  we will choose the packet whose index is
///     C                  computed by the formula above. See the
///     C                  include file 'sgparam.inc' for the value of
///     C                  IMPCLS.
///     C
///           CALL SGBWVS ( HANDLE, DESCR,  SEGID,  NCONST,
///          .              CONST,  IMPCLS                   )
///     C
///     C     Set the beginning and ending reference values for the
///     C     implicit indexing method.
///     C
///           REFS(1) = BEGIN_REF
///           REFS(2) = STEP_SIZE
///     C
///     C     Get the first data packet and put it in the generic
///     C     segment. At the same time, we write the bounds used for
///     C     the implicit indexing. We ignore the value of REF since
///     C     the reference values are equally spaced and we are using
///     C     an implicit indexing method. We do not check DONE here
///     C     because we assume that there is at least one data packet.
///     C
///           CALL GET_VAR_PKT ( PACKET, SIZE, REF, DONE )
///
///           CALL SGWVPK ( HANDLE, 1, SIZE, PACKET, 2, REFS )
///     C
///     C     We loop until done, obtaining a fixed size packet
///     C     and writing it to the generic segment in the file.
///     C
///           DO WHILE ( .NOT. DONE )
///     C
///     C        Get a variable size packet and a unique reference
///     C        value.
///     C
///              CALL GET_VAR_PKT ( PACKET, SIZE, REF, DONE )
///     C
///     C        Write the packet to the segment, unless we're done.
///     C        Because this segment is implicitly indexed, the last
///     C        two calling arguments are only used in the first call
///     C        to SGWFPK above. they are ignored in all subsequent
///     C        calls, so we may pass "dummy" arguments.
///     C
///              IF ( .NOT. DONE ) THEN
///
///                 CALL SGVFPK ( HANDLE, 1, SIZE, PACKET, DUM1, DUM2 )
///
///              END IF
///
///           END DO
///     C
///     C     End the segment and move on to other things.
///     C
///           CALL SGWES ( HANDLE )
///                             .
///                             .
///                             .
///
///  Example 4: Adding variable size packets more efficiently.
///
///     It is possible to add more than one variable size data packet
///     to a generic segment at one time. Doing this will usually prove
///     to be a more efficient way of adding the data packets, provided
///     there is sufficient storage to hold more than one data packet
///     available. This example demonstrates this capability.
///
///     For this example, we make no assumptions about the reference
///     values returned by GET_VAR_PKTS other than they are increasing.
///     Having no other information about the reference values, we must
///     use an explicit indexing method to store the packets.
///
///                             .
///                             .
///                             .
///     C
///     C     First we begin a variable size segment. To do this, we
///     C     need:
///     C
///     C        HANDLE -- The handle of a DAF opened with write
///     C                  access.
///     C        DESCR  -- The packed descriptor for the segment that
///     C                  we want to create.
///     C        SEGID  -- A short character string that provides an
///     C                  identifier for the segment.
///     C        NCONST -- The number of constant values to be
///     C                  associated with all of the packets in the
///     C                  segment.
///     C        CONST  -- An array of constant values to be associated
///     C                  with all of the packets in a segment.
///     C        EXPCLS -- The type of indexing scheme that we will use
///     C                  for searching the segment to obtain a data
///     C                  packet. In this case, we are going to use an
///     C                  explicit index, which requires a reference
///     C                  value for each data packet, and when
///     C                  searching for a data packet we will choose
///     C                  the packet with a reference value closest to
///     C                  the requested value. See the include file
///     C                  sgparam.inc for the value of EXPCLS.
///     C
///           CALL SGBWVS ( HANDLE, DESCR,  SEGID,
///     C    .              NCONST, CONST, EXPCLS  )
///     C
///     C     We loop until done, obtaining a fixed size packet
///     C     and writing it to the generic segment in the file.
///     C
///           DONE = .FALSE.
///           DO WHILE ( .NOT. DONE )
///     C
///     C        Get a collection of variable size packets and an
///     C        array of increasing reference values.
///     C
///              GET_VAR_PKTS ( NPKTS, PKTS, SIZES, REFS, DONE )
///     C
///     C        Write the packets to the segment if we have any. Since
///     C        we are using an explicit index, the number of
///     C        reference values is the same as the number of data
///     C        packets.
///     C
///              IF ( NPKTS .GT. 0 ) THEN
///
///                 CALL SGWVPK ( HANDLE, NPKTS, SIZES,
///          .                    PKTS,   NPKTS, REFS   )
///
///              END IF
///
///           END DO
///     C
///     C     End the segment and move on to other things.
///     C
///           CALL SGWES ( HANDLE )
///                             .
///                             .
///                             .
///
///     If we are using an implicit indexing method, multiple data
///     packets may be added with one call to SGWVPK as in the above
///     example for an explicit index, with the exception that there
///     are only two reference values, and they are specified on the
///     first call to SGWVPK, as in Example 3-B.
///
///  Example 5: Adding packets to multiple files.
///
///     It is possible to write multiple generic segments to different
///     DAFs at the same time. Only one generic segment may be written
///     to a particular DAF at any given time, however.
///
///     For this example we assume that we have previously opened four
///     DAF files, having the handles HANDL1, HANDL2, HANDL3, HANDL4.
///     We will be writing fixed size data packets to the DAFs
///     associated with handles HANDL2 and HANDL3, with packet sizes of
///     21 and 53, respectively. We will be writing variable size data
///     packets to the DAFs associated with handles HANDL1 and HANDL4.
///     We will be writing individual data packets to the files
///     associated with handles HANDL2 and HANDL4, and one or more data
///     packets to the files associated with handles HANDL1 and HANDL3.
///     On each trip through the loop in the example below, we will add
///     data to any of the segments whose status flags are not set. We
///     are done with the loop below when we have finished each of the
///     segments, as indicated by its status flag.
///
///     For this example, we make no assumptions about the reference
///     values returned by the GET_*_* subroutines other than they are
///     increasing. Having no other information about the reference
///     values, we must use an explicit indexing method to store the
///     packets.
///
///                             .
///                             .
///                             .
///     C
///     C     First we begin a generic segment of the appropriate type
///     C     in each of the files. segment. To do this, we need:
///     C
///     C        HANDL1, HANDL2, HANDL3, HANDL4 --
///     C
///     C           The handles of a DAFs opened with write access to
///     C           which we wish to add a new generic segment.
///     C
///     C        DESCR1, DESCR2, DESCR3, DESCR4  --
///     C
///     C           The packed descriptors for the segments that
///     C           we want to create.
///     C
///     C        SEGID1, SEGID2, SEGID3, SEGID4 --
///     C
///     C           A short character string that provides an
///     C           identifier for each of the segments we will be
///     C           creating.
///     C
///     C        NCON1, NCON2, NCON3, NCON4 --
///     C
///     C           The number of constant values to be associated with
///     C           all of the packets in each the segments we will be
///     C           creating.
///     C
///     C
///     C        CONST1, CONST2, CONST3, CONST4 --
///     C
///     C           An array of constant values to be associated with
///     C           all of the packets in each of the segments that we
///     C           are creating.
///     C
///     C        IDXT1, IDXT2, IDXT3, IDXT4 --
///     C
///     C          The type of indexing scheme that we will use for
///     C          searching each of the segments to obtain a data
///     C          packet. In this example, each of the generic
///     C          segments will use an explicit index, which requires
///     C          a reference value for each data packet. When
///     C          searching for a data packet we will choose the
///     C          packet with a reference value closest to the
///     C          requested value.
///     C
///     C            IDXT1 = EXPCLS
///     C            IDXT2 = EXPCLS
///     C            IDXT3 = EXPCLS
///     C            IDXT4 = EXPCLS
///     C
///           CALL SGBWVS ( HANDL1, DESCR1, SEGID1,
///          .              NCON1,  CONST1, IDXT1   )
///           CALL SGBWFS ( HANDL2, DESCR2, SEGID2, 21,
///          .              NCON2,  CONST2, IDXT2   )
///           CALL SGBWFS ( HANDL3, DESCR3, SEGID3, 53,
///          .              NCON3,  CONST3, IDXT3   )
///           CALL SGBWVS ( HANDL4, DESCR4, SEGID4,
///          .              NCON4,  CONST4, IDXT4   )
///     C
///     C     We loop until done, obtaining data packets and writing
///     C     them to the generic segments in the appropriate DAFs.
///     C
///     C     We keep track of a status flag, DONE1, DONE2, DONE3,
///     C     DONE4, for each of the segments we are writing. When we
///     C     have finished writing all of the segments, we exit the
///     C     loop.
///     C
///           DONE  = .FALSE.
///           DONE1 = .FALSE.
///           DONE2 = .FALSE.
///           DONE3 = .FALSE.
///           DONE4 = .FALSE.
///
///           DO WHILE ( .NOT. DONE )
///     C
///     C        Get data packets and reference values for HANDL1 and
///     C        write them to the generic segment in that file.
///     C
///              IF ( .NOT. DONE1 ) THEN
///                 GET_VAR_PKTS ( NPKTS, PKTS, SIZES, REFS, DONE1 )
///
///                 IF ( NPKTS .GT. 0 ) THEN
///                    CALL SGWVPK ( HANDL1, NPKTS, SIZES,
///          .                       PKTS,   NPKTS, REFS   )
///                 END IF
///              END IF
///     C
///     C        Get a data packet and reference value for HANDL2 and
///     C        write it to the generic segment in that file.
///     C
///              IF ( .NOT. DONE2 ) THEN
///                 CALL GET_FIX_PKT ( PACKET, REF, DONE2 )
///
///                 IF ( .NOT. DONE2 ) THEN
///                    CALL SGWFPK ( HANDL2, 1, PACKET, 1, REF )
///                 END IF
///              END IF
///     C
///     C        Get data packets and reference values for HANDL3 and
///     C        write them to the generic segment in that file.
///     C
///              IF ( .NOT. DONE3 ) THEN
///                 CALL GET_FIX_PKTS ( NPKTS, PKTS, REFS, DONE3 )
///
///                 IF ( NPKTS .GT. 0 ) THEN
///                    CALL SGWFPK ( HANDL3, NPKTS, PKTS, NPKTS, REFS )
///                 END IF
///              END IF
///     C
///     C        Get a data packet and reference value for HANDL4 and
///     C        write it to the generic segment in that file.
///     C
///              IF ( .NOT. DONE4 ) THEN
///                 GET_VAR_PKT ( PACKET, SIZE, REF, DONE4 )
///
///                 IF ( .NOT. DONE4 ) THEN
///                    CALL SGWVPK ( HANDL4, 1, SIZES, PKTS, 1, REFS )
///                 END IF
///              END IF
///     C
///     C        Set the DONE flag.
///     C
///              DONE = DONE1 .AND. DONE2 .AND. DONE3 .AND. DONE4
///
///           END DO
///     C
///     C     End the segments and move on to other things.
///     C
///           CALL SGWES ( HANDL1 )
///           CALL SGWES ( HANDL2 )
///           CALL SGWES ( HANDL3 )
///           CALL SGWES ( HANDL4 )
///                             .
///                             .
///                             .
/// ```
///
/// # Restrictions
///
/// ```text
///  1)  See the individual entry points for any restrictions they may
///      have.
/// ```
///
/// # Author and Institution
///
/// ```text
///  N.J. Bachman       (JPL)
///  J. Diaz del Rio    (ODC Space)
///  K.R. Gehringer     (JPL)
///  W.L. Taber         (JPL)
///  E.D. Wright        (JPL)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 1.2.1, 27-OCT-2021 (JDR)
///
///         Edited the header to comply with NAIF standard.
///
/// -    SPICELIB Version 1.2.0, 07-SEP-2001 (EDW)
///
///         Replaced DAFRDA calls with DAFGDA.
///         Removed DAFHLU calls; replaced ERRFN calls with ERRHAN.
///
/// -    SPICELIB Version 1.1.0, 30-JUL-1996 (KRG) (NJB)
///
///         Fixed an annoying little bug in the variable segments code
///         when ending a segment. Rather than storing an appropriate
///         offset from the beginning of the segment as the packet
///         address in the packet directory, the absolute address, the
///         DAF address, was stored. This bug has been fixed.
///
///         See SGWES for the details of the changes.
///
/// -    SPICELIB Version 1.0.0, 03-APR-1995 (KRG) (WLT)
/// ```
pub fn sgseqw(
    ctx: &mut SpiceContext,
    handle: i32,
    descr: &[f64],
    segid: &str,
    nconst: i32,
    const_: &[f64],
    npkts: i32,
    pktsiz: &[i32],
    pktdat: &[f64],
    nrefs: i32,
    refdat: &[f64],
    idxtyp: i32,
) -> crate::Result<()> {
    SGSEQW(
        handle,
        descr,
        segid.as_bytes(),
        nconst,
        const_,
        npkts,
        pktsiz,
        pktdat,
        nrefs,
        refdat,
        idxtyp,
        ctx.raw_context(),
    )?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SGSEQW ( Generic segments: Sequential writer. )
pub fn SGSEQW(
    HANDLE: i32,
    DESCR: &[f64],
    SEGID: &[u8],
    NCONST: i32,
    CONST: &[f64],
    NPKTS: i32,
    PKTSIZ: &[i32],
    PKTDAT: &[f64],
    NREFS: i32,
    REFDAT: &[f64],
    IDXTYP: i32,
    ctx: &mut Context,
) -> f2rust_std::Result<()> {
    //
    // SPICELIB Functions
    //

    //
    // Local parameters
    //
    // FPRINT is the integer value of the first printable ASCII
    // character.
    //
    // LPRINT is the integer value of the last printable ASCII character.
    //

    //
    // The number of reference values it takes to get a reference
    // directory value.
    //
    //
    // The length of a DAF internal filename.
    //
    //
    // The file table size. This needs to be the same as the file table
    // size in DAFAH.
    //
    //
    // Include the mnemonic values for the generic segment declarations
    // and the meta data information.
    //

    //
    // Local variables
    //
    // Variables with the name DUMMY* are used as place holders when
    // calling various subroutines. Their values are not used in any of
    // the entry points of this subroutine.
    //

    //
    // File table declarations. The file table is used to keep track of
    // the vital statistics for each of the generic segments being
    // written.
    //

    //
    // Saved values.
    //
    //
    // Save the file table.
    //
    //
    // Initial values
    //
    //
    // Standard SPICE error handling.
    //
    if RETURN(ctx) {
        return Ok(());
    }
    //
    // Signal an error if this routine is called directly.
    //
    CHKIN(b"SGSEQW", ctx)?;
    SETMSG(b"This routine should never be called directly. It exists as an umbrella routine to maintain all of the variables for the generic segment sequential writing entry points.", ctx);
    SIGERR(b"SPICE(BOGUSENTRY)", ctx)?;
    CHKOUT(b"SGSEQW", ctx)?;
    Ok(())
}

/// Generic segments: Begin a fixed size segment.
///
/// Begin writing a generic segment that will contain fixed size data
/// packets.
///
/// # Required Reading
///
/// * [DAF](crate::required_reading::daf)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  DESCRIPTION
///  --------  ---  --------------------------------------------------
///  HANDLE    I    Handle of a DAF file opened with write access.
///  DESCR     I    Descriptor for a generic segment.
///  SEGID     I    Identifier for a generic segment.
///  NCONST    I    Number of constant values in a generic segment.
///  CONST     I    Array of constant values for a generic segment.
///  PKTSIZ    I    Size of the data packets.
///  IDXTYP    I    Index type for the reference values.
/// ```
///
/// # Detailed Input
///
/// ```text
///  HANDLE   is the handle of a DAF file opened with write access.
///           This is the handle of the file in which a generic segment
///           will be written.
///
///  DESCR    is the descriptor for a segment that is being written.
///           This is the packed form of the DAF double precision and
///           integer summaries which contain ND double precision
///           numbers and NI integers.
///
///  SEGID    is an identifier for a segment that is being written.
///           This is a character string containing at most NC printing
///           ASCII characters where
///
///                             /  ND + ( NI + 1 )  \
///                  NC =  8 *  | ----------------- |
///                             \         2         /
///
///            SEGID may be blank.
///
///  NCONST   is the number of constant values to be placed in a
///           segment.
///
///  CONST    is an array of NCONST constant values for a segment.
///
///  PKTSIZ   is the size of fixed size packets. The size of a packet
///           is the number of double precision numbers contained in
///           the data packet.
///
///  IDXTYP   is the index type to use for the reference values.
///
///           Two forms of indexing are provided:
///
///              1) An implicit form of indexing based on using two
///                 values, a starting value, which will have an index
///                 of 1, and a step size between reference values,
///                 which are used to compute an index and a reference
///                 value associated with a specified key value. See
///                 the descriptions of the implicit types below for
///                 the particular formula used in each case.
///
///              2) An explicit form of indexing based on a reference
///                 value for each data packet.
///
///           See the chapter on generic segments in the DAF required
///           or the include file 'sgparam.inc' for more details
///           about the index types that are available.
/// ```
///
/// # Parameters
///
/// ```text
///  This subroutine makes use of parameters defined in the file
///  'sgparam.inc'.
/// ```
///
/// # Exceptions
///
/// ```text
///  1)  If this routine is called more than once for a particular file
///      and segment, the error SPICE(CALLEDOUTOFORDER) is signaled.
///
///  2)  If the length of the segment identifier, SEGID, is greater
///      than NC, as determined from the ND and NI values for a
///      particular DAF file, the error SPICE(SEGIDTOOLONG) is
///      signaled.
///
///  3)  If the segment identifier contains nonprinting characters, the
///      error SPICE(NONPRINTINGCHARS) is signaled.
///
///  4)  If the number of constant values, NCONST, is negative, the
///      error SPICE(NUMCONSTANTSNEG) is signaled.
///
///  5)  If the packet size, PKTSIZ, is not positive, the error
///      SPICE(NONPOSPACKETSIZE) is signaled.
///
///  6)  If the index type for the reference values is not recognized,
///      the error SPICE(UNKNOWNINDEXTYPE) is signaled.
///
///  7)  If the file table is full, the error SPICE(FILETABLEFULL) is
///      signaled.
/// ```
///
/// # Files
///
/// ```text
///  See HANDLE in the $Detailed_Input section.
/// ```
///
/// # Particulars
///
/// ```text
///  Begin writing a generic segment for fixed size data packets to
///  the DAF file associated with HANDLE.
/// ```
///
/// # Examples
///
/// ```text
///  See the $Examples section in the header for the main subroutine.
///  It contains examples which demonstrate the use of the entry points
///  in the generic segments sequential writer. The entry points which
///  comprise the generic segments sequential writer must be used
///  together in the proper manner. Rather than repeating the examples
///  for each entry point they are provided in a single location.
/// ```
///
/// # Author and Institution
///
/// ```text
///  J. Diaz del Rio    (ODC Space)
///  K.R. Gehringer     (JPL)
///  W.L. Taber         (JPL)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 1.0.1, 03-JUN-2021 (JDR)
///
///         Edited the header to comply with NAIF standard.
///
/// -    SPICELIB Version 1.0.0, 05-APR-1995 (KRG) (WLT)
/// ```
pub fn sgbwfs(
    ctx: &mut SpiceContext,
    handle: i32,
    descr: &[f64],
    segid: &str,
    nconst: i32,
    const_: &[f64],
    pktsiz: &[i32],
    idxtyp: i32,
) -> crate::Result<()> {
    SGBWFS(
        handle,
        descr,
        segid.as_bytes(),
        nconst,
        const_,
        pktsiz,
        idxtyp,
        ctx.raw_context(),
    )?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SGBWFS ( Generic segments: Begin a fixed size segment. )
pub fn SGBWFS(
    HANDLE: i32,
    DESCR: &[f64],
    SEGID: &[u8],
    NCONST: i32,
    CONST: &[f64],
    PKTSIZ: &[i32],
    IDXTYP: i32,
    ctx: &mut Context,
) -> f2rust_std::Result<()> {
    let save = ctx.get_vars::<SaveVars>();
    let save = &mut *save.borrow_mut();

    let DESCR = DummyArray::new(DESCR, 1..);
    let CONST = DummyArray::new(CONST, 1..);
    let PKTSIZ = DummyArray::new(PKTSIZ, 1..);
    let mut DUMMY1 = [b' '; IFNLEN as usize];
    let mut BEGADR: i32 = 0;
    let mut DUMMY2: i32 = 0;
    let mut DUMMY3: i32 = 0;
    let mut ICH: i32 = 0;
    let mut NC: i32 = 0;
    let mut ND: i32 = 0;
    let mut NI: i32 = 0;
    let mut SIDLEN: i32 = 0;

    //
    // SPICELIB functions
    //
    // INTEGER               LASTNB
    // INTEGER               ISRCHI
    //
    // LOGICAL               FAILED
    // LOGICAL               RETURN
    //
    //
    // Standard SPICE error handling.
    //
    if RETURN(ctx) {
        return Ok(());
    }

    CHKIN(b"SGBWFS", ctx)?;
    //
    // We need to do some sanity checks on our input arguments before we
    // should attempt to write anything to the file. So, let's start with
    // that.
    //
    // Check to see if the file attached to the handle is open for
    // writing. If not, an error is signaled.
    //
    DAFSIH(HANDLE, b"WRITE", ctx)?;

    if FAILED(ctx) {
        CHKOUT(b"SGBWFS", ctx)?;
        return Ok(());
    }
    //
    // Check to see if the handle is currently in the file table. If it
    // is, we've got a problem. This routine may only be called once for
    // each segment that is to contain fixed size packets, and it places
    // a handle in the file table. If the handle is currently in the
    // file table a segment has already been started by this routine or
    // SGBWVS. In either case, we cannot continue, so we signal an error.
    //
    if (save.NFT > 0) {
        save.INDEX = ISRCHI(HANDLE, save.NFT, save.FTHAN.as_slice());

        if (save.INDEX != 0) {
            SETMSG(b"A segment is already being written to the file \'#\'. A new segment cannot be started for this file until the current segment is finished. ", ctx);
            ERRHAN(b"#", HANDLE, ctx)?;
            SIGERR(b"SPICE(CALLEDOUTOFORDER)", ctx)?;
            CHKOUT(b"SGBWFS", ctx)?;
            return Ok(());
        }
    }
    //
    // Get the ND and NI values from the DAF file. We need these to know
    // the size of the descriptor and the length of the segment ID. The
    // length of the segment ID is determined by the following formula
    // using integer division:
    //
    //                             /  ND + ( NI + 1 )  \
    //                  NC =  8 *  | ----------------- |
    //                             \         2         /
    //
    DAFHSF(HANDLE, &mut ND, &mut NI, ctx)?;

    if FAILED(ctx) {
        CHKOUT(b"SGBWFS", ctx)?;
        return Ok(());
    }

    NC = (8 * (ND + ((NI + 1) / 2)));
    //
    // Get the length of the segment ID. Leading blanks are considered to
    // be important. A blank segment ID is OK too.
    //
    SIDLEN = LASTNB(SEGID);
    //
    // Check the segment ID to see if it is OK. Its length must be less
    // than NC and it must consist of only printing ASCII characters.
    //
    if (SIDLEN > NC) {
        SETMSG(b"Segment identifier contains more than # characters.", ctx);
        ERRINT(b"#", NC, ctx);
        SIGERR(b"SPICE(SEGIDTOOLONG)", ctx)?;
        CHKOUT(b"SGBWFS", ctx)?;
        return Ok(());
    }

    for I in 1..=SIDLEN {
        ICH = intrinsics::ICHAR(fstr::substr(SEGID, I..=I));

        if ((ICH < FPRINT) || (ICH > LPRINT)) {
            SETMSG(
                b"The segment identifier contains  a nonprinting character at location #.",
                ctx,
            );
            ERRINT(b"#", I, ctx);
            SIGERR(b"SPICE(NONPRINTINGCHARS)", ctx)?;
            CHKOUT(b"SGBWFS", ctx)?;
            return Ok(());
        }
    }
    //
    // Check to see if the number of constants is negative. This is all
    // we can do here, we cannot check the constant values.
    //
    if (NCONST < 0) {
        SETMSG(b"The number of constants specified was #. This number must be non-negative. Perhaps the variable was not properlyinitialized. ", ctx);
        ERRINT(b"#", NCONST, ctx);
        SIGERR(b"SPICE(NUMCONSTANTSNEG) ", ctx)?;
        CHKOUT(b"SGBWFS", ctx)?;
        return Ok(());
    }
    //
    // Check to see that the packet size is OK. It should be positive.
    //
    if (PKTSIZ[1] <= 0) {
        SETMSG(b"The size of the data packets must be positive. It was specified as #. Perhaps the input variable was not properly initialized. ", ctx);
        ERRINT(b"#", *PKTSIZ.first(), ctx);
        SIGERR(b"SPICE(NONPOSPACKETSIZE)", ctx)?;
        CHKOUT(b"SGBWFS", ctx)?;
        return Ok(());
    }
    //
    // Check to see if the index type is one that we recognize.
    //
    if ((IDXTYP < MNIDXT) || (IDXTYP > MXIDXT)) {
        SETMSG(b"The index type specified was #.  This is not a valid index type. Valid types are in the range from # to #.", ctx);
        ERRINT(b"#", IDXTYP, ctx);
        ERRINT(b"#", MNIDXT, ctx);
        ERRINT(b"#", MXIDXT, ctx);
        SIGERR(b"SPICE(UNKNOWNINDEXTYPE)", ctx)?;
        CHKOUT(b"SGBWFS", ctx)?;
        return Ok(());
    }
    //
    // Check to see whether we still have room in the file table.
    //
    if (save.NFT == FTSIZE) {
        SETMSG(b"There are already # files being written by generic segment writing routines. No more files may be written by the generic segment writers until one of those currently being written is closed via a call to SGWES.", ctx);
        ERRINT(b"#", save.NFT, ctx);
        SIGERR(b"SPICE(FILETABLEFULL)", ctx)?;
        CHKOUT(b"SGBWFS", ctx)?;
        return Ok(());
    }
    //
    // Set the flag which indicate whether this index type is an
    // explicit type or an implicit type.
    //
    save.EXPLCT = (((IDXTYP == EXPLT) || (IDXTYP == EXPLE)) || (IDXTYP == EXPCLS));
    //
    // At this point, we know that the input data is OK, in so far as we
    // can validate it, and we have room in the file table. So we proceed
    // with starting a segment for fixed size packets.
    //
    // Set the flag that indicate that this segment is a fixed size
    // segment.
    //
    save.FXDSEG = true;
    //
    // Get the address for the beginning of the array that we are going
    // to create. We have to get this by reading the file record.
    //
    DAFRFR(
        HANDLE,
        &mut ND,
        &mut NI,
        &mut DUMMY1,
        &mut DUMMY2,
        &mut DUMMY3,
        &mut BEGADR,
        ctx,
    )?;
    //
    // Begin a new segment in the DAF file.
    //
    DAFBNA(HANDLE, DESCR.as_slice(), SEGID, ctx)?;

    if FAILED(ctx) {
        CHKOUT(b"SGBWFS", ctx)?;
        return Ok(());
    }
    //
    // Write out the constants to the new segment, if there are any
    // constants.
    //
    if (NCONST > 0) {
        DAFADA(CONST.as_slice(), NCONST, ctx)?;

        if FAILED(ctx) {
            CHKOUT(b"SGBWFS", ctx)?;
            return Ok(());
        }
    }
    //
    // Store the information for this file and segment in the file table.
    //
    save.NFT = (save.NFT + 1);

    save.FTITYP[save.NFT] = IDXTYP;
    save.FTPKSZ[save.NFT] = PKTSIZ[1];
    save.FTMXSZ[save.NFT] = 0;

    save.FTNCON[save.NFT] = NCONST;
    save.FTNPKT[save.NFT] = 0;
    save.FTNREF[save.NFT] = 0;
    save.FTNRES[save.NFT] = 0;

    save.FTEXPL[save.NFT] = save.EXPLCT;

    save.FTFIXD[save.NFT] = save.FXDSEG;

    save.FTHAN[save.NFT] = HANDLE;
    save.FTBADR[save.NFT] = BEGADR;

    save.FTREFS[[1, save.NFT]] = 0.0;
    save.FTREFS[[2, save.NFT]] = 0.0;

    if save.EXPLCT {
        save.FTOFF[save.NFT] = 1;
    } else {
        save.FTOFF[save.NFT] = 0;
    }

    save.LSTHAN = HANDLE;
    save.INDEX = save.NFT;
    save.NUMFXD = (save.NUMFXD + 1);

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

/// Generic segments: Begin a variable size segment.
///
/// Begin writing a generic segment that will contain variable size
/// data packets.
///
/// # Required Reading
///
/// * [DAF](crate::required_reading::daf)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  DESCRIPTION
///  --------  ---  --------------------------------------------------
///  HANDLE    I    Handle of a DAF file opened with write access.
///  DESCR     I    Descriptor for a segment.
///  SEGID     I    Identifier for a segment.
///  NCONST    I    Number of constant values in a segment.
///  CONST     I    Array of constant values for a segment.
///  IDXTYP    I    Index type for the reference values.
/// ```
///
/// # Detailed Input
///
/// ```text
///  HANDLE   is the handle of a DAF file opened with write access.
///           This is the handle of the file in which a generic segment
///           will be written.
///
///  DESCR    is the descriptor for a segment that is being written.
///           This is the packed form of the DAF double precision and
///           integer summaries which contain ND double precision
///           numbers and NI integers.
///
///  SEGID    is an identifier for a segment that is being written.
///           This is a character string containing at most NC printing
///           ASCII characters where
///
///                             /  ND + ( NI + 1 )  \
///                  NC =  8 *  | ----------------- |
///                             \         2         /
///
///            SEGID may be blank.
///
///  NCONST   is the number of constant values to be placed in a
///           segment.
///
///  CONST    is an array of NCONST constant values for a segment.
///
///  IDXTYP   is the index type to use for the reference values.
///
///           Two forms of indexing are provided:
///
///              1) An implicit form of indexing based on using two
///                 values, a starting value, which will have an index
///                 of 1, and a step size between reference values,
///                 which are used to compute an index and a reference
///                 value associated with a specified key value. See
///                 the descriptions of the implicit types below for
///                 the particular formula used in each case.
///
///              2) An explicit form of indexing based on a reference
///                 value for each data packet.
///
///           See the chapter on generic segments in the DAF required
///           or the include file 'sgparam.inc' for more details
///           about the index types that are available.
/// ```
///
/// # Parameters
///
/// ```text
///  This subroutine makes use of parameters defined in the file
///  'sgparam.inc'.
/// ```
///
/// # Exceptions
///
/// ```text
///  1)  If this routine is called more than once for a particular file
///      and segment, the error SPICE(CALLEDOUTOFORDER) is signaled.
///
///  2)  If the length of the segment identifier, SEGID, is greater
///      than NC, as determined from the ND and NI values for a
///      particular DAF file, the error SPICE(SEGIDTOOLONG) is
///      signaled.
///
///  3)  If the segment identifier contains nonprinting characters, the
///      error SPICE(NONPRINTINGCHARS) is signaled.
///
///  4)  If the number of constant values, NCONST, is negative, the
///      error SPICE(NUMCONSTANTSNEG) is signaled.
///
///  5)  If the index type for the reference values is not recognized,
///      the error SPICE(UNKNOWNINDEXTYPE) is signaled.
///
///  6)  If the file table is full, the error SPICE(FILETABLEFULL) is
///      signaled.
/// ```
///
/// # Files
///
/// ```text
///  See HANDLE in the $Detailed_Input section.
/// ```
///
/// # Particulars
///
/// ```text
///  Begin writing a generic segment for variable size data packets to
///  the DAF file associated with HANDLE.
/// ```
///
/// # Examples
///
/// ```text
///  See the $Examples section in the header for the main subroutine.
///  It contains examples which demonstrate the use of the entry points
///  in the generic segments sequential writer. The entry points which
///  comprise the generic segments sequential writer must be used
///  together in the proper manner. Rather than repeating the examples
///  for each entry point they are provided in a single location.
/// ```
///
/// # Author and Institution
///
/// ```text
///  J. Diaz del Rio    (ODC Space)
///  K.R. Gehringer     (JPL)
///  W.L. Taber         (JPL)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 1.0.1, 03-JUN-2021 (JDR)
///
///         Edited the header to comply with NAIF standard.
///
/// -    SPICELIB Version 1.0.0, 05-APR-1995 (KRG) (WLT)
/// ```
pub fn sgbwvs(
    ctx: &mut SpiceContext,
    handle: i32,
    descr: &[f64],
    segid: &str,
    nconst: i32,
    const_: &[f64],
    idxtyp: i32,
) -> crate::Result<()> {
    SGBWVS(
        handle,
        descr,
        segid.as_bytes(),
        nconst,
        const_,
        idxtyp,
        ctx.raw_context(),
    )?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SGBWVS ( Generic segments: Begin a variable size segment. )
pub fn SGBWVS(
    HANDLE: i32,
    DESCR: &[f64],
    SEGID: &[u8],
    NCONST: i32,
    CONST: &[f64],
    IDXTYP: i32,
    ctx: &mut Context,
) -> f2rust_std::Result<()> {
    let save = ctx.get_vars::<SaveVars>();
    let save = &mut *save.borrow_mut();

    let DESCR = DummyArray::new(DESCR, 1..);
    let CONST = DummyArray::new(CONST, 1..);
    let mut DUMMY1 = [b' '; IFNLEN as usize];
    let mut BEGADR: i32 = 0;
    let mut DUMMY2: i32 = 0;
    let mut DUMMY3: i32 = 0;
    let mut ICH: i32 = 0;
    let mut NC: i32 = 0;
    let mut ND: i32 = 0;
    let mut NI: i32 = 0;
    let mut SIDLEN: i32 = 0;

    //
    // SPICELIB functions
    //
    // INTEGER               LASTNB
    // INTEGER               ISRCHI
    //
    // LOGICAL               FAILED
    // LOGICAL               RETURN
    //

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

    CHKIN(b"SGBWVS", ctx)?;
    //
    // We need to do some sanity checks on our input arguments before we
    // should attempt to write anything to the file. So, let's start with
    // that.
    //
    // Check to see if the file attached to the handle is open for
    // writing. If not, an error is signaled.
    //
    DAFSIH(HANDLE, b"WRITE", ctx)?;

    if FAILED(ctx) {
        CHKOUT(b"SGBWVS", ctx)?;
        return Ok(());
    }
    //
    // Check to see if the handle is currently in the file table. If it
    // is, we've got a problem. This routine may only be called once for
    // each segment that is to contain variable size packets, and it
    // places a handle into the file table. If the handle is currently in
    // the file table a segment has already been started by this routine
    // or SGBWFS. In either case, we cannot continue, so we signal an
    // error.
    //
    if (save.NFT > 0) {
        save.INDEX = ISRCHI(HANDLE, save.NFT, save.FTHAN.as_slice());

        if (save.INDEX != 0) {
            SETMSG(b"A segment is already being written to the file \'#\'. A new segment cannot be started for this file until the current segment is finished. ", ctx);
            ERRHAN(b"#", HANDLE, ctx)?;
            SIGERR(b"SPICE(CALLEDOUTOFORDER)", ctx)?;
            CHKOUT(b"SGBWVS", ctx)?;
            return Ok(());
        }
    }
    //
    // Get the ND and NI values from the DAF file. We need these to know
    // the size of the descriptor and the length of the segment ID. The
    // length of the segment ID is determined by the following formula
    // using integer division:
    //
    //                             /  ND + ( NI + 1 )  \
    //                  NC =  8 *  | ----------------- |
    //                             \         2         /
    //
    DAFHSF(HANDLE, &mut ND, &mut NI, ctx)?;

    if FAILED(ctx) {
        CHKOUT(b"SGBWVS", ctx)?;
        return Ok(());
    }

    NC = (8 * (ND + ((NI + 1) / 2)));
    //
    // Get the length of the segment ID. Leading blanks are considered to
    // be important. A blank segment ID is OK too.
    //
    SIDLEN = LASTNB(SEGID);
    //
    // Check the segment ID to see if it is OK. Its length must be less
    // than NC and it must consist of only printing ASCII characters.
    //
    if (SIDLEN > NC) {
        SETMSG(b"Segment identifier contains more than # characters.", ctx);
        ERRINT(b"#", NC, ctx);
        SIGERR(b"SPICE(SEGIDTOOLONG)", ctx)?;
        CHKOUT(b"SGBWVS", ctx)?;
        return Ok(());
    }

    for I in 1..=SIDLEN {
        ICH = intrinsics::ICHAR(fstr::substr(SEGID, I..=I));

        if ((ICH < FPRINT) || (ICH > LPRINT)) {
            SETMSG(
                b"The segment identifier contains  a nonprinting character at location #.",
                ctx,
            );
            ERRINT(b"#", I, ctx);
            SIGERR(b"SPICE(NONPRINTINGCHARS)", ctx)?;
            CHKOUT(b"SGBWVS", ctx)?;
            return Ok(());
        }
    }
    //
    // Check to see if the number of constants is negative. This is all
    // we can do here, we cannot check the constant values.
    //
    if (NCONST < 0) {
        SETMSG(b"The number of constants specified was #. This number must be non-negative. Perhaps the variable was not initialized. ", ctx);
        ERRINT(b"#", NCONST, ctx);
        SIGERR(b"SPICE(NUMCONSTANTSNEG) ", ctx)?;
        CHKOUT(b"SGBWVS", ctx)?;
        return Ok(());
    }

    //
    // Check to see if the index type is one that we recognize.
    //
    if ((IDXTYP < MNIDXT) || (IDXTYP > MXIDXT)) {
        SETMSG(b"The index type specified was #.  This is not a valid index type. Valid types are in the range from # to #.", ctx);
        ERRINT(b"#", IDXTYP, ctx);
        ERRINT(b"#", MNIDXT, ctx);
        ERRINT(b"#", MXIDXT, ctx);
        SIGERR(b"SPICE(UNKNOWNINDEXTYPE)", ctx)?;
        CHKOUT(b"SGBWVS", ctx)?;
        return Ok(());
    }
    //
    // Check to see if there is room in the file table.
    //
    if (save.NFT == FTSIZE) {
        SETMSG(b"There are already # files being written by generic segment writing routines. No more files may be written by the generic segment writers until one of those currently being written is closed via a call to SGWES. ", ctx);
        ERRINT(b"#", save.NFT, ctx);
        SIGERR(b"SPICE(FILETABLEFULL)", ctx)?;
        CHKOUT(b"SGBWVS", ctx)?;
        return Ok(());
    }

    //
    // Set the flag which indicate whether this index type is an
    // explicit type or an implicit type.
    //
    save.EXPLCT = (((IDXTYP == EXPLT) || (IDXTYP == EXPLE)) || (IDXTYP == EXPCLS));
    //
    // At this point, we know that the input data is OK, in so far as we
    // can validate it and that there is room in the file table. So we
    // proceed with starting a segment for fixed size packets.
    //
    // Set the flag that indicate that this segment is a variable size
    // segment.
    //
    save.FXDSEG = false;
    //
    // Get the address for the beginning of the array that we are going
    // to create. We have to get this by reading the file record.
    //
    DAFRFR(
        HANDLE,
        &mut ND,
        &mut NI,
        &mut DUMMY1,
        &mut DUMMY2,
        &mut DUMMY3,
        &mut BEGADR,
        ctx,
    )?;
    //
    // Begin a new segment in the DAF file.
    //
    DAFBNA(HANDLE, DESCR.as_slice(), SEGID, ctx)?;

    if FAILED(ctx) {
        CHKOUT(b"SGBWVS", ctx)?;
        return Ok(());
    }
    //
    // Write out the constants to the new segment, if there are any
    // constants.
    //
    if (NCONST > 0) {
        DAFADA(CONST.as_slice(), NCONST, ctx)?;

        if FAILED(ctx) {
            CHKOUT(b"SGBWVS", ctx)?;
            return Ok(());
        }
    }
    //
    // Save the information for this file and segment in the file table.
    //
    save.NFT = (save.NFT + 1);

    save.FTITYP[save.NFT] = IDXTYP;
    save.FTPKSZ[save.NFT] = 0;
    save.FTMXSZ[save.NFT] = 0;

    save.FTNCON[save.NFT] = NCONST;
    save.FTNPKT[save.NFT] = 0;
    save.FTNREF[save.NFT] = 0;
    save.FTNRES[save.NFT] = 0;

    save.FTEXPL[save.NFT] = save.EXPLCT;

    save.FTFIXD[save.NFT] = save.FXDSEG;

    save.FTHAN[save.NFT] = HANDLE;
    save.FTBADR[save.NFT] = BEGADR;

    save.FTREFS[[1, save.NFT]] = 0.0;
    save.FTREFS[[2, save.NFT]] = 0.0;

    if save.EXPLCT {
        save.FTOFF[save.NFT] = 2;
    } else {
        save.FTOFF[save.NFT] = 1;
    }

    save.LSTHAN = HANDLE;
    save.INDEX = save.NFT;
    save.NUMVAR = (save.NUMVAR + 1);

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

/// Generic segments: Write fixed size packets.
///
/// Write one or more fixed size data packets to the generic segment
/// currently being written to the DAF file associated with HANDLE.
///
/// # Required Reading
///
/// * [DAF](crate::required_reading::daf)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  DESCRIPTION
///  --------  ---  --------------------------------------------------
///  HANDLE    I    Handle of a DAF file opened with write access.
///  NPKTS     I    Number of data packets to write to a segment.
///  PKTDAT    I    Array of packet data.
///  NREFS     I    Number of reference values.
///  REFDAT    I    Reference data.
/// ```
///
/// # Detailed Input
///
/// ```text
///  HANDLE   is the handle of a DAF file opened with write access.
///           This is the handle of a file in which a generic segment
///           has been started and is currently being written.
///
///  NPKTS    is the number of data packets to write to a segment.
///
///  PKTDAT   is a singly dimensioned array containing the fixed size
///           data packets to be added to the segment associated with
///           HANDLE.
///
///           For fixed size data packets, PKTDAT will have the
///           following structure:
///
///              Packet #  Range of Locations
///              --------  ------------------------------------------
///
///                 1      PKTDAT(1)              to PKTDAT(PS)
///                 2      PKTDAT(PS+1)           to PKTDAT(2*PS)
///                 3      PKTDAT(2*PS+1)         to PKTDAT(3*PS)
///                 4      PKTDAT(3*PS+1)         to PKTDAT(4*PS)
///
///                                         .
///                                         .
///                                         .
///
///                NPKTS   PKTDAT((NPKTS-1)*PS+1) to PKTDAT(NPKTS*PS)
///
///           where PS = PKTSIZ.
///
///  NREFS    is the number of reference values.
///
///           For implicitly indexed packets, NREFS must have a value
///           of two (2).
///
///           When writing packets to a segment which uses an implicit
///           index type, the value specified by NREFS is used only on
///           the first call to SGWFPK. On all subsequent calls to
///           these subroutines for a particular implicitly indexed
///           segment, the value of NREFS is ignored.
///
///           For explicitly indexed packets, NREFS must be equal to
///           NPKTS, i.e., there should ba a reference value for each
///           data packet being written to the segment.
///
///           When writing packets to a segment which uses an explicit
///           index type, the value specified by NREFS is used on
///           every call to SGWFPK and it must be equal to NPKTS.
///
///  REFDAT   is the reference data values.
///
///           For implicitly indexed packets, there must be two (2)
///           values. The reference values represent a starting
///           reference value and a step size between consecutive
///           reference values, respectively.
///
///           In order to avoid, or at least minimize, numerical
///           difficulties associated with computing index values for
///           generic segments with implicit index types, the value of
///           the step size must be an integer, i.e., DINT(REFDAT(2))
///           must equal REFDAT(2).
///
///           When writing packets to a segment which uses an implicit
///           index type, the values specified by REFDAT are used only
///           on the first call to SGWFPK. On all subsequent calls to
///           this subroutine for a particular implicitly indexed
///           segment, REFDAT is ignored.
///
///           For explicitly indexed packets, there must be NPKTS
///           reference values and the values must be in increasing
///           order:
///
///              REFDAT(I) < REFDAT(I+1), I = 1, NPKTS-1
///
///           When writing packets to a segment which uses an explicit
///           index type, the values specified by REFDAT are used on
///           every call to SGWFPK. On all calls to these subroutines
///           after the first, the value of REFDAT(1) must be greater
///           than than the value of REFDAT(NPKTS) from the previous
///           call. This preserves the ordering of the reference
///           values for the entire segment.
/// ```
///
/// # Parameters
///
/// ```text
///  This subroutine makes use of parameters defined in the file
///  'sgparam.inc'.
/// ```
///
/// # Exceptions
///
/// ```text
///  1)  If there are no generic segments with fixed packet sizes
///      currently being written, the error SPICE(CALLEDOUTOFORDER) is
///      signaled.
///
///  2)  If there is not a generic segment with fixed packet size being
///      written to the file associated with HANDLE, the error
///      SPICE(SEGMENTNOTFOUND) is signaled.
///
///  3)  If the type of generic segment being written to this file is
///      not a fixed packet size generic segment, the error
///      SPICE(SEGTYPECONFLICT) is signaled.
///
///  4)  If the number of packets to be written to the generic segment
///      is not positive, the error SPICE(NUMPACKETSNOTPOS) is
///      signaled.
///
///  5)  If an explicitly indexed generic segment is being written and
///      the number of reference values, NREFS, is not equal to the
///      number of data packets being written, NPKTS, the error
///      SPICE(INCOMPATIBLENUMREF) is signaled.
///
///  6)  If an explicitly indexed generic segment is being written and
///      the reference values are not in increasing order, the error
///      SPICE(UNORDEREDREFS) is signaled.
///
///  7)  If an explicitly indexed generic segment is being written and
///      the first reference value on the second or later additions
///      of packets to the generic segment is not greater than the last
///      reference value from the previous addition of packets, the
///      error SPICE(UNORDEREDREFS) is signaled.
///
///  8)  If an implicitly indexed generic segment is being written and
///      the number of reference values, NREFS, is not equal to two (2)
///      on the first call to this subroutine for a particular segment,
///      the error SPICE(INCOMPATIBLENUMREF) is signaled.
///
///  9)  If an implicitly indexed generic segment is being written and
///      the second reference value, the step size used for indexing,
///      is not integral, i.e., DINT(REFDAT(2)) .NE. REFDAT(2), the
///      error SPICE(REFVALNOTINTEGER) is signaled.
/// ```
///
/// # Files
///
/// ```text
///  See HANDLE in the $Detailed_Input section.
/// ```
///
/// # Particulars
///
/// ```text
///  This routine will write one or more fixed size data packets to a
///  generic segment in the DAF file associated with HANDLE. The
///  generic segment must have been started by a call to SGBWFS.
/// ```
///
/// # Examples
///
/// ```text
///  See the $Examples section in the header for the main subroutine.
///  It contains examples which demonstrate the use of the entry points
///  in the generic segments sequential writer. The entry points which
///  comprise the generic segments sequential writer must be used
///  together in the proper manner. Rather than repeating the examples
///  for each entry point they are provided in a single location.
/// ```
///
/// # Author and Institution
///
/// ```text
///  J. Diaz del Rio    (ODC Space)
///  K.R. Gehringer     (JPL)
///  W.L. Taber         (JPL)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 1.0.1, 03-JUN-2021 (JDR)
///
///         Edited the header to comply with NAIF standard.
///
/// -    SPICELIB Version 1.0.0, 05-APR-1995 (KRG) (WLT)
/// ```
pub fn sgwfpk(
    ctx: &mut SpiceContext,
    handle: i32,
    npkts: i32,
    pktdat: &[f64],
    nrefs: i32,
    refdat: &[f64],
) -> crate::Result<()> {
    SGWFPK(handle, npkts, pktdat, nrefs, refdat, ctx.raw_context())?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SGWFPK ( Generic segments: Write fixed size packets. )
pub fn SGWFPK(
    HANDLE: i32,
    NPKTS: i32,
    PKTDAT: &[f64],
    NREFS: i32,
    REFDAT: &[f64],
    ctx: &mut Context,
) -> f2rust_std::Result<()> {
    let save = ctx.get_vars::<SaveVars>();
    let save = &mut *save.borrow_mut();

    let PKTDAT = DummyArray::new(PKTDAT, 1..);
    let REFDAT = DummyArray::new(REFDAT, 1..);

    //
    // SPICELIB functions
    //
    // INTEGER               LASTNB
    // INTEGER               ISRCHI
    //
    // LOGICAL               FAILED
    // LOGICAL               RETURN
    //

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

    CHKIN(b"SGWFPK", ctx)?;
    //
    // Check to see if this is the first time here. If it is, we have
    // been called out of order, so signal an error.
    //
    if (save.NUMFXD == 0) {
        SETMSG(b"No segment with fixed size packets is currently being written. This routine has been called out of order. The routine SGBWFS must be called before his routine may be called.", ctx);
        SIGERR(b"SPICE(CALLEDOUTOFORDER)", ctx)?;
        CHKOUT(b"SGWFPK", ctx)?;
        return Ok(());
    }
    //
    // Check to see if the last handle used is the same as the current
    // handle. This saves us a table lookup to get the appropriate index
    // into the file table to restore the information for that handle.
    //
    if (HANDLE != save.LSTHAN) {
        save.INDEX = ISRCHI(HANDLE, save.NFT, save.FTHAN.as_slice());

        if (save.INDEX == 0) {
            SETMSG(b"No segment with fixed size packets is associated with the file \'#\'. In order to write fixed size packets to a file the routine SGBWFS must be called to begin the segment.", ctx);
            ERRHAN(b"#", HANDLE, ctx)?;
            SIGERR(b"SPICE(SEGMENTNOTFOUND)", ctx)?;
            CHKOUT(b"SGWFPK", ctx)?;
            return Ok(());
        }

        save.EXPLCT = save.FTEXPL[save.INDEX];
        save.FXDSEG = save.FTFIXD[save.INDEX];
        save.LSTHAN = HANDLE;

        DAFCAD(HANDLE, ctx)?;

        if FAILED(ctx) {
            CHKOUT(b"SGWFPK", ctx)?;
            return Ok(());
        }
    }
    //
    // Check to see if the segment being written is a fixed size packet
    // segment or a variable size packet segment. If the latter, then
    // this is the wrong routine.
    //
    if !save.FXDSEG {
        SETMSG(b"The segment being written to the file  \'#\' is a variable packet size segment, not a fixed packet size segment.  The routine SGWVPK may be used to write variable size packets.", ctx);
        ERRHAN(b"#", HANDLE, ctx)?;
        SIGERR(b"SPICE(SEGTYPECONFLICT)", ctx)?;
        CHKOUT(b"SGWFPK", ctx)?;
        return Ok(());
    }
    //
    // At this point, we have a good file handle, an index into the file
    // table, and we know that we are working with a fixed packet size
    // segment. So, what we need to do now is verify the input arguments.
    //
    // Check the number of packets to be sure that it is positive.
    //
    if (NPKTS <= 0) {
        SETMSG(b"The number of packets to store is not positive.  The value supplied was #. Perhaps this packet count was uninitialized.", ctx);
        ERRINT(b"#", NPKTS, ctx);
        SIGERR(b"SPICE(NUMPACKETSNOTPOS)", ctx)?;
        CHKOUT(b"SGWFPK", ctx)?;
        return Ok(());
    }

    //
    // Now we get to some of the more interesting bits. We now need to
    // differentiate between the explicitly indexed types and the
    // implicitly indexed types, because they have different
    // characteristics and assumptions about how they are stored.
    //
    if save.EXPLCT {
        //
        // For explicitly indexed packets the number of reference values
        // must be equal to the number of packets. The references must
        // also be in increasing order.
        //
        if (NREFS != NPKTS) {
            SETMSG(b"The number of reference values supplied, #, is not compatible with explicitly indexed packets. Explicitly indexed packets require the number of reference values to equal the number of packets, in this case, #.", ctx);
            ERRINT(b"#", NREFS, ctx);
            ERRINT(b"#", NPKTS, ctx);
            SIGERR(b"SPICE(INCOMPATIBLENUMREF)", ctx)?;
            CHKOUT(b"SGWFPK", ctx)?;
            return Ok(());
        }
        //
        // If this is not the first time we have added data to this
        // segment, we need to be sure that all of the current reference
        // values are greater then the last reference value from the
        // previous addition of packets to the segment.
        //
        if (save.FTNPKT[save.INDEX] > 0) {
            if (save.FTREFS[[1, save.INDEX]] >= REFDAT[1]) {
                SETMSG(b"Reference values are out of order. The offending value, #, was found to be out of order. The reference values for explicitly indexed packets must be in increasing order, and the first reference value is less than or equal to the last reference value, #, from the previous addition of packets.", ctx);
                ERRDP(b"#", REFDAT[1], ctx);
                ERRDP(b"#", save.FTREFS[[1, save.INDEX]], ctx);
                SIGERR(b"SPICE(UNORDEREDREFS)", ctx)?;
                CHKOUT(b"SGWFPK", ctx)?;
                return Ok(());
            }
        }

        for I in 2..=NREFS {
            if (REFDAT[(I - 1)] >= REFDAT[I]) {
                SETMSG(b"Reference values are out of order. The offending value, #, was found to be out of order for index #. The reference values for explicitly indexed packets must be in increasing order.", ctx);
                ERRDP(b"#", REFDAT[(I - 1)], ctx);
                ERRINT(b"#", (I - 1), ctx);
                SIGERR(b"SPICE(UNORDEREDREFS)", ctx)?;
                CHKOUT(b"SGWFPK", ctx)?;
                return Ok(());
            }
        }
        //
        // Add the packets preceded by their reference values to the
        // segment. We put the reference values with the packets so that
        // we do not need to open a scratch file. We will use them to
        // construct a reference directory after all of the packets have
        // been added to the segment.
        //
        for I in 1..=NPKTS {
            DAFADA(REFDAT.subarray(I), 1, ctx)?;
            DAFADA(
                PKTDAT.subarray((((I - 1) * save.FTPKSZ[save.INDEX]) + 1)),
                save.FTPKSZ[save.INDEX],
                ctx,
            )?;

            if FAILED(ctx) {
                CHKOUT(b"SGWFPK", ctx)?;
                return Ok(());
            }
        }
        //
        // Save the last reference value in the file table so that we
        // can use it to verify that the next addition does not violate
        // the increasing order of the reference values.
        //
        save.FTREFS[[1, save.INDEX]] = REFDAT[NREFS];
        //
        // Update the counts for the number of packets, the number of
        // references.
        //
        save.FTNPKT[save.INDEX] = (save.FTNPKT[save.INDEX] + NPKTS);
        save.FTNREF[save.INDEX] = (save.FTNREF[save.INDEX] + NREFS);
    } else {
        //
        // For implicitly indexed packets the number of reference values
        // must be two (2), and the second reference value must be an
        // integer, i.e., DINT(REFDAT(2)) .eq. REFDAT(2). The number of
        // reference values and the integrality of the second reference
        // value are checked only on the first call to add variable length
        // data packets to a generic segment. In all subsequent calls,
        // these arguments are ignored.
        //

        if (save.FTNPKT[save.INDEX] == 0) {
            if (NREFS != 2) {
                SETMSG(b"The number of reference values supplied, #, is not compatible with implicitly indexed packets. Implicitly indexed packets require the number of reference values to be two (2).", ctx);
                ERRINT(b"#", NREFS, ctx);
                SIGERR(b"SPICE(INCOMPATIBLENUMREF)", ctx)?;
                CHKOUT(b"SGWFPK", ctx)?;
                return Ok(());
            }

            if (f64::trunc(REFDAT[2]) != REFDAT[2]) {
                SETMSG(
                    b"For implicitly indexed packets the step size must be an integer.",
                    ctx,
                );
                SIGERR(b"SPICE(REFVALNOTINTEGER)", ctx)?;
                CHKOUT(b"SGWFPK", ctx)?;
                return Ok(());
            }
        }
        //
        // Add the packets to the segment.
        //
        DAFADA(PKTDAT.as_slice(), (save.FTPKSZ[save.INDEX] * NPKTS), ctx)?;

        if FAILED(ctx) {
            CHKOUT(b"SGWFPK", ctx)?;
            return Ok(());
        }
        //
        // Save the last reference values and the number of reference
        // values in the file table. We only do this on the first time
        // through the routine.
        //
        if (save.FTNPKT[save.INDEX] == 0) {
            save.FTNREF[save.INDEX] = NREFS;
            save.FTREFS[[1, save.INDEX]] = REFDAT[1];
            save.FTREFS[[2, save.INDEX]] = REFDAT[2];
        }
        //
        // Update the count for the number of packets.
        //
        save.FTNPKT[save.INDEX] = (save.FTNPKT[save.INDEX] + NPKTS);
    }

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

/// Generic segment: Write variable size packets.
///
/// Write one or more variable size data packets to the generic
/// segment currently being written to the DAF file associated with
/// HANDLE.
///
/// # Required Reading
///
/// * [DAF](crate::required_reading::daf)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  DESCRIPTION
///  --------  ---  --------------------------------------------------
///  HANDLE    I    Handle of a DAF file opened with write access.
///  NPKTS     I    Number of data packets to write to a segment.
///  PKTSIZ    I    Array of sizes of variable size packets.
///  PKTDAT    I    Array of packet data.
///  NREFS     I    Number of reference values.
///  REFDAT    I    Reference data.
/// ```
///
/// # Detailed Input
///
/// ```text
///  HANDLE   is the handle of a DAF file opened with write access.
///           This is the handle of a file in which a generic segment
///           has been started and is currently being written.
///
///  NPKTS    is the number of data packets to write to a segment.
///
///  PKTSIZ   is the sizes of variable size packets.
///
///           By the size of a packet we mean the number of double
///           precision numbers contained in a data packet.
///
///           When writing a segment with variable size packets,
///           there must be an element in the array PKTSIZ for each of
///           the variable size data packets.
///
///  PKTDAT   is a singly dimensioned array containing the variable
///           size data packets to be added to the generic segment
///           associated with HANDLE.
///
///           For variable size data packets, PKTDAT will have the
///           following structure:
///
///              Packet #  Range of Locations
///              --------  ------------------------------------------
///
///                 1      PKTDAT(1)           to PKTDAT(P(1))
///                 2      PKTDAT(P(1)+1)      to PKTDAT(P(2))
///                 3      PKTDAT(P(2)+1)      to PKTDAT(P(3))
///                 4      PKTDAT(P(3)+1)      to PKTDAT(P(4))
///
///                                         .
///                                         .
///                                         .
///
///                NPKTS   PKTDAT(P(NPKTS-1)+1) to PKTDAT(P(NPKTS))
///
///                            I
///                           ---
///           where P(I) =    >   PKTSIZ(K).
///                           ---
///                          K = 1
///
///  NREFS    is the number of reference values.
///
///           For implicitly indexed packets, NREFS must have a value
///           of two (2).
///
///           When writing packets to a segment which uses an implicit
///           index type, the value specified by NREFS is used only on
///           the first call to SGWVPK. On all subsequent calls to
///           these subroutines for a particular implicitly indexed
///           segment, the value of NREFS is ignored.
///
///           For explicitly indexed packets, NREFS must be equal to
///           NPKTS, i.e., there should be a reference value for each
///           data packet being written to the segment.
///
///           When writing packets to a segment which uses an explicit
///           index type, the value specified by NREFS is used on
///           every call to SGWVPK and it must be equal to NPKTS.
///
///  REFDAT   is the reference data values.
///
///           For implicitly indexed packets, there must be two (2)
///           values. The reference values represent a starting
///           reference value and a step size between consecutive
///           reference values, respectively.
///
///           In order to avoid, or at least minimize, numerical
///           difficulties associated with computing index values for
///           generic segments with implicit index types, the value of
///           the step size must be an integer, i.e., DINT(REFDAT(2))
///           must equal REFDAT(2).
///
///           When writing packets to a segment which uses an implicit
///           index type, the values specified by REFDAT are used only
///           on the first call to SGWVPK. On all subsequent calls to
///           this subroutine for a particular implicitly indexed
///           segment, REFDAT is ignored.
///
///           For explicitly indexed packets, there must be NPKTS
///           reference values and the values must be in increasing
///           order:
///
///              REFDAT(I) < REFDAT(I+1), I = 1, NPKTS-1
///
///           When writing packets to a segment which uses an explicit
///           index type, the values specified by REFDAT are used on
///           every call to SGWVPK. On all calls to this subroutine
///           after the first, the value of REFDAT(1) must be greater
///           than than the value of REFDAT(NPKTS) from the previous
///           call. This preserves the ordering of the reference
///           values for the entire segment.
/// ```
///
/// # Parameters
///
/// ```text
///  This subroutine makes use of parameters defined in the file
///  'sgparam.inc'.
/// ```
///
/// # Exceptions
///
/// ```text
///  1)  If there are no generic segments with variable packet sizes
///      currently being written, the error SPICE(CALLEDOUTOFORDER)
///      is signaled.
///
///  2)  If there is not a generic segment with variable packet size
///      being written to the file associated with HANDLE, the error
///      SPICE(SEGMENTNOTFOUND) is signaled.
///
///  3)  If the type of generic segment being written to this file is
///      not a variable packet size generic segment, the error
///      SPICE(SEGTYPECONFLICT) is signaled.
///
///  4)  If the number of packets to be written to the generic segment
///      is not positive, the error SPICE(NUMPACKETSNOTPOS) is
///      signaled.
///
///  5)  If an explicitly indexed generic segment is being written and
///      the number of reference values, NREFS, is not equal to the
///      number of data packets being written, NPKTS, the error
///      SPICE(INCOMPATIBLENUMREF) is signaled.
///
///  6)  If an explicitly indexed generic segment is being written and
///      the reference values are not in increasing order, the error
///      SPICE(UNORDEREDREFS) is signaled.
///
///  7)  If an explicitly indexed generic segment is being written and
///      the first reference value on the second or later additions
///      of packets to the generic segment is not greater than the last
///      reference value from the previous addition of packets, the
///      error SPICE(UNORDEREDREFS) is signaled.
///
///  8)  If an explicitly indexed generic segment is being written and
///      one or more of the packet sizes is not positive, the error
///      SPICE(NONPOSPACKETSIZE) is signaled.
///
///  9)  If an implicitly indexed generic segment is being written and
///      the number of reference values, NREFS, is not equal to two (2)
///      on the first call to this subroutine for a particular segment,
///      the error SPICE(INCOMPATIBLENUMREF) is signaled.
///
///  10) If an implicitly indexed generic segment is being written and
///      the second reference value, the step size used for indexing,
///      is not integral, i.e., DINT(REFDAT(2)) .NE. REFDAT(2), the
///      error SPICE(REFVALNOTINTEGER) is signaled.
/// ```
///
/// # Files
///
/// ```text
///  See HANDLE in the $Detailed_Input section.
/// ```
///
/// # Particulars
///
/// ```text
///  This routine will write one or more variable size data packets to
///  a generic segment in the DAF file associated with HANDLE. The
///  generic segment must have been started by a call to SGBWVS.
/// ```
///
/// # Examples
///
/// ```text
///  See the $Examples section in the header for the main subroutine.
///  It contains examples which demonstrate the use of the entry points
///  in the generic segments sequential writer. The entry points which
///  comprise the generic segments sequential writer must be used
///  together in the proper manner. Rather than repeating the examples
///  for each entry point they are provided in a single location.
/// ```
///
/// # Author and Institution
///
/// ```text
///  N.J. Bachman       (JPL)
///  J. Diaz del Rio    (ODC Space)
///  K.R. Gehringer     (JPL)
///  W.L. Taber         (JPL)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 1.0.1, 27-OCT-2021 (JDR) (NJB)
///
///         Edited the header to comply with NAIF standard. Corrected
///         typos in comments.
///
/// -    SPICELIB Version 1.0.0, 05-APR-1995 (KRG) (WLT)
/// ```
pub fn sgwvpk(
    ctx: &mut SpiceContext,
    handle: i32,
    npkts: i32,
    pktsiz: &[i32],
    pktdat: &[f64],
    nrefs: i32,
    refdat: &[f64],
) -> crate::Result<()> {
    SGWVPK(
        handle,
        npkts,
        pktsiz,
        pktdat,
        nrefs,
        refdat,
        ctx.raw_context(),
    )?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SGWVPK ( Generic segment: Write variable size packets. )
pub fn SGWVPK(
    HANDLE: i32,
    NPKTS: i32,
    PKTSIZ: &[i32],
    PKTDAT: &[f64],
    NREFS: i32,
    REFDAT: &[f64],
    ctx: &mut Context,
) -> f2rust_std::Result<()> {
    let save = ctx.get_vars::<SaveVars>();
    let save = &mut *save.borrow_mut();

    let PKTSIZ = DummyArray::new(PKTSIZ, 1..);
    let PKTDAT = DummyArray::new(PKTDAT, 1..);
    let REFDAT = DummyArray::new(REFDAT, 1..);
    let mut DPKSIZ: f64 = 0.0;
    let mut PKTPOS: i32 = 0;

    //
    // SPICELIB functions
    //
    // INTEGER               LASTNB
    // INTEGER               ISRCHI
    //
    // LOGICAL               FAILED
    // LOGICAL               RETURN
    //

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

    CHKIN(b"SGWVPK", ctx)?;
    //
    // Check to see if this is the first time here. If it is, we have
    // been called out of order, so signal an error.
    //
    if (save.NUMVAR == 0) {
        SETMSG(b"No segment with variable size packets is currently being written. This routine has been called out of order. The routine SGBWVS must be called before his routine may be called.", ctx);
        SIGERR(b"SPICE(CALLEDOUTOFORDER)", ctx)?;
        CHKOUT(b"SGWVPK", ctx)?;
        return Ok(());
    }
    //
    // Check to see if the last handle used is the same as the current
    // handle. This saves us a table lookup to get the appropriate index
    // into the file table to restore the information for that handle.
    //
    if (HANDLE != save.LSTHAN) {
        save.INDEX = ISRCHI(HANDLE, save.NFT, save.FTHAN.as_slice());

        if (save.INDEX == 0) {
            SETMSG(b"No segment with variable size packets is associated with the file \'#\'. In order to write variable size packets to a file the routine SGBWVS must be called to begin the segment.", ctx);
            ERRHAN(b"#", HANDLE, ctx)?;
            SIGERR(b"SPICE(SEGMENTNOTFOUND)", ctx)?;
            CHKOUT(b"SGWVPK", ctx)?;
            return Ok(());
        }

        save.EXPLCT = save.FTEXPL[save.INDEX];
        save.FXDSEG = save.FTFIXD[save.INDEX];
        save.LSTHAN = HANDLE;

        DAFCAD(HANDLE, ctx)?;

        if FAILED(ctx) {
            CHKOUT(b"SGWVPK", ctx)?;
            return Ok(());
        }
    }
    //
    // Check to see if the segment being written is a fixed size packet
    // segment or a variable size packet segment. If the former, then
    // this is the wrong routine.
    //
    if save.FXDSEG {
        SETMSG(b"The segment being written to the file  \'#\' is a fixed packet size segment, not a variable packet size segment.  The routine SGWFPK may be used to write fixed size packets.", ctx);
        ERRHAN(b"#", HANDLE, ctx)?;
        SIGERR(b"SPICE(SEGTYPECONFLICT)", ctx)?;
        CHKOUT(b"SGWVPK", ctx)?;
        return Ok(());
    }
    //
    // At this point, we have a good file handle, an index into the file
    // table, and we know that we are working with a variable packet
    // size segment. So, what we need to do now is verify the input
    // arguments.
    //
    // Check the number of packets to be sure that it is positive.
    //
    if (NPKTS <= 0) {
        SETMSG(b"The number of packets to store is not positive.  The value supplied was #. Perhaps this packet count was uninitialized.", ctx);
        ERRINT(b"#", NPKTS, ctx);
        SIGERR(b"SPICE(NUMPACKETSNOTPOS)", ctx)?;
        CHKOUT(b"SGWVPK", ctx)?;
        return Ok(());
    }

    //
    // Now we get to some of the more interesting bits. We now need to
    // differentiate between the explicitly indexed types and the
    // implicitly indexed types, because they have different
    // characteristics and assumptions about how they are stored.
    //
    if save.EXPLCT {
        //
        // For explicitly indexed packets the number of reference values
        // must be equal to the number of packets. The references must
        // also be in increasing order.
        //
        if (NREFS != NPKTS) {
            SETMSG(b"The number of reference values supplied, #, is not compatible with explicitly indexed packets. Explicitly indexed packets require the number of reference values to equal the number of packets, in this case, #.", ctx);
            ERRINT(b"#", NREFS, ctx);
            ERRINT(b"#", NPKTS, ctx);
            SIGERR(b"SPICE(INCOMPATIBLENUMREF)", ctx)?;
            CHKOUT(b"SGWVPK", ctx)?;
            return Ok(());
        }
        //
        // If this is not the first time we have added data to this
        // segment, we need to be sure that all of the current reference
        // values are greater then the last reference value from the
        // previous addition of packets to the segment.
        //
        if (save.FTNPKT[save.INDEX] > 0) {
            if (save.FTREFS[[1, save.INDEX]] >= REFDAT[1]) {
                SETMSG(b"Reference values are out of order. The offending value, #, was found The reference values for explicitly to be out of order. indexed packets must be in increasing order, and the first reference value is less than or equal to the last reference value, #, from the previous addition of packets.", ctx);
                ERRDP(b"#", REFDAT[1], ctx);
                ERRDP(b"#", save.FTREFS[[1, save.INDEX]], ctx);
                SIGERR(b"SPICE(UNORDEREDREFS)", ctx)?;
                CHKOUT(b"SGWVPK", ctx)?;
                return Ok(());
            }
        }

        for I in 2..=NREFS {
            if (REFDAT[(I - 1)] >= REFDAT[I]) {
                SETMSG(b"Reference values are out of order. The offending value, #, was found to be out of order for index #. The reference values for explicitly indexed packets must be in increasing order.", ctx);
                ERRDP(b"#", REFDAT[(I - 1)], ctx);
                ERRINT(b"#", (I - 1), ctx);
                SIGERR(b"SPICE(UNORDEREDREFS)", ctx)?;
                CHKOUT(b"SGWVPK", ctx)?;
                return Ok(());
            }
        }
        //
        // Check the packet size to be sure that it is positive.
        //
        for I in 1..=NPKTS {
            if (PKTSIZ[I] <= 0) {
                SETMSG(b"The packet size for packet # was not positive. It had a value of #. All packet sizes must be greater then zero.", ctx);
                ERRINT(b"#", I, ctx);
                ERRINT(b"#", PKTSIZ[I], ctx);
                SIGERR(b"SPICE(NONPOSPACKETSIZE)", ctx)?;
                CHKOUT(b"SGWVPK", ctx)?;
                return Ok(());
            }
        }
        //
        // Add the packets preceded by their reference values and sizes to
        // the segment. We put the reference values with the packets so
        // that we do not need to open a scratch file. We will use them to
        // construct a reference directory after all of the packets have
        // been added to the segment.
        //
        PKTPOS = 1;

        for I in 1..=NPKTS {
            DPKSIZ = (PKTSIZ[I] as f64);

            DAFADA(REFDAT.subarray(I), 1, ctx)?;
            DAFADA(&[DPKSIZ], 1, ctx)?;
            DAFADA(PKTDAT.subarray(PKTPOS), PKTSIZ[I], ctx)?;

            if FAILED(ctx) {
                CHKOUT(b"SGWVPK", ctx)?;
                return Ok(());
            }

            PKTPOS = (PKTPOS + PKTSIZ[I]);
            save.FTPKSZ[save.INDEX] = (save.FTPKSZ[save.INDEX] + PKTSIZ[I]);
            //
            // Remember the maximum packet size encountered.
            //
            if (PKTSIZ[I] > save.FTMXSZ[save.INDEX]) {
                save.FTMXSZ[save.INDEX] = PKTSIZ[I];
            }
        }
        //
        // Save the last reference value in the file table so that we
        // can use it to verify that the next addition does not violate
        // the increasing order of the reference values.
        //
        save.FTREFS[[1, save.INDEX]] = REFDAT[NREFS];
        //
        // Update the counts for the number of packets, the number of
        // references.
        //
        save.FTNPKT[save.INDEX] = (save.FTNPKT[save.INDEX] + NPKTS);
        save.FTNREF[save.INDEX] = (save.FTNREF[save.INDEX] + NREFS);
    } else {
        //
        // For implicitly indexed packets the number of reference values
        // must be two (2), and the second reference value must be an
        // integer, i.e., DINT(REFDAT(2)) .eq. REFDAT(2). The number of
        // reference values and the integrality of the second reference
        // value are checked only on the first call to add variable length
        // data packets to a generic segment. In all subsequent calls,
        // these arguments are ignored.
        //
        if (save.FTNPKT[save.INDEX] == 0) {
            if (NREFS != 2) {
                SETMSG(b"The number of reference values supplied, #, is not compatible with implicitly indexed packets. Implicitly indexed packets require the number of reference values to be two (2).", ctx);
                ERRINT(b"#", NREFS, ctx);
                SIGERR(b"SPICE(INCOMPATIBLENUMREF)", ctx)?;
                CHKOUT(b"SGWVPK", ctx)?;
                return Ok(());
            }

            if (f64::trunc(REFDAT[2]) != REFDAT[2]) {
                SETMSG(
                    b"For implicitly indexed packets the step size must be an integer.",
                    ctx,
                );
                SIGERR(b"SPICE(REFVALNOTINTEGER)", ctx)?;
                CHKOUT(b"SGWVPK", ctx)?;
                return Ok(());
            }
        }

        //
        // Add the packets to the segment preceded by the size of the
        // packet.
        //
        PKTPOS = 1;

        for I in 1..=NPKTS {
            DPKSIZ = (PKTSIZ[I] as f64);

            DAFADA(&[DPKSIZ], 1, ctx)?;
            DAFADA(PKTDAT.subarray(PKTPOS), PKTSIZ[I], ctx)?;

            if FAILED(ctx) {
                CHKOUT(b"SGWVPK", ctx)?;
                return Ok(());
            }

            PKTPOS = (PKTPOS + PKTSIZ[I]);
            save.FTPKSZ[save.INDEX] = (save.FTPKSZ[save.INDEX] + PKTSIZ[I]);
        }
        //
        // Save the reference values and the number of reference values
        // in the file table. We only do this on the first time through
        // the routine.
        //
        if (save.FTNPKT[save.INDEX] == 0) {
            save.FTNREF[save.INDEX] = NREFS;
            save.FTREFS[[1, save.INDEX]] = REFDAT[1];
            save.FTREFS[[2, save.INDEX]] = REFDAT[2];
        }
        //
        // Update the counts for the number of packets.
        //
        save.FTNPKT[save.INDEX] = (save.FTNPKT[save.INDEX] + NPKTS);
    }

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

/// Generic segments: End a segment.
///
/// End the generic segment in the DAF file associated with HANDLE.
///
/// # Required Reading
///
/// * [DAF](crate::required_reading::daf)
///
/// # Brief I/O
///
/// ```text
///  VARIABLE  I/O  DESCRIPTION
///  --------  ---  --------------------------------------------------
///  HANDLE    I    Handle of a DAF file opened with write access.
/// ```
///
/// # Detailed Input
///
/// ```text
///  HANDLE   is the handle of a DAF file opened with write access.
///           This is the handle of the file which contains the generic
///           segment that we wish to end.
/// ```
///
/// # Parameters
///
/// ```text
///  This subroutine makes use of parameters defined in the file
///  'sgparam.inc'.
/// ```
///
/// # Exceptions
///
/// ```text
///  1)  If there are no generic segments currently being written, the
///      error SPICE(CALLEDOUTOFORDER) is signaled.
///
///  2)  If there is no generic segment being written to the file
///      associated with HANDLE, the error SPICE(SEGMENTNOTFOUND) is
///      signaled.
/// ```
///
/// # Files
///
/// ```text
///  See HANDLE in the $Detailed_Input section.
/// ```
///
/// # Particulars
///
/// ```text
///  This routine will end the generic segment started by a call to
///  either SGBWFS or SGBWVS that is currently being written to the DAF
///  file associated with HANDLE.
/// ```
///
/// # Examples
///
/// ```text
///  See the $Examples section in the header for the main subroutine.
///  It contains examples which demonstrate the use of the entry points
///  in the generic segments sequential writer. The entry points which
///  comprise the generic segments sequential writer must be used
///  together in the proper manner. Rather than repeating the examples
///  for each entry point they are provided in a single location.
/// ```
///
/// # Author and Institution
///
/// ```text
///  N.J. Bachman       (JPL)
///  J. Diaz del Rio    (ODC Space)
///  K.R. Gehringer     (JPL)
///  W.L. Taber         (JPL)
/// ```
///
/// # Version
///
/// ```text
/// -    SPICELIB Version 1.1.1, 03-JUN-2021 (JDR)
///
///         Edited the header to comply with NAIF standard. Removed
///         unnecessary $Revisions section.
///
/// -    SPICELIB Version 1.1.0, 30-JUL-1996 (KRG) (NJB)
///
///         Fixed an annoying little bug in the variable segments code
///         when ending a segment. Rather than storing an appropriate
///         offset from the beginning of the segment as the packet
///         address in the packet directory, the absolute address, the
///         DAF address, was stored. This bug has been fixed.
///
///         The address calculations, see the variable MYADDR, were fixed.
///         This involved initializing the variable outside of the loop
///         that scans through the packet data and then incrementing this
///         variable in the same way as PKTADR.
///
///         The changes were made in two places, for the explicitly indexed
///         case and for the implicitly indexed case.
///
/// -    SPICELIB Version 1.0.0, 05-APR-1995 (KRG) (WLT)
/// ```
pub fn sgwes(ctx: &mut SpiceContext, handle: i32) -> crate::Result<()> {
    SGWES(handle, ctx.raw_context())?;
    ctx.handle_errors()?;
    Ok(())
}

//$Procedure SGWES ( Generic segments: End a segment. )
pub fn SGWES(HANDLE: i32, ctx: &mut Context) -> f2rust_std::Result<()> {
    let save = ctx.get_vars::<SaveVars>();
    let save = &mut *save.borrow_mut();

    let mut XMETA = StackArray::<f64, 17>::new(1..=MXMETA);
    let mut MYREF: f64 = 0.0;
    let mut MYADDR: f64 = 0.0;
    let mut MYSIZE: f64 = 0.0;
    let mut META = StackArray::<i32, 17>::new(1..=MXMETA);
    let mut PKTADR: i32 = 0;
    let mut REFADR: i32 = 0;
    let mut SIZE: i32 = 0;

    //
    // SPICELIB functions
    //
    // INTEGER               LASTNB
    // INTEGER               ISRCHI
    //
    // LOGICAL               FAILED
    // LOGICAL               RETURN
    //

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

    CHKIN(b"SGWES", ctx)?;
    //
    // Check to see if we have any fixed or variable segments being
    // written.
    //
    if (save.NFT == 0) {
        SETMSG(b"No segment is currently being written. This routine has been called out of order. One of the routines SGBWFS or SGBWVS must be called before his routine may be called.", ctx);
        SIGERR(b"SPICE(CALLEDOUTOFORDER)", ctx)?;
        CHKOUT(b"SGWES", ctx)?;
        return Ok(());
    }
    //
    // Check to see if the last handle used is the same as the current
    // handle. This saves us a table lookup to get the appropriate index
    // into the file table to restore the information for that handle.
    //
    if (HANDLE != save.LSTHAN) {
        save.INDEX = ISRCHI(HANDLE, save.NFT, save.FTHAN.as_slice());

        if (save.INDEX == 0) {
            SETMSG(b"No segment is associated with the file \'#\'. In order to write packets to a segment one of the routines SGBWFS or SGBWVS must be called to begin a segment.", ctx);
            ERRHAN(b"#", HANDLE, ctx)?;
            SIGERR(b"SPICE(SEGMENTNOTFOUND)", ctx)?;
            CHKOUT(b"SGWES", ctx)?;
            return Ok(());
        }

        save.EXPLCT = save.FTEXPL[save.INDEX];
        save.FXDSEG = save.FTFIXD[save.INDEX];
        save.LSTHAN = HANDLE;

        DAFCAD(HANDLE, ctx)?;

        if FAILED(ctx) {
            CHKOUT(b"SGWES", ctx)?;
            return Ok(());
        }
    }
    //
    // We need to do different things depending on whether the reference
    // values are implicitly or explicitly defined. We will also need to
    // treat the cases of fixed size packets and variable size packets
    // differently.
    //
    if save.EXPLCT {
        //
        // We have an explicit segment.
        //
        if save.FXDSEG {
            //
            // We need to do a little bit of work to finish this case off.
            // We know that we do not need a list of packet starting
            // addresses or a packet directory, but we do need to store in
            // a contiguous block the references and a reference directory
            // if the number of references is greater than DIRSIZ.
            //
            // We need to do the following things:
            //
            // 1) Initialize the offset of the packet data from the
            //    beginning of the packet, set the size of the packet, and
            //    set the beginning address of the packet data area in the
            //    segment.
            //
            SIZE = (save.FTOFF[save.INDEX] + save.FTPKSZ[save.INDEX]);
            REFADR = (save.FTBADR[save.INDEX] + save.FTNCON[save.INDEX]);
            //
            // 2) Collect all of the references stored with the packets
            //    when they were written, and copy them into the
            //    reference area.
            //
            for I in 1..=save.FTNPKT[save.INDEX] {
                DAFGDA(
                    HANDLE,
                    REFADR,
                    REFADR,
                    std::slice::from_mut(&mut MYREF),
                    ctx,
                )?;
                DAFADA(&[MYREF], 1, ctx)?;

                if FAILED(ctx) {
                    CHKOUT(b"SGWES", ctx)?;
                    return Ok(());
                }

                REFADR = (REFADR + SIZE);
            }
            //
            // 3) Create a reference directory if the number of
            //    references is greater than DIRSIZ.
            //
            if (save.FTNREF[save.INDEX] > DIRSIZ) {
                REFADR = (save.FTBADR[save.INDEX] + save.FTNCON[save.INDEX]);
                REFADR = (((REFADR + (save.FTNPKT[save.INDEX] * SIZE)) + DIRSIZ) - 1);

                for I in 1..=((save.FTNREF[save.INDEX] - 1) / DIRSIZ) {
                    DAFGDA(
                        HANDLE,
                        REFADR,
                        REFADR,
                        std::slice::from_mut(&mut MYREF),
                        ctx,
                    )?;
                    DAFADA(&[MYREF], 1, ctx)?;

                    if FAILED(ctx) {
                        CHKOUT(b"SGWES", ctx)?;
                        return Ok(());
                    }

                    REFADR = (REFADR + DIRSIZ);
                }
            }
            //
            // 4) Construct the meta data for the segment.
            //
            SIZE = ((save.FTOFF[save.INDEX] + save.FTPKSZ[save.INDEX]) * save.FTNPKT[save.INDEX]);

            META[CONBAS] = 0;
            META[NCON] = save.FTNCON[save.INDEX];
            META[PKTBAS] = (META[CONBAS] + META[NCON]);
            META[NPKT] = save.FTNPKT[save.INDEX];
            META[PKTOFF] = save.FTOFF[save.INDEX];
            META[PDRBAS] = 0;
            META[NPDR] = 0;
            META[PDRTYP] = 0;
            META[REFBAS] = (META[PKTBAS] + SIZE);
            META[NREF] = save.FTNREF[save.INDEX];
            META[RDRBAS] = (META[REFBAS] + META[NREF]);
            META[NRDR] = ((save.FTNREF[save.INDEX] - 1) / DIRSIZ);
            META[RDRTYP] = save.FTITYP[save.INDEX];
            META[RSVBAS] = 0;
            META[NRSV] = 0;
            META[PKTSZ] = save.FTPKSZ[save.INDEX];
            META[NMETA] = MXMETA;
        } else {
            //
            // We need to do a little bit of work to finish this case off.
            // We know that we need a packet directory and we need to store
            // in a contiguous block the references and a reference
            // directory if the number of references is greater than
            // DIRSIZ.
            //
            // We need to do the following things:
            //
            // 1) Set the beginning address of the packet data area in the
            //    segment and initialize the address of the first data
            //    packet.
            //
            PKTADR = ((save.FTBADR[save.INDEX] + save.FTNCON[save.INDEX]) + save.FTOFF[save.INDEX]);
            MYADDR = ((save.FTOFF[save.INDEX] + 1) as f64);
            //
            // 2) Create a packet directory. The packet directory consists
            //    of the beginning addresses for each of the packets and a
            //    fake beginning for an extra packet so that we can easily
            //    compute the size of the last packet.
            //
            for I in 1..=save.FTNPKT[save.INDEX] {
                DAFGDA(
                    HANDLE,
                    (PKTADR - 1),
                    (PKTADR - 1),
                    std::slice::from_mut(&mut MYSIZE),
                    ctx,
                )?;
                DAFADA(&[MYADDR], 1, ctx)?;

                if FAILED(ctx) {
                    CHKOUT(b"SGWES", ctx)?;
                    return Ok(());
                }

                SIZE = (MYSIZE as i32);
                PKTADR = ((PKTADR + SIZE) + save.FTOFF[save.INDEX]);
                MYADDR = (MYADDR + ((SIZE + save.FTOFF[save.INDEX]) as f64));
            }
            //
            // Put in the fake beginning for an extra packet. PKTADR should
            // contain the proper value.
            //
            MYADDR = (MYADDR as f64);

            DAFADA(&[MYADDR], 1, ctx)?;

            if FAILED(ctx) {
                CHKOUT(b"SGWES", ctx)?;
                return Ok(());
            }

            //
            // 3) Collect all of the references, stored with the packets
            //    when they were written, and copy them into the
            //    reference area.
            //
            REFADR = (save.FTBADR[save.INDEX] + save.FTNCON[save.INDEX]);

            for I in 1..=save.FTNPKT[save.INDEX] {
                DAFGDA(
                    HANDLE,
                    REFADR,
                    REFADR,
                    std::slice::from_mut(&mut MYREF),
                    ctx,
                )?;
                DAFGDA(
                    HANDLE,
                    (REFADR + 1),
                    (REFADR + 1),
                    std::slice::from_mut(&mut MYSIZE),
                    ctx,
                )?;
                DAFADA(&[MYREF], 1, ctx)?;

                if FAILED(ctx) {
                    CHKOUT(b"SGWES", ctx)?;
                    return Ok(());
                }

                SIZE = (MYSIZE as i32);
                REFADR = ((REFADR + SIZE) + save.FTOFF[save.INDEX]);
            }
            //
            // 3) Create a reference directory if the number of
            //    references is greater than DIRSIZ. Note that we have one
            //    more packet directory item than we have data packets.
            //    This allows us to compute the size of the last data
            //    packet.
            //
            if (save.FTNREF[save.INDEX] > DIRSIZ) {
                REFADR = (save.FTBADR[save.INDEX] + save.FTNCON[save.INDEX]);
                REFADR = (REFADR + save.FTPKSZ[save.INDEX]);
                REFADR = (REFADR + (save.FTOFF[save.INDEX] * save.FTNPKT[save.INDEX]));
                REFADR = ((REFADR + save.FTNPKT[save.INDEX]) + 1);
                REFADR = ((REFADR + DIRSIZ) - 1);

                for I in 1..=((save.FTNREF[save.INDEX] - 1) / DIRSIZ) {
                    DAFGDA(
                        HANDLE,
                        REFADR,
                        REFADR,
                        std::slice::from_mut(&mut MYREF),
                        ctx,
                    )?;
                    DAFADA(&[MYREF], 1, ctx)?;

                    if FAILED(ctx) {
                        CHKOUT(b"SGWES", ctx)?;
                        return Ok(());
                    }

                    REFADR = (REFADR + DIRSIZ);
                }
            }
            //
            // 4) Construct the meta data for the segment.
            //
            META[CONBAS] = 0;
            META[NCON] = save.FTNCON[save.INDEX];
            META[PKTBAS] = (META[CONBAS] + META[NCON]);
            META[NPKT] = save.FTNPKT[save.INDEX];
            META[PKTOFF] = save.FTOFF[save.INDEX];
            META[PDRBAS] = ((META[PKTBAS] + save.FTPKSZ[save.INDEX])
                + (save.FTOFF[save.INDEX] * save.FTNPKT[save.INDEX]));
            META[NPDR] = (save.FTNPKT[save.INDEX] + 1);
            META[PDRTYP] = 1;
            META[REFBAS] = (META[PDRBAS] + META[NPDR]);
            META[NREF] = save.FTNREF[save.INDEX];
            META[RDRBAS] = (META[REFBAS] + META[NREF]);
            META[NRDR] = ((save.FTNREF[save.INDEX] - 1) / DIRSIZ);
            META[RDRTYP] = save.FTITYP[save.INDEX];
            META[RSVBAS] = 0;
            META[NRSV] = 0;
            META[PKTSZ] = save.FTMXSZ[save.INDEX];
            META[NMETA] = MXMETA;
        }
    } else {
        //
        // We have an implicitly indexed segment.
        //
        if save.FXDSEG {
            //
            // There is no packet directory, so we just write the reference
            // values. There is no reference directory either, because
            // implicitly indexed packets only have two (2) reference
            // values.
            //
            DAFADA(
                save.FTREFS.subarray([1, save.INDEX]),
                save.FTNREF[save.INDEX],
                ctx,
            )?;

            if FAILED(ctx) {
                CHKOUT(b"SGWES", ctx)?;
                return Ok(());
            }
            //
            // Now we need to construct the meta data for this segment. We
            // will write it to the file a bit later.
            //
            SIZE = ((save.FTOFF[save.INDEX] + save.FTPKSZ[save.INDEX]) * save.FTNPKT[save.INDEX]);

            META[CONBAS] = 0;
            META[NCON] = save.FTNCON[save.INDEX];
            META[PKTBAS] = (META[CONBAS] + META[NCON]);
            META[NPKT] = save.FTNPKT[save.INDEX];
            META[PKTOFF] = save.FTOFF[save.INDEX];
            META[PDRBAS] = 0;
            META[NPDR] = 0;
            META[PDRTYP] = 0;
            META[REFBAS] = (META[PKTBAS] + SIZE);
            META[NREF] = save.FTNREF[save.INDEX];
            META[RDRBAS] = (META[REFBAS] + META[NREF]);
            META[NRDR] = 0;
            META[RDRTYP] = save.FTITYP[save.INDEX];
            META[RSVBAS] = 0;
            META[NRSV] = 0;
            META[PKTSZ] = save.FTPKSZ[save.INDEX];
            META[NMETA] = MXMETA;
        } else {
            //
            // We need to do a little bit of work to finish this case off.
            // We know that we need a packet directory, but we do not need
            // a reference directory.
            //
            // We need to do the following things:
            //
            // 1) Set the beginning address of the packet data area in the
            //    segment and initialize the address of the first data
            //    packet.
            //
            PKTADR = ((save.FTBADR[save.INDEX] + save.FTNCON[save.INDEX]) + save.FTOFF[save.INDEX]);
            MYADDR = ((save.FTOFF[save.INDEX] + 1) as f64);
            //
            // 2) Create a packet directory. The packet directory consists
            //    of the beginning addresses for each of the packets and a
            //    fake beginning for an extra packet so that we can easily
            //    compute the size of the last packet.
            //
            for I in 1..=save.FTNPKT[save.INDEX] {
                DAFGDA(
                    HANDLE,
                    (PKTADR - 1),
                    (PKTADR - 1),
                    std::slice::from_mut(&mut MYSIZE),
                    ctx,
                )?;
                DAFADA(&[MYADDR], 1, ctx)?;

                if FAILED(ctx) {
                    CHKOUT(b"SGWES", ctx)?;
                    return Ok(());
                }

                SIZE = (MYSIZE as i32);
                PKTADR = ((PKTADR + SIZE) + save.FTOFF[save.INDEX]);
                MYADDR = (MYADDR + ((SIZE + save.FTOFF[save.INDEX]) as f64));
            }
            //
            // Put in the fake beginning for an extra packet. PKTADR should
            // contain the proper value.
            //
            MYADDR = ((PKTADR - save.FTBADR[save.INDEX]) as f64);

            DAFADA(&[MYADDR], 1, ctx)?;

            if FAILED(ctx) {
                CHKOUT(b"SGWES", ctx)?;
                return Ok(());
            }
            //
            // 3) Construct the meta data for the segment.
            //
            META[CONBAS] = 0;
            META[NCON] = save.FTNCON[save.INDEX];
            META[PKTBAS] = (META[CONBAS] + META[NCON]);
            META[NPKT] = save.FTNPKT[save.INDEX];
            META[PKTOFF] = save.FTOFF[save.INDEX];
            META[PDRBAS] = ((META[PKTBAS] + save.FTPKSZ[save.INDEX])
                + (save.FTOFF[save.INDEX] * save.FTNPKT[save.INDEX]));
            META[NPDR] = (save.FTNPKT[save.INDEX] + 1);
            META[PDRTYP] = 1;
            META[REFBAS] = (META[PDRBAS] + META[NPDR]);
            META[NREF] = save.FTNREF[save.INDEX];
            META[RDRBAS] = (META[REFBAS] + META[NREF]);
            META[NRDR] = 0;
            META[RDRTYP] = save.FTITYP[save.INDEX];
            META[RSVBAS] = 0;
            META[NRSV] = 0;
            META[PKTSZ] = save.FTMXSZ[save.INDEX];
            META[NMETA] = MXMETA;
        }
    }
    //
    // Write the meta data to the segment and end the segment.
    //
    for I in 1..=MXMETA {
        XMETA[I] = (META[I] as f64);
    }

    DAFADA(XMETA.as_slice(), MXMETA, ctx)?;
    //
    // End the segment.
    //
    DAFENA(ctx)?;

    if FAILED(ctx) {
        CHKOUT(b"SGWES", ctx)?;
        return Ok(());
    }
    //
    // Now we need to clean up after ourselves, removing the information
    // for the segment we just ended from the file table.
    //
    save.NFT = (save.NFT - 1);

    for I in save.INDEX..=save.NFT {
        save.FTBADR[I] = save.FTBADR[(I + 1)];
        save.FTHAN[I] = save.FTHAN[(I + 1)];
        save.FTITYP[I] = save.FTITYP[(I + 1)];
        save.FTNCON[I] = save.FTNCON[(I + 1)];
        save.FTNPKT[I] = save.FTNPKT[(I + 1)];
        save.FTNREF[I] = save.FTNREF[(I + 1)];
        save.FTNRES[I] = save.FTNRES[(I + 1)];
        save.FTOFF[I] = save.FTOFF[(I + 1)];
        save.FTPKSZ[I] = save.FTPKSZ[(I + 1)];
        save.FTFIXD[I] = save.FTFIXD[(I + 1)];
        save.FTEXPL[I] = save.FTEXPL[(I + 1)];
    }

    if save.FXDSEG {
        save.NUMFXD = (save.NUMFXD - 1);
    } else {
        save.NUMVAR = (save.NUMVAR - 1);
    }

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