simple_components_4.68.0_da9b0f3a/py.adb

   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
--                                                                    --
--  package Py                      Copyright (c)  Dmitry A. Kazakov  --
--  Implementation                                 Luebeck            --
--                                                 Winter, 2018       --
--                                                                    --
--                                Last revision :  13:35 10 Sep 2023  --
--                                                                    --
--  This  library  is  free software; you can redistribute it and/or  --
--  modify it under the terms of the GNU General Public  License  as  --
--  published by the Free Software Foundation; either version  2  of  --
--  the License, or (at your option) any later version. This library  --
--  is distributed in the hope that it will be useful,  but  WITHOUT  --
--  ANY   WARRANTY;   without   even   the   implied   warranty   of  --
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU  --
--  General  Public  License  for  more  details.  You  should  have  --
--  received  a  copy  of  the GNU General Public License along with  --
--  this library; if not, write to  the  Free  Software  Foundation,  --
--  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.    --
--                                                                    --
--  As a special exception, if other files instantiate generics from  --
--  this unit, or you link this unit with other files to produce  an  --
--  executable, this unit does not by  itself  cause  the  resulting  --
--  executable to be covered by the GNU General Public License. This  --
--  exception  does not however invalidate any other reasons why the  --
--  executable file might be covered by the GNU Public License.       --
--____________________________________________________________________--

with Ada.IO_Exceptions;    use Ada.IO_Exceptions;
with Strings_Edit;         use Strings_Edit;
with Strings_Edit.Quoted;  use Strings_Edit.Quoted;
with Strings_Edit.UTF8;    use Strings_Edit.UTF8;

with System.Address_To_Access_Conversions;
with Ada.Characters.Latin_1;
with Ada.Calendar.Formatting;
with Ada.Calendar.Time_Zones;
with Ada.Directories;
with Ada.Tags;
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
with Strings_Edit.ISO_8601;
with Strings_Edit.UTF8.Categorization;
with Py.Load_Python_Library;

package body Py is
--
-- Python library bug work-around.  The exported  exception  objects are
-- broken. The true object will be detected by other means.
--
   TypeError   : Object := Null_Object;
   SystemError : Object := Null_Object;

   Too_Large_Integer : constant String := "Integer value is too large";

   procedure Load (Name : String := "") is
   begin
      Py.Load_Python_Library.Load (Name);
   end Load;

   procedure Check_Error is
   begin
      if Null_Object /= Links.Err_Occurred.all then
         declare
            Error_Type  : Object := Null_Object;
            Error_Value : Object := Null_Object;
            Traceback   : Object := Null_Object;
            function Message return String is
               Encoded : Handle;
               Ptr     : aliased Char_Ptrs.Pointer;
               Size    : aliased ssize_t;
            begin
               if Error_Value = Null_Object then
                  return "[No error message]";
               end if;
               Encoded.Ptr :=
                  Links.Unicode_AsEncodedString (Error_Value);
               if Encoded.Ptr = Null_Object then
                  Encoded.Ptr := Links.Object_Str (Error_Type);
                  if Encoded.Ptr = Null_Object then
                     Err_Clear;
                     return "[Malcoded error message]";
                  else
                     Size := Links.Unicode_GetLength (Encoded.Ptr);
                     if Size < 0 then
                        Err_Clear;
                        return "[Malformed type]";
                     elsif Size = 0 then
                        return "";
                     else
                        Err_Clear;
                        declare
                           Result  : String (1..Integer (Size * 4));
                           Pointer : Integer := 1;
                        begin
                           for Index in 0..Size - 1 loop
                              Put
                              (  Result,
                                 Pointer,
                                 Code_Point
                                 (  Wide_Wide_Character'Pos
                                    (  Links.Unicode_ReadChar
                                       (  Encoded.Ptr,
                                          Index
                              )  )  )  );
                              if Is_Err_Occurred then
                                 Err_Clear;
                                 return "[Malcoded type]";
                              end if;
                           end loop;
                           return Result (1..Pointer - 1);
                        end;
                     end if;
                  end if;
               else
                  if ( -1
                     =  Links.Bytes_AsStringAndSize
                        (  Encoded.Ptr,
                           Ptr'Access,
                           Size'Access
                     )  )  then
                     return "[Malformed message]";
                  else
                     return To_Ada
                            (  Char_Ptrs.Value (Ptr, ptrdiff_t (Size)),
                               False
                            );
                  end if;
               end if;
            end Message;
         begin
            Links.Err_Fetch (Error_Type, Error_Value, Traceback);
            Links.Err_NormalizeException
            (  Error_Type,
               Error_Value,
               Traceback
            );
            declare
               Text : constant String := Message;
            begin
               Links.Err_Restore (Error_Type, Error_Value, Traceback);
               Raise_Exception (Python_Error'Identity, Text);
            end;
         end;
      end if;
   end Check_Error;

   Reserved : Keyword_Tables.Table;

   procedure Check_Links (Library_Name : String) is
      procedure Error (Entry_Name : String) is
      begin
         Raise_Exception
         (  Use_Error'Identity,
            (  "Failed to locate entry "
            &  Entry_Name
            &  " in the Python DLL "
            &  Quote (Library_Name)
         )  );
      end Error;
   begin
      if Links.AddPendingCall = null then
         Error ("Py_AddPendingCall");
      elsif Links.Bool_FromLong = null then
         Error ("PyBool_FromLong");
      elsif Links.ByteArray_AsString = null then
         Error ("PyByteArray_AsString");
      elsif Links.ByteArray_FromStringAndSize = null then
         Error ("PyByteArray_FromStringAndSize");
      elsif Links.ByteArray_Size = null then
         Error ("PyByteArray_Size");
      elsif Links.ByteArray_Type = Null_Object then
         Error ("PyByteArray_Type");
      elsif Links.Bytes_AsStringAndSize = null then
         Error ("PyBytes_AsStringAndSize");
      elsif Links.Bytes_FromStringAndSize = null then
         Error ("PyBytes_FromStringAndSize");
      elsif Links.Bytes_Size = null then
         Error ("PyBytes_Size");
      elsif Links.Bytes_Type = Null_Object then
         Error ("PyBytes_Type");
      elsif Links.Capsule_GetContext = null then
         Error ("PyCapsule_GetContext");
      elsif Links.Capsule_GetDestructor = null then
         Error ("PyCapsule_GetDestructor");
      elsif Links.Capsule_GetName = null then
         Error ("PyCapsule_GetName");
      elsif Links.Capsule_GetPointer = null then
         Error ("PyCapsule_GetPointer");
      elsif Links.Capsule_Import = null then
         Error ("PyCapsule_Import");
      elsif Links.Capsule_IsValid = null then
         Error ("PyCapsule_IsValid");
      elsif Links.Capsule_New = null then
         Error ("PyCapsule_New");
      elsif Links.Capsule_SetContext = null then
         Error ("PyCapsule_SetContext");
      elsif Links.Capsule_SetDestructor = null then
         Error ("PyCapsule_SetDestructor");
      elsif Links.Capsule_SetName = null then
         Error ("PyCapsule_SetName");
      elsif Links.Capsule_SetPointer = null then
         Error ("PyCapsule_SetPointer");
      elsif Links.Callable_Check = null then
         Error ("PyCallable_Check");
      elsif Links.CompileString = null then
         Error ("Py_CompileString");
      elsif Links.DecRef = null then
         Error ("Py_DecRef");
  --  elsif Links.Dict_Check = null then
  --     Error ("Py_Dict_Check");
  --  elsif Links.Dict_CheckExact = null then
  --     Error ("Py_Dict_CheckExact");
      elsif Links.Dict_Clear = null then
         Error ("Py_Dict_Clear");
      elsif Links.Dict_Contains = null then
         Error ("Py_Dict_Contains");
      elsif Links.Dict_Copy = null then
         Error ("Py_Dict_Copy");
      elsif Links.Dict_Keys = null then
         Error ("Py_Dict_Keys");
      elsif Links.Dict_DelItem = null then
         Error ("Py_Dict_DelItem");
      elsif Links.Dict_DelItemString = null then
         Error ("Py_Dict_DelItemString");
      elsif Links.Dict_GetItemString = null then
         Error ("Py_Dict_GetItemString");
      elsif Links.Dict_Merge = null then
         Error ("Py_Dict_Merge");
      elsif Links.Dict_Next = null then
         Error ("Py_Dict_Next");
      elsif Links.Dict_Items = null then
         Error ("Py_Dict_Items");
      elsif Links.Dict_New = null then
         Error ("Py_Dict_New");
--    elsif Links.Dict_SetDefault = null then
--       Error ("Py_Dict_SetDefault");
      elsif Links.Dict_SetItem = null then
         Error ("Py_Dict_SetItem");
      elsif Links.Dict_SetItemString = null then
         Error ("Py_Dict_SetItemString");
      elsif Links.Dict_Size = null then
         Error ("Py_Dict_Size");
      elsif Links.Dict_Type = Null_Object then
         Error ("PyDict_Type");
      elsif Links.EndInterpreter = null then
         Error ("Py_EndInterpreter");
      elsif Links.Err_BadArgument = null then
         Error ("PyErr_BadArgument");
      elsif Links.Err_BadInternalCall = null then
         Error ("PyErr_BadInternalCall");
      elsif Links.Err_Clear = null then
         Error ("PyErr_Clear");
      elsif Links.Err_Fetch = null then
         Error ("PyErr_Fetch");
      elsif Links.Err_NewException = null then
         Error ("PyErr_NewException");
      elsif Links.Err_NormalizeException = null then
         Error ("PyErr_NormalizeException");
      elsif Links.Err_Occurred = null then
         Error ("PyErr_Occurred");
      elsif Links.Err_SetString = null then
         Error ("PyErr_SetString");
      elsif Links.Eval_InitThreads = null then
         Error ("PyEval_InitThreads");
      elsif Links.Eval_RestoreThread = null then
         Error ("PyEval_RestoreThread");
      elsif Links.Eval_SaveThread = null then
         Error ("PyEval_SaveThread");
      elsif Links.Exc_KeyError = null then
         Error ("PyExc_KeyError");
      elsif Links.Exc_LookupError = null then
         Error ("PyExc_LookupError");
      elsif Links.Exc_NameError = null then
         Error ("PyExc_NameError");
      elsif Links.Exc_PermissionError = null then
         Error ("PyExc_RuntimeError");
      elsif Links.Exc_RuntimeError = null then
         Error ("PyExc_RuntimeError");
      elsif Links.Exc_SyntaxError = null then
         Error ("PyExc_SyntaxError");
      elsif Links.Exc_SystemError = null then
         Error ("PyExc_SystemError");
      elsif Links.Exc_TypeError = null then
         Error ("PyExc_TypeError");
      elsif Links.Exc_TimeoutError = null then
         Error ("PyExc_TimeoutError");
      elsif Links.Exc_ValueError = null then
         Error ("PyExc_ValueError");
      elsif Links.FinalizeEx = null then
         Error ("Py_FinalizeEx");
--    elsif Links.GILState_Check = null then
--       Error ("PyGILState_Check");
      elsif Links.GILState_Ensure = null then
         Error ("PyGILState_Ensure");
      elsif Links.GILState_Release = null then
         Error ("PyGILState_Release");
      elsif Links.Float_AsDouble = null then
         Error ("PyFloat_AsDouble");
      elsif Links.Float_FromDouble = null then
         Error ("PyFloat_FromDouble");
      elsif Links.Float_Type = Null_Object then
         Error ("PyFloat_Type");
      elsif Links.Import_AddModule = null then
         Error ("PyImport_AddModule");
      elsif Links.Import_AppendInittab = null then
         Error ("PyImport_AppendInittab");
      elsif Links.Import_ExecCodeModuleEx = null then
         Error ("PyImport_ExecCodeModuleEx");
      elsif Links.Import_GetModule = null then
         Error ("PyImport_GetModule");
      elsif Links.Import_ImportModule = null then
         Error ("PyImport_ImportModule");
      elsif Links.IncRef = null then
         Error ("Py_IncRef");
      elsif Links.InitializeEx = null then
         Error ("Py_InitializeEx");
      elsif Links.Iter_Check = null then
         Error ("PyIter_Check");
      elsif Links.Iter_Next = null then
         Error ("PyIter_Next");
      elsif Links.List_Append = null then
         Error ("PyList_Append");
      elsif Links.List_AsTuple = null then
         Error ("PyList_AsTuple");
--    elsif Links.List_Check = null then
--       Error ("PyList_Check");
      elsif Links.List_Insert = null then
         Error ("PyList_Insert");
      elsif Links.List_GetItem = null then
         Error ("PyList_GetItem");
      elsif Links.List_GetSlice = null then
         Error ("PyList_GetSlice");
      elsif Links.List_New = null then
         Error ("PyList_New");
      elsif Links.List_Reverse = null then
         Error ("PyList_Reverse");
      elsif Links.List_SetItem = null then
         Error ("PyList_SetItem");
      elsif Links.List_SetSlice = null then
         Error ("PyList_SetSlice");
      elsif Links.List_Size = null then
         Error ("PyList_Size");
      elsif Links.List_Sort = null then
         Error ("PyList_Sort");
      elsif Links.List_Type = Null_Object then
         Error ("PyList_Type");
      elsif Links.Long_AsLong = null then
         Error ("PyLong_AsLong");
      elsif Address (Links.Long_AsLongLong) = Null_Address then
         Error ("PyLong_AsLongLong");
      elsif Links.Long_AsUnsignedLong = null then
         Error ("PyLong_AsUnsignedLong");
      elsif Address (Links.Long_AsUnsignedLongLong) = Null_Address then
         Error ("PyLong_AsUnsignedLongLong");
      elsif Links.Long_FromLong = null then
         Error ("PyLong_FromLong");
      elsif Address (Links.Long_FromLongLong) = Null_Address then
         Error ("PyLong_FromLongLong");
      elsif Links.Long_FromUnsignedLong = null then
         Error ("PyLong_FromUnsignedLong");
      elsif Address (Links.Long_FromUnsignedLongLong) =
                                                       Null_Address then
         Error ("PyLong_FromUnsignedLongLong");
      elsif Links.Long_Type = Null_Object then
         Error ("PyLong_Type");
      elsif Links.Module_AddObject = null then
         Error ("PyModule_AddObject");
      elsif Links.Module_Create = null then
         Error ("PyModule_Create2");
      elsif Links.Module_GetDict = null then
         Error ("PyModule_GetDict");
      elsif Links.Module_GetName = null then
         Error ("PyModule_GetName");
      elsif Links.NewInterpreter = null then
         Error ("Py_NewInterpreter");
      elsif Links.None = Null_Object then
         Error ("_PyNone_Struct");
      elsif Links.Object_Bytes = null then
         Error ("PyObject_Bytes");
--    elsif Links.Object_CallNoArgs = null then
--       Error ("PyObject_CallNoArgs");
      elsif Links.Object_CallObject = null then
         Error ("PyObject_CallObject");
      elsif Links.Object_DelItem = null then
         Error ("PyObject_DelItem");
      elsif Links.Object_Dir = null then
         Error ("PyObject_Dir");
      elsif Links.Object_GetAttr = null then
         Error ("PyObject_GetAttr");
      elsif Links.Object_GetAttrString = null then
         Error ("PyObject_GetAttrString");
      elsif Links.Object_GetItem = null then
         Error ("PyObject_GetItem");
      elsif Links.Object_GetIter = null then
         Error ("PyObject_GetIter");
      elsif Links.Object_GenericGetAttr = null then
         Error ("PyObject_GenericGetAttr");
      elsif Links.Object_GenericSetAttr = null then
         Error ("PyObject_GenericSetAttr");
      elsif Links.Object_HasAttr = null then
         Error ("PyObject_HasAttr");
      elsif Links.Object_HasAttrString = null then
         Error ("PyObject_HasAttrString");
      elsif Links.Object_IsInstance = null then
         Error ("PyObject_IsInstance");
      elsif Links.Object_IsSubclass = null then
         Error ("PyObject_IsSubclass");
      elsif Links.Object_RichCompareBool = null then
         Error ("PyObject_RichCompareBool");
      elsif Links.Object_SetAttr = null then
         Error ("PyObject_SetAttr");
      elsif Links.Object_SetAttrString = null then
         Error ("PyObject_SetAttrString");
      elsif Links.Object_SetItem = null then
         Error ("PyObject_SetItem");
      elsif Links.Object_Size = null then
         Error ("PyObject_Size");
      elsif Links.Object_Str = null then
         Error ("PyObject_Str");
      elsif Links.Object_Type = null then
         Error ("PyObject_Type");
      elsif Links.Sequence_Check = null then
         Error ("PySequence_Check");
      elsif Links.Sequence_Concat = null then
         Error ("PySequence_Concat");
      elsif Links.Sequence_Contains = null then
         Error ("PySequence_Contains");
      elsif Links.Sequence_Count = null then
         Error ("PySequence_Count");
      elsif Links.Sequence_DelItem = null then
         Error ("PySequence_DelItem");
      elsif Links.Sequence_DelSlice = null then
         Error ("PySequence_DelSlice");
      elsif Links.Sequence_GetItem = null then
         Error ("PySequence_GetItem");
      elsif Links.Sequence_GetSlice = null then
         Error ("PySequence_GetSlice");
      elsif Links.Sequence_Index = null then
         Error ("PySequence_Index");
      elsif Links.Sequence_List = null then
         Error ("PySequence_List");
      elsif Links.Sequence_Repeat = null then
         Error ("PySequence_Repeat");
      elsif Links.Sequence_SetItem = null then
         Error ("PySequence_SetItem");
      elsif Links.Sequence_SetSlice = null then
         Error ("PySequence_SetSlice");
      elsif Links.Sequence_Size = null then
         Error ("PySequence_Size");
      elsif Links.Sequence_Tuple = null then
         Error ("PySequence_Tuple");
      elsif Links.Set_Add = null then
         Error ("PySet_Add");
      elsif Links.Set_Clear = null then
         Error ("PySet_Clear");
      elsif Links.Set_Contains = null then
         Error ("PySet_Contains");
      elsif Links.Set_Discard = null then
         Error ("PySet_Discard_Ptr");
      elsif Links.FrozenSet_New = null then
         Error ("PyFrozenset_New");
      elsif Links.Set_New = null then
         Error ("PySet_New");
      elsif Links.Set_Pop = null then
         Error ("PySet_Pop");
      elsif Links.Set_Size = null then
         Error ("PySet_Size");
      elsif Links.Set_Type = Null_Object then
         Error ("PySet_Type");
      elsif Links.Sys_GetObject = null then
         Error ("PySys_GetObject");
--    elsif Links.Sys_GetSizeOf = null then
--       Error ("_PySys_GetSizeOf");
      elsif Links.ThreadState_Get = null then
         Error ("PyThreadState_Get");
      elsif Links.ThreadState_Swap = null then
         Error ("PyThreadState_Swap");
      elsif Links.Unicode_AsEncodedString = null then
         Error ("PyUnicode_AsEncodedString");
      elsif Links.Tuple_GetItem = null then
         Error ("PyTuple_GetItem");
      elsif Links.Tuple_GetSlice = null then
         Error ("PyTuple_GetSlice");
      elsif Links.Tuple_New = null then
         Error ("PyTuple_New");
      elsif Links.Tuple_SetItem = null then
         Error ("PyTuple_SetItem");
      elsif Links.Tuple_Size = null then
         Error ("PyTuple_Size");
      elsif Links.Tuple_Type = Null_Object then
         Error ("PyTuple_Type");
      elsif Links.Type_FromSpec = null then
         Error ("PyType_Type_FromSpec");
      elsif Links.Type_FromSpecWithBases = null then
         Error ("PyType_FromSpecWithBases");
      elsif Links.Type_IsSubtype = null then
         Error ("PyType_IsSubtype");
      elsif Links.Type_Type = Null_Object then
         Error ("PyType_Type");
      elsif Links.Unicode_GetLength = null then
         Error ("Unicode_GetLength");
      elsif Links.Unicode_DecodeFSDefault = null then
         Error ("PyUnicode_DecodeFSDefault");
      elsif Links.Unicode_FromString = null then
         Error ("Unicode_FromString");
      elsif Links.Unicode_FromStringAndSize = null then
         Error ("Unicode_FromStringAndSize");
      elsif Links.Unicode_ReadChar = null then
         Error ("Unicode_ReadChar");
      elsif Links.Unicode_Type = Null_Object then
         Error ("PyUnicode_Type");
      end if;
      Reserved.Add ("False",    True);
      Reserved.Add ("None",     True);
      Reserved.Add ("True",     True);
      Reserved.Add ("and",      True);
      Reserved.Add ("as",       True);
      Reserved.Add ("assert",   True);
      Reserved.Add ("break",    True);
      Reserved.Add ("class",    True);
      Reserved.Add ("continue", True);
      Reserved.Add ("def",      True);
      Reserved.Add ("del",      True);
      Reserved.Add ("elif",     True);
      Reserved.Add ("else",     True);
      Reserved.Add ("except",   True);
      Reserved.Add ("finally",  True);
      Reserved.Add ("for",      True);
      Reserved.Add ("from",     True);
      Reserved.Add ("global",   True);
      Reserved.Add ("if",       True);
      Reserved.Add ("import",   True);
      Reserved.Add ("in",       True);
      Reserved.Add ("is",       True);
      Reserved.Add ("lambda",   True);
      Reserved.Add ("nonlocal", True);
      Reserved.Add ("not",      True);
      Reserved.Add ("or",       True);
      Reserved.Add ("pass",     True);
      Reserved.Add ("raise",    True);
      Reserved.Add ("return",   True);
      Reserved.Add ("try",      True);
      Reserved.Add ("while",    True);
      Reserved.Add ("with",     True);
      Reserved.Add ("yield",    True);
   end Check_Links;

   procedure Check_Handle (Object : Handle) is
      pragma Inline (Check_Handle);
   begin
      if Object.Ptr = Null_Object then
         Raise_Exception (Constraint_Error'Identity, "Null object");
      end if;
   end Check_Handle;

   procedure Check_Spelling (Name : String) is
      use Keyword_Tables;
      Offset : constant Integer := Locate (Reserved, Name);
   begin
      if Offset > 0 then
         Raise_Exception
         (  Use_Error'Identity,
            (  Quote (GetName (Reserved, Offset))
            &  " is a reserved keyword"
         )  );
      end if;
   end Check_Spelling;

   function Check_Matched (Source : String; Pointer : Integer)
      return Boolean is
      use Strings_Edit.UTF8.Categorization;
      Index : Integer;
      This  : UTF8_Code_Point;
   begin
      Index := Pointer;
      Get (Source, Index, This);
      if not Is_Alphanumeric (This) then
         return True;
      end if;
      Index := Pointer;
      Get_Backwards (Source, Index, This);
      return not Is_Alphanumeric (This);
   exception
      when others =>
         return True;
   end Check_Matched;

   function As_Integer64 (Value : Object)
      return Interfaces.Integer_64 is
      function To_Integer
               (  Ptr      : Long_AsLongLong_Ptr;
                  Data     : Py.Object;
                  Overflow : access int
               )  return Interfaces.Integer_64;
      pragma Import (C, To_Integer, "long_toint64");
      Result   : Interfaces.Integer_64;
      Overflow : aliased int;
   begin
      Result :=
         To_Integer (Links.Long_AsLongLong, Value, Overflow'Access);
      Check_Error;
      if Overflow = 0 then
         return Result;
      else
         Raise_Exception (Constraint_Error'Identity, Too_Large_Integer);
      end if;
   end As_Integer64;

   function As_String (Value : Object) return String is
      Length : ssize_t;
   begin
      Length := Links.Unicode_GetLength (Value);
      if Length < 0 then
         Check_Error;
         return "";
      elsif Length = 0 then
         return "";
      else
         declare
            Result  : String (1..Integer (Length * 4));
            Pointer : Integer := 1;
         begin
            for Index in 0..Length - 1 loop
               Put
               (  Result,
                  Pointer,
                  Code_Point
                  (  Wide_Wide_Character'Pos
                     (  Links.Unicode_ReadChar (Value, Index)
               )  )  );
            end loop;
            Check_Error;
            return Result (1..Pointer - 1);
         end;
      end if;
   end As_String;

   function As_String (Object : Handle) return String is
   begin
      Check_Handle (Object);
      return As_String (Object.Ptr);
   end As_String;

   function As_Unsigned64 (Value : Object)
      return Interfaces.Unsigned_64 is
      function To_Integer
               (  Ptr      : Long_AsUnsignedLongLong_Ptr;
                  Data     : Py.Object;
                  Overflow : access int
               )  return Interfaces.Unsigned_64;
      pragma Import (C, To_Integer, "long_touint64");
      Result   : Interfaces.Unsigned_64;
      Overflow : aliased int;
   begin
      Result := To_Integer
                (  Links.Long_AsUnsignedLongLong,
                   Value,
                   Overflow'Access
                );
      Check_Error;
      if Overflow = 0 then
         return Result;
      else
         Raise_Exception (Constraint_Error'Identity, Too_Large_Integer);
      end if;
   end As_Unsigned64;

   function ByteArray_AsString (Object : Handle) return String is
      use Char_Ptrs;
      Ptr  : aliased Pointer;
      Size : constant ssize_t := ByteArray_Size (Object);
   begin
      if Size = 0 then
         return "";
      end if;
      Ptr := Links.ByteArray_AsString (Object.Ptr);
      declare
         Result : String (1..Natural (Size));
      begin
         for Index in Result'Range loop
            Result (Index) := To_Ada (Ptr.all);
            Increment (Ptr);
         end loop;
         return Result;
      end;
   end ByteArray_AsString;

   function ByteArray_AsString (Object : Handle)
      return Stream_Element_Array is
      use Char_Ptrs;
      Ptr  : aliased Pointer;
      Size : constant ssize_t := ByteArray_Size (Object);
   begin
      if Size = 0 then
         return (1..0 => 0);
      end if;
      Ptr := Links.ByteArray_AsString (Object.Ptr);
      declare
         Result : Stream_Element_Array
                  (  1
                  .. Stream_Element_Count (Size)
                  );
      begin
         for Index in Result'Range loop
            Result (Index) := char'Pos (Ptr.all);
            Increment (Ptr);
         end loop;
         return Result;
      end;
   end ByteArray_AsString;

   function ByteArray_FromString (Value : String) return Handle is
      Result : Handle;
   begin
      if Value'Length = 0 then
         Result.Ptr :=
            Links.ByteArray_FromStringAndSize (Null_Address, 0);
      else
         Result.Ptr :=
            Links.ByteArray_FromStringAndSize
            (  Value'Address,
               Value'Length
            );
      end if;
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end ByteArray_FromString;

   function ByteArray_FromString (Value : Stream_Element_Array)
      return Handle is
      Result : Handle;
   begin
      if Value'Length = 0 then
         Result.Ptr :=
            Links.ByteArray_FromStringAndSize (Null_Address, 0);
      else
         Result.Ptr :=
            Links.ByteArray_FromStringAndSize
            (  Value'Address,
               Value'Length
            );
      end if;
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end ByteArray_FromString;

   function ByteArray_Size (Object : Handle) return ssize_t is
      Result : ssize_t;
   begin
      Check_Handle (Object);
      Result := Links.ByteArray_Size (Object.Ptr);
      if Result < 0 then
         Check_Error;
      end if;
      return Result;
   end ByteArray_Size;

   function ByteArray_Type return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.ByteArray_Type;
      Links.IncRef (Result.Ptr);
      return Result;
   end ByteArray_Type;

   function Bytes_AsString (Object : Handle) return String is
      use Char_Ptrs;
      Ptr  : aliased Pointer;
      Size : aliased ssize_t := 0;
   begin
      Check_Handle (Object);
      if -1 = Links.Bytes_AsStringAndSize
              (  Object.Ptr,
                 Ptr'Access,
                 Size'Access
              )  then
         Check_Error;
      end if;
      if Ptr = null or else Size = 0 then
         return "";
      else
         declare
            Result : String (1..Integer (Size));
         begin
            for Index in Result'Range loop
               Result (Index) := To_Ada (Ptr.all);
               Increment (Ptr);
            end loop;
            return Result;
         end;
      end if;
   end Bytes_AsString;

   function Bytes_AsString (Object : Handle)
      return Stream_Element_Array is
      use Char_Ptrs;
      Ptr  : aliased Pointer;
      Size : aliased ssize_t := 0;
   begin
      Check_Handle (Object);
      if -1 = Links.Bytes_AsStringAndSize
              (  Object.Ptr,
                 Ptr'Access,
                 Size'Access
              )  then
         Check_Error;
      end if;
      if Ptr = null or else Size = 0 then
         return (1..0 => 0);
      else
         declare
            Result : Stream_Element_Array
                     (  1
                     .. Stream_Element_Count (Size)
                     );
         begin
            for Index in Result'Range loop
               Result (Index) := char'Pos (Ptr.all);
               Increment (Ptr);
            end loop;
            return Result;
         end;
      end if;
   end Bytes_AsString;

   function Bytes_FromString (Value : String) return Handle is
      Result : Handle;
   begin
      if Value'Length = 0 then
         Result.Ptr :=
            Links.Bytes_FromStringAndSize (Null_Address, 0);
      else
         Result.Ptr :=
            Links.Bytes_FromStringAndSize (Value'Address, Value'Length);
      end if;
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Bytes_FromString;

   function Bytes_FromString (Value : Stream_Element_Array)
      return Handle is
      Result : Handle;
   begin
      if Value'Length = 0 then
         Result.Ptr :=
            Links.Bytes_FromStringAndSize (Null_Address, 0);
      else
         Result.Ptr :=
            Links.Bytes_FromStringAndSize (Value'Address, Value'Length);
      end if;
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Bytes_FromString;

   function Bytes_Size (Object : Handle) return ssize_t is
      Result : ssize_t;
   begin
      Check_Handle (Object);
      Result := Links.Bytes_Size (Object.Ptr);
      if Result < 0 then
         Check_Error;
      end if;
      return Result;
   end Bytes_Size;

   function Bytes_Type return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.Bytes_Type;
      Links.IncRef (Result.Ptr);
      return Result;
   end Bytes_Type;

   function Callable_Check (Object : Handle) return int is
   begin
      Check_Handle (Object);
      return Links.Callable_Check (Object.Ptr);
   end Callable_Check;

   Single_Input    : constant := 256;
   File_Input      : constant := 257;
   Eval_Input      : constant := 258;
   Func_Type_Input : constant := 345;

   function Compile
            (  Source    : String;
               File_Name : String
            )  return Handle is
      function Get_Name return String is
         Line_Start : Boolean := True;
         Pointer    : Integer := Source'First;
         Start      : Integer;
      begin
         while Pointer <= Source'Last loop
            case Source (Pointer) is
               when 'd' =>
                  Pointer := Pointer + 1;
                  if Line_Start then
                     if Is_Prefix ("ef", Source, Pointer) then
                        Pointer := Pointer + 2;
                        Start   := Pointer;
                        Get (Source, Pointer);
                        if Start /= Pointer then
                           Start := Pointer;
                           while Pointer <= Source'Last loop
                              case Source (Pointer) is
                                 when Character'Val (9)  |
                                      Character'Val (13) |
                                      ' '                |
                                      '('                =>
                                    return Source (Start..Pointer - 1);
                                 when others =>
                                    Pointer := Pointer + 1;
                              end case;
                           end loop;
                           return Source (Start..Pointer - 1);
                        end if;
                     end if;
                  end if;
                  Line_Start := False;
               when Character'Val (10) =>
                  Line_Start := True;
                  Pointer    := Pointer + 1;
               when Character'Val (9) | Character'Val (13) | ' ' =>
                  Pointer := Pointer + 1;
               when others =>
                  Line_Start := False;
                  Pointer := Pointer + 1;
            end case;
         end loop;
         return "";
      end Get_Name;

      Name   : constant String := Get_Name;
      Code   : Handle;
      Module : Handle;
      Func   : Handle;
   begin
      if Name'Length = 0 then
         Raise_Exception
         (  Data_Error'Identity,
            "No function definition found"
         );
      end if;
      Code.Ptr :=
         Links.CompileString
         (  To_C (Source),
            To_C (File_Name),
            File_Input
         );
      if Code.Ptr = Null_Object then
         Check_Error;
      end if;
      Module.Ptr :=
         Links.Import_ExecCodeModuleEx
         (  To_C (File_Name & '.' & Name),
            Code.Ptr
         );
      if Module.Ptr = Null_Object then
         Check_Error;
      end if;
      Func.Ptr := Links.Object_GetAttrString (Module.Ptr, To_C (Name));
      if Func.Ptr = Null_Object then
         Check_Error;
      end if;
      return Func;
   end Compile;

   procedure Dict_DelItem (Dictionary : Handle; Key : Handle) is
   begin
      Check_Handle (Dictionary);
      Check_Handle (Key);
      case Links.Dict_DelItem (Dictionary.Ptr, Key.Ptr) is
         when 0 =>
            null;
         when others =>
            Check_Error;
      end case;
   end Dict_DelItem;

   procedure Dict_DelItemString (Dictionary : Handle; Key : String) is
   begin
      Check_Handle (Dictionary);
      case Links.Dict_DelItemString (Dictionary.Ptr, To_C (Key)) is
         when 0 =>
            null;
         when others =>
            Check_Error;
      end case;
   end Dict_DelItemString;

   function Dict_GetItemString
            (  Dictionary : Handle;
               Key        : String
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (Dictionary);
      Result.Ptr :=
         Links.Dict_GetItemString (Dictionary.Ptr, To_C (Key));
      if Result.Ptr /= Null_Object then -- Borrowed reference
         Links.IncRef (Result.Ptr);
      end if;
      return Result;
   end Dict_GetItemString;

--  function Dict_Check (Dictionary : Handle; Exact : Boolean := False)
--     return Boolean is
--  begin
--     Check_Handle (Dictionary);
--     if Exact then
--        return 0 /= Links.Dict_CheckExact (Dictionary.Ptr);
--     else
--        return 0 /= Links.Dict_Check (Dictionary.Ptr);
--     end if;
--  end Dict_Check;

   procedure Dict_Clear (Dictionary : Handle) is
   begin
      Check_Handle (Dictionary);
      Links.Dict_Clear (Dictionary.Ptr);
   end Dict_Clear;

   function Dict_Contains (Dictionary : Handle; Key : Handle)
      return Boolean is
   begin
      Check_Handle (Dictionary);
      Check_Handle (Key);
      case Links.Dict_Contains (Dictionary.Ptr, Key.Ptr) is
         when 0 =>
            return False;
         when 1 =>
            return True;
         when others =>
            Raise_Exception
            (  Python_Error'Identity,
               "Error in Dict_Contains"
            );
      end case;
   end Dict_Contains;

   function Dict_Copy (Dictionary : Handle) return Handle is
      Result : Handle;
   begin
      Check_Handle (Dictionary);
      Result.Ptr := Links.Dict_Copy (Dictionary.Ptr);
      if Result.Ptr = Null_Object then -- New reference
         Check_Error;
      end if;
      return Result;
   end Dict_Copy;

   function Dict_Keys (Dictionary : Handle) return Handle is
      Result : Handle;
   begin
      Check_Handle (Dictionary);
      Result.Ptr := Links.Dict_Keys (Dictionary.Ptr);
      if Result.Ptr = Null_Object then -- New reference
         Check_Error;
      end if;
      return Result;
   end Dict_Keys;

   procedure Dict_Merge
             (  Dictionary : Handle;
                Update     : Handle;
                Override   : Boolean
             )  is
   begin
      Check_Handle (Dictionary);
      Check_Handle (Update);
      if Override then
         if 0 = Links.Dict_Merge (Dictionary.Ptr, Update.Ptr, 1) then
            return;
         end if;
      else
         if 0 = Links.Dict_Merge (Dictionary.Ptr, Update.Ptr, 0) then
            return;
         end if;
      end if;
      Raise_Exception
      (  Python_Error'Identity,
         "Dictionaries merging error"
      );
   end Dict_Merge;

   function Dict_Next
            (  Dictionary : Handle;
               Position   : access ssize_t;
               Key        : access Handle;
               Value      : access Handle
            )  return Boolean is
   begin
      Check_Handle (Dictionary);
      Invalidate (Key.all);
      Invalidate (Value.all);
      if 0 = Links.Dict_Next
             (  Dictionary.Ptr,
                Position,
                Key.Ptr'Access,
                Value.Ptr'Access
             )  then
         return False;
      else
         Links.IncRef (Key.Ptr);
         Links.IncRef (Value.Ptr);
         return True;
      end if;
   end Dict_Next;

   function Dict_Items (Dictionary : Handle) return Handle is
      Result : Handle;
   begin
      Check_Handle (Dictionary);
      Result.Ptr := Links.Dict_Items (Dictionary.Ptr);
      if Result.Ptr = Null_Object then -- New reference
         Check_Error;
      end if;
      return Result;
   end Dict_Items;

   function Dict_New return Handle is
   begin
      return (Ada.Finalization.Controlled with Links.Dict_New.all);
   end Dict_New;

--  function Dict_SetDefault
--           (  Dictionary : Handle;
--              Key        : Handle;
--              Default    : Handle
--           )  return Handle is
--     Result : Handle;
--  begin
--     Check_Handle (Dictionary);
--     Check_Handle (Key);
--     Check_Handle (Default);
--     Result.Ptr := Links.Dict_SetDefault
--                   (  Dictionary.Ptr,
--                      Key.Ptr,
--                      Default.Ptr
--                   );
--     Links.IncRef (Result.Ptr);
--     return Result;
--  end Dict_SetDefault;

   procedure Dict_SetItem
             (  Dictionary : Handle;
                Key        : Handle;
                Value      : Handle
             ) is
   begin
      Check_Handle (Dictionary);
      Check_Handle (Key);
      Check_Handle (Value);
      if 0 /= Links.Dict_SetItem
              (  Dictionary.Ptr,
                 Key.Ptr,
                 Value.Ptr
              )
      then
         Raise_Exception
         (  Data_Error'Identity,
            "Failed to set dictionary item"
         );
      end if;
   end Dict_SetItem;

   procedure Dict_SetItemString
             (  Dictionary : Handle;
                Key        : String;
                Value      : Handle
             ) is
   begin
      Check_Handle (Dictionary);
      Check_Handle (Value);
      if 0 /= Links.Dict_SetItemString
              (  Dictionary.Ptr,
                 To_C (Key),
                 Value.Ptr
              )
      then
         Raise_Exception
         (  Data_Error'Identity,
            "Failed to set dictionary item by string"
         );
      end if;
   end Dict_SetItemString;

   function Dict_Size (Dictionary : Handle) return ssize_t is
      Result : ssize_t;
   begin
      Check_Handle (Dictionary);
      Result := Links.Dict_Size (Dictionary.Ptr);
      Check_Error;
      return Result;
   end Dict_Size;

   function Dict_Type return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.Dict_Type;
      Links.IncRef (Result.Ptr);
      return Result;
   end Dict_Type;

   procedure Err_Clear is
   begin
      Links.Err_Clear.all;
   end Err_Clear;

   function Err_Occurred return Handle is
   begin
      return (Ada.Finalization.Controlled with Links.Err_Occurred.all);
   end Err_Occurred;

   procedure Eval_InitThreads is
   begin
      Links.Eval_InitThreads.all;
   end Eval_InitThreads;

   procedure Eval_RestoreThread (State : ThreadState) is
   begin
      Links.Eval_RestoreThread (State);
   end Eval_RestoreThread;

   function Eval_SaveThread return ThreadState is
   begin
      return Links.Eval_SaveThread.all;
   end Eval_SaveThread;

   procedure Finalize (Lock : in out Global_Interpreter_Lock) is
   begin
      Links.GILState_Release (Lock.State);
   end Finalize;

   function FinalizeEx return int is
   begin
      TypeError   := Null_Object;
      SystemError := Null_Object;
      return Links.FinalizeEx.all;
   end FinalizeEx;

   function Float_AsDouble (Object : Handle) return double is
      Result : constant double := Links.Float_AsDouble (Object.Ptr);
   begin
      Check_Error;
      return Result;
   end Float_AsDouble;

   function Float_FromDouble (Value : double) return Handle is
      Result : constant Object := Links.Float_FromDouble (Value);
   begin
      if Result = Null_Object then
         Check_Error;
      end if;
      return (Ada.Finalization.Controlled with Result);
   end Float_FromDouble;

   function Float_Type return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.Float_Type;
      Links.IncRef (Result.Ptr);
      return Result;
   end Float_Type;

-- function GILState_Check return Boolean is
-- begin
--    return 0 /= Links.GILState_Check.all;
-- end GILState_Check;

   procedure Initialize is
   begin
      Links.InitializeEx (0);
   end Initialize;

   function Import
            (  File_Name  : String;
               Entry_Name : String
            )  return Handle is
      use Ada.Directories;
      Name_Start  : Integer := File_Name'First;
      Name_Stop   : Integer := File_Name'Last;
      System_Path : Handle;
      Module_Name : Handle;
      Module      : Handle;
      Result      : Handle;
   begin
      for Index in reverse File_Name'Range loop
         case File_Name (Index) is
            when '.' =>
               if Name_Stop = File_Name'Last then
                  Name_Stop := Index - 1;
               end if;
            when '/' | '\' =>
               Name_Start := Index + 1;
               exit;
            when others =>
               null;
         end case;
      end loop;
      if Name_Stop < Name_Start then
         Raise_Exception
         (  Ada.IO_Exceptions.Name_Error'Identity,
            "Module name is empty"
         );
      end if;
      Module_Name :=
         Unicode_FromString (File_Name (Name_Start..Name_Stop));
      Module.Ptr := Links.Import_GetModule (Module_Name.Ptr);
      if Module.Ptr = Null_Object then
         System_Path := Sys_GetObject ("path");
         declare
            Restore_Path : Boolean := False;
         begin
            if Is_Valid (System_Path) then
               if Name_Start - 1 > File_Name'First then -- Have a path
                  List_Insert
                  (  System_Path,
                     0,
                     Unicode_FromString
                     (  File_Name (File_Name'First..Name_Start - 2)
                  )  );
               else
                  List_Insert
                  (  System_Path,
                     0,
                     Unicode_FromString (Current_Directory)
                  );
               end if;
               Restore_Path := True;
            end if;
            Module.Ptr := Links.Import_Import (Module_Name.Ptr);
            if Module.Ptr = Null_Object then
               Check_Error;
            end if;
            if Restore_Path then
               if 0 > Links.List_SetSlice
                      (  System_Path.Ptr,
                         0,
                         0,
                         Null_Object
                      )  then
                  Check_Error;
               end if;
            end if;
         exception
            when others =>
               if Restore_Path then
                  if 0 > Links.List_SetSlice
                         (  System_Path.Ptr,
                            0,
                            0,
                            Null_Object
                         )  then
                     null;
                  end if;
               end if;
               raise;
         end;
      end if;
      Result := Object_GetAttrString (Module, Entry_Name);
      if Callable_Check (Result) = 0 then
         Raise_Exception
         (  Mode_Error'Identity,
            Entry_Name & " is not callable"
         );
      end if;
      return Result;
   end Import;

   function Import_AddModule (Name : String) return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.Import_AddModule (To_C (Name));
      if Result.Ptr = Null_Object then
         Check_Error;
      else -- Borrowed reference
         Links.IncRef (Result.Ptr);
      end if;
      return Result;
   end Import_AddModule;

   function Import_AppendInittab
            (  Name : char_array;
               Init : InitTab
            )  return int is
   begin
      return Links.Import_AppendInittab (Name, Init);
   end Import_AppendInittab;

   function Import_ExecCodeModuleEx
            (  Name : String;
               Code : Handle;
               Path : String := ""
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (Code);
      if Path'Length = 0 then
         Result.Ptr :=
            Links.Import_ExecCodeModuleEx (To_C (Name), Code.Ptr);
      else
         declare
            File_Path : constant char_array := To_C (Path);
         begin
            Result.Ptr :=
               Links.Import_ExecCodeModuleEx
               (  To_C (Name),
                  Code.Ptr,
                  File_Path (File_Path'First)'Unchecked_Access
               );
         end;
      end if;
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Import_ExecCodeModuleEx;

   function Import_GetModule (Name : String) return Handle is
      Result : Handle;
      Object : constant Handle := Unicode_FromString (Name);
   begin
      Result.Ptr := Links.Import_GetModule (Object.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Import_GetModule;

   function Import_Import (Name : Handle) return Handle is
      Result : Handle;
   begin
      Check_Handle (Name);
      Result.Ptr := Links.Import_Import (Name.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Import_Import;

   procedure Import_Import
             (  Name        : Handle;
                Module      : out Handle;
                Destination : in out String;
                Pointer     : in out Integer;
                No_Error    : out Boolean;
                Decorator   : String := Character'Val (13) &
                                        Character'Val (10) &
                                        "   "
             )  is
   begin
      Initialize (Module);
      Check_Handle (Name);
      Module.Ptr := Links.Import_Import (Name.Ptr);
      if (  Module.Ptr = Null_Object
         or else
            Null_Object /= Links.Err_Occurred.all
         )  then
         Error_Traceback (Destination, Pointer, No_Error, Decorator);
      else
         No_Error := True;
      end if;
   end Import_Import;

   procedure Import_Import
             (  Name        : String;
                Module      : out Handle;
                Destination : in out String;
                Pointer     : in out Integer;
                No_Error    : out Boolean;
                Decorator   : String := Character'Val (13) &
                                        Character'Val (10) &
                                        "   "
             )  is
   begin
      Invalidate (Module);
      Module.Ptr := Links.Import_ImportModule (To_C (Name));
      if (  Module.Ptr = Null_Object
         or else
            Null_Object /= Links.Err_Occurred.all
         )  then
         Error_Traceback (Destination, Pointer, No_Error, Decorator);
      else
         No_Error := True;
      end if;
   end Import_Import;

   function Import_ImportModule (Name : String) return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.Import_ImportModule (To_C (Name));
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Import_ImportModule;

   procedure Initialize (Lock : in out Global_Interpreter_Lock) is
   begin
      Lock.State := Links.GILState_Ensure.all;
   end Initialize;

   procedure Invalidate (Object : in out Handle) is
   begin
      if Object.Ptr /= Null_Object then
         Links.DecRef (Object.Ptr);
         Object.Ptr := Null_Object;
      end if;
   end Invalidate;

   function Is_Err_Occurred return Boolean is
   begin
      return Null_Object /= Links.Err_Occurred.all;
   end Is_Err_Occurred;

   function Is_In (Object : Handle; Class : Handle) return Boolean is
   begin
      Check_Handle (Class);
      return Object_IsInstance (Object, Class);
   end Is_In;

   function Is_None (Object : Handle) return Boolean is
   begin
      return Object.Ptr = Null_Object or else Object.Ptr = Links.None;
   end Is_None;

   function Is_Null (Reference : Object) return Boolean is
   begin
      return Reference = Null_Object;
   end Is_Null;

   function Is_Valid (Object : Handle) return Boolean is
   begin
      return Object.Ptr /= Null_Object;
   end Is_Valid;

   procedure Adjust (Object : in out Handle) is
   begin
      if Object.Ptr /= Null_Object then
         Links.IncRef (Object.Ptr);
      end if;
   end Adjust;

   procedure Error_Traceback
             (  Destination : in out String;
                Pointer     : in out Integer;
                No_Error    : out Boolean;
                Decorator   : String := Character'Val (13) &
                                        Character'Val (10) &
                                        "   ";
                Clear_Error : Boolean := True
             )  is
      Error : Object;
   begin
      Error := Links.Err_Occurred.all;
      if Error = Null_Object then
         No_Error := True;
         return;
      end if;
      No_Error := False;
      declare
         Class    : Handle;
         Message  : Handle;
         Trace    : Handle;
         Position : Integer := Pointer;
      begin
         Links.Err_Fetch (Class.Ptr, Message.Ptr, Trace.Ptr);
         Links.Err_NormalizeException
         (  Class.Ptr,
            Message.Ptr,
            Trace.Ptr
         );
         Put (Destination, Position, Object_Str (Message));
         Put (Destination, Position, " [");
         Put (Destination, Position, Object_Str (Class));
         Put (Destination, Position, "]");
         if not Is_Valid (Trace) then
            return;
         end if;
         declare
            Func   : Handle;
            Module : Handle;
         begin
            Module :=
               Import_Import (Unicode_DecodeFSDefault ("traceback"));
            Func := Object_GetAttrString (Module, "format_tb");
            if Callable_Check (Func) = 0 then
               declare
                  Args  : Handle;
                  Value : Handle;
               begin
                  Args := Tuple_New (1);
                  Tuple_SetItem (Args, 0, Trace);
                  Value := Object_CallObject (Func, Args);
                  if Is_Valid (Value) then
                     declare
                        Length : constant ssize_t := List_Size (Value);
                        Item   : Object;
                     begin
                        for Index in 0..Length - 1 loop
                           Item :=
                              Links.List_GetItem (Value.Ptr, Index);
                           if Item /= Null_Object then
                              Put (Destination, Position, Decorator);
                              Put
                              (  Destination,
                                 Position,
                                 As_String (Item)
                              );
                           end if;
                        end loop;
                     end;
                  end if;
               end;
            end if;
         end;
         if not Clear_Error then
            Links.Err_Restore (Class.Ptr, Message.Ptr, Trace.Ptr);
         end if;
         Pointer := Position;
      exception
         when others =>
            Links.Err_Restore (Class.Ptr, Message.Ptr, Trace.Ptr);
            raise;
      end;
   end Error_Traceback;

   procedure Finalize (Object : in out Handle) is
   begin
      Invalidate (Object);
   end Finalize;

   function Iter_Check (Iterator : Handle) return Boolean is
   begin
      return
      (  Iterator.Ptr /= Null_Object
      and then
         0 /= Links.Iter_Check (Iterator.Ptr)
      );
   end Iter_Check;

   function Iter_Next (Iterator : Handle) return Handle is
      Result : Handle;
   begin
      Check_Handle (Iterator);
      Result.Ptr := Links.Iter_Next (Iterator.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Iter_Next;

   procedure List_Append (List : Handle; Item : Handle) is
   begin
      Check_Handle (List);
      if Links.List_Append (List.Ptr, Item.Ptr) = -1 then
         Check_Error;
      end if;
   end List_Append;

   function List_AsTuple (List : Handle) return Handle is
      Result : Handle;
   begin
      Check_Handle (List);
      Result.Ptr := Links.List_AsTuple (List.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end List_AsTuple;

-- function List_Check (List : Handle; Exact : Boolean := False)
--    return Boolean is
-- begin
--    Check_Handle (List);
--    if Exact then
--       return 0 /= Links.List_CheckExact (List.Ptr);
--    else
--        return 0 /= Links.List_Check (List.Ptr);
--    end if;
-- end List_Check;

   function List_New (Size : ssize_t) return Handle is
   begin
      return (Ada.Finalization.Controlled with Links.List_New (Size));
   end List_New;

   function List_GetItem
            (  List  : Handle;
               Index : ssize_t
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (List);
      Result.Ptr := Links.List_GetItem (List.Ptr, Index);
      if Result.Ptr = Null_Object then
         Check_Error;
      else
         Links.IncRef (Result.Ptr); -- Borrowed reference
      end if;
      return Result;
   end List_GetItem;

   function List_GetSlice
            (  List : Handle;
               Low  : ssize_t;
               High : ssize_t
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (List);
      Result.Ptr := Links.List_GetSlice (List.Ptr, Low, High);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end List_GetSlice;

   procedure List_Insert
             (  List  : Handle;
                Index : ssize_t;
                Item  : Handle
             )  is
   begin
      Check_Handle (List);
      Check_Handle (Item);
      if Links.List_Insert (List.Ptr, Index, Item.Ptr) = -1 then
         Check_Error;
      end if;
   end List_Insert;

   procedure List_Reverse (List : Handle) is
   begin
      Check_Handle (List);
      if Links.List_Reverse (List.Ptr) = -1 then
         Check_Error;
      end if;
   end List_Reverse;

   procedure List_SetItem
             (  List  : Handle;
                Index : ssize_t;
                Item  : Handle
             )  is
   begin
      Check_Handle (List);
      Check_Handle (Item);
      if Links.List_SetItem (List.Ptr, Index, Item.Ptr) = -1 then
         Check_Error;
      end if;
   end List_SetItem;

   procedure List_SetSlice
             (  List  : Handle;
                Low   : ssize_t;
                High  : ssize_t
             )  is
   begin
      Check_Handle (List);
      if (  Links.List_SetSlice (List.Ptr, Low, High, Null_Object)
         = -1
         )  then
         Check_Error;
      end if;
   end List_SetSlice;

   procedure List_SetSlice
             (  List  : Handle;
                Low   : ssize_t;
                High  : ssize_t;
                Items : Handle
             )  is
   begin
      Check_Handle (List);
      Check_Handle (Items);
      if Links.List_SetSlice (List.Ptr, Low, High, Items.Ptr) = -1 then
         Check_Error;
      end if;
   end List_SetSlice;

   function List_Size (Object : Handle) return ssize_t is
   begin
      if Object.Ptr = Null_Object then
         return 0;
      else
         return Links.List_Size (Object.Ptr);
      end if;
   end List_Size;

   procedure List_Sort (List : Handle) is
   begin
      Check_Handle (List);
      if Links.List_Sort (List.Ptr) = -1 then
         Check_Error;
      end if;
   end List_Sort;

   function List_Type return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.List_Type;
      Links.IncRef (Result.Ptr);
      return Result;
   end List_Type;

   function Long_AsLong (Object : Handle) return long is
      Result : constant long := Links.Long_AsLong (Object.Ptr);
   begin
      Check_Error;
      return Result;
   end Long_AsLong;

   function Long_AsInteger64 (Object : Handle)
      return Interfaces.Integer_64 is
   begin
      return As_Integer64 (Object.Ptr);
   end Long_AsInteger64;

   function Long_AsUnsignedLong (Object : Handle)
      return unsigned_long is
      Result : constant unsigned_long :=
                        Links.Long_AsUnsignedLong (Object.Ptr);
   begin
      Check_Error;
      return Result;
   end Long_AsUnsignedLong;

   function Long_AsUnsigned64 (Object : Handle)
      return Interfaces.Unsigned_64 is
   begin
      return As_Unsigned64 (Object.Ptr);
   end Long_AsUnsigned64;

   function Long_FromLong (Value : long) return Handle is
      Result : constant Object := Links.Long_FromLong (Value);
   begin
      if Result = Null_Object then
         Check_Error;
      end if;
      return (Ada.Finalization.Controlled with Result);
   end Long_FromLong;

   function Long_FromInteger64 (Value : Interfaces.Integer_64)
      return Handle is
      function ">"
               (  Ptr   : Long_FromLongLong_Ptr;
                  Value : Interfaces.Integer_64
               )  return Py.Object;
      pragma Import (C, ">", "long_fromint64");
      Result : constant Object := Links.Long_FromLongLong > Value;
   begin
      if Result = Null_Object then
         Check_Error;
      end if;
      return (Ada.Finalization.Controlled with Result);
   end Long_FromInteger64;

   function Long_FromUnsignedLong (Value : unsigned_long)
      return Handle is
      Result : constant Object := Links.Long_FromUnsignedLong (Value);
   begin
      if Result = Null_Object then
         Check_Error;
      end if;
      return (Ada.Finalization.Controlled with Result);
   end Long_FromUnsignedLong;

   function Long_FromUnsigned64 (Value : Interfaces.Unsigned_64)
      return Handle is
      function ">"
               (  Ptr   : Long_FromUnsignedLongLong_Ptr;
                  Value : Interfaces.Unsigned_64
               )  return Py.Object;
      pragma Import (C, ">", "long_fromuint64");
      Result : constant Object :=
               Links.Long_FromUnsignedLongLong > Value;
   begin
      if Result = Null_Object then
         Check_Error;
      end if;
      return (Ada.Finalization.Controlled with Result);
   end Long_FromUnsigned64;

   function Long_Type return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.Long_Type;
      Links.IncRef (Result.Ptr);
      return Result;
   end Long_Type;

   procedure Module_AddObject
             (  Module : Handle;
                Name   : String;
                Value  : Handle
             )  is
   begin
      Check_Handle (Module);
      Check_Handle (Value);
      if 0 > Links.Module_AddObject
             (  Module.Ptr,
                To_C (Name),
                Value.Ptr
             )  then -- Failure
         Check_Error;
      else -- Success, the reference is stolen
         Links.IncRef (Value.Ptr);
      end if;
   end Module_AddObject;

   function Module_Create
            (  Modules : ModuleDef;
               Version : int := 1013
            )  return Object is
   begin
      return Links.Module_Create (Modules, Version);
   end Module_Create;

   function Module_GetDict (Module : Handle) return Handle is
      Result : Handle;
   begin
      Check_Handle (Module);
      Result.Ptr := Links.Module_GetDict (Module.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      else
         Links.IncRef (Result.Ptr); -- Borrowed reference
      end if;
      return Result;
   end Module_GetDict;

   function Module_GetName (Module : Handle) return String is
      Result : chars_ptr;
   begin
      Check_Handle (Module);
      Result := Links.Module_GetName (Module.Ptr);
      if Result = Null_Ptr then
         Check_Error;
         return "";
      else
         return Value (Result);
      end if;
   end Module_GetName;

   function No_Value return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.None;
      Links.IncRef (Result.Ptr);
      return Result;
   end No_Value;

   function Object_Bytes (Object : Handle) return Handle is
      Result : Handle;
   begin
      Check_Handle (Object);
      Result.Ptr := Links.Object_Bytes (Object.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Object_Bytes;

   function Object_Call
            (  Operation : Handle;
               Arguments : Handle;
               Keyed     : Handle;
               Check     : Boolean := False
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (Operation);
      Result.Ptr :=
         Links.Object_Call (Operation.Ptr, Arguments.Ptr, Keyed.Ptr);
      if Check and then Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Object_Call;

   function Object_CallNoArgs
            (  Operation : Handle;
               Check     : Boolean := False
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (Operation);
      if Links.Object_CallNoArgs = null then
         declare
            Arguments : constant Handle := Tuple_New (0);
         begin
            Result.Ptr :=
               Links.Object_CallObject (Operation.Ptr, Arguments.Ptr);
            if Check and then Result.Ptr = Null_Object then
               Check_Error;
            end if;
         end;
      else
         Result.Ptr :=
            Links.Object_CallNoArgs (Operation.Ptr);
         if Check and then Result.Ptr = Null_Object then
            Check_Error;
         end if;
      end if;
      return Result;
   end Object_CallNoArgs;

   function Object_CallObject
            (  Operation : Handle;
               Arguments : Handle;
               Check     : Boolean := False
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (Operation);
      Result.Ptr :=
         Links.Object_CallObject (Operation.Ptr, Arguments.Ptr);
      if Check and then Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Object_CallObject;

   procedure Object_DelItem
            (  Object : Handle;
               Key    : Handle
            )  is
   begin
      Check_Handle (Object);
      Check_Handle (Key);
      if (  -1
         =  Links.Object_DelItem (Object.Ptr, Key.Ptr)
         )  then
         Check_Error;
      end if;
   end Object_DelItem;

   function Object_GenericGetAttr
            (  Object : Handle;
               Name   : Handle
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (Object);
      Check_Handle (Name);
      Result.Ptr := -- New reference
         Links.Object_GenericGetAttr (Object.Ptr, Name.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Object_GenericGetAttr;

   procedure Object_GenericSetAttr
            (  Object : Handle;
               Name   : Handle;
               Value  : Handle
            )  is
   begin
      Check_Handle (Object);
      Check_Handle (Name);
      Check_Handle (Value);
      if (  -1
         =  Links.Object_GenericSetAttr
            (  Object.Ptr,
               Name.Ptr,
               Value.Ptr
         )  )  then
         Check_Error;
      end if;
   end Object_GenericSetAttr;

   function Object_GetAttr
            (  Object    : Handle;
               Attribute : Handle
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (Object);
      Check_Handle (Attribute);
      Result.Ptr := -- New reference
         Links.Object_GetAttr (Object.Ptr, Attribute.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Object_GetAttr;

   function Object_GetAttrString
            (  Object : Handle;
               Name   : String
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (Object);
      Result.Ptr := -- New reference
         Links.Object_GetAttrString (Object.Ptr, To_C (Name));
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Object_GetAttrString;

   function Object_GetItem
            (  Object : Handle;
               Key    : Handle
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (Object);
      Check_Handle (Key);
      Result.Ptr := -- New reference
         Links.Object_GetAttr (Object.Ptr, Key.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Object_GetItem;

   function Object_GetIter (Object : Handle) return Handle is
      Result : Handle;
   begin
      Check_Handle (Object);
      Result.Ptr := -- New reference
         Links.Object_GetIter (Object.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Object_GetIter;

   function Object_Dir (Object : Handle) return Handle is
       Result : Handle;
   begin
      Check_Handle (Object);
      Result.Ptr := Links.Object_Dir (Object.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Object_Dir;

   function Object_HasAttr
            (  Object    : Handle;
               Attribute : Handle
            )  return Boolean is
   begin
      Check_Handle (Object);
      Check_Handle (Attribute);
      return 0 /= Links.Object_HasAttr (Object.Ptr, Attribute.Ptr);
   end Object_HasAttr;

   function Object_HasAttrString
            (  Object : Handle;
               Name   : String
            )  return Boolean is
   begin
      Check_Handle (Object);
      return 0 /= Links.Object_HasAttrString (Object.Ptr, To_C (Name));
   end Object_HasAttrString;

   Head_Size : ssize_t := 0;

   function Object_HeadSize return ssize_t is
   begin
      if Head_Size = 0 then
         declare
            use Ada.Characters.Latin_1;
            Args   : Handle;
            Size   : Handle;
            Helper : Handle;
         begin
            Helper :=
               Compile
               (  "import sys"         & LF &
                  "def FloatSizeOf():" & LF &
                  "   x = 0.0;"        & LF &
                  "   return sys.getsizeof(x)",
                  "py.adb"
               );
            Args := Py.Tuple_New (0);
            Size := Py.Object_CallObject (Helper, Args, True);
            Head_Size :=
               ssize_t (Links.Long_AsLong (Size.Ptr)) - double'Size / 8;
         end;
      end if;
      return Head_Size;
   end Object_HeadSize;

   function Object_IsInstance
            (  Object : Handle;
               Class  : Handle
            )  return Boolean is
      Result : int;
   begin
      Check_Handle (Object);
      Check_Handle (Class);
      Result := Links.Object_IsInstance (Object.Ptr, Class.Ptr);
      if Result = -1 then
         Check_Error;
      end if;
      return Result /= 0;
   end Object_IsInstance;

   function Object_IsSubclass
            (  Derived : Handle;
               Class   : Handle
            )  return Boolean is
      Result : int;
   begin
      Check_Handle (Derived);
      Check_Handle (Class);
      Result := Links.Object_IsSubclass (Derived.Ptr, Class.Ptr);
      if Result = -1 then
         Check_Error;
      end if;
      return Result /= 0;
   end Object_IsSubclass;

   function Object_RichCompareBool
            (  Left      : Handle;
               Right     : Handle;
               Operation : Comparison_Type
            )  return Boolean is
      Op : int;
   begin
      Check_Handle (Left);
      Check_Handle (Right);
      case Operation is
         when LT => Op := 0;
         when LE => Op := 1;
         when EQ => Op := 2;
         when NE => Op := 3;
         when GT => Op := 4;
         when GE => Op := 5;
      end case;
      case Links.Object_RichCompareBool (Left.Ptr, Right.Ptr, Op) is
         when 0 =>
            return False;
         when 1 =>
            return True;
         when others =>
            Check_Error;
            return False;
      end case;
   end Object_RichCompareBool;

   procedure Object_SetAttr
            (  Object    : Handle;
               Attribute : Handle;
               Value     : Handle
            )  is
   begin
      Check_Handle (Object);
      Check_Handle (Attribute);
      Check_Handle (Value);
      if (  -1
         =  Links.Object_SetAttr
            (  Object.Ptr,
               Attribute.Ptr,
               Value.Ptr
         )  )  then
         Check_Error;
      end if;
   end Object_SetAttr;

   procedure Object_SetAttr
            (  Object    : Handle;
               Attribute : Handle
            )  is
   begin
      Check_Handle (Object);
      Check_Handle (Attribute);
      if (  -1
         =  Links.Object_SetAttr
            (  Object.Ptr,
               Attribute.Ptr,
               Null_Object
         )  )  then
         Check_Error;
      end if;
   end Object_SetAttr;

   procedure Object_SetAttrString
            (  Object : Handle;
               Name   : String;
               Value  : Handle
            )  is
   begin
      Check_Handle (Object);
      Check_Handle (Value);
      if (  -1
         =  Links.Object_SetAttrString
            (  Object.Ptr,
               To_C (Name),
               Value.Ptr
         )  )  then
         Check_Error;
      end if;
   end Object_SetAttrString;

   procedure Object_SetAttrString
            (  Object : Handle;
               Name   : String
            )  is
   begin
      Check_Handle (Object);
      if (  -1
         =  Links.Object_SetAttrString
            (  Object.Ptr,
               To_C (Name),
               Null_Object
         )  )  then
         Check_Error;
      end if;
   end Object_SetAttrString;

   procedure Object_SetItem
            (  Object : Handle;
               Key    : Handle;
               Value  : Handle
            )  is
   begin
      Check_Handle (Object);
      Check_Handle (Key);
      Check_Handle (Value);
      if (  -1
         =  Links.Object_SetItem (Object.Ptr, Key.Ptr, Value.Ptr)
         )  then
         Check_Error;
      end if;
   end Object_SetItem;

   function Object_Size (Object : Handle) return ssize_t is
      Result : ssize_t;
   begin
      Check_Handle (Object);
      Result := Links.Object_Size (Object.Ptr);
      if Result < 0 then
         Check_Error;
      end if;
      return Result;
   end Object_Size;

   function Object_Str (Value : Object) return String is
   begin
      if Value = Null_Object then
         return "";
      end if;
      declare
         Result : constant Object := Links.Object_Str (Value);
      begin
         if Result = Null_Object then
            return "";
         else
            return As_String
                   (  (Ada.Finalization.Controlled with Result)
                   );
         end if;
      end;
   end Object_Str;

   function Object_Str (Object : Handle) return String is
   begin
      if Object.Ptr = Null_Object then
         return "";
      else
         return Object_Str (Object.Ptr);
      end if;
   end Object_Str;

   function Object_Type (Object : Handle) return Handle is
      Result : Handle;
   begin
      Check_Handle (Object);
      Result.Ptr := Links.Object_Type (Object.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Object_Type;

   function Parse
            (  Args     : Object;
               Keywords : Object;
               List     : Argument_List
            )  return Object_Array is
      use Object_Tables;

      procedure Error (Message : String) is
      begin
         Throw_TypeError (Message);
         Raise_Exception (Python_Error'Identity, Message);
      end Error;

      Unmatched : ssize_t := 0;
      Result    : Object_Array (1..List.Length) :=
                     (others => Null_Object);
   begin
      if Keywords /= Null_Object then
         Unmatched := Links.Dict_Size (Keywords);
      end if;
      if Result'Length < (Links.Tuple_Size (Args) + Unmatched) then
         Error ("Too many arguments");
      end if;
      for Index in 1..Links.Tuple_Size (Args) loop
         Result (Argument_Position (Index)) :=
            Links.Tuple_GetItem (Args, Index - 1);
      end loop;
      for Index in Argument_Position (Links.Tuple_Size (Args) + 1)
                .. Result'Last loop
         declare
            Name : constant String :=
                            GetName (List.Keys, List.Offsets (Index));
         begin
            if Keywords /= Null_Object then
               Result (Index) :=
                  Links.Dict_GetItemString (Keywords, To_C (Name));
            end if;
            if Result (Index) = Null_Object then
               if not List.Optional (Index) then
                  Error ("Missing mandatory argument " & Quote (Name));
               end if;
            else
               Unmatched := Unmatched - 1;
            end if;
         end;
      end loop;
      if Unmatched > 0 then
         declare
            Key      : aliased Object;
            Value    : aliased Object;
            Position : aliased ssize_t := 0;
         begin
            while 0 /= Links.Dict_Next
                       (  Keywords,
                          Position'Access,
                          Key'Access,
                          Value'Access
                       )  loop
               declare
                  Name : constant String := As_String (Key);
               begin
                  if 0 >= Locate (List.Keys, Name) then
                     Error ("Unmatched argument " & Quote (Name));
                  end if;
               end;
            end loop;
         end;
      end if;
      return Result;
   end Parse;

   function Quit (Data : System.Address) return int is
   begin
      Links.Err_SetString (Links.Exc_SystemError.all, "Abort" & Nul);
      return 0;
   end Quit;

   procedure Request_Abort is
   begin
      if 0 = Links.AddPendingCall (Quit'Access, System.Null_Address)
      then
         null;
      end if;
   end Request_Abort;

   procedure Reraise_As (ID : Exception_ID) is
      Error : Object;
   begin
      Error := Links.Err_Occurred.all;
      if Error /= Null_Object then
         declare
            Class   : Handle;
            Message : Handle;
            Trace   : Handle;
         begin
            Links.Err_Fetch (Class.Ptr, Message.Ptr, Trace.Ptr);
            Links.Err_NormalizeException
            (  Class.Ptr,
               Message.Ptr,
               Trace.Ptr
            );
            Raise_Exception (ID, Object_Str (Message));
         end;
      end if;
   end Reraise_As;

   function Sequence_Check (Sequence : Handle) return Boolean is
   begin
      return
      (  Sequence.Ptr /= Null_Object
      and then
         0 /= Links.Sequence_Check (Sequence.Ptr)
      );
   end Sequence_Check;

   function Sequence_Concat (Left, Right : Handle) return Handle is
      Result : Handle;
   begin
      Check_Handle (Left);
      Check_Handle (Right);
      Result.Ptr := Links.Sequence_Concat (Left.Ptr, Right.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Sequence_Concat;

   function Sequence_Contains (Sequence : Handle; Item : Handle)
      return Boolean is
      Result : int;
   begin
      Check_Handle (Sequence);
      Check_Handle (Item);
      Result := Links.Sequence_Contains (Sequence.Ptr, Item.Ptr);
      if Result = -1 then
         Check_Error;
      end if;
      return Result /= 0;
   end Sequence_Contains;

   function Sequence_Count (Sequence : Handle; Item : Handle)
      return Natural is
      Result : ssize_t;
   begin
      Check_Handle (Sequence);
      Check_Handle (Item);
      Result := Links.Sequence_Count (Sequence.Ptr, Item.Ptr);
      if Result = -1 then
         Check_Error;
      end if;
      return Natural (Result);
   end Sequence_Count;

   procedure Sequence_DelItem (Sequence : Handle; Index : ssize_t) is
   begin
      Check_Handle (Sequence);
      if Links.Sequence_DelItem (Sequence.Ptr, Index) = -1 then
         Check_Error;
      end if;
   end Sequence_DelItem;

   procedure Sequence_DelSlice
             (  Sequence : Handle;
                Low      : ssize_t;
                High     : ssize_t
             )  is
   begin
      Check_Handle (Sequence);
      if Links.Sequence_DelSlice (Sequence.Ptr, Low, High) = -1 then
         Check_Error;
      end if;
   end Sequence_DelSlice;

   function Sequence_GetItem
            (  Sequence : Handle;
               Index    : ssize_t
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (Sequence);
      Result.Ptr := Links.Sequence_GetItem (Sequence.Ptr, Index);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Sequence_GetItem;

   function Sequence_GetSlice
            (  Sequence : Handle;
               Low      : ssize_t;
               High     : ssize_t
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (Sequence);
      Result.Ptr := Links.Sequence_GetSlice (Sequence.Ptr, Low, High);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Sequence_GetSlice;

   function Sequence_Index
            (  Sequence : Handle;
               Item     : Handle
            )  return ssize_t is
      Result : ssize_t;
   begin
      Check_Handle (Sequence);
      Check_Handle (Item);
      Result := Links.Sequence_Index (Sequence.Ptr, Item.Ptr);
      if Result < 0 then
         Check_Error;
      end if;
      return Result;
   end Sequence_Index;

   function Sequence_List (Sequence : Handle) return Handle is
      Result : Handle;
   begin
      Check_Handle (Sequence);
      Result.Ptr := Links.Sequence_List (Sequence.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Sequence_List;

   function Sequence_Repeat
            (  Sequence : Handle;
               Count    : Positive := 1
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (Sequence);
      Result.Ptr :=
         Links.Sequence_Repeat (Sequence.Ptr, ssize_t (Count));
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Sequence_Repeat;

   procedure Sequence_SetItem
             (  Sequence : Handle;
                Index    : ssize_t;
                Item     : Handle
             )  is
   begin
      Check_Handle (Sequence);
      Check_Handle (Item);
      if Links.Sequence_SetItem (Sequence.Ptr, Index, Item.Ptr) = -1
      then
         Check_Error;
      end if;
   end Sequence_SetItem;

   procedure Sequence_SetSlice
             (  Sequence : Handle;
                Low      : ssize_t;
                High     : ssize_t;
                Items    : Handle
             )  is
   begin
      Check_Handle (Sequence);
      Check_Handle (Items);
      if (  Links.Sequence_SetSlice
            (  Sequence.Ptr,
               Low,
               High,
               Items.Ptr
            )
         = -1
         )  then
         Check_Error;
      end if;
   end Sequence_SetSlice;

   function Sequence_Size (Sequence : Handle) return ssize_t is
      Result : ssize_t;
   begin
      Check_Handle (Sequence);
      Result := Links.Sequence_Size (Sequence.Ptr);
      if Result < 0 then
         Check_Error;
      end if;
      return Result;
   end Sequence_Size;

   function Sequence_Tuple (Sequence : Handle) return Handle is
      Result : Handle;
   begin
      Check_Handle (Sequence);
      Result.Ptr := Links.Sequence_Tuple (Sequence.Ptr);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Sequence_Tuple;

   procedure Set_Add (Set : Handle; Item : Handle) is
      Result : int;
   begin
      Check_Handle (Set);
      Check_Handle (Item);
      Result := Links.Set_Add (Set.Ptr, Item.Ptr);
      Check_Error;
   end Set_Add;

   procedure Set_Clear (Set : Handle) is
      Result : int;
   begin
      Check_Handle (Set);
      Result := Links.Set_Clear (Set.Ptr);
      Check_Error;
   end Set_Clear;

   function Set_Contains (Set : Handle; Item : Handle) return Boolean is
      Result : Boolean;
   begin
      Check_Handle (Set);
      Check_Handle (Item);
      Result := Links.Set_Contains (Set.Ptr, Item.Ptr) = 1;
      Check_Error;
      return Result;
   end Set_Contains;

   function Set_Discard (Set : Handle; Item : Handle) return Boolean is
      Result : Boolean;
   begin
      Check_Handle (Set);
      Check_Handle (Item);
      Result := Links.Set_Discard (Set.Ptr, Item.Ptr) = 1;
      Check_Error;
      return Result;
   end Set_Discard;

   function Set_New (Frozen : Boolean) return Handle is
      Result : Object;
   begin
      if Frozen then
         Result := Links.FrozenSet_New.all;
      else
         Result := Links.Set_New.all;
      end if;
      return (Ada.Finalization.Controlled with Result);
   end Set_New;

   function Set_Pop (Set : Handle) return Handle is
      Result : Object;
   begin
      Check_Handle (Set);
      Result := Links.Set_Pop (Set.Ptr);
      if Result = Null_Object then
         Check_Error;
      end if;
      return (Ada.Finalization.Controlled with Result);
   end Set_Pop;

   function Set_Size (Set : Handle) return ssize_t is
      Result : ssize_t;
   begin
      Check_Handle (Set);
      Result := Links.Set_Size (Set.Ptr);
      Check_Error;
      return Result;
   end Set_Size;

   function Set_Type return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.Set_Type;
      Links.IncRef (Result.Ptr);
      return Result;
   end Set_Type;

   function Sys_GetObject (Name : String) return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.Sys_GetObject (To_C (Name));
      if Result.Ptr /= Null_Object then
         Links.IncRef (Result.Ptr); -- Borrowed reference
      end if;
      return Result;
   end Sys_GetObject;

-- function Sys_GetSizeOf (Object : Handle) return ssize_t is
--    Result : ssize_t;
-- begin
--    Check_Handle (Object);
--    Result := Links.Sys_GetSizeOf (Object.Ptr);
--    if Result < 0 then
--       Check_Error;
--    end if;
--    return Result;
-- end Sys_GetSizeOf;

   function ThreadState_Get return ThreadState is
   begin
      return Links.ThreadState_Get.all;
   end ThreadState_Get;

   function ThreadState_Swap (State : ThreadState) return ThreadState is
   begin
      return Links.ThreadState_Swap (State);
   end ThreadState_Swap;

   procedure Throw_KeyError (Message : String) is
   begin
      Links.Err_SetString (Links.Exc_KeyError.all, To_C (Message));
   end Throw_KeyError;

   procedure Throw_LookupError (Message : String) is
   begin
      Links.Err_SetString (Links.Exc_LookupError.all, To_C (Message));
   end Throw_LookupError;

   procedure Throw_NameError (Message : String) is
   begin
      Links.Err_SetString (Links.Exc_NameError.all, To_C (Message));
   end Throw_NameError;

   procedure Throw_PermissionError (Message : String) is
   begin
      Links.Err_SetString (Links.Exc_PermissionError.all, To_C (Message));
   end Throw_PermissionError;

   procedure Throw_RunTimeError (Message : String) is
   begin
      Links.Err_SetString (Links.Exc_RunTimeError.all, To_C (Message));
   end Throw_RunTimeError;

   procedure Throw_SyntaxError (Message : String) is
   begin
      Links.Err_SetString (Links.Exc_SyntaxError.all, To_C (Message));
   end Throw_SyntaxError;

   procedure Throw_SystemError (Error : Exception_Occurrence) is
   begin
      Links.Err_SetString
      (  Links.Exc_SystemError.all,
         To_C (Exception_Message (Error))
      );
   end Throw_SystemError;

   procedure Throw_TimeoutError (Message : String) is
   begin
      Links.Err_SetString (Links.Exc_TimeoutError.all, To_C (Message));
   end Throw_TimeoutError;

   procedure Throw_TypeError (Message : String) is
   begin
      Links.Err_SetString (Links.Exc_KeyError.all, To_C (Message));
   end Throw_TypeError;

   procedure Throw_ValueError (Message : String) is
   begin
      Links.Err_SetString (Links.Exc_ValueError.all, To_C (Message));
   end Throw_ValueError;

   function To_Ada (Value : Handle) return Boolean is
   begin
      Check_Handle (Value);
      if Value = To_Python (True) then
         return True;
      elsif Value = To_Python (False) then
         return False;
      else
         Raise_Exception
         (  Data_Error'Identity,
            "Not a Boolean"
         );
      end if;
   end To_Ada;

   function To_Ada (Value : Object) return Time is
      Date : constant String := Object_Str (Value);
   begin
      return Strings_Edit.ISO_8601.Value (Date);
   exception
      when End_Error =>
         Raise_Exception
         (  Data_Error'Identity,
            "No time"
         );
      when Ada.Calendar.Time_Zones.Unknown_Zone_Error =>
         Raise_Exception
         (  Data_Error'Identity,
            "Unknown time zone"
         );
      when others =>
         Raise_Exception
         (  Data_Error'Identity,
            "Invalid time"
         );
   end To_Ada;

   function To_Ada (Value : Handle) return Time is
   begin
      return To_Ada (Value.Ptr);
   end To_Ada;

   function To_Python (Value : Boolean) return Handle is
   begin
      if Value then
         return
            (Ada.Finalization.Controlled with Links.Bool_FromLong (1));
      else
         return
            (Ada.Finalization.Controlled with Links.Bool_FromLong (0));
      end if;
   end To_Python;

   function To_Python (Value : Time) return Handle is
      use Ada.Calendar.Formatting;
      function From_Address is
         new Ada.Unchecked_Conversion
             (  System.Address,
                DateTime_CAPI_Ptr
             );
      Year        : Year_Number;
      Month       : Month_Number;
      Day         : Day_Number;
      Hour        : Hour_Number;
      Minute      : Minute_Number;
      Second      : Second_Number;
      Sub_Second  : Second_Duration;
      Leap_Second : Boolean;
      Result      : Object;
   begin
      if Links.DateTime_CAPI = null then
         Links.DateTime_CAPI :=
            From_Address
            (  Links.Capsule_Import ("datetime.datetime_CAPI" & Nul)
            );
         if Links.DateTime_CAPI = null then
            Raise_Exception
            (  Use_Error'Identity,
               "Failed to locate datetime.datetime_CAPI"
            );
         end if;
      end if;
      Split
      (  Date        => Value,
         Year        => Year,
         Month       => Month,
         Day         => Day,
         Hour        => Hour,
         Minute      => Minute,
         Second      => Second,
         Sub_Second  => Sub_Second,
         Leap_Second => Leap_Second
      );
      Result :=
         Links.DateTime_CAPI.DateTime_FromDateAndTime
         (  Year        => int (Year),
            Month       => int (Month),
            Day         => int (Day),
            Hour        => int (Hour),
            Minute      => int (Minute),
            Second      => int (Second),
            Microsecond => int
                           (  Long_Float'Floor
                              (  Long_Float (Sub_Second) * 1_000_000.0
                           )  ),
            Zone        => Links.DateTime_CAPI.TimeZone_UTC,
            DateType    => Links.DateTime_CAPI.DateTimeType
         );
      if Result = Null_Object then
         Check_Error;
      end if;
      return (Ada.Finalization.Controlled with Result);
   end To_Python;

--     procedure Throw_ValueError (Message : String) is
--     begin
--        Links.Err_SetString (Links.Exc_ValueError, To_C (Message));
--     end Throw_ValueError;

   function Tuple_GetItem
             (  Tuple    : Handle;
                Position : ssize_t
             )  return Handle is
      Result : Handle;
   begin
      Check_Handle (Tuple);
      Result.Ptr := Links.Tuple_GetItem (Tuple.Ptr, Position);
      if Result.Ptr = Null_Object then
         Check_Error;
      else
         Links.IncRef (Result.Ptr); -- Borrowed reference
      end if;
      return Result;
   end Tuple_GetItem;

   function Tuple_GetSlice
            (  Tuple : Handle;
               Low   : ssize_t;
               High  : ssize_t
            )  return Handle is
      Result : Handle;
   begin
      Check_Handle (Tuple);
      Result.Ptr := Links.Tuple_GetSlice (Tuple.Ptr, Low, High);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Tuple_GetSlice;

   function Tuple_New (Size : ssize_t) return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.Tuple_New (Size);
      if Result.Ptr = Null_Object then
         Check_Error;
      end if;
      return Result;
   end Tuple_New;

   procedure Tuple_SetItem
              (  Tuple    : Handle;
                 Position : ssize_t;
                 Item     : Handle
              )  is
   begin
      Check_Handle (Tuple);
      if Links.Tuple_SetItem (Tuple.Ptr, Position, Item.Ptr) = 0  then
         Links.IncRef (Item.Ptr); -- Success, reference stolen
      else
         Check_Error;
      end if;
   end Tuple_SetItem;

   function Tuple_Size (Tuple : Handle) return ssize_t is
      Result : ssize_t := 0;
   begin
      if Tuple.Ptr /= Null_Object then
         Result := Links.Tuple_Size (Tuple.Ptr);
         Check_Error;
      end if;
      return Result;
   end Tuple_Size;

   function Tuple_Type return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.Tuple_Type;
      Links.IncRef (Result.Ptr);
      return Result;
   end Tuple_Type;

   function Type_IsSubtype (Sub, Super : Handle) return Boolean is
      Result : int;
   begin
      Check_Handle (Sub);
      Check_Handle (Super);
      Result := Links.Type_IsSubtype (Sub.Ptr, Super.Ptr);
      if Result = -1 then
         Check_Error;
      end if;
      return Result /= 0;
   end Type_IsSubtype;

   function Type_Type return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.Type_Type;
      Links.IncRef (Result.Ptr);
      return Result;
   end Type_Type;

   function Unicode_DecodeFSDefault (Name : String) return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.Unicode_DecodeFSDefault (To_C (Name));
      if Result.Ptr = Null_Object then -- New reference
         Check_Error;
      end if;
      return Result;
   end Unicode_DecodeFSDefault;

   function Unicode_FromString (Name : String) return Handle is
      Result : Handle;
   begin
      if Name'Length = 0 then
         Result.Ptr := Links.Unicode_FromString ((0..1 => NUL));
      else
         Result.Ptr :=
            Links.Unicode_FromStringAndSize (Name'Address, Name'Length);
      end if;
      if Result.Ptr = Null_Object then -- New reference
         Check_Error;
      end if;
      return Result;
   end Unicode_FromString;

   function Unicode_GetLength (Object : Handle) return ssize_t is
      Result : ssize_t := 0;
   begin
      if Object.Ptr /= Null_Object then
         Result := Links.Unicode_GetLength (Object.Ptr);
         Check_Error;
      end if;
      return Result;
   end Unicode_GetLength;

   function Unicode_ReadChar (Object : Handle; Index : ssize_t)
      return Wide_Wide_Character is
      Result : Wide_Wide_Character;
   begin
      Check_Handle (Object);
      Result := Links.Unicode_ReadChar (Object.Ptr, Index);
      Check_Error;
      return Result;
   end Unicode_ReadChar;

   function Unicode_Type return Handle is
      Result : Handle;
   begin
      Result.Ptr := Links.Unicode_Type;
      Links.IncRef (Result.Ptr);
      return Result;
   end Unicode_Type;

   function "+" (Left : String) return Argument_List is
      use Object_Tables;
      Result : Argument_List (1);
   begin
      Result.Keys.Add (Left, 1);
      Result.Offsets  (1) := 1;
      Result.Optional (1) := False;
      return Result;
   end "+";

   function "+" (Left, Right : String) return Argument_List is
      use Object_Tables;
      Result : Argument_List (2);
   begin
      Result.Keys.Add (Left,  1);
      Result.Keys.Add (Right, 2);
      Result.Offsets (GetTag (Result.Keys, 1)) := 1;
      Result.Offsets (GetTag (Result.Keys, 2)) := 2;
      Result.Optional (1) := False;
      Result.Optional (2) := False;
      return Result;
   end "+";

   function "+" (List : Argument_List; Key : String)
      return Argument_List is
      use Object_Tables;
      Result : Argument_List (List.Length + 1);
      Offset : Natural;
   begin
      Result.Keys := List.Keys;
      Result.Keys.Add (Key, Result.Length, Offset);
      for Index in 1..GetSize (Result.Keys) loop
         Result.Offsets (GetTag (Result.Keys, Index)) := Index;
      end loop;
      Result.Optional (List.Optional'Range) := List.Optional;
      Result.Optional (Result.Length) := False;
      return Result;
   end "+";

   function "-" (Left : String) return Argument_List is
      use Object_Tables;
      Result : Argument_List (1);
   begin
      Result.Keys.Add (Left, 1);
      Result.Offsets  (1) := 1;
      Result.Optional (1) := True;
      return Result;
   end "-";

   function "-" (Left, Right : String) return Argument_List is
      Result : Argument_List := Left + Right;
   begin
      Result.Optional (2) := True;
      return Result;
   end "-";

   function "-" (List : Argument_List; Key : String)
      return Argument_List is
      Result : Argument_List := List + Key;
   begin
      Result.Optional (Result.Length) := True;
      return Result;
   end "-";

   package body Generic_Capsule is
      Name : constant char_array :=
                      To_C (Ada.Tags.Expanded_Name (Capsule_Name'Tag));

      procedure Destructor (Capsule : Object);
      pragma Convention (C, Destructor);

      package Conversion is
         new System.Address_To_Access_Conversions (Object_Type);

      type Local_Ptr is access procedure (Capsule : Object);
      pragma Convention (C, Local_Ptr);

      function From_Local_Ptr is
         new Ada.Unchecked_Conversion
             (  Local_Ptr,
                Capsule_Destructor_Ptr
             );

      procedure Free is
         new Ada.Unchecked_Deallocation
             (  Object_Type,
                Conversion.Object_Pointer
             );

      procedure Destructor (Capsule : Object) is
         Ptr : Conversion.Object_Pointer;
      begin
         Ptr := Conversion.To_Pointer
                (  Links.Capsule_GetPointer (Capsule, Name)
                );
         Free (Ptr);
      end Destructor;

      function Create (Value : Object_Type) return Handle is
         Ptr    : constant Object_Type_Ptr := new Object_Type'(Value);
         Result : Handle;
      begin
         Result.Ptr :=
            Links.Capsule_New
            (  Ptr.all'Address,
               Name,
               From_Local_Ptr (Destructor'Access)
            );
         return Result;
      end Create;

      function Get (Value : Handle) return Object_Type_Ptr is
         Address : System.Address;
      begin
         Check_Handle (Value);
         Address := Links.Capsule_GetPointer (Value.Ptr, Name);
         if Address = System.Null_Address then
            Check_Error;
            return null;
         else
            return Conversion.To_Pointer (Address).all'Unchecked_Access;
         end if;
      end Get;

      function Is_Valid (Value : Handle) return Boolean is
      begin
         if Value.Ptr = Null_Object then
            return False;
         end if;
         return Links.Capsule_IsValid (Value.Ptr, Name) = 1;
      end Is_Valid;

   end Generic_Capsule;

end Py;