summaryrefslogtreecommitdiff
path: root/modules/language/python/module/decimal.scm
blob: 31b8140c6e63dcf44e26e88fd060323b199d6477 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
(define-module (language python module decimal)
  #:use-module ((language python module collections) #:select (namedtuple))
  #:use-module ((language python module itertools) #:select (chain repeat))
  #:use-module ((language python module sys) #:select (maxsize hash_info))
  #:use-module (language python module)
  #:use-module ((language python module python) #:select
		(isinstance str float int tuple classmethod pow))
  #:use-module (language python list)
  #:use-module (language python string)
  #:use-module (language python for)
  #:use-module (language python try)
  #:use-module (language python hash)
  #:use-module (language python dict)
  #:use-module (language python def)
  #:use-module (language python exceptions)
  #:use-module (language python bool)
  #:use-module (oop pf-objects)
  #:use-module (language python module re)
  #:use-module (ice-9 control)
  #:use-module (ice-9 match)
  #:export
  (        ;; Two major classes
   Decimal Context

	   ;; Named tuple representation
	   DecimalTuple

	   ;; Contexts
	   DefaultContext BasicContext ExtendedContext
		    
	   ;; Exceptions
	   DecimalException Clamped InvalidOperation DivisionByZero
	   Inexact Rounded Subnormal Overflow Underflow
	   FloatOperation

	   ;; Exceptional conditions that trigger InvalidOperation
	   DivisionImpossible InvalidContext ConversionSyntax DivisionUndefined

	   ;; Constants for use in setting up contexts
	   ROUND_DOWN ROUND_HALF_UP ROUND_HALF_EVEN ROUND_CEILING
	   ROUND_FLOOR ROUND_UP ROUND_HALF_DOWN ROUND_05UP

	   ;; Functions for manipulating contexts
	   setcontext getcontext localcontext

	   ;; Limits for the C version for compatibility
	   MAX_PREC  MAX_EMAX MIN_EMIN MIN_ETINY))


(define-syntax-rule (aif it p . l) (let ((it p)) (if it . l)))

#|
This is the copyright information of the file ported over to scheme
# Copyright (c) 2004 Python Software Foundation.
# All rights reserved.

# Written by Eric Price <eprice at tjhsst.edu>
#    and Facundo Batista <facundo at taniquetil.com.ar>
#    and Raymond Hettinger <python at rcn.com>
#    and Aahz <aahz at pobox.com>
#    and Tim Peters

# This module should be kept in sync with the latest updates of the
# IBM specification as it evolves.  Those updates will be treated
# as bug fixes (deviation from the spec is a compatibility, usability
# bug) and will be backported.  At this point the spec is stabilizing
# and the updates are becoming fewer, smaller, and less significant.
|#

(define guile:modulo (@ (guile) modulo))

(define __name__   "decimal")
(define __xname__  __name__)
(define __version__ "1.70")
;; Highest version of the spec this complies with
;; See http://speleotrove.com/decimal/


(define DecimalTuple (namedtuple "DecimalTuple" "sign digits exponent"))

;; Rounding
(define ROUND_DOWN      'ROUND_DOWN)
(define ROUND_HALF_UP   'ROUND_HALF_UP)
(define ROUND_HALF_EVEN 'ROUND_HALF_EVEN)
(define ROUND_CEILING   'ROUND_CEILING)
(define ROUND_FLOOR     'ROUND_FLOOR)
(define ROUND_UP        'ROUND_UP)
(define ROUND_HALF_DOWN 'ROUND_HALF_DOWN)
(define ROUND_05UP      'ROUND_05UP)

;; Compatibility with the C version
(define MAX_PREC 425000000)
(define MAX_EMAX 425000000)
(define MIN_EMIN -425000000)

(if (= maxsize  (- (ash 1 63) 1))
    (begin
      (set! MAX_PREC 999999999999999999)
      (set! MAX_EMAX 999999999999999999)
      (set! MIN_EMIN -999999999999999999)))

(define MIN_ETINY  (- MIN_EMIN (- MAX_PREC 1)))

;; Context
(define-inlinable (cx-prec     x) (rawref x 'prec))
(define-inlinable (cx-emax     x) (rawref x 'Emax))
(define-inlinable (cx-emin     x) (rawref x 'Emin))
(define-inlinable (cx-etiny    x) ((ref x 'Etiny)))
(define-inlinable (cx-etop     x) ((ref x 'Etop)))
(define-inlinable (cx-copy     x) ((ref x 'copy)))
(define-inlinable (cx-clear_flags x) ((ref x 'clear_flags)))
(define-inlinable (cx-raise    x) (ref x '_raise_error))
(define-inlinable (cx-error    x) (ref x '_raise_error))
(define-inlinable (cx-capitals x) (rawref x 'capitals))
(define-inlinable (cx-cap      x) (rawref x 'capitals))
(define-inlinable (cx-rounding x) (rawref x 'rounding))
(define-inlinable (cx-clamp    x) (rawref x 'clamp))
(define-inlinable (cx-traps    x) (rawref x 'traps))
(define-inlinable (cx-flags    x) (rawref x 'flags))

;; Errors

(define-python-class DecimalException (ArithmeticError)
    "Base exception class.

    Used exceptions derive from this.
    If an exception derives from another exception besides this (such as
    Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
    called if the others are present.  This isn't actually used for
    anything, though.

    handle  -- Called when context._raise_error is called and the
               trap_enabler is not set.  First argument is self, second is the
               context.  More arguments can be given, those being after
               the explanation in _raise_error (For example,
               context._raise_error(NewError, '(-x)!', self._sign) would
               call NewError().handle(context, self._sign).)

    To define a new exception, it should be sufficient to have it derive
    from DecimalException.
    "
    
    (define handle
      (lambda (self context . args)
        (values))))


(define-python-class Clamped (DecimalException)
    "Exponent of a 0 changed to fit bounds.

    This occurs and signals clamped if the exponent of a result has been
    altered in order to fit the constraints of a specific concrete
    representation.  This may occur when the exponent of a zero result would
    be outside the bounds of a representation, or when a large normal
    number would have an encoded exponent that cannot be represented.  In
    this latter case, the exponent is reduced to fit and the corresponding
    number of zero digits are appended to the coefficient ('fold-down').
    ")

(define-python-class InvalidOperation (DecimalException)
    "An invalid operation was performed.

    Various bad things cause this:

    Something creates a signaling NaN
    -INF + INF
    0 * (+-)INF
    (+-)INF / (+-)INF
    x % 0
    (+-)INF % x
    x._rescale( non-integer )
    sqrt(-x) , x > 0
    0 ** 0
    x ** (non-integer)
    x ** (+-)INF
    An operand is invalid

    The result of the operation after these is a quiet positive NaN,
    except when the cause is a signaling NaN, in which case the result is
    also a quiet NaN, but with the original sign, and an optional
    diagnostic information.
    "
    (define handle
      (lambda (self context . args)
        (if (bool args)
	    (let ((ans  (_dec_from_triple
			 (ref (car args) '_sign)
			 (ref (car args) '_int)
			 "n" #t)))
	      ((ref ans '_fix_nan) context))
	    _NaN))))

(define-python-class ConversionSyntax (InvalidOperation)
    "Trying to convert badly formed string.

    This occurs and signals invalid-operation if a string is being
    converted to a number and it does not conform to the numeric string
    syntax.  The result is [0,qNaN].
    "
    (define handle
      (lambda x _NaN)))

(define-python-class DivisionByZero (DecimalException ZeroDivisionError)
    "Division by 0.

    This occurs and signals division-by-zero if division of a finite number
    by zero was attempted (during a divide-integer or divide operation, or a
    power operation with negative right-hand operand), and the dividend was
    not zero.

    The result of the operation is [sign,inf], where sign is the exclusive
    or of the signs of the operands for divide, or is 1 for an odd power of
    -0, for power.
    "

    (define handle
      (lambda (self context sign . args)
        (pylist-ref _SignedInfinity sign))))

(define-python-class DivisionImpossible (InvalidOperation)
    "Cannot perform the division adequately.

    This occurs and signals invalid-operation if the integer result of a
    divide-integer or remainder operation had too many digits (would be
    longer than precision).  The result is [0,qNaN].
    "

    (define handle
      (lambda x _NaN)))

(define-python-class DivisionUndefined (InvalidOperation ZeroDivisionError)
    "Undefined result of division.

    This occurs and signals invalid-operation if division by zero was
    attempted (during a divide-integer, divide, or remainder operation), and
    the dividend is also zero.  The result is [0,qNaN].
    "

    (define handle
      (lambda x _NaN)))

(define-python-class Inexact (DecimalException)
    "Had to round, losing information.

    This occurs and signals inexact whenever the result of an operation is
    not exact (that is, it needed to be rounded and any discarded digits
    were non-zero), or if an overflow or underflow condition occurs.  The
    result in all cases is unchanged.

    The inexact signal may be tested (or trapped) to determine if a given
    operation (or sequence of operations) was inexact.
    ")

(define-python-class InvalidContext (InvalidOperation)
    "Invalid context.  Unknown rounding, for example.

    This occurs and signals invalid-operation if an invalid context was
    detected during an operation.  This can occur if contexts are not checked
    on creation and either the precision exceeds the capability of the
    underlying concrete representation or an unknown or unsupported rounding
    was specified.  These aspects of the context need only be checked when
    the values are required to be used.  The result is [0,qNaN].
    "

    (define handle
      (lambda x _NaN)))

(define-python-class Rounded (DecimalException)
    "Number got rounded (not  necessarily changed during rounding).

    This occurs and signals rounded whenever the result of an operation is
    rounded (that is, some zero or non-zero digits were discarded from the
    coefficient), or if an overflow or underflow condition occurs.  The
    result in all cases is unchanged.

    The rounded signal may be tested (or trapped) to determine if a given
    operation (or sequence of operations) caused a loss of precision.
    ")

(define-python-class Subnormal (DecimalException)
    "Exponent < Emin before rounding.

    This occurs and signals subnormal whenever the result of a conversion or
    operation is subnormal (that is, its adjusted exponent is less than
    Emin, before any rounding).  The result in all cases is unchanged.

    The subnormal signal may be tested (or trapped) to determine if a given
    or operation (or sequence of operations) yielded a subnormal result.
    ")

(define-python-class Overflow (Inexact Rounded)
    "Numerical overflow.

    This occurs and signals overflow if the adjusted exponent of a result
    (from a conversion or from an operation that is not an attempt to divide
    by zero), after rounding, would be greater than the largest value that
    can be handled by the implementation (the value Emax).

    The result depends on the rounding mode:

    For round-half-up and round-half-even (and for round-half-down and
    round-up, if implemented), the result of the operation is [sign,inf],
    where sign is the sign of the intermediate result.  For round-down, the
    result is the largest finite number that can be represented in the
    current precision, with the sign of the intermediate result.  For
    round-ceiling, the result is the same as for round-down if the sign of
    the intermediate result is 1, or is [0,inf] otherwise.  For round-floor,
    the result is the same as for round-down if the sign of the intermediate
    result is 0, or is [1,inf] otherwise.  In all cases, Inexact and Rounded
    will also be raised.
    "

    (define handle
      (let ((l (list ROUND_HALF_UP ROUND_HALF_EVEN
		     ROUND_HALF_DOWN ROUND_U)))
	(lambda (self context sign . args)
	  (let/ec ret
	    (if (memq (ref context 'rounding) l)
		(ret (pylist-ref _SignedInfinity sign)))
            
	    (if (= sign 0)
		(if (eq? (ref context 'rounding) ROUND_CEILING)
		    (ret (pylist-ref _SignedInfinity sign))
		    (ret (_dec_from_triple
			  sign
			  (* "9" (cx-prec context))
			  (+ (- (cx-emax context) (cx-prec context)) 1)))))

	    (if (= sign 1)
		(if (eq? (ref context 'rounding) ROUND_FLOOR)
		    (ret (pylist-ref _SignedInfinity sign))
		    (ret (_dec_from_triple
			  sign
			  (* "9" (cx-prec context))
			  (+ (- (cx-emax context) (cx-prec context)) 1))))))))))


(define-python-class Underflow (Inexact Rounded Subnormal)
    "Numerical underflow with result rounded to 0.

    This occurs and signals underflow if a result is inexact and the
    adjusted exponent of the result would be smaller (more negative) than
    the smallest value that can be handled by the implementation (the value
    Emin).  That is, the result is both inexact and subnormal.

    The result after an underflow will be a subnormal number rounded, if
    necessary, so that its exponent is not less than Etiny.  This may result
    in 0 with the sign of the intermediate result and an exponent of Etiny.

    In all cases, Inexact, Rounded, and Subnormal will also be raised.
    ")

(define-python-class FloatOperation (DecimalException TypeError)
    "Enable stricter semantics for mixing floats and Decimals.

    If the signal is not trapped (default), mixing floats and Decimals is
    permitted in the Decimal() constructor, context.create_decimal() and
    all comparison operators. Both conversion and comparisons are exact.
    Any occurrence of a mixed operation is silently recorded by setting
    FloatOperation in the context flags.  Explicit conversions with
    Decimal.from_float() or context.create_decimal_from_float() do not
    set the flag.

    Otherwise (the signal is trapped), only equality comparisons and explicit
    conversions are silent. All other mixed operations raise FloatOperation.
    ")

;; List of public traps and flags
(define _signals
  (vector Clamped DivisionByZero Inexact Overflow Rounded,
            Underflow InvalidOperation Subnormal FloatOperation))

;; Map conditions (per the spec) to signals
(define _condition_map
  `((,ConversionSyntax   . ,InvalidOperation)
    (,DivisionImpossible . ,InvalidOperation)
    (,DivisionUndefined  . ,InvalidOperation)
    (,InvalidContext     . ,InvalidOperation)))

;; Valid rounding modes
(define _rounding_modes
  (list ROUND_DOWN ROUND_HALF_UP ROUND_HALF_EVEN ROUND_CEILING
	ROUND_FLOOR ROUND_UP ROUND_HALF_DOWN ROUND_05UP))

;; ##### Context Functions ##################################################

;; The getcontext() and setcontext() function manage access to a thread-local
;; current context.
(define *context* (make-fluid #f))
(define (getcontext)
  (fluid-ref *context*))
(define (setcontext context)
  (fluid-set! *context* context))

;; ##### Decimal class #######################################################

;; Do not subclass Decimal from numbers.Real and do not register it as such
;; (because Decimals are not interoperable with floats).  See the notes in
;; numbers.py for more detail.

(define _dec_from_triple
  (lam (sign coefficient exponent (= special #f))
    "Create a decimal instance directly, without any validation,
    normalization (e.g. removal of leading zeros) or argument
    conversion.

    This function is for *internal use only*.
    "
    (Decimal sign coefficient exponent special)))

(define (get-parsed-sign m)
  (if (equal? ((ref m 'group) "sign") "-")
      1
      0))

(define (get-parsed-int m)
  ((ref m 'group) "int"))

(define (get-parsed-frac m)
  ((ref m 'group) "frac"))

(define (get-parsed-exp m)
  ((ref m 'group) "exp"))

(define (get-parsed-diag m)
  ((ref m 'group) "diag"))

(define (get-parsed-sig m)
  ((ref m 'group) "signal"))

(def (_mk self __init__ (= value "0") (= context None))
       "Create a decimal point instance.

        >>> Decimal('3.14')              # string input
        Decimal('3.14')
        >>> Decimal((0, (3, 1, 4), -2))  # tuple (sign, digit_tuple, exponent)
        Decimal('3.14')
        >>> Decimal(314)                 # int
        Decimal('314')
        >>> Decimal(Decimal(314))        # another decimal instance
        Decimal('314')
        >>> Decimal('  3.14  \\n')        # leading and trailing whitespace okay
        Decimal('3.14')
        "

        ;; Note that the coefficient, self._int, is actually stored as
        ;; a string rather than as a tuple of digits.  This speeds up
        ;; the "digits to integer" and "integer to digits" conversions
        ;; that are used in almost every arithmetic operation on
        ;; Decimals.  This is an internal detail: the as_tuple function
        ;; and the Decimal constructor still deal with tuples of
        ;; digits.

        ;; From a string
        ;; REs insist on real strings, so we can too.
        (cond
	 ((isinstance value str)
	    (let ((m (_parser (scm-str str))))
	      (if (not m)
                (let ((context (if (eq? context None)
				   (getcontext)
				   context)))
		  ((cx-raise context)
		   ConversionSyntax
		   (+ "Invalid literal for Decimal: " value))))

	      (let ((sign     (get-parsed-sign m))
		    (intpart  (get-parsed-int  m))
		    (fracpart (get-parsed-frac m))
		    (exp      (get-parsed-exp  m))
		    (diag     (get-parsed-diag m))
		    (signal   (get-parsed-sig  m)))
		
		(set self 'sign sign)
		
		(if (not (eq? intpart None))
		    (begin
		      (set self '_int (str (int (+ intpart fracpart))))
		      (set self '_exp (- exp (len fracpart)))
		      (set self '_is_special #f))
		    (begin
		      (if (not (eq? diag None))
			  (begin
			    ;; NaN
			    (set self '_int
				 (py-lstrip (str (int (if (bool diag)
							  diag
							  "0")))
					    "0"))
			    (if signal
				(set self '_exp "N")
				(set self '_exp "n")))
			  (begin
			    ;; infinity
			    (set self '_int "0")
			    (set self '_exp "F")))
		      (set self '_is_special #t))))))
	 
	;; From an integer	   
        ((isinstance value int)
	 (if (>= value 0)
	     (set self '_sign 0)
	     (set self '_sign 1))
	 (set self '_exp 0)
         (set self '_int (str (abs value)))
	 (set self '_is_special #f))
	
        ;; From another decimal
        ((isinstance value Decimal)
            (set self '_exp        (ref value '_exp       ))
            (set self '_sign       (ref value '_sign      ))
            (set self '_int        (ref value '_int       ))
            (set self '_is_special (ref value '_is_special)))

        ;; From an internal working value
        ((isinstance value _WorkRep)
	 (set self '_exp        (int (ref value '_exp)))
	 (set self '_sign       (ref value '_sign))
	 (set self '_int        (str (ref value 'int)))
	 (set self '_is_special #f))

        ;; tuple/list conversion (possibly from as_tuple())
        ((isinstance value (list list tuple))
            (if (not (= (len value) 3))
                (raise (ValueError
			(+ "Invalid tuple size in creation of Decimal "
			   "from list or tuple.  The list or tuple "
			   "should have exactly three elements."))))
	    ;; # process sign.  The isinstance test rejects floats
	    (let ((v0 (pylist-ref value 0))
		  (v1 (pylist-ref value 1))
		  (v2 (pylist-ref value 2)))
	      (if (not (and (isinstance v0 int)
			    (or (= v0 0) (= v0 1))))
		  (raise (ValueError
			  (+ "Invalid sign.  The first value in the tuple "
			     "should be an integer; either 0 for a "
			     "positive number or 1 for a negative number."))))
	      (set self '_sign v0)
            (if (eq? v2 'F)
		(begin
		  (set self '_int "0")
		  (set self '_exp v2)
		  (set self 'is_special #t))
		(let ((digits (py-list)))
		  ;; process and validate the digits in value[1]
		  (for ((digit : v1)) ()
		       (if (and (isinstance digit int)
				(<= 0 digit)
				(<= digit 9))
			   ;; skip leading zeros
			   (if (or (bool digits) (> digit 0))
			       (pylist-append! digits digit))
			   (raise (ValueError
				   (+ "The second value in the tuple must "
				      "be composed of integers in the range "
				      "0 through 9.")))))
		  
		  (cond
		   ((or (eq? v2 'n) (eq? v2 'N))
		    (begin
		      ;; NaN: digits form the diagnostic
		      (set self '_int  (py-join "" (map str digits)))
		      (set self '_exp  v2)
			(set self '_is_special #t)))
		   ((isinstance v2  int)
		    ;; finite number: digits give the coefficient
		    (set self '_int (py-join "" (map str digits)))
		    (set self '_exp v2)
		    (set self '_is_special #f))
		   (else
		    (raise (ValueError
			    (+ "The third value in the tuple must "
			       "be an integer, or one of the "
			       "strings 'F', 'n', 'N'.")))))))))

	((isinstance value float)
	 (let ((context (if (eq? context None)
			    (getcontext)
			    context)))
	   ((cx-error context)
	    FloatOperation,
	    (+ "strict semantics for mixing floats and Decimals are "
	       "enabled"))
	   
	   (__init__ self ((ref Decimal 'from_float) value))))

	(else
	 (raise (TypeError
		 (format #f "Cannot convert %r to Decimal" value))))))

(define-inlinable (divmod x y)
  (values (quotient x y) (modulo x y)))

(define-syntax twix
  (syntax-rules (let let* if)
    ((_ a) a)
    ((_ (let ((a aa) ...) b ...) . l)
     (let ((a aa) ...) b ... (twix . l)))
    ((_ (let (a ...)) . l)
     (a ... (twix . l)))
    ((_ (let* (a ...) b ...) . l)
     (let* (a ...) b ... (twix . l)))
    ((_ (if . u) . l)
     (begin (if . u) (twix . l)))
    ((_ (a it code ...) . l)
     (aif it a (begin code ...) (twix . l)))))

(define-syntax-rule (norm-op self op)
  (begin
    (set! op ((ref self '_convert_other) op))
    (if (eq? op NotImplemented)
	op
	#f)))

(define-syntax-rule (get-context context code)
  (let ((context (if (eq? context None)
		     (getcontext)
		     context)))
    code))

(define-syntax-rule (un-special self context)
  (if ((ref self '_is_special))
      (let ((ans ((ref self '_check_nans) #:context context)))
	(if (bool ans)
	    ans
	    #f))
      #f))

(define-syntax-rule (bin-special o1 o2 context)
  (if (or (ref o1  '_is_special)
	  (ref o2  '_is_special))
      (or (un-special o1 context) (un-special o2 context))))

(define-syntax-rule (add-special self other context)
  (or (bin-special self other context)
      (if ((ref self '_isinfinity))
	  ;; If both INF, same sign =>
	  ;; same as both, opposite => error.
	  (if (and (not (= (ref self '_sign) (ref other '_sign)))
		   ((ref other '_isinfinity)))
	      ((cx-error context) InvalidOperation "-INF + INF")
	      (Decimal self))	      
	  (if ((ref other '_isinfinity))
	      (Decimal other) ; Can't both be infinity here
	      #f))))

(define-syntax-rule (mul-special self other context resultsign)
  (if (or (ref self '_is_special) (ref other '_is_special))
      (twix
       ((bin-special self other context) it it)
	       
       ((if ((ref self '_isinfinity))
	    (if (not (bool other))
		((cx-error context) InvalidOperation "(+-)INF * 0")
		(pylist-ref _SignedInfinity resultsign))
	    #f) it it)

       (if ((ref other '_isinfinity))
	   (if (not (bool self))
	       ((cx-error context) InvalidOperation "(+-)INF * 0")
	       (pylist-ref _SignedInfinity resultsign))
	   #f))
      #f))

  (define-syntax-rule (div-special self other context sign)
    (if (or (ref self '_is_special) (ref other '_is_special))
	(twix
	 ((bin-special self other context) it it)
	       
	 ((and ((ref self '_isinfinity)) ((ref other '_isinfinity))) it
	  ((cx-error context) InvalidOperation "(+-)INF/(+-)INF"))

	 (((ref self '_isinfinity)) it
          (pylist-ref _SignedInfinity sign))

	 (((ref other '_isinfinity)) it
	  ((cx-error context) Clamped "Division by infinity")
	  (_dec_from_triple sign  "0" (cx-etiny context))))))
        

(define-python-class Decimal (object)
    "Floating point class for decimal arithmetic."
    
    
    ;; Generally, the value of the Decimal instance is given by
    ;;  (-1)**_sign * _int * 10**_exp
    ;; Special values are signified by _is_special == True

    (define __init__
      (case-lambda
       ((self sign coefficient exponent special)
	(set self '_sign       sign)
	(set self '_int        coefficient)
	(set self '_exp        exponent)
	(set self '_is_special special))
       
       ((self)
	(_mk self __init__))
       ((self a)
	(_mk self __init__ a))
       ((self a b)
	(_mk self __init__ a b))))

    (define from_float
      (classmethod
       (lambda (cls f)
        "Converts a float to a decimal number, exactly.

        Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
        Since 0.1 is not exactly representable in binary floating point, the
        value is stored as the nearest representable value which is
        0x1.999999999999ap-4.  The exact equivalent of the value in decimal
        is 0.1000000000000000055511151231257827021181583404541015625.

        >>> Decimal.from_float(0.1)
        Decimal('0.1000000000000000055511151231257827021181583404541015625')
        >>> Decimal.from_float(float('nan'))
        Decimal('NaN')
        >>> Decimal.from_float(float('inf'))
        Decimal('Infinity')
        >>> Decimal.from_float(-float('inf'))
        Decimal('-Infinity')
        >>> Decimal.from_float(-0.0)
        Decimal('-0')

        "
	(define (frexp x)
	  (if (< x 0) (set! x (- x)))
	  
	  (let lp ((l (string->list (format #f "~e" x))) (r1 '()))
	    (match l
	       ((#\. . l)
		(let lp ((l l) (r2 '()))
		  (match l
		    ((#\E . l)
		     (let* ((n (length r1))
			    (m (list->string (append (reverse r1) (reverse r2))))
			    (e (+ (- n 1) (string->number (list->string l)))))
		       (cons m e)))
		    ((x . l)
		     (lp l (cons x r2))))))
	       
	       ((x . l)
		(lp l (cons x r1))))))
		
		    
        (cond
	 ((isinstance f  int)                ; handle integer inputs
	  (cls f))
	 ((not (isinstance f float))
	  (raise (TypeError "argument must be int or float.")))
	 ((or (inf? f) (nan? f))
	  (cls (cond
		((nan? f)          "")
		((eq? f (inf))     "")
		((eq? f (- (inf))) ""))))
	 (else
	  (let* ((sign (if (>= f 0) 0 1))
		 (me   (frexp f))
		 (m    (car me))
		 (e    (cdr me))
		 (res  (_dec_from_triple sign m e)))
	    (if (eq? cls Decimal)
		res
		(cls res))))))))
    
    (define _isnan
      (lambda (self)
        "Returns whether the number is not actually one.

        0 if a number
        1 if NaN
        2 if sNaN
        "
        (if (ref self '_is_special)
            (let ((exp (ref self '_exp)))
	      (cond
	       ((eq? exp 'n) 1)
	       ((eq? exp 'N) 2)
	       (else         0)))
	    0)))
    
    (define _isinfinity
      (lambda (self)
        "Returns whether the number is infinite

        0 if finite or not a number
        1 if +INF
        -1 if -INF
        "
        (if (eq? (ref self '_exp) 'F)
            (if (eq? (ref self '_sign) 1)
                -1
		1)
	    0)))
    
    (define _check_nans
      (lam (self (= other None) (= context None))
        "Returns whether the number is not actually one.

        if self, other are sNaN, signal
        if self, other are NaN return nan
        return 0

        Done before operations.
        "

        (let ((self_is_nan ((ref self '_isnan)))
	      (other_is_nan
	       (if (eq? other None)
		   #f
		   ((ref other '_isnan)))))
	  
	  (if (or self_is_nan other_is_nan)
	      (let ((context (if (eq? context None)
				 (getcontext)
				 context)))
		(cond
		 ((eq? self_is_nan 2)
		  ((cx-error context) InvalidOperation "sNaN" self))
		 ((eq? other_is_nan 2)
		  ((cx-error context) InvalidOperation "sNaN" other))
		 (self_is_nan
		  ((ref self '_fix_nan) context))
		 (else
		  ((ref other '_fix_nan) context))))
	      0))))
		 

    (define _compare_check_nans
      (lambda (self other context)
        "Version of _check_nans used for the signaling comparisons
        compare_signal, __le__, __lt__, __ge__, __gt__.

        Signal InvalidOperation if either self or other is a (quiet
        or signaling) NaN.  Signaling NaNs take precedence over quiet
        NaNs.

        Return 0 if neither operand is a NaN.

        "
        (let ((context (if (eq? context None)
			   (getcontext)
			   context)))

	  (if (or (ref self  '_is_special)
		  (ref other '_is_special))
	      (cond
	       (((ref self 'is_snan))
		((cx-error context)
		 InvalidOperation
		 "comparison involving sNaN" self))

 	       (((ref other 'is_snan))
		((cx-error context)
		 InvalidOperation
		 "comparison involving sNaN" other))
		
	       (((ref self 'is_qnan))
		((cx-error context)
		 InvalidOperation
		 "comparison involving NaN" self))

 	       (((ref other 'is_qnan))
		((cx-error context)
		 InvalidOperation
		 "comparison involving NaN" other))
	       
	       (else 0))
	      0))))

    (define __bool__
      (lambda (self)
        "Return True if self is nonzero; otherwise return False.

        NaNs and infinities are considered nonzero.
        "
        (or (ref self '_is_special) (not (equal? (ref self '_int) "0")))))

    (define _cmp
      (lambda (self other)
        "Compare the two non-NaN decimal instances self and other.

        Returns -1 if self < other, 0 if self == other and 1
        if self > other.  This routine is for internal use only."

	(let ((self_sign  (ref self  '_sign))
	      (other_sign (ref other '_sign)))
	  (cond
	   ((or (ref self '_is_special) (ref other '_is_special))
	    (let ((self_inf  ((ref self  '_isinfinity)))
		  (other_inf ((ref other '_isinfinity))))
	      (cond
	       ((eq? self_inf other_inf) 0)
	       ((< self_inf other_inf)  -1)
	       (else                     1))))
	    
	   ;; check for zeros;  Decimal('0') == Decimal('-0')
	   ((not (bool self))
	    (if (not (bool other))
		0
		(let ((s (ref other '_sign)))
		  (if (= s 0)
		      -1
		      1))))
	   ((not (bool other))
	    (let ((s (ref self '_sign)))
	      (if (= s 0)
		  1
		  -1)))
	  
	   ((< other_sign self_sign)
	    -1)
	   ((< self_sign other_sign)
	    1)

	   (else
	    (let ((self_adjusted  ((ref self  'adjusted)))
		  (other_adjusted ((ref other 'adjusted)))
		  (self_exp       (ref self  '_exp))
		  (other_exp      (ref other '_exp)))
	      (cond
	       ((= self_adjusted other_adjusted)
		(let ((self_padded  (+ (ref self '_int)
				       (* "0" (- self_exp  other_exp))))
		      (other_padded (+ (ref other '_int)
				       (* "0" (- other_exp  self_exp)))))
		  (cond
		   ((equal? self_padded other_padded)
		    0)
		   ((< self_padded other_padded)
		    (if (= self_sign 0)
			-1
			1))
		   (else
		    (if (= self_sign 0)
			1
			-1)))))
	       ((> self_adjusted other_adjusted)
		(if (= self_sign 0)
		    1
		    -1))
	       (else
		(if (= self_sign 0)
		    -1
		    1)))))))))
    
    ;; Note: The Decimal standard doesn't cover rich comparisons for
    ;; Decimals.  In particular, the specification is silent on the
    ;; subject of what should happen for a comparison involving a NaN.
    ;; We take the following approach:
    ;;
    ;;   == comparisons involving a quiet NaN always return False
    ;;   != comparisons involving a quiet NaN always return True
    ;;   == or != comparisons involving a signaling NaN signal
    ;;      InvalidOperation, and return False or True as above if the
    ;;      InvalidOperation is not trapped.
    ;;   <, >, <= and >= comparisons involving a (quiet or signaling)
    ;;      NaN signal InvalidOperation, and return False if the
    ;;      InvalidOperation is not trapped.
    ;;
    ;; This behavior is designed to conform as closely as possible to
    ;; that specified by IEEE 754.
    
    (define __eq__
      (lam (self other (= context None))
	   (let* ((so    (_convert_for_comparison self other #:equality_op #t))
		  (self  (car  so))
		  (other (cadr so)))
	     
	     (cond
	      ((eq? other NotImplemented)
	       other)
	      ((bool ((ref self '_check_nans) other context))
	       #f)
	      (else (= ((ref self '_cmp) other) 0))))))

    (define _xlt
      (lambda (<)
	(lam (self other (= context None))
	     (let* ((so (_convert_for_comparison self other #:equality_op #t))
		    (self  (car  so))
		    (other (cadr so)))
	     
	       (cond
		((eq? other NotImplemented)
		 other)
		((bool ((ref self '_compare_check_nans) other context))
		 #f)
		(else (< ((ref self '_cmp) other) 0)))))))
      
    (define __lt__ (_xlt < ))
    (define __le__ (_xlt <=))
    (define __gt__ (_xlt > ))
    (define __ge__ (_xlt >=))

    (define compare
      (lam (self other (= context None))
        "Compare self to other.  Return a decimal value:

        a or b is a NaN ==> Decimal('NaN')
        a < b           ==> Decimal('-1')
        a == b          ==> Decimal('0')
        a > b           ==> Decimal('1')
        "
        (let ((other (_convert_other other #:raiseit #t)))
	  ;; Compare(NaN, NaN) = NaN
	  (if (or (ref self '_is_special)
		  (and (bool other)
		       (ref other '_is_special)))
	      (aif it ((ref self '_check_nans) other context)
		   it
		   (Decimal ((ref self '_cmp) other)))))))

    (define __hash__
      (lambda (self)
	"x.__hash__() <==> hash(x)"

        ;; In order to make sure that the hash of a Decimal instance
        ;; agrees with the hash of a numerically equal integer, float
        ;; or Fraction, we follow the rules for numeric hashes outlined
        ;; in the documentation.  (See library docs, 'Built-in Types').
        (cond
	 ((ref self '_is_special)
	  (cond
	   (((ref self 'is_snan))
	    (raise (TypeError "Cannot hash a signaling NaN value.")))
	   (((ref self 'is_snan))
	    (hash (nan) pyhash-N))
	   ((= 1 (ref self '_sign))
	    (hash (- (inf)) pyhash-N))
	   (else
	    (hash (inf) pyhash-N))))
	    
	 (else
	  (let* ((exp (ref self '_exp))
		 (exp_hash
		  (if (>= exp 0)
		      (pow 10            exp     pyhash-N)
		      (pow _PyHASH_10INV (- exp) pyhash-N)))
		 
		 (hash_
		  (modulo (* (int (ref self '_int)) exp_hash)
			   pyhash-N))

		 (ans
		  (if (>= self 0) hash_ (- hash_))))
	    (if (= ans -1) -2 ans))))))
    
    (define as_tuple
      (lambda (self)
        "Represents the number as a triple tuple.

        To show the internals exactly as they are.
        "
	(DecimalTuple (ref self '_sign)
		      (tuple (map int (ref self '_int)))
		      (ref self '_exp))))

    (define as_integer_ratio
      (lambda (self)
        "Express a finite Decimal instance in the form n / d.

        Returns a pair (n, d) of integers.  When called on an infinity
        or NaN, raises OverflowError or ValueError respectively.

        >>> Decimal('3.14').as_integer_ratio()
        (157, 50)
        >>> Decimal('-123e5').as_integer_ratio()
        (-12300000, 1)
        >>> Decimal('0.00').as_integer_ratio()
        (0, 1)
        "
        (if (ref self '_is_special)
            (if ((ref self 'is_nan))
                (raise (ValueError
			"cannot convert NaN to integer ratio"))
                (raise (OverflowError
			"cannot convert Infinity to integer ratio"))))

        (if (not (bool self))
            (values 0 1)
	    (let* ((s (ref self '_sign))
		   (n (int (ref self '_int)))
		   (e (ref self '_exp))
		   (x
		    (* n (if (> exp 0)
			     (expt 10 exp)
			     (/ 1 (expt 10 (- expt)))))))
	      (values (numerator x)
		      (denominator x))))))
    
    (define __repr__
      (lambda (self)
        "Represents the number as an instance of Decimal."
        ;# Invariant:  eval(repr(d)) == d
        (format #f "Decimal('~a')" (str self))))

    (define __str__
      (lam (self  (= eng #f) (= context None))
        "Return string representation of the number in scientific notation.

        Captures all of the information in the underlying representation.
        "
	(let* ((sign         (if (= (ref self '_sign) 0) "" "-"))
	       (exp          (ref self '_exp))
	       (i            (ref self '_int))
	       (leftdigits   (+ exp (len i)))
	       (dotplace     #f)
	       (intpart      #f)
	       (fracpart     #f)
	       (exppart      #f))
	  
	  (cond
	   ((ref self '_is_special)
            (cond
	     ((eq? (ref self '_exp) 'F)
	      (+ sign "Infinity"))
	     ((eq? (ref self '_exp) 'n)
	      (+ sign  "NaN" (ref self '_int)))
	     (else ; self._exp == 'N'
	      (+ sign  "sNaN" (ref self '_int)))))
	   (else
	    ;; dotplace is number of digits of self._int to the left of the
	    ;; decimal point in the mantissa of the output string (that is,
	    ;; after adjusting the exponent)
	    (cond
	     ((and (<= exp 0) (> leftdigits  -6))
	      ;; no exponent required
	      (set! dotplace leftdigits))
	     
	     ((not eng)
	      ;; usual scientific notation: 1 digit on left of the point
	      (set! dotplace 1))
	     
	     ((equal? i "0")
	      ;; engineering notation, zero
	      (set! dotplace (- (modulo (+ leftdigits 1) 3) 1)))
	     (else
	      ;; engineering notation, nonzero
	      (set! dotplace (- (modulo (+ leftdigits 1) 3) 1))))

	    (cond
	     ((<= dotplace 0)
	      (set! intpart "0")
	      (set! fracpart (+ "." + (* "0" (- dotplace)) + i)))
	     ((>= dotplace (len i))
	      (set! intpart (+ i (* "0" (- dotplace (len i)))))
	      (set! fracpart ""))
	     (else
	      (set! intpart (pylist-slice i None dotplace None))
	      (set! fracpart (+ '.' (pylist-slice i dotplace None None)))))

	    
	    (cond
	     ((= leftdigits dotplace)
	      (set! exp ""))
	     (else
	      (let ((context (if (eq? context None)
				 (getcontext)
				 context)))
		(set! exp
		      (+ (pylist-ref '("e" "E") (cx-capitals context))
			 (format #f "%@d" (- leftdigits dotplace)))))))
	    (+ sign intpart fracpart exp))))))
    
    (define to_eng_string
      (lam (self (= context None))
        "Convert to a string, using engineering notation if an exponent is needed.
        Engineering notation has an exponent which is a multiple of 3.  This
        can leave up to 3 digits to the left of the decimal place and may
        require the addition of either one or two trailing zeros.
        "
        ((ref self '__str__) #:eng #t #:contect context)))

    (define __neg__
      (lam (self (= context None))
        "Returns a copy with the sign switched.

        Rounds, if it has reason.
        "
	(twix 
	  ((un-special self context) it it)
	  (let* ((context (if (eq? context None)
			      (getcontext)
			      context))
		 (ans     (if (and (not (bool self))
				   (not (eq? (cx-rounding context)
					     ROUND_FLOOR)))
			      ;; -Decimal('0') is Decimal('0'),
			      ;; not Decimal('-0'), except
			      ;; in ROUND_FLOOR rounding mode.
			      ((ref self 'copy_abs))
			      ((ref self 'copy_negate)))))
	    
	    ((ref ans '_fix) context)))))

    (define __pos__
      (lam (self (= context None))
        "Returns a copy, unless it is a sNaN.

        Rounds the number (if more than precision digits)
        "
	(twix
	 ((un-special self context) it it)
	 
	 (let* ((context (if (eq? context None)
			     (getcontext)
			     context))
		(ans     (if (and (not (bool self))
				  (not (eq? (cx-rounding context)
					    ROUND_FLOOR)))
			     ;; -Decimal('0') is Decimal('0'),
			     ;; not Decimal('-0'), except
			     ;; in ROUND_FLOOR rounding mode.
			     ((ref self 'copy_abs))
			     (Decimal self))))

	   ((ref ans '_fix) context)))))

    (define __abs__
      (lam (self  (= round #t) (= context None))
	"Returns the absolute value of self.

        If the keyword argument 'round' is false, do not round.  The
        expression self.__abs__(round=False) is equivalent to
        self.copy_abs().
        "
	(twix
	 ((not (bool round)) it
	  ((ref self 'copy_abs)))

	 ((un-special self context) it it)

	 (if (= (ref self '_sign) 1)
	     ((ref self '__neg__) #:context context)
	     ((ref self '__pos__) #:context context)))))
    

    (define __add__
      (lam (self other (= context None))
        "Returns self + other.

        -INF + INF (or the reverse) cause InvalidOperation errors.
        "
	(twix
	 ((norm-op self other) it it)
	 
	 (let (get-context context))
	 
	 ((add-special self other context) it it)
	 		 
	 (let* ((negativezero 0)
		(self_sign    (ref self  '_sign))
		(other_sign   (ref other '_sign))
		(self_exp     (ref self  '_sign))
		(other_exp    (ref other '_sign))
		(prec         (cx-prec context))
		(exp          (min self_exp other_exp))		    
		(sign         #f)
		(ans          #f))
	  
	   (if (and (eq? (cx-rounding context) ROUND_FLOOR)
		    (not (= self_sign other_sign)))
	       ;; If the answer is 0, the sign should be negative,
	       ;; in this case.
	       (set! negativezero 1)))

	 ((if (and (not (bool self)) (not (bool other)))
	      (begin
		(set! sign (min self_sign other_sign))
		(if (= negativezero 1)
		    (set! sign 1))
		(set! ans (_dec_from_triple sign "0" exp))
		(set! ans ((ref ans '_fix) context))
		ans)
	      #f) it it)

	 ((if (not (bool self))
	      (begin
		(set! exp (max exp (- other_exp prec 1)))
		(set! ans ((ref other '_rescale) exp
			   (cx-rounding context)))
		(set! ans ((ref ans '_fix) context))
		ans)
	      #f) it it)

	 ((if (not (bool other))
	      (begin
		(set! exp (max exp (- self_exp prec 1)))
		(set! ans ((ref self '_rescale) exp
			   (cx-rounding context)))
		(set! ans ((ref ans '_fix) context))
		ans)
	      #f) it it)
		
		
	 (let* ((op1    (_WorkRep self))
		(op2    (_WorkRep other))
		(ab     (_normalize op1 op2 prec))
		(op1_i  (car  ab))
		(op2_i  (cadr ab))
		(result (_WorkRep))))

	 ((cond
	   ((not (= (ref op1 'sign) (ref op2 'sign)))
	    ;; Equal and opposite
	    (twix
	     ((= op1_i op2_i) it
	      (set! ans (_dec_from_triple negativezero "0" exp))
	      (set! ans ((ref ans '_fix) context))
	      ans)
		    
	     (begin
	       (if (< op1_i op2_i)
		   (let ((t op1))
		     (set! op1 op2)
		     (set! op2 t)))
		    
	       (if (= (ref op1 'sign) 1)			
		   (let ((t (ref op1 'sign)))
		     (set result 'sign 1)
		     (set op1 'sign (ref op2 'sign))
		     (set op2 'sign t))
		   (set result 'sign 0))
	       #f)))
	   ((= (ref op1 'sign) 1)
	    (set result 'sign 1)
	    #f)

	   (else
	    (set result 'sign 0)
	    #f)) it it)

	 (begin
	   (if (= (ref op2 'sign) 0)
	       (set result 'int (+ (ref op1 'int) (ref op2 'int)))
	       (set result 'int (- (ref op1 'int) (ref op2 'int))))

	   (set result 'exp (ref op1 'exp))
	   (set! ans (Decimal result))
	   ((ref ans '_fix) context)))))

    (define __radd__ __add__)

    (define __sub__
      (lam (self other (= context None))
	"Return self - other"
	(twix
	 ((norm-op self other)            it it)
	 ((bin-special self other context) it it)
	 ((ref self '__add__)
	  ((ref other 'copy_negate)) #:context context))))

    (define  __rsub__
      (lam (self other (= context None))
        "Return other - self"
    	(twix
	 ((norm-op self other) it it)
	 ((ref 'other '__sub__) self  #:context context))))

    (define __mul__
      (lam (self other (= context None))
        "Return self * other.

        (+-) INF * 0 (or its reverse) raise InvalidOperation.
        "
	(twix
	 ((norm-op self other) it it)	 
	 (let (get-context context))
	 
	 (let ((resultsign (logxor (ref self  '_sign)
				   (ref other '_sign)))))

	 ((mul-special self other context resultsign) it it)

	 (let ((resultexp (+ (ref self '_exp) (ref other '_exp)))))

	 ;; Special case for multiplying by zero
	 ((or (not (bool self)) (not (bool other))) it
	  (let ((ans (_dec_from_triple resultsign "0" resultexp)))
	    ((ref ans '_fix) context)))
	 
	 ;; Special case for multiplying by power of 10
	 ((equal? (ref self '_int) "1") it
	  (let ((ans (_dec_from_triple resultsign (ref other '_int) resultexp)))
	    ((ref ans '_fix) context)))

	 ((equal? (ref other '_int) "1") it
	  (let ((ans (_dec_from_triple resultsign (ref self '_int) resultexp)))
	    ((ref ans '_fix) context)))

	 (let* ((op1 (_WorkRep self))
		(op2 (_WorkRep other))
		(ans (_dec_from_triple resultsign
				       (str (* (ref op1 'int) (ref op2 'int)))
				       resultexp)))
	   ((ref ans '_fix) context)))))
  
    (define __rmul__ __mul__)

    (define __truediv__
      (lam (self other (= context None))
	"Return self / other."
	(twix
	 ((norm-op self other) it it)	 
	 (let (get-context context))
   
	 (let ((sign (logxor (ref self  '_sign)
			     (ref other '_sign)))))

	 ((div-special self other context sign) it it)	 

	 ;; Special cases for zeroes
        ((if (not (bool other))
	     (if (not (bool self))
                 ((cx-error context) DivisionUndefined "0 / 0")
		 ((cx-error context) DivisionByZero    "x / 0" sign))
	     #f) it it)

	(let ((exp    #f)
	      (coeff  #f)
	      (nself  (len (ref self '_int)))
	      (nother (len (ref other '_int))))
	  (if (not (bool self))
	      (begin
		(set! exp   (- (ref self '_exp) (ref other '_exp)))
		(set! coeff 0))
	      ;; OK, so neither = 0, INF or NaN
	      (let ((shift (+ nother (- nself) prec 1))
		    (op1   (_WorkRep self))
		    (op2   (_WorkRep other)))
		(set! exp (- (ref self '_exp) (ref other '_exp) shift))
		(call-with-values
		    (lambda ()
		      (if (>= shift 0)
			  (divmod (* (ref op1 'int) (expt 10 shift))
				  (ref op2 'int))
			  (divmod (ref op1 'int)
				  (* (ref op2 'int) (expt 10 shift)))))
		  (lambda (coeff- remainder)
		    (set! coeff
			  (if (not (= remainder 0))
			      ;; result is not exact adjust to ensure
			      ;; correct rounding
			      (if (= (modulus coeff- 5) 0)
				  (+ coeff- 1)
				  coeff)
			      (let ((ideal_exp (- (ref self '_exp)
						  (ref other '_exp))))
				(let lp ((coeff- coeff-) (exp- exp))
				  (if (and (< exp- indeal_exp)
					   (= (modulo coeff 10) 0))
				      (lp (/ coeff 10) (+ exp- 1))
				      (begin
					(set exp exp-)
					coeff))))))))))
			      
			    
	  (let ((ans (_dec_from_triple sign, (str coeff) exp)))
	    ((ref ans '_fix) context))))))

    (define _divide
      (lambda (self other context)	
        "Return (self // other, self % other), to context.prec precision.

        Assumes that neither self nor other is a NaN, that self is not
        infinite and that other is nonzero.
        "
	(apply values
	(twix
	 (let (let ((sign
		     (logxor (ref self  '_sign)
			     (ref other '_sign)))
		    (ideal_exp
		     (if ((ref other '_isinfinity))
			 (ref self '_exp)
			 (min (ref self 'exp) (ref other '_exp))))
		    (expdiff
		     (- ((ref self 'adjusted)) ((ref other 'adjusted)))))))
	 
	 ((or (not (bool self))
	      ((ref other '_isinfinity))
	      (<= expdiff -1)) it
	   (list (_dec_from_tripple sign "0" 0)
		 ((ref self '_rescale) ideal_exp (cx-rounding context))))
	 
	 ((if (<= expdiff  (cx-prec context))
	      (let ((op1 (_WorkRep self))
		    (op2 (_WorkRep other)))
		(if (>= (ref op1 'exp) (ref op2 'exp))
		    (set op1 'int (* (ref op1 'int)
				     (expt 10 (- (ref op1 'exp)
						 (ref op2 'exp)))))
		    (set op2 'int (* (ref op2 'int)
				     (expt 10 (- (ref op2 'exp)
						 (ref op1 'exp))))))
		(call-with-values (lambda () (divmod (ref op1 'int)
						     (ref op2 'int)))
		  (lambda (q r)		
		    (if (< q (expt 10 (cx-prec context)))
			(list (_dec_from_triple sign (str q) 0)
			      (_dec_from_triple (ref self '_sign)
						(str r)
						ideal_exp))
			#f))))
	      #f) it it)
	 (begin
	   ;; Here the quotient is too large to be representable
	   (let ((ans ((cx-raise context) DivisionImpossible
		       "quotient too large in //, % or divmod")))
	     (list ans ans)))))))
  #|
    (define __rtruediv__
      (lam (self other (= context None))
	""Swaps self/other and returns __truediv__.""
	(twix
	 ((norm-op self other) it it)	 
	 ((ref other '__truediv__) self #:context context))))
    
    (define __divmod__
      (lam (self other (= context None))
        "
        Return (self // other, self % other)
        "
	(apply values
	(twix
	 ((norm-op self other) it it)	 

	 (let (get-context context))
	 
	 ((add-special o1 o2 context) it it)
	 
	 (((ref self '_check_nans) other context) it
	  (list it it))

	 (let (let ((sign
		     (logxor (ref self  '_sign)
			     (ref other '_sign))))))

	 (((ref self '_isinfinity)) it
	  (if ((ref other '_isinfinity))
	      (let ((ans ((cx-error context) InvalidOperation
			  "divmod(INF, INF)")))
		(list ans ans))
	      (list (list-ref _SignedInfinity sign)
		    ((cx-raise context) InvalidOperation, "INF % x"))))

	 ((not (bool other)) it
	  (if (not (bool self))
	      (let ((ans ((cx-error context) DivisionUndefined
			  "divmod(0, 0)")))
		(list ans ans))
	      (list ((cx-error context) DivisionByZero "x // 0" sign)
		    ((cx-error context) InvalidOperation "x % 0"))))
	     
	 (call-with-values (lambda () ((ref self '_divide) other context))
	   (lambda (quotient remainder)
	     (let ((remainder ((ref remainder '_fix) context)))
	       (list quotient remainder))))))))

    (define __rdivmod__
      (lam (self other (= context None))
	"Swaps self/other and returns __divmod__."
    	(twix
	 ((norm-op self other) it it)	 
	 ((ref other '__divmod__) self #:context context))))

    (define __mod__
      (lam (self other (= context None))
        "
        self % other
        "
	(twix
	 ((norm-op self other) it it)	 

	 (let (get-context context))

	 ((bin-special o1 o2 context) it it)

	 (((ref self '_isinfinity)) it
	  ((cx-error context) InvalidOperation "INF % x"))
	 
	 ((not (bool other))
          (if (bool self)
	      ((cx-error context) InvalidOperation  "x % 0")          
	      ((cx-error context) DivisionUndefined "0 % 0")))

	 (let* ((remainder ((ref self '_divide) other context)))
	   ((ref remainder '_fix) context)))))

    (define __rmod__
      (lam (self other (= context None))
	"Swaps self/other and returns __mod__."
    	(twix
	 ((norm-op self other) it it)	 
	 ((ref other '__mod__) self #:context context))))

    (define remainder_near
      (lambda (self other (= context None))
        "
        Remainder nearest to 0-  abs(remainder-near) <= other/2
        "
	(twix
	 ((norm-op self other) it it)

	 (let (get-context context))

	 ((bin-special self other context) it it)

	 ;; self == +/-infinity -> InvalidOperation
	 (((ref self '_isinfinity)) it
	  ((cx-error context) InvalidOperation "remainder_near(infinity, x)"))

	 ;; other == 0 -> either InvalidOperation or DivisionUndefined
	 ((not (bool other)) it
	  (if (not (bool self))
	      ((cx-error context) InvalidOperation  "remainder_near(x, 0)")
	      ((cx-error context) DivisionUndefined "remainder_near(0, 0)")))

	 ;; other = +/-infinity -> remainder = self
	 (((ref other '_isinfinity())) it
	  (let ((ans (Decimal self)))
            ((ref ans '_fix) context)))

	 ;; self = 0 -> remainder = self, with ideal exponent
	 (let (let ((ideal_exponent (min (ref self '_exp) (ref other '_exp))))))

	 ((not (bool self)) it
	  (let ((ans (_dec_from_triple (ref self '_sign) "0" ideal_exponent)))
            ((ref ans '_fix) context)))

	 ;; catch most cases of large or small quotient
	 (let (let ((expdiff
		     (- ((ref self 'adjusted)) ((red other 'adjusted)))))))
	 
        ((>= expdiff (+ (cx-prec context) 1)) it
	 ;; expdiff >= prec+1 => abs(self/other) > 10**prec
	 ((cx-error context) DivisionImpossible))
	
        ((<= expdiff -2) it
	 ;; expdiff <= -2 => abs(self/other) < 0.1
	 (let ((ans ((ref self '_rescale)
		     ideal_exponent (cx-rounding context))))
	   ((ref ans '_fix) context)))

        (let ((op1  (_WorkRep self))
	      (op2  (_WorkRep other)))

	  ;; adjust both arguments to have the same exponent, then divide
	  (if (>= (ref op1 'exp) (ref op2 'exp))
	      (set op1 'int (* (ref op1 'int)
			       (expt 10 (- (ref op1 'exp) (ref op2 'exp)))))
	      (set op2 'int (* (ref op2 'int)
			       (expt 10 (- (ref op2 'exp) (ref op1 'exp))))))
	  
	  (call-with-values (lambda () (divmod (ref op1 'int) (ref op2 'int)))
	    (lambda (q r)

	      ;; remainder is r*10**ideal_exponent; other is +/-op2.int *
	      ;; 10**ideal_exponent.   Apply correction to ensure that
	      ;; abs(remainder) <= abs(other)/2
	      (if (> (+ (* 2 r)  + (logand q 1)) (ref op2 'int))
		  (set! r (- r (ref op2 'int)))
		  (set! q (+ q 1)))

	      (if (>= q (expt 10 (cx-prec context)))
		  ((cx-error context) DivisionImpossible)
		  (let ((sign (ref self '_sign)))
		    (if (< r 0)
			(set! sign (- 1 sign))
			(set! r    (- r)))
		    (let ((ans (_dec_from_triple sign (str r) ideal_exponent)))
		      ((ref ans '_fix) context))))))))))

    (define __floordiv__
      (lambda (self other (= context None))
        "self // other"
	(twix
	 ((norm-op self other) it it)

	 (let (get-context context))

	 ((bin-special self other context) it it)

	 (((ref self '_isinfinity)) it
	  (if ((ref other '_isinfinity))
               ((cx-error context) InvalidOperation "INF // INF")
	       (pylist-ref _SignedInfinity (logxor (ref self  '_sign)
						   (ref other '_sign)))))

	 ((not (bool other)) it
	  (if (bool self)
	      ((cx-error context) DivisionByZero    "x // 0"
	       (logxor (ref self  '_sign) (ref other '_sign)))
	      ((cx-error context) DivisionUndefined "0 // 0")))

	 ((ref self '_divide) other context))))

    (define __rfloordiv__
      (lam (self other (= context None))
	"Swaps self/other and returns __floordiv__."
	(twix
	 ((norm-op self other) it it)	 
	 ((ref other '__floordiv__) self #:context context))))

    (define __float__
      (lambda (self)
        "Float representation."
        (if ((ref self '_isnan))
            (if ((ref self 'is_snan))
                (raise (ValueError "Cannot convert signaling NaN to float"))
		(if (= (ref self '_sign))
		    (- (nan))
		    (nan)))
	    (if ((ref self '_isspecial))
		(if (= (ref self '_sign))
		    (- (inf))
		    (inf)))
	    (float (str self)))))
    
    (define __int__
      (lambda (self)
        "Converts self to an int, truncating if necessary."
	(if ((ref self '_isnan))
	    (raise (ValueError "Cannot convert NaN to integer"))
	    (if ((ref self '_isspecial))
		(raise (OverflowError "Cannot convert infinity to integer"))
		(let ((s (if (= (ref self '_sign) 1) -1 1)))
		  (if (>= (ref self '_exp) 0)
		      (* s (int (ref self '_int)) (expt 10 (ref self '_exp)))
		      (* s (int (or (bool (py-slice (ref self '_int)
						    None (ref self '_exp) None))
				    "0")))))))))

    (define __trunc__ __int__)

    (define real
      (property (lambda (self) self)))
    
    (define imag
      (property
       (lambda (self)
	 (Decimal 0))))

    (define conjugate
      (lambda (self) self))
    
    (define __complex__
      (lambda (self)
        (complex (float self))))

    (define _fix_nan
      (lambda (self context)
        "Decapitate the payload of a NaN to fit the context"
        (let ((payload (ref self '_int))
	      
	      ;; maximum length of payload is precision if clamp=0,
	      ;; precision-1 if clamp=1.
	      (max_payload_len
	       (- (ref context 'prec)
		  (ref context 'clamp))))
	  
	  (if (> (len payload)  max_payload_len)
	      (let ((payload (py-lstrip
			      (pylist-slice payload
					    (- (len payload) max_payload_len)
					    None None)  "0")))
		(_dec_from_triple (ref self '_sign) payload (ref self '_exp)
				  #t))
	      (Decimal self)))))

    (define _fix 
      (lambda (self context)
        "Round if it is necessary to keep self within prec precision.

        Rounds and fixes the exponent.  Does not raise on a sNaN.

        Arguments:
        self - Decimal instance
        context - context used.
        "

	(twix
	 (((ref self '_is_special)) it
	  (if ((ref self '_isnan))
	      ;; decapitate payload if necessary
	      ((ref self '_fix_nan) context)

	      ;; self is +/-Infinity; return unaltered
	      (Decimal self)))

	 ;; if self is zero then exponent should be between Etiny and
	 ;; Emax if clamp==0, and between Etiny and Etop if clamp==1.
	 (let ((Etiny (cx-etiny context))
	       (Etop  (cx-etop  context))))
	 
	 ((not (bool self)) it
	  (let ((exp_max (if (= (cx-clamp context) 0)
			     (cx-emax context)
			     Etop))
		(new_exp (min (max (ref self '_exp) Etiny) exp_max)))
            (if (not (= new_exp (ref self '_exp)))
		(begin
		  ((cx-error context) Clamped)
		  (_dec_from_triple (ref self '_sign) "0" new_exp))
		(Decimal self))))

	 ;; exp_min is the smallest allowable exponent of the result,
	 ;; equal to max(self.adjusted()-context.prec+1, Etiny)
	 (let ((exp_min (+ (len (ref self '_int))
			   (ref self '_exp)
			   (- (cx-prec context))))))
	 ((> exp_min Etop) it
	  ;; overflow: exp_min > Etop iff self.adjusted() > Emax
	  (let ((ans ((cx-error context) Overflow "above Emax"
		      (ref self '_sign))))
            ((cx-error context) Inexact)
	    ((cx-error context) Rounded)
	    ans))

	 (let* ((self_is_subnormal (< exp_min Etiny))
		(exp_min           (if self_is_subnormal Eriny exp_min))))

	 ;; round if self has too many digits
	 ((< self._exp exp_min) it
	  (let ((digits (+ (len (ref self '_int))
			   (ref self '_exp)
			   (- exp_min))))
            (if (< digits 0)
                (set! self (_dec_from_triple (ref self '_sign)
					     "1" (- exp_min 1)))
                (set! digits 0))
	    
            (let* ((ans #f)
		   (rounding_method (pylist-ref
				     (ref self '_pick_rounding_function)
				     (cx-rounding context)))
		   (changed (rounding_method self digits))
		   (coeff   (or (bool (pylist-slice (ref self '_int)
						    None digits None)) "0")))
	      (if (> changed  0)
		  (begin
		    (set! coeff (str (+ (int coeff) 1)))
		    (if (> (len coeff) (cx-prec context))
			(begin
			  (set! coeff (pylist-clice coeff None -1 None))
			  (set! exp_min (+ exp_min  1))))))

	      ;; check whether the rounding pushed the exponent out of range
	      (if (> exp_min  Etop)
		  (set! ans
			((cx-error context) Overflow "above Emax"
			 (ref self '_sign)))
		  (set! ans (_dec_from_triple (ref self '_sign) coeff exp_min)))

	      ;; raise the appropriate signals, taking care to respect
	      ;; the precedence described in the specification
	      (if (and changed self_is_subnormal)
		  ((cx-error context) Underflow))
	      (if self_is_subnormal
		  ((cx-error context) Subnormal))
	      (if changed
		  ((cx-error context) Inexact))

	      ((cx-error context) Rounded)

	      (if (not (bool ans))
		  ;; raise Clamped on underflow to 0
		  ((cx-error context) Clamped))

	      ans)))
	 (begin
	   (if self_is_subnormal
	       ((cx-error context) Subnormal))


	   ;; fold down if clamp == 1 and self has too few digits
	   (if (and (= (cx-clamp context) 1) (> (ref self '_exp) Etop))
	       (begin
		 ((cx-error context) Clamped)
		 (let ((self_padded  (+ (ref self '_int)
					(* "0"
					   (- (ref self '_exp) Etop)))))
		   (_dec_from_triple (ref self '_sign) self_padded Etop)))
	       
	       ;; here self was representable to begin with; return unchanged
	       (Decimal self))))))
    
    

    ;; for each of the rounding functions below:
    ;;   self is a finite, nonzero Decimal
    ;;   prec is an integer satisfying 0 <= prec < len(self._int)
    ;;
    ;; each function returns either -1, 0, or 1, as follows:
    ;;   1 indicates that self should be rounded up (away from zero)
    ;;   0 indicates that self should be truncated, and that all the
    ;;    digits to be truncated are zeros (so the value is unchanged)
    ;;  -1 indicates that there are nonzero digits to be truncated

    (define _round_down
      (lambda (self prec)
        "Also known as round-towards-0, truncate."
        (if (_all_zeros (ref self '_int) prec)
            0
	    -1)))

    (define _round_up
      (lambda (self prec)
        "Rounds away from 0."
        (- (_round_down self prec))))

    (define _round_half_up
      (lambda (self prec)
        "Rounds 5 up (away from 0)"
        (cond
	 ((in (pylist-ref (ref self '_int) prec) "56789")
	  1)
	 ((_all_zeros (ref self '_int) prec)
	  0)
	 (else -1))))
    
    (define _round_half_down
      (lambda (self prec)
        "Round 5 down"
        (if (_exact_half (ref self '_int) prec)
            -1
            (_round_half_up self prec))))

    (define _round_half_even
      (lambda (self prec)
        "Round 5 to even, rest to nearest."
        (if (and (_exact_half (ref self '_int) prec)
		 (or (= prec 0)
		     (in (pylist-ref (ref self '_int) (- prec 1)) "02468")))
            -1)
       (_round_half_up self prec)))

    (define _round_ceiling
      (lambda (self prec)
        "Rounds up (not away from 0 if negative.)"
        (if (= (ref self '_sign) 1)
            (_round_down self prec)
	    (- (_round_down self prec)))))

    (define _round_floor
      (lambda (self prec)
        "Rounds down (not towards 0 if negative)"
        (if (= (ref self '_sign) 1)
	    (- (_round_down self prec))
	    (_round_down self prec))))
    
    (define _round_05up
      (lambda (self prec)
        "Round down unless digit prec-1 is 0 or 5."
        (if (and prec (not (in (pylist-ref (ref self '_int) (- prec 1) "05"))))
	    (_round_down self prec)
	    (- (_round_down self prec)))))
    
    (define _pick_rounding_function
      (dict `((,ROUND_DOWN      . ,_round_down   )
	      (,ROUND_UP        . ,_round_up     )
	      (,ROUND_HALF_UP   . ,_round_half_up)
	      (,ROUND_HALF_DOWN . ,_round_half_down)
	      (,ROUND_HALF_EVEN . ,_round_half_even)
	      (,ROUND_CEILING   . ,_round_ceiling)
	      (,ROUND_FLOOR     . ,_round_floor)
	      (,ROUND_05UP      . ,_round_05up))))

    (define __round__
      (lam (self  (= n None))
        "Round self to the nearest integer, or to a given precision.

        If only one argument is supplied, round a finite Decimal
        instance self to the nearest integer.  If self is infinite or
        a NaN then a Python exception is raised.  If self is finite
        and lies exactly halfway between two integers then it is
        rounded to the integer with even last digit.

        >>> round(Decimal('123.456'))
        123
        >>> round(Decimal('-456.789'))
        -457
        >>> round(Decimal('-3.0'))
        -3
        >>> round(Decimal('2.5'))
        2
        >>> round(Decimal('3.5'))
        4
        >>> round(Decimal('Inf'))
        Traceback (most recent call last):
          ...
        OverflowError: cannot round an infinity
        >>> round(Decimal('NaN'))
        Traceback (most recent call last):
          ...
        ValueError: cannot round a NaN

        If a second argument n is supplied, self is rounded to n
        decimal places using the rounding mode for the current
        context.

        For an integer n, round(self, -n) is exactly equivalent to
        self.quantize(Decimal('1En')).

        >>> round(Decimal('123.456'), 0)
        Decimal('123')
        >>> round(Decimal('123.456'), 2)
        Decimal('123.46')
        >>> round(Decimal('123.456'), -2)
        Decimal('1E+2')
        >>> round(Decimal('-Infinity'), 37)
        Decimal('NaN')
        >>> round(Decimal('sNaN123'), 0)
        Decimal('NaN123')

        "
        (if (not (eq? n None))
            ;; two-argument form: use the equivalent quantize call
            (if (not (isinstance n int))
                (raise (TypeError
			"Second argument to round should be integral"))
		(let ((exp (_dec_from_triple 0, "1", (- n))))
		  ((ref self 'quantize) exp)))

	    ;; one-argument form
	    (if (ref self '_is_special)
		(if ((ref self 'is_nan))
		    (raise (ValueError    "cannot round a NaN"))
		    (raise (OverflowError "cannot round an infinity")))
		(int ((ref self '_rescale) 0 ROUND_HALF_EVEN))))))

    (define __floor__
      (lambda (self)
        "Return the floor of self, as an integer.

        For a finite Decimal instance self, return the greatest
        integer n such that n <= self.  If self is infinite or a NaN
        then a Python exception is raised.

        "
	(if (ref self '_is_special)
		(if ((ref self 'is_nan))
		    (raise (ValueError    "cannot round a NaN"))
		    (raise (OverflowError "cannot round an infinity")))
		(int ((ref self '_rescale) 0 ROUND_FLOOR)))))

    (define __ceil__
      (lambda (self)
        """Return the ceiling of self, as an integer.

        For a finite Decimal instance self, return the least integer n
        such that n >= self.  If self is infinite or a NaN then a
        Python exception is raised.

        """
	(if (ref self '_is_special)
	    (if ((ref self 'is_nan))
		(raise (ValueError    "cannot round a NaN"))
		(raise (OverflowError "cannot round an infinity")))
	    (int ((ref self '_rescale) 0 ROUND_CEILING)))))

    (define fma
      (lam (self other third (= context None))
        "Fused multiply-add.

        Returns self*other+third with no rounding of the intermediate
        product self*other.

        self and other are multiplied together, with no rounding of
        the result.  The third operand is then added to the result,
        and a single final rounding is performed.
        "
	(twix
	 (let ((other (_convert_other other #:raiseit #t))
	       (third (_convert_other third #:raiseit #t))
	       (fin   (lambda (product)
			((ref product '__add__) third context)))))
	 ;; compute product; raise InvalidOperation if either operand is
	 ;; a signaling NaN or if the product is zero times infinity.	 
        ((if (or (ref self '_is_special) (ref other '_is_special))
	     (twix
	      (let (get-context context))
	      ((equals? (ref self '_exp) "N")  it
	       ((cx-error context) InvalidOperation "sNaN" self))
	      ((equals? (ref other '_exp) "N") it
	       ((cx-error context) InvalidOperation "sNaN" other))
	      ((equals? (ref self '_exp) "n")  it
	       (fin self))
	      ((equals? (ref other '_exp) "n") it
	       (fin other))
	      ((equals? (ref self '_exp) "F")  it
	       (if (not (bool other))
		   ((cx-error context) InvalidOperation "INF * 0 in fma")
		   (pylist-ref _SignedInfinity
			       (logxor (ref self  '_sign)
				       (ref other '_sign)))))
	      ((equals? (ref other '_exp) "F")  it
	       (if (not (bool self))
		   ((cx-error context) InvalidOperation "0 * INF in fma")
		   (pylist-ref _SignedInfinity
			       (logxor (ref self  '_sign)
				       (ref other '_sign)))))
	      #f)) it it)
	
	(fin
	 (_dec_from_triple (logxor (ref self '_sign) (ref other '_sign))
			   (str (* (int (ref self '_int))
				   (int (ref other '_int))))
			   (+ (ref self '_exp) (ref other '_exp)))))))
    
    (define _power_modulo
      (lam (self other modulo (= context None))
        "Three argument version of __pow__"
	(twix
	 ((norm-op self other ) it it)
	 ((norm-op self modulo) it it)
	 (let (get-context context))

	 ;; deal with NaNs: if there are any sNaNs then first one wins,
	 ;; (i.e. behaviour for NaNs is identical to that of fma)
	 (let ((self_is_nan   (ref self   '_isnan))
	       (other_is_nan  (ref other  '_isnan))
	       (modulo_is_nan (ref modulo '_isnan))))
	 
	 ((or (bool self_is_nan) (bool other_is_nan) (bool modulo_is_nan)) it
	  (cond
	   ((= self_is_nan 2)
	    ((cx-error context) InvalidOperation, "sNaN"  self))
	   ((= other_is_nan 2)
	    ((cx-error context) InvalidOperation, "sNaN"  other))
	   ((modulo_is_nan 2)
	    ((cx-error context) InvalidOperation, "sNaN"  modulo))
	   ((bool self_is_nan)
	    (_fix_nan self context))
	   ((bool other_is_nan)
	    (_fix_nan other context))
	   (else
	    (_fix_nan modulo context))))
         
	 ;;check inputs: we apply same restrictions as Python's pow()
	 ((not (and ((ref self   '_isinteger))
		    ((ref other  '_isinteger))
		    ((ref modulo '_isinteger)))) it
	  ((cx-error context) InvalidOperation
	   (+ "pow() 3rd argument not allowed "
	      "unless all arguments are integers")))
	 
	 ((< other 0) it
	  ((cx-error context) InvalidOperation
	   (+ "pow() 2nd argument cannot be "
	      "negative when 3rd argument specified")))

	 ((not (bool modulo)) it
	     ((cx-error context) InvalidOperation
	      "pow() 3rd argument cannot be 0"))

	 ;; additional restriction for decimal: the modulus must be less
	 ;; than 10**prec in absolute value
	 ((>= ((ref modulo 'adjusted)) (cx-prec context)) it
	  ((cx-error context) InvalidOperation
	   (+ "insufficient precision: pow() 3rd "
	      "argument must not have more than "
	      "precision digits")))

	 ;; define 0**0 == NaN, for consistency with two-argument pow
	 ;; (even though it hurts!)
	 ((and (not (bool other)) (not (bool self)))
	  ((cx-error context) InvalidOperation
	   (+ "at least one of pow() 1st argument "
	      "and 2nd argument must be nonzero ;"
	      "0**0 is not defined")))

	 ;; compute sign of result
	 (let ((sign     (if ((ref other '_iseven))
			     0
			     (ref self '_sign)))
	       (base     (_WorkRep ((ref self  'to_integral_value))))
	       (exponent (_WorkRep ((ref other 'to_integral_value)))))


	   ;; convert modulo to a Python integer, and self and other to
	   ;; Decimal integers (i.e. force their exponents to be >= 0)
	   (set! modulo (abs (int modulo)))

	   ;; compute result using integer pow()
	   (set! base (guile:modulo
		       (* (guile:modulo (ref base 'int) modulo)
			  (modulo-expt 10 (ref base 'exp) modulo))
		       modulo))
	   
	   (let lp ((i (ref exponent 'exp)))
	     (if (> i 0)
		 (begin
		   (set! base (modulo-expt base 10 modulo))
		   (lp (- i 1)))))
	   
	   (set! base (modulo-expt base (ref exponent 'int) modulo))
	   
	   (_dec_from_triple sign (str base) 0)))))

    (define _power_exact
      (lambda (self other p)
        "Attempt to compute self**other exactly.

        Given Decimals self and other and an integer p, attempt to
        compute an exact result for the power self**other, with p
        digits of precision.  Return None if self**other is not
        exactly representable in p digits.

        Assumes that elimination of special cases has already been
        performed: self and other must both be nonspecial; self must
        be positive and not numerically equal to 1; other must be
        nonzero.  For efficiency, other._exp should not be too large,
        so that 10**abs(other._exp) is a feasible calculation."

        ;; In the comments below, we write x for the value of self and y for the
        ;; value of other.  Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
        ;; and yc positive integers not divisible by 10.

        ;; The main purpose of this method is to identify the *failure*
        ;; of x**y to be exactly representable with as little effort as
        ;; possible.  So we look for cheap and easy tests that
        ;; eliminate the possibility of x**y being exact.  Only if all
        ;; these tests are passed do we go on to actually compute x**y.

        ;; Here's the main idea.  Express y as a rational number m/n, with m and
        ;; n relatively prime and n>0.  Then for x**y to be exactly
        ;; representable (at *any* precision), xc must be the nth power of a
        ;; positive integer and xe must be divisible by n.  If y is negative
        ;; then additionally xc must be a power of either 2 or 5, hence a power
        ;; of 2**n or 5**n.
        ;;
        ;; There's a limit to how small |y| can be: if y=m/n as above
        ;; then:
        ;;
        ;;  (1) if xc != 1 then for the result to be representable we
        ;;      need xc**(1/n) >= 2, and hence also xc**|y| >= 2.  So
        ;;      if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
        ;;      2**(1/|y|), hence xc**|y| < 2 and the result is not
        ;;      representable.
        ;;
        ;;  (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1.  Hence if
        ;;      |y| < 1/|xe| then the result is not representable.
        ;;
        ;; Note that since x is not equal to 1, at least one of (1) and
        ;; (2) must apply.  Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
        ;; 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
        ;;
        ;; There's also a limit to how large y can be, at least if it's
        ;; positive: the normalized result will have coefficient xc**y,
        ;; so if it's representable then xc**y < 10**p, and y <
        ;; p/log10(xc).  Hence if y*log10(xc) >= p then the result is
        ;; not exactly representable.

        ;; if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
        ;; so |y| < 1/xe and the result is not representable.
        ;; Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
        ;; < 1/nbits(xc).

	(twix
	 (let ()
	   (define-syntax-rule (clean xc xe n +)
	     (let lp ()
	       (if (= (modulo xc n) 0)
		   (begin
		     (set! xc (/ xc n))
		     (set! xe (+ xe 1))
		     (lp))))))

	 (let* ((x  (_WorkRep self))
		(xc (ref x 'int))
		(xe (ref x 'exp)))
	   (clean xc xe 10 +))
	 
	 (let* ((y  (_WorkRep other))
		(yc (ref y 'int))
		(ye (ref y 'exp)))
	   (clean yc ye 10 +))
	 
        ;; case where xc == 1: result is 10**(xe*y), with xe*y
        ;; required to be an integer
        ((= xc 1) it
	 (set! xe (* xe yc))

	 ;; result is now 10**(xe * 10**ye);  xe * 10**ye must be integral
	 (clean xe ye 10 +)
	 
	 (if (< ye 0)
	     None
	     (let ((exponent (* xe (expt 10 ye)))
		   (zeros    #f))
	       (if (= (ref y 'sign) 1)
		   (set! exponent (- exponent)))
	       
	       ;;if other is a nonnegative integer, use ideal exponent
	       (if (and ((ref other '_isinteger)) (= (ref other '_sign) 0))
		   (begin
		     (let ((ideal_exponent (* (ref self '_exp) (int other))))
		       (set! zeros (min (- exponent ideal_exponent) (- p 1)))))
		   (set! zeros 0))

	       (_dec_from_triple 0 (+ "1" (* "0" zeros)) exponent-zeros))))

        ;; case where y is negative: xc must be either a power
        ;; of 2 or a power of 5.
        ((= (ref y 'sign) 1) it
	 (let ((last_digit (modulo xc 10)))
	   (twix
            ((cond
	      ((= (modulo last_digit 2) 0)
	       ;; quick test for power of 2
	       (twix
		((not (= (logand xc (- xc)) xc))
		 None)
		;; now xc is a power of 2; e is its exponent
		(let ((e (- (_nbits xc) 1))))
		
		;; We now have:
		;;
		;;   x = 2**e * 10**xe, e > 0, and y < 0.
		;;
		;; The exact result is:
		;;
		;;   x**y = 5**(-e*y) * 10**(e*y + xe*y)
		;;
		;; provided that both e*y and xe*y are integers.
		;; Note that if
		;; 5**(-e*y) >= 10**p, then the result can't be expressed
		;; exactly with p digits of precision.
		;;
		;; Using the above, we can guard against large values of ye.
		;; 93/65 is an upper bound for log(10)/log(5), so if
		;;
		;;   ye >= len(str(93*p//65))
		;;
		;; then
		;;
		;;   -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
		;;
		;; so 5**(-e*y) >= 10**p, and the coefficient of the result
		;; can't be expressed in p digits.
		
		;; emax >= largest e such that 5**e < 10**p.
		(let ((emax (quotient (* p 93) 65))))

		((>= ye (len (str emax))) it
		 None)

		;; Find -e*y and -xe*y; both must be integers
		(let ()
		  (set! e  (_decimal_lshift_exact (* e  yc) ye))
		  (set! xe (_decimal_lshift_exact (* xe yc) ye)))
		  
		((or (eq? e None) (eq? xe None)) it
		 None)

		((> e emax)
		 None)

		(begin
		  (set! xc (expt 5 e))
		  #f)))
	    
	      ((= last_digit 5)
	       (twix
                ;; e >= log_5(xc) if xc is a power of 5; we have
                ;; equality all the way up to xc=5**2658
                (let* ((e         (quotient (* (_nbits xc) 28) 65))
		       (q         (expt 5 e))
		       (xc        (quotient q xz))
		       (remainder (modulo   q xc))))
		
                ((not (= remainder 0)) it
		 None)
		
		(let () (clean xc e 5 -))
                
                ;; Guard against large values of ye, using the same logic as in
                ;; the 'xc is a power of 2' branch.  10/3 is an upper bound for
                ;; log(10)/log(2).
                (let ((emax (quotient (* p 10) 3))))

		((>= ye (len (str emax)))
		 None)

		(let ()
		  (set! e  (_decimal_lshift_exact (* e  yc) ye))
		  (set! xe (_decimal_lshift_exact (* xe yc) ye)))

                ((or (eq? e None= (eq? xe None))) it
		 None)

                ((> e emax)
		 None)

		(begin
		  (set! xc (expt 2 e))
		  #f)))

	      (else
	       None)) it it)

	    ((>= xc (expt 10 p)) it it)

            (begin
	      (set! xe (+ (- e) (- xe)))
	      (_dec_from_triple 0 (str xc) xe)))))

        ;; now y is positive; find m and n such that y = m/n
	(let ((m #f) (n #f) (xc_bits (_nbits xc))))
	((if (>= ye 0) it
	     (begin
	       (set! m (* yc (expt 10 ye)))
	       (set! n 1)
	       #f)
	     (twix
	      ((and (not (= xe 0)) (<= (len (str (abs (* yc xe)))) (- ye))) it
	       None)
	   
	      ((and (not (= xc 1))
		    (<= (len (str (* (abs yc) xc_bits))) (- ye))) it
		None)

	      (begin
		(set! m yc)
		(set! n (expt 10 (- ye)))

		(let lp()
		  (if (and (= (modulo m 2) 0) (= (modulo n 2) 0))
		      (begin
			(set! m (quotient m 2))
			(set! n (quotient n 2)))))
		(let lp()
		  (if (and (= (modulo m 5) 0) (= (modulo n 5) 0))
		      (begin
			(set! m (quotient m 5))
			(set! n (quotient n 5)))))
		#f))) it it)
	
        ;; compute nth root of xc*10**xe
        ((if (> n 1)
	     (begin
	       (twix
		;; if 1 < xc < 2**n then xc isn't an nth power
		((and (not (= xc 1)) (<= xc_bits n)) it
		 None)

		((not (= (modulo xe n) 0)) it
		 None)

		(begin
		  (let ((a (ash 1 (- (quotient (- xc_bits) n)))))
		    (set! xe (quotient xe n))
		
		    ;; compute nth root of xc using Newton's method	       
		    (let lp ()
		      (let* ((x (expt a (- n 1)))
			     (q (quotient xc x))
			     (r (modulo   xc x)))
			(if (<= a q)
			    (if (not (and (= a q) (= r 0)))
				None
				(begin
				  (set! xc a)
				  #f))
			    (begin
			      (set! a (quotient (+ (* a (- n 1)) q) n))
			      (lp)))))))))
	     #f) it it)

        ;; now xc*10**xe is the nth root of the original xc*10**xe
        ;; compute mth power of xc*10**xe

        ;; if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
        ;; 10**p and the result is not representable.
        ((and (> xc 1) (> m (quotient (* p 100) (_log10_lb xc)))) it
	 None)

	(let ()
	  (set! xc (expt xc m))
	  (set! xe (xe * m)))
	
        ((> xc  (expt 10 p)) it
	 None)

	(begin
	  ;; by this point the result *is* exactly representable
	  ;; adjust the exponent to get as close as possible to the ideal
	  ;; exponent, if necessary
	  (let* ((str_xc (str xc))
		 (zeros (if (and ((ref other '_isinteger))
				 (= (ref other '_sign) 0))
			    (let ((ideal_exponent
				   (* (ref self '_exp) (int other))))
			      (min (- xe ideal_exponent)
				   (- p  (len str_xc))))
			    0)))
	    (_dec_from_triple 0  (+ str_xc (* '0' zeros)) (- xe zeros)))))))

    (define __pow__
      (lam (self other (= modulo None) (= context None))
        "Return self ** other [ % modulo].

        With two arguments, compute self**other.

        With three arguments, compute (self**other) % modulo.  For the
        three argument form, the following restrictions on the
        arguments hold:

         - all three arguments must be integral
         - other must be nonnegative
         - either self or other (or both) must be nonzero
         - modulo must be nonzero and must have at most p digits,
           where p is the context precision.

        If any of these restrictions is violated the InvalidOperation
        flag is raised.

        The result of pow(self, other, modulo) is identical to the
        result that would be obtained by computing (self**other) %
        modulo with unbounded precision, but is computed more
        efficiently.  It is always exact.
        "

	(twix
	 ((not (eq= modulo None)) it
	  ((ref self '_power_modulo) other modulo context))

	 ((norm-op self other ) it it)
	 (let (get-context context))

	 ;; either argument is a NaN => result is NaN
	 (bin-special self other context)

	 ;; 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
	 ((not (bool other))
	  (if (not (bool self))
	      ((cx-error context) InvalidOperation "0 ** 0")
	      _One))
	 
	 ;; result has sign 1 iff self._sign is 1 and other is an odd integer
	 (let ((result_sign  0)))

	 ((if (= (ref self '_sign) 1)
	      (twix
		((if ((ref other '_isinteger))
		     (if (not ((ref other '_iseven)))
			 (begin
			   (set! result_sign 1)
			   #f)
			 #f)
		     ;; -ve**noninteger = NaN
		     ;; (-0)**noninteger = 0**noninteger
		     (if (bool self)
			 ((cx-error context) InvalidOperation 
			  "x ** y with x negative and y not an integer")
			 #f)) it it)
		(begin
		  ;; negate self, without doing any unwanted rounding
		  (set! self ((ref self 'copy_negate)))
		  #f))	      
	      #f) it it)

        ;; 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
        ((not (bool self)) it
	 (if (= (ref other '_sign) 0)
	     (_dec_from_triple result_sign "0" 0)
	     (pylist-ref _SignedInfinity result_sign)))

        ;; Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
        (((self '_isinfinity)) it
	 (if (= (ref other '_sign) 0)
	     (pylist-ref _SignedInfinity result_sign)
	     (_dec_from_triple result_sign "0" 0)))

        ;; 1**other = 1, but the choice of exponent and the flags
        ;; depend on the exponent of self, and on whether other is a
        ;; positive integer, a negative integer, or neither
	(let ((prec (cx-prec context))))
	
        ((equal? self _One) it
	 (let ((exp  #f))	      
	   (if ((ref other '_isinteger))
	       ;; exp = max(self._exp*max(int(other), 0),
	       ;; 1-context.prec) but evaluating int(other) directly
	       ;; is dangerous until we know other is small (other
	       ;; could be 1e999999999)
	       (let ((multiplier
		      (cond
		       ((= (ref other '_sign) 1)
			0)
		       ((> other prec)
			prec)
		       (else
			(int other)))))

		 (set! exp (* (ref self '_exp) multiplier))
		 (if (< exp (- 1 prec))
		     (begin
		       (set! exp (- 1 prec))
		       ((cx-error context) Rounded))))
	       (begin
		 ((cx-error context) Inexact)
		 ((cx-error context) Rounded)
		 (set! exp (- 1 prec))))

	   (_dec_from_triple result_sign  (+ "1" (* "0" (- exp)) exp))))

        ;; compute adjusted exponent of self
        (let ((self_adj ((ref self 'adjusted)))))

        ;; self ** infinity is infinity if self > 1, 0 if self < 1
        ;; self ** -infinity is infinity if self < 1, 0 if self > 1
        (((ref other '_isinfinity))
	 (if (eq? (= (ref other '_sign) 0)
		  (< self_adj           0))
	     (_dec_from_triple result_sign "0" 0)
	     (pylist-ref _SignedInfinity result_sign)))

        ;; from here on, the result always goes through the call
        ;; to _fix at the end of this function.
        (let ((ans   None)
	      (exact False)
	      (bound (+ ((ref self '_log10_exp_bound))
			((ref other 'adjusted)))))

	  ;; crude test to catch cases of extreme overflow/underflow.  If
	  ;; log10(self)*other >= 10**bound and bound >= len(str(Emax))
	  ;; then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
	  ;; self**other >= 10**(Emax+1), so overflow occurs.  The test
	  ;; for underflow is similar.
        
        (if (eq? (>= self_adj 0) (= (ref other '_sign) 0))
            ;; self > 1 and other +ve, or self < 1 and other -ve
            ;; possibility of overflow
            (if (>= bound (len (str (cx-emax context))))
                (set! ans
		      (_dec_from_triple result_sign "1"
					(+ (cx-emax context) 1))))
	    
            ;; self > 1 and other -ve, or self < 1 and other +ve
            ;; possibility of underflow to 0
            (let ((Etiny (cx-etiny context)))
	      (if (>= bound (len (str (- Etiny))))
		  (set! ans (_dec_from_triple result_sign "1" (- Etiny 1))))))

        ;; try for an exact result with precision +1
        (when (eq? ans None)
	  (set! ans ((ref self '_power_exact) other (+ prec 1)))
	  (when (not (eq? ans None))	      
	    (if (= result_sign 1)
		(set! ans (_dec_from_triple 1  (ref ans '_int)
					    (ref ans '_exp))))
	    (set! exact #t)))

        ;; usual case: inexact result, x**y computed directly as exp(y*log(x))
        (when (eq? ans None)
	  (let* ((p  prec)
		     
		 (x  (_WorkRep self))
		 (xc (ref x 'int))
		 (xe (ref x 'exp))

		 (y  (_WorkRep other))
		 (yc (ref y 'int))
		 (ye (ref y 'exp)))

            (if (= (ref y 'sign) 1)
                (set! yc (- yc)))

            ;; compute correctly rounded result:  start with precision +3,
            ;; then increase precision until result is unambiguously roundable
	    (call-with-values
		(lambda ()
		  (let lp ((extra 3))
		    (call-with-values
			(lambda () (_dpower xc xe yc ye (+ p extra)))
		      (lambda (coeff exp)		  
			(if (modulo coeff
				    (* 5 (expt 10 (- (len (str coeff)) p 1))))
			    (values coeff exp)
			    (lp (+ extra 3)))))))
	      (lambda (coeff exp)	    
		(set! ans (_dec_from_triple result_sign (strcoeff) exp))))))

        ;; unlike exp, ln and log10, the power function respects the
        ;; rounding mode; no need to switch to ROUND_HALF_EVEN here

        ;; There's a difficulty here when 'other' is not an integer and
        ;; the result is exact.  In this case, the specification
	;; requires that the Inexact flag be raised (in spite of
	;; exactness), but since the result is exact _fix won't do this
        ;; for us.  (Correspondingly, the Underflow signal should also
        ;; be raised for subnormal results.)  We can't directly raise
        ;; these signals either before or after calling _fix, since
	;; that would violate the precedence for signals.  So we wrap
        ;; the ._fix call in a temporary context, and reraise
        ;; afterwards.
        (if (and exact (not ((ref other '_isinteger))))
	    (begin
	      ;; pad with zeros up to length context.prec+1 if necessary; this
	      ;; ensures that the Rounded signal will be raised.
	      (if (<= (len (ref ans '_int)) prec)
		  (let ((expdiff (+ prec 1 (- (len (ref ans '_int))))))
		    (set! ans (_dec_from_triple (ref ans '_sign)
						(+ (ref ans '_int)
						   (* "0" expdiff))
						(- (ref ans '_exp) expdiff)))))

	      ;; create a copy of the current context, with cleared flags/traps
	      (let ((newcontext (cx-copy context)))
		(cx-clear_flags newcontext))

	      (for ((exception : _signals)) ()
		   (pylist-set! (cx-traps newcontext) exception 0)
		   (values))

	      ;; round in the new context
	      (set! ans ((ref ans '_fix) newcontext))

	      ;; raise Inexact, and if necessary, Underflow
	      ((cx-error newcontext) Inexact)
	      (if (bool (pylist-ref (cx-flags newcontext) Subnormal))
		  ((cx-error newcontext) Underflow))

	      ;; propagate signals to the original context; _fix could
	      ;; have raised any of Overflow, Underflow, Subnormal,
	      ;; Inexact, Rounded, Clamped.  Overflow needs the correct
	      ;; arguments.  Note that the order of the exceptions is
	      ;; important here.
	      (if (bool (pylist-ref (cx-flags newcontext) Overflow))
		  ((cx-error newcontext)
		   Overflow "above Emax" (ref ans '_sign)))
	      
	      (for ((exception : (list Underflow Subnormal
				       Inexact   Rounded Clamped))) ()
		(if (bool (pylist-ref (cx-flags newcontext) exception))
                    ((cx-error newcontext) exception)
		    (values))))
	    
	    (set! ans ((ref ans '_fix) context)))

        ans))))

    (define __rpow__
      (lam (self other (= context None))
	   "Swaps self/other and returns __pow__."
	   (twix
	    ((norm-op self other) it it)
	    ((ref 'other '__pow__) self  #:context context))))

    (define normalize
      (lam (self (= context None))
        "Normalize- strip trailing 0s, change anything equal to 0 to 0e0"
	
	(twix
	 (let (get-context context))
	 (un-special self context)
	 (let ((dup ((ref self _fix) context))))
	 (((dup '_isinfinity)) it dup)
	 ((not (bool dup))
	  (_dec_from_triple (reg dup '_sign) "0" 0))

	 (let* ((_int    (ref dup '_int))
		(exp_max (let ((i (cx-clamp context)))
			   (if (= i 0)
			       (cx-emax context)
			       (cx-etop context))))
	       (let lp ((end (len _int)) (exp (ref dup '_exp)))
		 (if (and (equal? (pylist-ref _int (- end-1))
				  "0")
			  (< exp exp_max))
		     (lp (- end 1) (+ exp 1))
		     (_dec_from_triple
		      (ref dup '_sign)
		      (pylist-slice _int None end None)
		      exp))))))))

    (define quantize
      (lam (self exp (= rounding None) (= context None))
        "Quantize self so its exponent is the same as that of exp.

        Similar to self._rescale(exp._exp) but with error checking.
        "
	(twix
	 (let* ((exp      (_convert_other exp #:raiseit #t))
		(context  (if (eq? context  None) (getcontext) context))
		(rounding (if (eq? rounding None)
			      (cx-rounding context)
			      rounding))))
	  
        ((if (or ((self '_is_special)) ((exp '_is_special)))
	     (let ((ans ((ref self '_check_nans) exp context)))
	       (cond
		((bool ans)
		   ans)
		((or ((ref exp '_isinfinity)) ((ref self '_isinfinity)))
		 (if (and ((ref exp '_isinfinity))
			  ((ref self '_isinfinity)))
		     (Decimal self))  ; if both are inf, it is OK
		 ((cx-error context) InvalidOperation "quantize with one INF"))
		(else
		 #f)))
	     #f) it it)
	
        ;; exp._exp should be between Etiny and Emax
	(let ((_eexp (ref exp '_exp))
	      (Emax  (cx-emax context))))
	
        ((not (and (<= (cx-etiny context) eexp) (<= eexp Emax))) it
	 ((cx-error context) InvalidOperation,
	  "target exponent out of bounds in quantize"))

        ((not (bool self)) it
	 (let ((ans (_dec_from_triple (ref self '_sign) "0" _eexp)))
	   ((ref ans '_fix) context)))

        (let ((self_adjusted ((ref self 'adjusted)))
	      (prec          (cx-prec context))))

	((> self_adjusted (cx-emax context)) it
	 ((cx-error context) InvalidOperation,
	  "exponent of quantize result too large for current context"))
	
        ((> (+ self_adjusted (- _eexp)  1) prec) it
	 ((cx-error context) InvalidOperation,
	  "quantize result has too many digits for current context"))

	(let ((ans ((ref self '_rescale) _eexp rounding))))
	 
	(if (> ((ref ans 'adjusted)) Emax) it
	    ((cx-error context) InvalidOperation,
	     "exponent of quantize result too large for current context"))
	
        ((> (len (ref ans '_int)) prec)
	 ((cx-error context) InvalidOperation,
	  "quantize result has too many digits for current context"))


	(begin
	  ;; raise appropriate flags
	  (if (and (bool ans) (< ((ref ans 'adjusted)) (cx-emin context)))
	      ((cx-error context) Subnormal))

	  (when (> (reg ans '_exp) (ref self '_exp))
	    (if (not (equal? ans self))
		((cx-error context) Inexact))
	    ((cx-error context) Rounded))
	            
	  ;; call to fix takes care of any necessary folddown, and
	  ;; signals Clamped if necessary
	  ((ref ans '_fix) context)))))
    
    (define same_quantum
      (lam (self other (= context None))
        "Return True if self and other have the same exponent; otherwise
        return False.

        If either operand is a special value, the following rules are used:
           * return True if both operands are infinities
           * return True if both operands are NaNs
           * otherwise, return False.
        "
        (let ((other (_convert_other other #:raiseit #t)))
	  (if (or (ref self '_is_special) (ref other '_is_special))
	      (or (and ((ref self 'is_nan))      ((ref other 'is_nan)))
		  (and ((ref self 'is_infinite)) ((ref other 'is_infinite))))))
	
        (= (ref self '_exp) (ref other '_exp))))

    (define _rescale
      (lam (self exp rounding)
        "Rescale self so that the exponent is exp, either by padding with zeros
        or by truncating digits, using the given rounding mode.

        Specials are returned without change.  This operation is
        quiet: it raises no flags, and uses no information from the
        context.

        exp = exp to scale to (an integer)
        rounding = rounding mode
        "

	(cond
	 ((ref self '_is_special) it
	  (Decimal self))
	 
	 ((not (bool self)) it
	  (_dec_from_triple (ref self '_sign) "0" exp))

	 (let ((_exp  (ref self '_exp))
	       (_sign (ref self '_sign))
	       (_int  (ref self '_int))))

	 ((>= _exp exp)
            ;; pad answer with zeros if necessary
            (_dec_from_triple _sign (+ _int (* "0" (- _exp exp))) exp))

	 
        ;; too many digits; round and lose data.  If self.adjusted() <
        ;; exp-1, replace self by 10**(exp-1) before rounding
        (let ((digits (+ (len _int) _exp (- exp))))
	  (if (< digits 0)
	      (set! self (_dec_from_triple _sign "1" (- exp 1)))
	      (set! digits 0))

	  (let* ((this_function (pylist-ref (ref self '_pick_rounding_function)
					    rounding))
		 (changed       (this_function self digits))
		 (coeff         (or (bool
				     (pylist-slice _int None digits None))
				    "0")))
	    (if (= changed 1)
		(set! coeff (str (+ (int coeff) 1))))

	    (_dec_from_triple _sign coeff exp))))))

    (define _round
      (lam (self places rounding)
        "Round a nonzero, nonspecial Decimal to a fixed number of
        significant figures, using the given rounding mode.

        Infinities, NaNs and zeros are returned unaltered.

        This operation is quiet: it raises no flags, and uses no
        information from the context.

        "
        (cond
	 ((<= places 0)
	  (raise (ValueError "argument should be at least 1 in _round")))
	 ((or (ref self '_is_special) (not (bool self)))
	  (Decimal self))
	 (else
	  (let ((ans ((ref self '_rescale) (+ ((self 'adjusted)) 1 (- places))
		      rounding)))
	    ;; it can happen that the rescale alters the adjusted exponent;
	    ;; for example when rounding 99.97 to 3 significant figures.
	    ;; When this happens we end up with an extra 0 at the end of
	    ;; the number; a second rescale fixes this.
	    (if (not (= ((ref ans 'adjusted)) ((ref self 'adjusted))))
		(set! ans ((ref ans '_rescale) (+ ((ans 'adjusted)) 1
						  (- places))
			   rounding)))
	    ans)))))

    (define to_integral_exact
      (lam (self (= rounding None) (= context None))
        "Rounds to a nearby integer.

        If no rounding mode is specified, take the rounding mode from
        the context.  This method raises the Rounded and Inexact flags
        when appropriate.

        See also: to_integral_value, which does exactly the same as
        this method except that it doesn't raise Inexact or Rounded.
        "
	(cond
        ((ref self '_is_special)
	 (let ((ans ((ref self '_check_nans) #:context context)))
	   (if (bool ans)
               ans
	       (Decimal self))))
	        
        ((>= (ref self '_exp) 0)
	 (Decimal self))
        ((not (boool self))	 
	 (_dec_from_triple (ref self '_sign) "0" 0))
	(else
	 (let* ((context  (if (eq? context  None) (getcontext) context))
		(rounding (if (eq? rounding None)
			      (cx-rounding context)
			      rounding))
		(ans      ((ref self '_rescale) 0 rounding)))
	   
	   (if (not (equal? ans self))
	       ((cx-error context) Inexact))
	   
	   ((cx-error context) Rounded)

	   ans)))))

    (define to_integral_value
      (lam (self (= rounding None) (= context None))
	"Rounds to the nearest integer, without raising inexact, rounded."
	(let* ((context  (if (eq? context  None) (getcontext) context))
	       (rounding (if (eq? rounding None)
			     (cx-rounding context)
			     rounding)))
	  
	  (cond
	   ((ref self '_is_special)
	    (let ((ans ((ref self '_check_nans) #:context context)))
	      (if (bool ans)
		  ans
		  (Decimal self))))
	    
	   ((>= (ref self '_exp) 0)
	    (Decimal self))
	    
	   (else
            ((ref self '_rescale) 0 rounding))))))

    ;; the method name changed, but we provide also the old one,
    ;; for compatibility
    (define to_integral to_integral_value)

    (define sqrt
      (lam (self (= context None))
	"Return the square root of self."
	(twix
	 (let (get-context context))	 

	 ((if (ref self '_is_special)
	      (let ((ans ((ref self '_check_nans) #:context context)))
		(if (bool ans)
		    ans
		    (if (and ((self '_isinfinity)) (= (ref self '_sign) 0))
			(Decimal self)
			#f)))

	      #f) it it)

	 ((not (bool self)) it
	  ;; exponent = self._exp // 2.  sqrt(-0) = -0
	  (let ((ans (_dec_from_triple (ref self '_sign) "0"
				       (quotient (ref self '_exp) 2))))
	    ((ref ans '_fix) context)))

	 ((= (ref self '_sign) 1)
	  ((cx-error context) InvalidOperation "sqrt(-x), x > 0"))

        ;; At this point self represents a positive number.  Let p be
        ;; the desired precision and express self in the form c*100**e
        ;; with c a positive real number and e an integer, c and e
        ;; being chosen so that 100**(p-1) <= c < 100**p.  Then the
        ;; (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
        ;; <= sqrt(c) < 10**p, so the closest representable Decimal at
        ;; precision p is n*10**e where n = round_half_even(sqrt(c)),
        ;; the closest integer to sqrt(c) with the even integer chosen
        ;; in the case of a tie.
        ;;
        ;; To ensure correct rounding in all cases, we use the
        ;; following trick: we compute the square root to an extra
        ;; place (precision p+1 instead of precision p), rounding down.
        ;; Then, if the result is inexact and its last digit is 0 or 5,
        ;; we increase the last digit to 1 or 6 respectively; if it's
        ;; exact we leave the last digit alone.  Now the final round to
        ;; p places (or fewer in the case of underflow) will round
        ;; correctly and raise the appropriate flags.

        ;; use an extra digit of precision
        (let* ((prec  (+ (cx-prec context) 1))
	       (op    (_WorkRep self))
	       (e     (ash (ref op 'exp) -1))
	       (c     #f)
	       (l     #f)
	       (shift #f)
	       (exact #f))

	  ;; write argument in the form c*100**e where e = self._exp//2
	  ;; is the 'ideal' exponent, to be used if the square root is
	  ;; exactly representable.  l is the number of 'digits' of c in
	  ;; base 100, so that 100**(l-1) <= c < 100**l.
	  (if (= (logand (ref op 'exp)  1) 1)
	      (begin
		(set! c (* (ref op 'int) 10))
		(set! l (+ (ash (len (ref self '_int)) -1)  1)))
	      (begin
		(set! c (ref op 'int))
		(set! l (ash (+ (len (ref self '_int)) 1) -1))))

	  ;; rescale so that c has exactly prec base 100 'digits'
	  (set! shift (- prec l))
	  (if (>= shift 0)
	      (begin
		(set! c (* c (expt 100 shift)))
		(set! exact #t))
	      (let ((x (expt 100 (- shift))))
		(set! c (quotient c x))
		(let ((remainder (modulo c x)))
		  (set! exact (= remainder 0)))))

	  (set! e (- e shift))

	  ;; find n = floor(sqrt(c)) using Newton's method
	  (let ((n (let lp ((n  (expt 10 prec)))
		     (let ((q (quotient c n)))
		       (if (<= n q)
			   n
			   (lp (ash (+ n q) -1)))))))

	    (set! exact (and exact (= (* n n) c)))

	    (if exact
		;; result is exact; rescale to use ideal exponent e
		(begin
		  (if (>= shift 0)
		      ;; assert n % 10**shift == 0
		      (set! n (quotient n (expt 10 shift)))         
		      (set! n (*        n (expt 10 (- shift)))))
		  (set! e (+ e shift)))
		;; result is not exact; fix last digit as described above
		(if (= (modulo n 5) 0)
		    (set! n (+ n 1))))

	    (let ((ans (_dec_from_triple 0 (str n) e))
		  ;; round, and fit to current context
		  (context  ((ref context '_shallow_copy)))
		  (rounding ((ref context '_set_rounding) ROUND_HALF_EVEN))
		  (ans      ((ref ans '_fix) context)))
	      (set context 'rounding rounding)
	      ans))))))
    
    (define max
      (lam (self other (= context None))
        "Returns the larger value.

        Like max(self, other) except if one is not a number, returns
        NaN (and signals if one is sNaN).  Also rounds.
        "
	(twix
	 (let ((other (_convert_other other #:raiseit #t))))
	 (let (get-context context))
	 ((if (or (ref self '_is_special) (ref other '_is_special))
	      (begin
		;; If one operand is a quiet NaN and the other is number, then
		;; the number is always returned
		(let ((sn ((ref self  '_isnan)))
		      (on ((ref other '_isnan))))
		  (if (or (bool sn) (bool on))
		      (if (and (= on 1) (= sn 0))
			  ((ref self '_fix) context)
			  (if (and (= sn 1) (= on 0))
			      ((ref other '_fix) context)
			      ((ref self '_check_nans) other context)))
		      #f)))
	      #f) it it)

	 (let ((c ((ref self '_cmp) other)))
	   (if (= c 0)
	       ;; If both operands are finite and equal in numerical value
	       ;; then an ordering is applied:
	       ;;
	       ;; If the signs differ then max returns the operand with the
	       ;; positive sign and min returns the operand with the negative
	       ;; sign
	       ;;
	       ;; If the signs are the same then the exponent is used to select
	       ;; the result.  This is exactly the ordering used in
	       ;; compare_total.
	       (set! c ((ref self 'compare_total) other)))

	   (let ((ans (if (= c -1)
			  other
			  self)))

	     ((ref ans '_fix) context))))))

    (define min
      (lam (self other (= context None))
        "Returns the larger value.

        Like max(self, other) except if one is not a number, returns
        NaN (and signals if one is sNaN).  Also rounds.
        "
	(twix
	 (let ((other (_convert_other other #:raiseit #t))))
	 (let (get-context context))
	 ((if (or (ref self '_is_special) (ref other '_is_special))
	      (begin
		;; If one operand is a quiet NaN and the other is number, then
		;; the number is always returned
		(let ((sn ((ref self  '_isnan)))
		      (on ((ref other '_isnan))))
		  (if (or (bool sn) (bool on))
		      (if (and (= on 1) (= sn 0))
			  ((ref self '_fix) context)
			  (if (and (= sn 1) (= on 0))
			      ((ref other '_fix) context)
			      ((ref self '_check_nans) other context)))
		      #f)))
	      #f) it it)

	 (let ((c ((ref self '_cmp) other)))
	   (if (= c 0)
	       ;; If both operands are finite and equal in numerical value
	       ;; then an ordering is applied:
	       ;;
	       ;; If the signs differ then max returns the operand with the
	       ;; positive sign and min returns the operand with the negative
	       ;; sign
	       ;;
	       ;; If the signs are the same then the exponent is used to select
	       ;; the result.  This is exactly the ordering used in
	       ;; compare_total.
	       (set! c ((ref self 'compare_total) other)))

	   (let ((ans (if (= c -1)
			  self
			  other)))

	     ((ref ans '_fix) context))))))

    (define _isinteger
      (lambda (self)
        "Returns whether self is an integer"
        (cond
	 ((bool (ref self '_is_special))
          #f)
	 ((>= (ref self '_exp) 0)
	  #t)
	 (else
	  (let ((rest (pylist-ref (ref self '_int) (ref self '_exp))))
	    (equal? rest "0"*(len rest)))))))

    (define _iseven
      (lambda (self)
        "Returns True if self is even.  Assumes self is an integer."
        (if (or (not (bool self)) (> (ref self '_exp) 0))
            #t
	    (in (pylist-ref (ref self '_int) (+ -1 (ref self '_exp)))
		"02468"))))

    (define adjusted
      (lambda (self)
        "Return the adjusted exponent of self"
        (try
          (lambda () (+ (ref self '_exp) + (len (ref self '_int)) -1))
	  ;; If NaN or Infinity, self._exp is string
	  (#:except TypeError (lambda z 0)))))

    (define canonical
      (lambda (self)
        "Returns the same Decimal object.

        As we do not have different encodings for the same number, the
        received object already is in its canonical form.
        "
	self))

    (define compare_signal
      (lam (self other (= context None))
        "Compares self to the other operand numerically.

        It's pretty much like compare(), but all NaNs signal, with signaling
        NaNs taking precedence over quiet NaNs.
        "
        (let* ((other (_convert_other other #:raiseit #t))
	       (ans   ((ref self '_compare_check_nans) other context)))
	  (if (bool ans)
	      and
	      ((ref self 'compare) other #:context context)))))

    (define compare_total
      (lam (self other (= context None))
        "Compares self to other using the abstract representations.

        This is not like the standard compare, which use their numerical
        value. Note that a total ordering is defined for all possible abstract
        representations.
        "

	(twix
	 (let ((other (_convert_other other #:raiseit #t))))

	 ;; if one is negative and the other is positive, it's easy
        ((and (bool (ref self '_sign)) (not (bool other '_sign))) it
	 _NegativeOne)

	((and (not (bool (ref self '_sign))) (bool other '_sign)) it
	 One)
	
        (let ((sign      (ref self '_sign))
	      ;; let's handle both NaN types
	      (self_nan  ((ref self  '_isnan)))
	      (other_nan ((ref other '_isnan)))))
	
        ((if (or (bool self_nan) (bool other_nan))
	     (if (= self_nan other_nan)
                ;; compare payloads as though they're integers
		 (let ((self_key  (list (len (ref self '_int))
					(ref self '_int)))
		       (other_key (list (len (ref other '_int))
					(ref other '_int))))
		   (cond
		    ((< self_key other_key)
		     (if (bool sign)
			 _One
			 _NegativeOne)
		     ((> self_key other_key)
		      (if sign
			  _NegativeOne
			  _One))
		     (else
		      _Zero))))

		 (if (bool sign)
		     (cond
		      ((= self_nan 1)
			 _NegativeOne)
		      ((= other_nan 1)
		       _One)
		      ((= self_nan 2)
		       _NegativeOne)
		      ((= other_nan 2)
		       _One)
		      (else
		       #f))		     
		     (cond
		      ((= self_nan 1)
		       _One)
		      ((= other_nan 1)
		       _NegativeOne)
		      ((= self_nan 2)
		       _One)
		      ((= other_nan 2)
		       _NegativeOne)
		      (else #f))))
	     #f) it it)

        ((< self other) it
	 _NegativeOne)

	((> self > other) it
	 _One)

        ((< (ref self '_exp) (ref other '_exp)) it
	 (if (bool sign)
	     _One
	     _NegativeOne))
	
        ((> (ref self '_exp) (ref other '_exp)) it
	 (if (bool sign)
	     _NegativeOne
	     _One))
	
	_Zero)))


    (define compare_total_mag
      (lam (self other (= context None))
        "Compares self to other using abstract repr., ignoring sign.

        Like compare_total, but with operand's sign ignored and assumed to be 0.
        "
        (let* ((other (_convert_other other #:raiseit #t))
	       (s     ((ref self  'copy_abs)))
	       (o     ((ref other 'copy_abs))))
	  ((ref s 'compare_total) o))))

    (define copy_abs
      (lambda (self)
        "Returns a copy with the sign set to 0. "
	(_dec_from_triple 0 (ref self '_int)
			  (ref self '_exp) (ref self '_is_special))))

    (define copy_negate
      (lambda (self)
        "Returns a copy with the sign inverted."
        (if (bool (ref self '_sign))
	    (_dec_from_triple 0 (ref self '_int)
			  (ref self '_exp) (ref self '_is_special))
	    (_dec_from_triple 1 (ref self '_int)
			      (ref self '_exp) (ref self '_is_special)))))
    
    (define copy_sign
      (lam (self other (= context None))
        "Returns self with the sign of other."
        (let ((other (_convert_other other #:raiseit #t)))
	  (_dec_from_triple (ref other 'sign) (ref self '_int)
			    (ref self '_exp) (ref self '_is_special)))))

    (define exp
      (lam (self (= context None))
        "Returns e ** self."

	(twix
	 (let (get-context context code))

	 ;; exp(NaN) = NaN
	 (let ((ans ((ref self '_check_nans) #:context context))))
	     
	 (ans it it)

	 ;; exp(-Infinity) = 0
	 ((= ((ref self '_isinfinity)) -1)
	  _Zero)

	 ;; exp(0) = 1
	 ((not (bool self))
	  _One)

	 ;; exp(Infinity) = Infinity
	 ((= ((ref self '_isinfinity)) 1)
	  (Decimal self))

	 ;; the result is now guaranteed to be inexact (the true
	 ;; mathematical result is transcendental). There's no need to
	 ;; raise Rounded and Inexact here---they'll always be raised as
	 ;; a result of the call to _fix.
	 (let ((p   (ctx-prec context))
	       (adj ((ref self 'adjusted)))))

	 ;; we only need to do any computation for quite a small range
	 ;; of adjusted exponents---for example, -29 <= adj <= 10 for
	 ;; the default context.  For smaller exponent the result is
	 ;; indistinguishable from 1 at the given precision, while for
	 ;; larger exponent the result either overflows or underflows.
	 (let* ((sign  (ref self '_sign))
		(emax  (ctx-emax context))
		(etiny (ctx-etiny context))
		(ans
		 (cond
		  ((and (= sign 0)
			(> adj (len (str (* (+ emax 1) 3)))))
		   ;; overflow
		   (_dec_from_triple 0  "1" (+ emax 1)))
		  
		  ((and (= sign 1)
			(> adj (len (str (* (- 1 etiny) 3)))))
		   ;; underflow to 0
		   (_dec_from_triple 0 "1" (- etiny 1)))
		  ((and (= sign  0) (< adj (- p)))
		   ;; p+1 digits; final round will raise correct flags
		   (_dec_from_triple 0 (+ "1" (* "0" (- p 1)) "1") (- p)))
		  ((and (= sign 1) (< adj (- (+ p 1))))
		   ;; p+1 digits; final round will raise correct flags
		   (_dec_from_triple 0  (* "9" (+ p 1)) (- (+ p 1))))
		  (else
		   ;; general case
		   (let* ((op (_WorkRep self))
			  (c  (ref op 'int))
			  (e  (ref op 'exp)))
		     (if (= (ref op 'sign) 1)
			 (set! c (- c)))
		    
		     ;; compute correctly rounded result: increase precision by
		     ;; 3 digits at a time until we get an unambiguously
		     ;; roundable result
		    
		     (let lp ((extra 3))
		       (call-with-values (lambda () (_dexp c e (+ p extra)))
			 (lambda (coeff exp)
			   (if (not (= (modulo
					coeff
					(* 5 (expt 10
						   (- (len (str coeff)) p 1))))
				       0))
			      
			       (_dec_from_triple 0 (str coeff) exp)
			       (lp (+ ex 3))))))))))))

	 ;; at this stage, ans should round correctly with *any*
	 ;; rounding mode, not just with ROUND_HALF_EVEN
	
	 (let* ((context  ((ref context '_shallow_copy)))
		(rounding ((ref context '_set_rounding) ROUND_HALF_EVEN))
		(ans      ((ref ans '_fix) context)))
	  
	   (set context 'rounding rounding)
	   ans))))
    
    (define is_canonical
      (lambda (self)
        "Return True if self is canonical; otherwise return False.

        Currently, the encoding of a Decimal instance is always
        canonical, so this method returns True for any Decimal.
        "
        #t))

    (define is_finite
      (lambda (self)
        "Return True if self is finite; otherwise return False.

        A Decimal instance is considered finite if it is neither
        infinite nor a NaN.
        "
	(not (ref self '_is_special))))

    (define is_infinite
      (lambda (self)
        "Return True if self is infinite; otherwise return False."
        (equal? (ref self '_exp) "F")))

    (define is_nan
      (lambda (self)
        "Return True if self is a qNaN or sNaN; otherwise return False."
	(let ((e (ref self '_exp)))
	  (or (equal? e "n") (equal? e "N")))))

    (define is_normal
      (lam (self (= context None))
        "Return True if self is a normal number; otherwise return False."
        (if (or (bool (ref self '_is_special)) (not (bool self)))
            #f
	    (let ((context (if (eq? context None)
			       (getcontext)
			       context)))
	      (<= (cttx-emin context) ((ref self 'adjusted)))))))

    (define is_qnan
      (lambda (self)
        "Return True if self is a quiet NaN; otherwise return False."
       (equal? (ref self '_exp) "n")))

    (define is_signed
      (lambda (self)
        "Return True if self is negative; otherwise return False."
       (= (ref self '_sign) 1 )))

    (define is_snan
      (lambda (self)
        "Return True if self is a signaling NaN; otherwise return False."
	(equal? (ref self '_exp) "N")))

    (define is_subnormal
      (lam (self (= context None))
	   "Return True if self is subnormal; otherwise return False."
	   (if (or (bool (ref self '_is_special)) (not (bool self)))
	       #f
	       (let ((context (if (eq? context None)
				  (getcontext)
				  context)))
		 (> (cttx-emin context) ((ref self 'adjusted)))))))

    (define is_zero
      (lambda (self)
        "Return True if self is a zero; otherwise return False."
        (and (not (bool (ref self '_is_special)))
	     (equal? (ref self '_int) "0"))))

    (define _ln_exp_bound
      (lambda (self)
        "Compute a lower bound for the adjusted exponent of self.ln().
        In other words, compute r such that self.ln() >= 10**r.  Assumes
        that self is finite and positive and that self != 1.
        "

        ;; for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
        (let ((adj (+ (ref self '_exp) (len (ref self '_int)) (- 1))))
	  (cond
	   ((>= adj 1)
            ;; argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
            (- (len (str (floordiv (* adj 23) 10))) 1))
	   ((<= adj -2)
            ;; argument <= 0.1
            (- (len (str (floordiv (* (- (+ 1 adj)) 23) 10))) 1))
	   (else
	    (let* ((op (_WorkRep self))
		   (c  (ref op 'int))
		   (e  (ref op 'exp)))
	      (if (= adj 0)
		  ;; 1 < self < 10
		  (let ((num (str (- c (expt 10 (- e)))))
			(den (str c)))
		    (- (len num) (len den) - (< num den)))
		  ;; adj == -1, 0.1 <= self < 1
		  (+ e (len (str (- (expt 10 (- e)) c))) (- 1)))))))))


    (define ln
      (lam (self (= context None))
        "Returns the natural (base e) logarithm of self."

	(twix
	 (let (get-context context code))

	 ;; ln(NaN) = NaN
	 (let ((ans ((ref self '_check_nans) #:context context))))
	 (ans it it)

	 ;; ln(0.0) == -Infinity
         ((not (bool self))
	  _NegativeInfinity)

	 ;; ln(Infinity) = Infinity
	 ((= ((ref self '_isinfinity)) 1)
          _Infinity)

	 ;; ln(1.0) == 0.0
	 (if (equal? self _One)
	     _Zero)

	 ;; ln(negative) raises InvalidOperation
	 ((= (ref self '_sign) 1)
	  ((ctx-error context) InvalidOperation,
	   "ln of a negative value"))

	 ;; result is irrational, so necessarily inexact
	 (let* ((op (_WorkRep self))
		(c  (ref op 'int))
		(e  (ref op 'exp))
		(p  (ctx-prec context))))
	   

	 ;; correctly rounded result: repeatedly increase precision by 3
	 ;; until we get an unambiguously roundable result
	 (let ((places (+ p
			  (- ((ref self '_ln_exp_bound)))
			  2)) ;; at least p+3 places
	       (ans #f))
	    (let lp ((places places))
	      (let ((coeff (_dlog c  e places)))
		;; assert len(str(abs(coeff)))-p >= 1
		(if (not (= (modulo coeff
				    (* 5 (expr 10 (- (len (str (abs coeff)))
						     p 1))))
			    0))
		    (set! ans (_dec_from_triple (int (< coeff 0))
						(str (abs coeff))
						(- places)))
						    
		    (lp (+ places 3)))))

	    (let* ((context  ((ref context '_shallow_copy)))
		   (rounding ((ref context '_set_rounding) ROUND_HALF_EVEN))
		   (ans      ((ref ans '_fix) context)))
	      (set context 'rounding rounding)
	      ans)))))

    (define _log10_exp_bound
      (lambda (self)
        "Compute a lower bound for the adjusted exponent of self.log10().
        In other words, find r such that self.log10() >= 10**r.
        Assumes that self is finite and positive and that self != 1.
        "

        ;; For x >= 10 or x < 0.1 we only need a bound on the integer
        ;; part of log10(self), and this comes directly from the
        ;; exponent of x.  For 0.1 <= x <= 10 we use the inequalities
        ;; 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
        ;; (1-1/x)/2.31 > 0.  If x < 1 then |log10(x)| > (1-x)/2.31 > 0

        (let ((adj (+ (ref self '_exp) (len (ref self '_int)) (- 1))))
	  (cond
	   ((>=adj 1)
	    ;; self >= 10
	    (- (len (str adj)) 1))
	   ((<= adj -2)
	    ;;# self < 0.1
	    (- (len (str (- (+ 1 adj)))) 1))
	   (else
	    (let* ((op (_WorkRep self))
		   (c  (ref op 'int))
		   (e  (ref op 'exp)))
	      (if(= adj 0)
		 ;; 1 < self < 10
		 (let ((num (str (- c (expt 10 (- e)))))
		       (den (str (* 231 c))))
		   (+ (len num) (- (len den)) (- (< num den)) 2))	       
		 ;; adj == -1, 0.1 <= self < 1
		 (let ((num (str (- (expt 10 (- e)) c))))
		   (+ (len num) e (- (< num "231")) (- 1))))))))))

    (define log10
      (lam (self (= context None))
        "Returns the base 10 logarithm of self."
	(twix
	 (let (get-context context code))

	 ;; log(NaN) = NaN
	 (let ((ans ((ref self '_check_nans) #:context context))))
	 (ans it it)

	 ;; log10(0.0) == -Infinity
         ((not (bool self))
	  _NegativeInfinity)

	 ;; log10(Infinity) = Infinity
	 ((= ((ref self '_isinfinity)) 1)
          _Infinity)

	 ;; log10(1.0) == 0.0
	 (if (equal? self _One)
	     _Zero)

	 ;; ln(negative) raises InvalidOperation
	 ((= (ref self '_sign) 1)
	  ((ctx-error context) InvalidOperation,
	   "log10 of a negative value"))

	 (let ((ans #f)))
	 
	 ;; log10(10**n) = n
	 (begin
	   (if (and (equal? (string-ref (ref self '_int) 0) #\1)
		    (equal? (pylist-slice (ref self '_int) 1 None None)
			    (* "0" (- (len (ref self '_int)) 1))))
	       ;;answer may need rounding
	       (set! ans (Decimal (+ self._exp (len (ref self '_int)) (- 1))))
	       ;; result is irrational, so necessarily inexact
	       (let* ((op (_WorkRep self))
		      (c  (ref op 'int))
		      (e  (ref op 'exp))
		      (p  (ctx-prec context)))

		 ;; correctly rounded result: repeatedly increase precision
		 ;; until result is unambiguously roundable
		 (let lp ((places (+ p (- ((ref self '_log10_exp_bound))) 2)))
		   (let ((coeff (_dlog10 c e places)))
		     ;; assert len(str(abs(coeff)))-p >= 1
		     (if (not (= (modulo coeff
					 (* 5 (expt 10
						    (- (len (str (abs coeff)))
						       p 1))))
				 0))
			 (set! ans
			       (_dec_from_triple (int (< coeff 0))
						 (str (abs coeff))
						 (- places)))
			 (lp (+ places 3)))))))

	   (let* ((context  ((ref context '_shallow_copy)))
		  (rounding ((ref context '_set_rounding) ROUND_HALF_EVEN))
		  (ans      ((ref ans '_fix) context)))
	     (set context 'rounding rounding)
	     ans)))))

    (define logb
      (lam (self (= context None))
        " Returns the exponent of the magnitude of self's MSD.

        The result is the integer which is the exponent of the magnitude
        of the most significant digit of self (as though it were truncated
        to a single digit while maintaining the value of that digit and
        without limiting the resulting exponent).
        "
	(twix
	 (let (get-context context code))

	 ;; logb(NaN) = NaN
	 (let ((ans ((ref self '_check_nans) #:context context))))
	 (ans it it)

        ;; logb(+/-Inf) = +Inf
        (((ref self '_isinfinity))
	 _Infinity)

        ;; logb(0) = -Inf, DivisionByZero
        ((not (bool self))
	 ((ctx-error context) DivisionByZero "logb(0)" 1))

        ;; otherwise, simply return the adjusted exponent of self, as a
        ;; Decimal.  Note that no attempt is made to fit the result
        ;; into the current context.
        (let ((ans (Decimal ((ref self 'adjusted)))))
	  ((ref ans '_fix) context)))))

    (define _islogical
      (lambda (self)
        "Return True if self is a logical operand.

        For being logical, it must be a finite number with a sign of 0,
        an exponent of 0, and a coefficient whose digits must all be
        either 0 or 1.
        "
        (if (or (not (= (ref self '_sign) 0))
		(not (= (ref self '_exp)  0)))
            #f
	    (for ((dig : (ref self '_int))) ()
		 (if (not (or (equal? dig "0") (equal? dig "1")))
		     (break #f))
		 #:final #t))))
    
    (define _fill_logical
      (lambda (self context opa opb)
	(define (o opa dif)
	  (cond
	   ((> dif 0)
	    (* "0" dif) opa)
	   ((< dif 0)
	    (pylist-slice opa (- (ctx-prec context) None None)))
	   (else
	    opa)))
	
        (let* ((dif (- (ctx-prec context) (len opa)))
	       (opa (o opa diff))
	       (dif (- (ctx-prec context) (len opb)))
	       (opb (o opb diff)))
	  (values opa opb))))

    (define logical_*
      (lambda (logand)
      (lam (self other (= context None))
	"Applies an 'and' operation between self and other's digits."

	(twix
	 (let (get-context context code))	 
	 (let ((other (_convert_other other #:raiseit #t))))

	 ((or (not ((ref self '_islogical))  (not ((ref other '_islogical)))))
	  ((ctx-error context) InvalidOperation))

	 ;; fill to context.prec
	 (call-with-values
	     (lambda ()
	       ((ref self '_fill_logical)
		context (ref self '_int) (ref other '_int)))
	   (lambda (opa opb)
	     ;; make the operation, and clean starting zeroes
	     (_dec_from_triple
	      0
	      (for ((a : opa) (b : opb)) ((l '()) (f #t))
		   (let ((i (logand (int a) (int b))))
		     (if (and f (= i 0))
			 (values l                #t)
			 (values (cons (str i) l) #f)))
		   #:final
		   (if (null? l)
		       "0"
		       (list->string (reverse l))))
	      0)))))))

    (define logical_and (logical_* logand))
    (define logical_or  (logical_* logior))
    (define logical_xor (logical_* logxor))
    
    (define logical_invert
      (lam (self (= context None))
        "Invert all its digits."
        (let ((context (if (eq? context None)
			   (getcontext)
			   context)))
	  (logical_xor self
		       (_dec_from_triple 0 (* "1" (ctx-prec context)) 0)
		       context))))

    (define x_mag
      (lambda (nott)
      (lambda (self other (= context None))
        "Compares the values numerically with their sign ignored."
	(twix
	 (let ((other (_convert_other other  #:raiseit #t))))
	 (let (get-context context code))	 

	 ((if (or (bool (ref self '_is_special)) (bool (other '_is_special)))
	      ;; If one operand is a quiet NaN and the other is number, then the
	      ;; number is always returned
	      (let ((sn ((ref self  '_isnan)))
		    (on ((ref other '_isnan))))
		(if (or (bool sn) (bool on))
		    (cond
		     ((and (= on 1) (= sn 0))
		      ((ref self '_fix) context))
		     ((and (= on 0) (= sn 1))
		      ((ref other '_fix) context))
		     (else
		      ((ref self '_check_nans) other context)))
		    #f))
	      #f) it it)

	 (let* ((s   ((ref self 'copy_abs)))
		(o   ((ref other 'copy_abs)))
		(c   ((ref s '_cmp) o))
		(c   (if (= c 0)
			 ((self 'compare_total) other)
			 c))
		(ans (if (nott (= c -1)) other self)))
		 
	   ((ref ans '_fix) context))))))

    (define max_mag (x_mag (lambda (x) x)))
    (define min_mag (x_mag not))
      
    (define next_minus
      (lam (self (= context None))
	"Returns the largest representable number smaller than itself."

	(twix
	 (let (get-context context code))	 
	 
	 (let ((ans ((ref self '_check_nans) #:context context))))
	 (ans it it)

        ((= ((ref self '_isinfinity)) -1)
	 _NegativeInfinity)

	((= ((ref self '_isinfinity)) 1)
	 (_dec_from_triple 0  (* '9' (ctx-prec context)) (ctx-etop context)))

	
	(let* ((context  ((ref context 'copy)))
	       (rounding ((ref context '_set_rounding) ROUND_FLOOR)))
	  ((context '_ignore_all_flags))
	  (let ((new_self ((ref self '_fix) context)))
	    (if (not (equal? self new_self))
		new_self
		((ref self '__sub__)
		 (_dec_from_triple 0 "1" (- (ctx-etiny context) 1))
		 context)))))))
    
    (define next_plus
      (lam (self (= context None))
	"Returns the largest representable number smaller than itself."

	(twix
	 (let (get-context context code))	 
	 
	 (let ((ans ((ref self '_check_nans) #:context context))))
	 (ans it it)

        ((= ((ref self '_isinfinity)) 1)
	 _Infinity)

	((= ((ref self '_isinfinity)) -1)
	 (_dec_from_triple 1  (* '9' (ctx-prec context)) (ctx-etop context)))

	
	(let* ((context  ((ref context 'copy)))
	       (rounding ((ref context '_set_rounding) ROUND_CEILING)))
	  ((context '_ignore_all_flags))
	  (let ((new_self ((ref self '_fix) context)))
	    (if (not (equal? self new_self))
		new_self
		((ref self '__add__)
		 (_dec_from_triple 0 "1" (- (ctx-etiny context) 1))
		 context)))))))
    
    (define next_toward
      (lam (self other (= context None))
        "Returns the number closest to self, in the direction towards other.

        The result is the closest representable number to self
        (excluding self) that is in the direction towards other,
        unless both have the same value.  If the two operands are
        numerically equal, then the result is a copy of self with the
        sign set to be the same as the sign of other.
        "

	(twix
	 (let ((other (_convert_other other  #:raiseit #t))))
	 (let (get-context context code))	 

	 (let ((ans ((ref self '_check_nans) #:context context))))
	 (ans it it)

	 (let ((comparison ((ref self '_cmp) other))))
	 
	 ((= comparison 0)
	  ((ref self 'copy_sign) other))

        (let ((ans (if (= comparison -1)
		       ((ref self 'next_plus)  context)
		       ;; comparison == 1
		       ((ref self 'next_minus) context))))

	  ;; decide which flags to raise using value of ans
	  (cond
	   (((ref ans '_isinfinity))
	    ((ctx-error context) Overflow "Infinite result from next_toward"
	     (ref ans '_sign))
	    ((ctx-error context) Inexact)
	    ((ctx-error context) Rounded))
	      
	    ((< ((ref ans 'adjusted)) (ctx-emin context))
	     ((ctx-error context) Underflow)
	     ((ctx-error context) Subnormal)
	     ((ctx-error context) Inexact)
	     ((ctx-error context) Rounded)
	     ;; if precision == 1 then we don't raise Clamped for a
	     ;; result 0E-Etiny.
	     (if (not (bool ans))
		 ((ctx-error context) Clamped)))
	    (else #f))

	  ans))))

    (define number_class
      (lam (self (= context None))
        "Returns an indication of the class of self.

        The class is one of the following strings:
          sNaN
          NaN
          -Infinity
          -Normal
          -Subnormal
          -Zero
          +Zero
          +Subnormal
          +Normal
          +Infinity
        "
	(twix
	 (((ref self 'is_snan)) it
	  "sNaN")
	 (((ref self 'is_qnan)) it
	  "NaN")
	 (let ((inf ((ref self '_isinfinity)))))
	 ((= inf 1)  it
	  "+Infinity")
	 ((= inf -1) it
	  "-Infinity")
        (((ref self 'is_zero)) it
	 (if (bool (ref self '_sign))
	     "-Zero"
	     "+Zero"))

	(let (get-context context code))	 

        (((ref self 'is_subnormal) #:context context)
	 (if (bool (ref self '_sign))
	     "-Subnormal"
	     "+Subnormal"))

	;; just a normal, regular, boring number, :)
        (if (bool (ref self '_sign))
            "-Normal"
	    "+Normal"))))

    (define radix
      (lambda (self)
        "Just returns 10, as this is Decimal"
        (Decimal 10)))

    (define rotate
      (lam (self other (= context None))
	"Returns a rotated copy of self, value-of-other times."
	(twix
	 (let (get-context context code))	 	 
	 (let ((other (_convert_other other  #:raiseit #t))))

	 (let ((ans ((ref other '_check_nans) #:context context))))
	 (ans it it)
	 
	 ((not (= (ref other '_exp) 0))
	  ((ctx-error context) InvalidOperation))

	 (let ((o (int other))
	       (p (ctx-prec context))))
	 
	 ((not (and (<= (- p) o) (<= o p)))	  
	  ((ctx-error context) InvalidOperation))

        (((ref self '_isinfinity))
	 (Decimal self))

        ;; get values, pad if necessary
        (let ((torot   (int other))
	      (rotdig  (ref self '_int))
	      (topad   (- p (len rotdig))))
	  (cond
	   ((> topad 0)
	    (set! rotdig (+ (* "0" topad) + rotdig)))
	   ((< topad 0)
            (set! rotdig (pylist-slice rotdig (- topad) None None)))
	   (else #f))

	  (let ((rotated (+ (pylist-slice rotdig torot None  None)
			    (pylist-slice rotdig None  torot None))))
	    (_dec_from_triple (ref self '_sign)
			      (or (bool (py-lstrip rotated "0")) "0")
			      (ref self '_exp)))))))

    (define scaleb
      (lam (self other (= context None))
	"Returns self operand after adding the second value to its exp."
	(twix
	 (let (get-context context code))	 	 
	 (let ((other (_convert_other other  #:raiseit #t))))

	 (let ((ans ((ref other '_check_nans) #:context context))))
	 (ans it it)

	 ((not (= (ref other '_exp)))
	  ((ctx-error context) InvalidOperation))
	 
	 (let ((liminf  (* -2  (+ (ctx-emax context) (ctx-prec context))))
	       (limsup  (*  2  (+ (ctx-emax context) (ctx-prec context))))))

	 ((not (let ((o (int other)))
		 (and (<= liminf o)
		      (<= o limsup))))
	  ((ctx-error context) InvalidOperation))

	 (((ref self '_isinfinity))
	  (Decimal self))

	 (let* ((d (_dec_from_triple (ref self '_sign)
				     (ref self '_int)
				     (+ (ref self '_exp) (int other))))
		(d ((ref d '_fix) context)))
	   d))))

    (define shift
      (lam (self other (= context None))
	"Returns a rotated copy of self, value-of-other times."
	(twix
	 (let (get-context context code))	 	 
	 (let ((other (_convert_other other  #:raiseit #t))))

	 (let ((ans ((ref other '_check_nans) #:context context))))
	 (ans it it)
	 
	 ((not (= (ref other '_exp) 0))
	  ((ctx-error context) InvalidOperation))

	 (let ((o (int other))
	       (p (ctx-prec context))))
	 
	 ((not (and (<= (- p) o) (<= o p)))	  
	  ((ctx-error context) InvalidOperation))

        (((ref self '_isinfinity))
	 (Decimal self))

        ;; get values, pad if necessary
        (let ((torot   (int other))
	      (rotdig  (ref self '_int))
	      (topad   (- p (len rotdig))))

	  (cond
	   ((> topad 0)
	    (set! rotdig (+ (* "0" topad) + rotdig)))
	   ((< topad 0)
            (set! rotdig (pylist-slice rotdig (- topad) None None)))
	   (else #f))

	  
	  ;; let's shift!
	  (let ((shifted (if (< torot 0)
            (pylist-slice rotdig None torot None)
            (pylist-slice (+ rotdig (* "0" torot))
            (- p) None None))))

	    (_dec_from_triple (ref self '_sign)
			      (or (bool (py-lstrip shifted "0")) "0")
			      (ref self '_exp)))))))

    ;; Support for pickling, copy, and deepcopy
    ;; def __reduce__(self):
    ;;    return (self.__class__, (str(self),))

    ;; def __copy__(self):
    ;;     if type(self) is Decimal:
    ;;        return self     # I'm immutable; therefore I am my own clone
    ;;    return self.__class__(str(self))

    ;; def __deepcopy__(self, memo):
    ;;    if type(self) is Decimal:
    ;;        return self     # My components are also immutable
    ;;    return self.__class__(str(self))
    |#
    ;; PEP 3101 support.  the _localeconv keyword argument should be
    ;; considered private: it's provided for ease of testing only.    
    (define __format__
      (lam (self specifier (= context None) (= _localeconv None))
        "Format a Decimal instance according to the given specifier.

        The specifier should be a standard format specifier, with the
        form described in PEP 3101.  Formatting types 'e', 'E', 'f',
        'F', 'g', 'G', 'n' and '%' are supported.  If the formatting
        type is omitted it defaults to 'g' or 'G', depending on the
        value of context.capitals.
        "

        ;; Note: PEP 3101 says that if the type is not present then
        ;; there should be at least one digit after the decimal point.
        ;; We take the liberty of ignoring this requirement for
        ;; Decimal---it's presumably there to make sure that
        ;; format(float, '') behaves similarly to str(float).
        (if (eq? context None)
            (set! context (getcontext)))

	(twix
	 (let ((spec
		(_parse_format_specifier specifier
					 #:_localeconv _localeconv))))

	 (let ((type (pylist-ref spec "type"))))
	 ;; special values don't care about the type or precision
	 ((bool (ref self '_is_special)) it
	  (let ((sign (_format_sign (ref self '_sign) spec))
		(body (str ((ref self 'copy_abs)))))
	    (if (equal? type "%")
		(set! body (+ body "%")))
	    (_format_align sign body spec)))

	 ;; a type of None defaults to 'g' or 'G', depending on context
	 (if (eq? type None)
	     (pylist-set! spec "type"
			  (if (= (cx-cap context) 0) "g" "G")))

	 (let ((type (pylist-ref spec "type"))))
	 ;; if type is '%', adjust exponent of self accordingly
	 (if (equal? type "%")
	     (set! self
		   (_dec_from_triple (ref self '_sign)
				     (ref self '_int)
				     (+ (ref self '_exp) 2))))

	 ;; round if necessary, taking rounding mode from the context
	 (let ((rounding  (cx-rounding context))
	       (precision (pylist-ref spec "precision")))
	   (if (not (eq? precision None))
	       (cond
		((in type "eE")
		 (set! self ((ref self '_round) (+ precision 1) rounding)))
		((in type "fF%")
		 (set! self ((ref self '_rescale) (- precision) rounding)))
		((and (in type "gG") (> (len (ref self '_int)) precision))
		 (set! self  ((ref self '_round) precision rounding)))
		(else #t))))
	  
	 ;; special case: zeros with a positive exponent can't be
	 ;; represented in fixed point; rescale them to 0e0.
	 (if (and (not (bool self)) (> (ref self '_exp) 0) (in type "fF%"))
	     (set! self ((ref self '_rescale) 0 rounding)))

	 ;; figure out placement of the decimal point
	 (let* ((leftdigits (+ (ref self '_exp) (len (ref self '_int))))
		(dotplace
		 (cond
		  ((in type "eE")
		   (if (and (not (bool self)) (not (eq? precision None)))
		       (- 1 precision)
		       1))
		 ((in type "fF%")
		  leftdigits)
		 ((in type "gG")
		  (if (and (<= (ref self '_exp) 0) (> leftdigits -6))
		      leftdigits
		      1))
		 (else
		  1))))
		 
	   ;; find digits before and after decimal point, and get exponent
	   (call-with-values
	       (lambda ()
		 (cond
		  ((< dotplace 0)
		   (values '0'
			   (+ (* "0" (- dotplace)) (ref self '_int))))
		  ((> dotplace (len (ref self '_int)))
		   (values (+ (ref self '_int) (* "0" (- dotplace
							 (len (ref self '_int)))))
			   ""))
		  (else
		   (values
		    (or (bool (pylist-slice (ref self '_int) None dotplace None))
			"0")
		    (pylist-slice (ref self '_int) dotplace None None)))))
	     (lambda (intpart fracpart)
	       (let ((exp (- leftdigits dotplace)))
		 ;; done with the decimal-specific stuff;  hand over the rest
		 ;; of the formatting to the _format_number function
		 (_format_number (ref self '_sign) intpart fracpart exp spec)))))))))
#|
(define _dec_from_triple
  (lam (sign  coefficient  exponent (= special #f))
    "Create a decimal instance directly, without any validation,
    normalization (e.g. removal of leading zeros) or argument
    conversion.

    This function is for *internal use only*.
    "

    (let ((self ((ref object '__new__) Decimal)))
      (set self '_sign       sign)
      (set self '_int        coefficient)      
      (set self '_exp        exponent)
      (set self '_is_special special)

      self)))

;; Register Decimal as a kind of Number (an abstract base class).
;; However, do not register it as Real (because Decimals are not
;; interoperable with floats).
;; _numbers.Number.register(Decimal)


;; ##### Context class #######################################################

(define-python-class _ContextManager (object)
    "Context manager class to support localcontext().

      Sets a copy of the supplied context in __enter__() and restores
      the previous decimal context in __exit__()
    "
    (define __init__
      (lambda (self new_context)
        (set self 'new_context ((ref new_context 'copy)))))
    
    (define __enter__
      (lambda (self)
        (set self 'saved_context (getcontext))
        (setcontext (ref self 'new_context))
        (ref self 'new_context)))
    
    (define __exit__
      (lambda (self t v tb)
        (setcontext (ref self 'saved_context)))))

(define DefaultContext #f)

(define-syntax-rule (setq s q m)
  (set s 'q (if (eq? q None) (ref m 'q) q)))

(define-python-class Context (object)
    "Contains the context for a Decimal instance.

    Contains:
    prec - precision (for use in rounding, division, square roots..)
    rounding - rounding type (how you round)
    traps - If traps[exception] = 1, then the exception is
                    raised when it is caused.  Otherwise, a value is
                    substituted in.
    flags  - When an exception is caused, flags[exception] is set.
             (Whether or not the trap_enabler is set)
             Should be reset by user of Decimal instance.
    Emin -   Minimum exponent
    Emax -   Maximum exponent
    capitals -      If 1, 1*10^1 is printed as 1E+1.
                    If 0, printed as 1e1
    clamp -  If 1, change exponents if too high (Default 0)
    "

    (define __init__
      (lam (self (= prec  None) (= rounding None) (= Emin None)
		 (= Emax  None) (= capitals None) (= clamp None)
		 (= flags None) (= traps None)    (= _ignored_flags None))
        ;; Set defaults; for everything except flags and _ignored_flags,
        ;; inherit from DefaultContext.
        (let ((dc DefaultContext))
	  (setq self prec     dc)
	  (setq self rounding dc)
	  (setq self Emin     dc)
	  (setq self Emax     dc)
	  (setq self capitals dc)
	  (setq self clamp    dc)

	  (set self '_ignored_flags
	       (if (eq? _ignored_flags None)
		   (py-list)
		   _ignored_flags))
	  (set self 'traps
	       (cond
		((eq? traps None)
		 ((ref (ref dc traps) 'copy)))
		((not (isinstance traps dict))
		 (dict (for ((s : (+ _signals traps))) ((l '()))
			    (cons (list s (int (in s traps))) l)
			    #:final (reverse l))))
		(else traps)))

	  (set self 'flags
	       (cond
		((eq? flags None)
		 ((ref dict 'fromkeys) _signals 0))
		((not (isinstance flags dict))
		 (dict (for ((s : (+ _signals flags))) ((l '()))
			    (cons (list s (int (in s flags))) l)
			    #:final (reverse l))))
		(else flags))))))

    (define _set_integer_check
      (lambda (self name value vmin vmax)
        (if (not (isinstance value int))
            (raise (TypeError (format #f "~a must be an integer" name))))
	
        (cond
	 ((equal? vmin "-inf")
	  (if (> value vmax)
	      (raise (ValueError (format #f "~a must be in [~a, ~a]. got: ~a"
					 name vmin vmax value)))))
	 ((equal? vmax "inf")
	  (if (< value vmin)
	      (raise (ValueError (format #f "~a must be in [~a, ~a]. got: ~a"
					 name vmin vmax value)))))
	 (else
	  (if (or (< value vmin) (> value vmax))
	      (raise (ValueError (format #f "~a must be in [~a, ~a]. got ~a"
					 name vmin vmax value))))))
        (rawset self (string->symbol name) value)))

    (define _set_signal_dict
      (lambda (self name d)
        (if (not (isinstance d dict))
            (raise (TypeError (format #f "~a must be a signal dict" d))))
	
        (for ((key : d)) ()
	     (if (not (in key _signals))
		 (raise (KeyError (format #f "~a is not a valid signal dict"
					  d)))))
        (for ((key : _signals)) ()
	     (if (not (in key d))
		 (raise (KeyError (format #f "~a is not a valid signal dict"
					  d)))))
        (rawset self (string->symbol name) d)))

    (define __setattr__
      (lambda (self name value)
        (cond
	 ((equal? name "prec")
          ((ref self '_set_integer_check) name value 1 "inf"))
	 ((equal? name "Emin")
	  ((ref self '_set_integer_check) name value "-inf" 0))
	 ((equal? name "Emax")
	  ((ref self '_set_integer_check) name value 0 "inf"))
	 ((equal? name "capitals")
	  ((ref self '_set_integer_check) name value 0 1))
	 ((equal? name "clamp")
	  ((ref self '_set_integer_check) name value 0 1))
	 ((equal? name "rounding")
	  (if (not (member (string->symbol value) _rounding_modes))
	      ;; raise TypeError even for strings to have consistency
	      ;; among various implementations.
	      (raise (TypeError (format #f "~a: invalid rounding mode" value))))
	  (rawset self (string->symbol name) (string->symbol value)))
	 ((or (equal? name "flags") (equal? name "traps"))
	  ((ref self '_set_signal_dict) name value))
	 ((equal? name "_ignored_flags")
	  (rawset self (string->symbol name) value))
	 (else
	  (raise (AttributeError
		  (format #f
			  "'decimal.Context' object has no attribute '~a'"
			  name)))))))

    (define __delattr__
      (lambda (self name)
        (raise (AttributeError (format #f "~a cannot be deleted" name)))))

    ;;# Support for pickling, copy, and deepcopy
    ;;def __reduce__(self):
    ;;    flags = [sig for sig, v in self.flags.items() if v]
    ;;    traps = [sig for sig, v in self.traps.items() if v]
    ;;    return (self.__class__,
    ;;            (self.prec, self.rounding, self.Emin, self.Emax,
    ;;             self.capitals, self.clamp, flags, traps))

    (define __repr__
      (lambda (self)
        "Show the current context."
	(format #f "Context(prec=~a, rounding=~a, Emin=~a, Emax=~a capitals=~a clamp=~a, flags=~a, traps=~a)"
		(ref self 'prec)
		(ref self 'rounding)
		(ref self 'Emin)
		(ref self 'Emax)
		(ref self 'capitals)
		(ref self 'clamp)
		(for ((k v : (ref self 'flags))) ((l '()))
		     (cons k l)
		     #:final (reverse l))
		(for ((k v : (ref self 'traps))) ((l '()))
		     (cons k l)
		     #:final (reverse l)))))
    
    (define clear_flags
      (lambda (self)
        "Reset all flags to zero"
        (for ((flag : (ref self 'flags))) ()
	     (pylist-set! (ref self 'flags) flag 0))))

    (define clear_traps
      (lambda (self)
        "Reset all traps to zero"
        (for ((flag : (ref self 'traps))) ()
	     (pylist-set! (ref self 'traps) flag 0))))

    (define _shallow_copy
      (lambda (self)
        "Returns a shallow copy from self."
        (Context (ref self 'prec)
		 (ref self 'rounding)
		 (ref self 'Emin)
		 (ref self 'Emax)
		 (ref self 'capitals)
		 (ref self 'clamp)
		 (ref self 'flags)
		 (ref self 'traps)
		 (ref self '_ignored_flags))))
    
    (define copy
      (lambda (self)
        "Returns a deep copy from self."
	(Context (ref self 'prec)
		 (ref self 'rounding)
		 (ref self 'Emin)
		 (ref self 'Emax)
		 (ref self 'capitals)
		 (ref self 'clamp)
		 ((ref (ref self 'flags) 'copy))
		 ((ref (ref self 'traps) 'copy))
		 (ref self '_ignored_flags))))

    (define __copy__ copy)
    
    (define _raise_error
      (lam (self condition (= explanation None) (* args))
        "Handles an error

        If the flag is in _ignored_flags, returns the default response.
        Otherwise, it sets the flag, then, if the corresponding
        trap_enabler is set, it reraises the exception.  Otherwise, it returns
        the default value after setting the flag.
        "
        (let ((error ((ref _condition_map 'get) condition condition)))
	  (if (in error (ref self '_ignored_flags))
	      ;; Don't touch the flag
	      (py-apply (ref (error) 'handle) self (* args))
	      (begin
		(pylist-set! (ref self 'flags) error 1)
		(if (not (bool (pylist-ref (ref self 'traps) error)))
		    ;; The errors define how to handle themselves.
		    (py-apply (ref (condition) 'handle) self (* args))
		    
		    ;; Errors should only be risked on copies of the context
		    ;; self._ignored_flags = []
		    (raise (error explanation))))))))

    (define _ignore_all_flags
      (lambda (self)
        "Ignore all flags, if they are raised"
        (py-apply (ref self '_ignore_flags) (*_signals))))

    (define _ignore_flags
      (lambda (self . flags)
        "Ignore the flags, if they are raised"
        ;; Do not mutate-- This way, copies of a context leave the original
        ;; alone.
        (set self '_ignored_flags (+ (ref self '_ignored_flags) (py-list flags)))
        (py-list flags)))

    (define _regard_flags
      (lambda (self . flags)
        "Stop ignoring the flags, if they are raised"
        (let ((flags
	       (if (and (pair? flags) (isinstance (car flags) (tuple,list)))
		   (car flags)
		   flags)))
	  (for ((flag : flags)) ()
	       ((ref (ref self '_ignored_flags) 'remove) flag)))))

    ;; We inherit object.__hash__, so we must deny this explicitly
    (define __hash__ None)

    (define Etiny
      (lambda (self)
        "Returns Etiny (= Emin - prec + 1)"
        (int (+ (- (ref self 'Emin) (ref self 'prec)) 1))))

    (define (Etop self)
        "Returns maximum exponent (= Emax - prec + 1)"
        (int (+ (- (ref self 'Emax) (ref self 'prec)) 1)))

    (define (_set_rounding self type)
        "Sets the rounding type.

        Sets the rounding type, and returns the current (previous)
        rounding type.  Often used like:

        context = context.copy()
        # so you don't change the calling context
        # if an error occurs in the middle.
        rounding = context._set_rounding(ROUND_UP)
        val = self.__sub__(other, context=context)
        context._set_rounding(rounding)

        This will make it round up for that operation.
        "
        (let ((rounding (ref self 'rounding)))
	  (set self 'rounding type)
	  rounding))

    (define create_decimal
      (lam (self (= num "0"))
        "Creates a new Decimal instance but using self as context.

        This method implements the to-number operation of the
        IBM Decimal specification."

        (if (or (and (isinstance num str) (not (equal? num ((ref num 'strip)))))
		(in "_" num))
            ((ref self '_raise_error) ConversionSyntax
	     "trailing or leading whitespace and "
	     "underscores are not permitted.")
	    (let ((d (Decimal num #:context self)))
	      (if (and ((ref d '_isnan)) (> (len (ref d '_int)) (- (ref self 'prec)
								   (ref self 'clamp))))
		  ((ref self '_raise_error) ConversionSyntax
		   "diagnostic info too long in NaN")
		  ((ref d '_fix) self))))))

    (define create_decimal_from_float
      (lambda (self f)
        "Creates a new Decimal instance from a float but rounding using self
        as the context.

        >>> context = Context(prec=5, rounding=ROUND_DOWN)
        >>> context.create_decimal_from_float(3.1415926535897932)
        Decimal('3.1415')
        >>> context = Context(prec=5, traps=[Inexact])
        >>> context.create_decimal_from_float(3.1415926535897932)
        Traceback (most recent call last):
            ...
        decimal.Inexact: None

        "
        (let ((d ((ref Decimal 'from_float) f)))       ; An exact conversion
	  ((ref d '_fix) self))))                      ; Apply the context rounding

    ;; Methods
    (define abs
      (lambda (self a)
        "Returns the absolute value of the operand.

        If the operand is negative, the result is the same as using the minus
        operation on the operand.  Otherwise, the result is the same as using
        the plus operation on the operand.

        >>> ExtendedContext.abs(Decimal('2.1'))
        Decimal('2.1')
        >>> ExtendedContext.abs(Decimal('-100'))
        Decimal('100')
        >>> ExtendedContext.abs(Decimal('101.5'))
        Decimal('101.5')
        >>> ExtendedContext.abs(Decimal('-101.5'))
        Decimal('101.5')
        >>> ExtendedContext.abs(-1)
        Decimal('1')
        "
        (let ((a (_convert_other a #:raiseit #t)))
	  ((ref a '__abs__) #:context self))))

    (define add
      (lambda (self a b)
        "Return the sum of the two operands.

        >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
        Decimal('19.00')
        >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
        Decimal('1.02E+4')
        >>> ExtendedContext.add(1, Decimal(2))
        Decimal('3')
        >>> ExtendedContext.add(Decimal(8), 5)
        Decimal('13')
        >>> ExtendedContext.add(5, 5)
        Decimal('10')
        "
        (let* ((a (_convert_other a #:raiseit #t))
	       (r ((ref a '__add__) b #:context self)))
	  (if (equal? r NotImplemented)
	      (raise (TypeError (fromat #f "Unable to convert ~a to Decimal" b)))
	      r))))

    (define _apply
      (lambda (self a)
        (str ((ref a '_fix) self))))

    (define canonical
      (lambda (self a)
        "Returns the same Decimal object.

        As we do not have different encodings for the same number, the
        received object already is in its canonical form.

        >>> ExtendedContext.canonical(Decimal('2.50'))
        Decimal('2.50')
        "
        (if (not (isinstance a Decimal))
            (raise (TypeError "canonical requires a Decimal as an argument.")))

	((ref a 'canonical))))

    (define compare
      (lambda (self a b):
        "Compares values numerically.

        If the signs of the operands differ, a value representing each operand
        ('-1' if the operand is less than zero, '0' if the operand is zero or
        negative zero, or '1' if the operand is greater than zero) is used in
        place of that operand for the comparison instead of the actual
        operand.

        The comparison is then effected by subtracting the second operand from
        the first and then returning a value according to the result of the
        subtraction: '-1' if the result is less than zero, '0' if the result is
        zero or negative zero, or '1' if the result is greater than zero.

        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
        Decimal('-1')
        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
        Decimal('0')
        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
        Decimal('0')
        >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
        Decimal('1')
        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
        Decimal('1')
        >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
        Decimal('-1')
        >>> ExtendedContext.compare(1, 2)
        Decimal('-1')
        >>> ExtendedContext.compare(Decimal(1), 2)
        Decimal('-1')
        >>> ExtendedContext.compare(1, Decimal(2))
        Decimal('-1')
        "
        (let ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'compare) b #:context self))))

    (define compare_signal
      (lambda (self a b)
        "Compares the values of the two operands numerically.

        It's pretty much like compare(), but all NaNs signal, with signaling
        NaNs taking precedence over quiet NaNs.

        >>> c = ExtendedContext
        >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
        Decimal('-1')
        >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
        Decimal('0')
        >>> c.flags[InvalidOperation] = 0
        >>> print(c.flags[InvalidOperation])
        0
        >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
        Decimal('NaN')
        >>> print(c.flags[InvalidOperation])
        1
        >>> c.flags[InvalidOperation] = 0
        >>> print(c.flags[InvalidOperation])
        0
        >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
        Decimal('NaN')
        >>> print(c.flags[InvalidOperation])
        1
        >>> c.compare_signal(-1, 2)
        Decimal('-1')
        >>> c.compare_signal(Decimal(-1), 2)
        Decimal('-1')
        >>> c.compare_signal(-1, Decimal(2))
        Decimal('-1')
        "
	(let ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'compare_signal) b #:context self))))

    (define compare_total
      (lambda (self a b)
        "Compares two operands using their abstract representation.

        This is not like the standard compare, which use their numerical
        value. Note that a total ordering is defined for all possible abstract
        representations.

        >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
        Decimal('-1')
        >>> ExtendedContext.compare_total(Decimal('-127'),  Decimal('12'))
        Decimal('-1')
        >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
        Decimal('-1')
        >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
        Decimal('0')
        >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('12.300'))
        Decimal('1')
        >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('NaN'))
        Decimal('-1')
        >>> ExtendedContext.compare_total(1, 2)
        Decimal('-1')
        >>> ExtendedContext.compare_total(Decimal(1), 2)
        Decimal('-1')
        >>> ExtendedContext.compare_total(1, Decimal(2))
        Decimal('-1')
        "
	(let ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'compare_total) b #:context self))))

    (define compare_total_mag
      (lambda (self a b)
        "Compares two operands using their abstract representation ignoring sign.

        Like compare_total, but with operand's sign ignored and assumed to be 0.
        "
	(let ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'compare_total_mag) b #:context self))))

    (define copy_abs
      (lambda (self a)
        "Returns a copy of the operand with the sign set to 0.

        >>> ExtendedContext.copy_abs(Decimal('2.1'))
        Decimal('2.1')
        >>> ExtendedContext.copy_abs(Decimal('-100'))
        Decimal('100')
        >>> ExtendedContext.copy_abs(-1)
        Decimal('1')
        "
	(let ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'copy_abs)))))
    
    (define copy_decimal
      (lambda (self a)
        "Returns a copy of the decimal object.

        >>> ExtendedContext.copy_decimal(Decimal('2.1'))
        Decimal('2.1')
        >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
        Decimal('-1.00')
        >>> ExtendedContext.copy_decimal(1)
        Decimal('1')
        "
	(let ((a (_convert_other a #:raiseit #t)))
	  (Decimal a))))
    
    (define copy_negate
      (lambda (self a)
        "Returns a copy of the operand with the sign inverted.

        >>> ExtendedContext.copy_negate(Decimal('101.5'))
        Decimal('-101.5')
        >>> ExtendedContext.copy_negate(Decimal('-101.5'))
        Decimal('101.5')
        >>> ExtendedContext.copy_negate(1)
        Decimal('-1')
        "
	(let ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'copy_negate)))))
    
    (define copy_sign
      (lambda (self a b)
        "Copies the second operand's sign to the first one.

        In detail, it returns a copy of the first operand with the sign
        equal to the sign of the second operand.

        >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
        Decimal('1.50')
        >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
        Decimal('1.50')
        >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
        Decimal('-1.50')
        >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
        Decimal('-1.50')
        >>> ExtendedContext.copy_sign(1, -2)
        Decimal('-1')
        >>> ExtendedContext.copy_sign(Decimal(1), -2)
        Decimal('-1')
        >>> ExtendedContext.copy_sign(1, Decimal(-2))
        Decimal('-1')
        "
	(let ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'copy_sign) b))))

    (define divide
      (lambda (self a b)
        "Decimal division in a specified context.

        >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
        Decimal('0.333333333')
        >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
        Decimal('0.666666667')
        >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
        Decimal('2.5')
        >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
        Decimal('0.1')
        >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
        Decimal('1')
        >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
        Decimal('4.00')
        >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
        Decimal('1.20')
        >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
        Decimal('10')
        >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
        Decimal('1000')
        >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
        Decimal('1.20E+6')
        >>> ExtendedContext.divide(5, 5)
        Decimal('1')
        >>> ExtendedContext.divide(Decimal(5), 5)
        Decimal('1')
        >>> ExtendedContext.divide(5, Decimal(5))
        Decimal('1')
        "
        (let* ((a (_convert_other a #:raiseit #t))
	       (r ((ref a '__truediv__) b #:context self)))
	  (if (equal? r NotImplemented)
	      (raise (TypeError (format #t "Unable to convert ~a to Decimal" b)))
	      r))))
    
    (define divide_int
      (lambda (self a b)
        "Divides two numbers and returns the integer part of the result.

        >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
        Decimal('0')
        >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
        Decimal('3')
        >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
        Decimal('3')
        >>> ExtendedContext.divide_int(10, 3)
        Decimal('3')
        >>> ExtendedContext.divide_int(Decimal(10), 3)
        Decimal('3')
        >>> ExtendedContext.divide_int(10, Decimal(3))
        Decimal('3')
        "
	(let* ((a (_convert_other a #:raiseit #t))
	       (r ((ref a '__floordiv__) b #:context self)))
	  (if (equal? r NotImplemented)
	      (raise (TypeError (format #t "Unable to convert ~a to Decimal" b)))
	      r))))
    
    (define divmod
      (lambda (self a b)
        "Return (a // b, a % b).

        >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
        (Decimal('2'), Decimal('2'))
        >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
        (Decimal('2'), Decimal('0'))
        >>> ExtendedContext.divmod(8, 4)
        (Decimal('2'), Decimal('0'))
        >>> ExtendedContext.divmod(Decimal(8), 4)
        (Decimal('2'), Decimal('0'))
        >>> ExtendedContext.divmod(8, Decimal(4))
        (Decimal('2'), Decimal('0'))
        "
	(let* ((a (_convert_other a #:raiseit #t))
	       (r ((ref a '__divmod__) b #:context self)))
	  (if (equal? r NotImplemented)
	      (raise (TypeError (format #t "Unable to convert ~a to Decimal" b)))
	      r))))

    (define exp
      (lambda (self a)
        "Returns e ** a.

        >>> c = ExtendedContext.copy()
        >>> c.Emin = -999
        >>> c.Emax = 999
        >>> c.exp(Decimal('-Infinity'))
        Decimal('0')
        >>> c.exp(Decimal('-1'))
        Decimal('0.367879441')
        >>> c.exp(Decimal('0'))
        Decimal('1')
        >>> c.exp(Decimal('1'))
        Decimal('2.71828183')
        >>> c.exp(Decimal('0.693147181'))
        Decimal('2.00000000')
        >>> c.exp(Decimal('+Infinity'))
        Decimal('Infinity')
        >>> c.exp(10)
        Decimal('22026.4658')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'exp) #:context self))))
    
    (define fma
      (lambda (self a b c)
        "Returns a multiplied by b, plus c.

        The first two operands are multiplied together, using multiply,
        the third operand is then added to the result of that
        multiplication, using add, all with only one final rounding.

        >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
        Decimal('22')
        >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
        Decimal('-8')
        >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
        Decimal('1.38435736E+12')
        >>> ExtendedContext.fma(1, 3, 4)
        Decimal('7')
        >>> ExtendedContext.fma(1, Decimal(3), 4)
        Decimal('7')
        >>> ExtendedContext.fma(1, 3, Decimal(4))
        Decimal('7')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'fma) b c #:context self))))

    (define is_canonical
      (lambda (self a)
        "Return True if the operand is canonical; otherwise return False.

        Currently, the encoding of a Decimal instance is always
        canonical, so this method returns True for any Decimal.

        >>> ExtendedContext.is_canonical(Decimal('2.50'))
        True
        "
        (if (not (isinstance a Decimal))
            (raise (TypeError "is_canonical requires a Decimal as an argument."))
	    ((ref a 'is_canonical)))))

    (define is_finite
      (lambda (self a)
        "Return True if the operand is finite; otherwise return False.

        A Decimal instance is considered finite if it is neither
        infinite nor a NaN.

        >>> ExtendedContext.is_finite(Decimal('2.50'))
        True
        >>> ExtendedContext.is_finite(Decimal('-0.3'))
        True
        >>> ExtendedContext.is_finite(Decimal('0'))
        True
        >>> ExtendedContext.is_finite(Decimal('Inf'))
        False
        >>> ExtendedContext.is_finite(Decimal('NaN'))
        False
        >>> ExtendedContext.is_finite(1)
        True
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'finite)))))

    (define is_infinite
      (lambda (self a)
        "Return True if the operand is infinite; otherwise return False.

        >>> ExtendedContext.is_infinite(Decimal('2.50'))
        False
        >>> ExtendedContext.is_infinite(Decimal('-Inf'))
        True
        >>> ExtendedContext.is_infinite(Decimal('NaN'))
        False
        >>> ExtendedContext.is_infinite(1)
        False
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'is_infinite)))))

    (define is_nan
      (lambda (self a)
        "Return True if the operand is a qNaN or sNaN;
        otherwise return False.

        >>> ExtendedContext.is_nan(Decimal('2.50'))
        False
        >>> ExtendedContext.is_nan(Decimal('NaN'))
        True
        >>> ExtendedContext.is_nan(Decimal('-sNaN'))
        True
        >>> ExtendedContext.is_nan(1)
        False
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'is_nan)))))

    (define is_normal
      (lambda (self a)
        "Return True if the operand is a normal number;
        otherwise return False.

        >>> c = ExtendedContext.copy()
        >>> c.Emin = -999
        >>> c.Emax = 999
        >>> c.is_normal(Decimal('2.50'))
        True
        >>> c.is_normal(Decimal('0.1E-999'))
        False
        >>> c.is_normal(Decimal('0.00'))
        False
        >>> c.is_normal(Decimal('-Inf'))
        False
        >>> c.is_normal(Decimal('NaN'))
        False
        >>> c.is_normal(1)
        True
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'is_normal) #:context self))))
    
    (define is_qnan
      (lambda (self a)
        "Return True if the operand is a quiet NaN; otherwise return False.

        >>> ExtendedContext.is_qnan(Decimal('2.50'))
        False
        >>> ExtendedContext.is_qnan(Decimal('NaN'))
        True
        >>> ExtendedContext.is_qnan(Decimal('sNaN'))
        False
        >>> ExtendedContext.is_qnan(1)
        False
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'is_qnan)))))

    (define is_signed
      (lambda (self a)
        "Return True if the operand is negative; otherwise return False.

        >>> ExtendedContext.is_signed(Decimal('2.50'))
        False
        >>> ExtendedContext.is_signed(Decimal('-12'))
        True
        >>> ExtendedContext.is_signed(Decimal('-0'))
        True
        >>> ExtendedContext.is_signed(8)
        False
        >>> ExtendedContext.is_signed(-8)
        True
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'is_signed)))))

        
    (define is_snan
      (lambda (self a)
        "Return True if the operand is a signaling NaN;
        otherwise return False.

        >>> ExtendedContext.is_snan(Decimal('2.50'))
        False
        >>> ExtendedContext.is_snan(Decimal('NaN'))
        False
        >>> ExtendedContext.is_snan(Decimal('sNaN'))
        True
        >>> ExtendedContext.is_snan(1)
        False
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'is_snan)))))


    (define is_subnormal
      (lambda (self a)
	"Return True if the operand is subnormal; otherwise return False.

        >>> c = ExtendedContext.copy()
        >>> c.Emin = -999
        >>> c.Emax = 999
        >>> c.is_subnormal(Decimal('2.50'))
        False
        >>> c.is_subnormal(Decimal('0.1E-999'))
        True
        >>> c.is_subnormal(Decimal('0.00'))
        False
        >>> c.is_subnormal(Decimal('-Inf'))
        False
        >>> c.is_subnormal(Decimal('NaN'))
        False
        >>> c.is_subnormal(1)
        False
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'is_subnormal) #:context self))))

    (define is_zero
      (lambda (self a)
        "Return True if the operand is a zero; otherwise return False.

        >>> ExtendedContext.is_zero(Decimal('0'))
        True
        >>> ExtendedContext.is_zero(Decimal('2.50'))
        False
        >>> ExtendedContext.is_zero(Decimal('-0E+2'))
        True
        >>> ExtendedContext.is_zero(1)
        False
        >>> ExtendedContext.is_zero(0)
        True
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'is_zero)))))

    (define ln
      (lambda (self a)
        "Returns the natural (base e) logarithm of the operand.

        >>> c = ExtendedContext.copy()
        >>> c.Emin = -999
        >>> c.Emax = 999
        >>> c.ln(Decimal('0'))
        Decimal('-Infinity')
        >>> c.ln(Decimal('1.000'))
        Decimal('0')
        >>> c.ln(Decimal('2.71828183'))
        Decimal('1.00000000')
        >>> c.ln(Decimal('10'))
        Decimal('2.30258509')
        >>> c.ln(Decimal('+Infinity'))
        Decimal('Infinity')
        >>> c.ln(1)
        Decimal('0')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'ln) #:context self))))

    (define log10
      (lambda (self a)
        "Returns the base 10 logarithm of the operand.

        >>> c = ExtendedContext.copy()
        >>> c.Emin = -999
        >>> c.Emax = 999
        >>> c.log10(Decimal('0'))
        Decimal('-Infinity')
        >>> c.log10(Decimal('0.001'))
        Decimal('-3')
        >>> c.log10(Decimal('1.000'))
        Decimal('0')
        >>> c.log10(Decimal('2'))
        Decimal('0.301029996')
        >>> c.log10(Decimal('10'))
        Decimal('1')
        >>> c.log10(Decimal('70'))
        Decimal('1.84509804')
        >>> c.log10(Decimal('+Infinity'))
        Decimal('Infinity')
        >>> c.log10(0)
        Decimal('-Infinity')
        >>> c.log10(1)
        Decimal('0')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'log10) #:context self))))

    (define logb
      (lambda (self a)
        " Returns the exponent of the magnitude of the operand's MSD.

        The result is the integer which is the exponent of the magnitude
        of the most significant digit of the operand (as though the
        operand were truncated to a single digit while maintaining the
        value of that digit and without limiting the resulting exponent).

        >>> ExtendedContext.logb(Decimal('250'))
        Decimal('2')
        >>> ExtendedContext.logb(Decimal('2.50'))
        Decimal('0')
        >>> ExtendedContext.logb(Decimal('0.03'))
        Decimal('-2')
        >>> ExtendedContext.logb(Decimal('0'))
        Decimal('-Infinity')
        >>> ExtendedContext.logb(1)
        Decimal('0')
        >>> ExtendedContext.logb(10)
        Decimal('1')
        >>> ExtendedContext.logb(100)
        Decimal('2')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'logb) #:context self))))

    (define logical_and
      (lambda (self a b)
        "Applies the logical operation 'and' between each operand's digits.

        The operands must be both logical numbers.

        >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
        Decimal('0')
        >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
        Decimal('0')
        >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
        Decimal('0')
        >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
        Decimal('1')
        >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
        Decimal('1000')
        >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
        Decimal('10')
        >>> ExtendedContext.logical_and(110, 1101)
        Decimal('100')
        >>> ExtendedContext.logical_and(Decimal(110), 1101)
        Decimal('100')
        >>> ExtendedContext.logical_and(110, Decimal(1101))
        Decimal('100')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'logical_and) b #:context self))))

    (define logical_invert
      (lambda (self a)
        "Invert all the digits in the operand.

        The operand must be a logical number.

        >>> ExtendedContext.logical_invert(Decimal('0'))
        Decimal('111111111')
        >>> ExtendedContext.logical_invert(Decimal('1'))
        Decimal('111111110')
        >>> ExtendedContext.logical_invert(Decimal('111111111'))
        Decimal('0')
        >>> ExtendedContext.logical_invert(Decimal('101010101'))
        Decimal('10101010')
        >>> ExtendedContext.logical_invert(1101)
        Decimal('111110010')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'logical_invert) #:context self))))

    (define logical_or
      (lambda (self a b)
	"Applies the logical operation 'or' between each operand's digits.

        The operands must be both logical numbers.

        >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
        Decimal('0')
        >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
        Decimal('1')
        >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
        Decimal('1')
        >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
        Decimal('1')
        >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
        Decimal('1110')
        >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
        Decimal('1110')
        >>> ExtendedContext.logical_or(110, 1101)
        Decimal('1111')
        >>> ExtendedContext.logical_or(Decimal(110), 1101)
        Decimal('1111')
        >>> ExtendedContext.logical_or(110, Decimal(1101))
        Decimal('1111')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'logical_or) b #:context self))))
	
    (define logical_xor
      (lambda (self a b)
        "Applies the logical operation 'xor' between each operand's digits.

        The operands must be both logical numbers.

        >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
        Decimal('0')
        >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
        Decimal('1')
        >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
        Decimal('1')
        >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
        Decimal('0')
        >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
        Decimal('110')
        >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
        Decimal('1101')
        >>> ExtendedContext.logical_xor(110, 1101)
        Decimal('1011')
        >>> ExtendedContext.logical_xor(Decimal(110), 1101)
        Decimal('1011')
        >>> ExtendedContext.logical_xor(110, Decimal(1101))
        Decimal('1011')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'logical_xor) b #:context self))))
	
    (define max
      (lambda (self a b)
        "max compares two values numerically and returns the maximum.

        If either operand is a NaN then the general rules apply.
        Otherwise, the operands are compared as though by the compare
        operation.  If they are numerically equal then the left-hand operand
        is chosen as the result.  Otherwise the maximum (closer to positive
        infinity) of the two operands is chosen as the result.

        >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
        Decimal('3')
        >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
        Decimal('3')
        >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
        Decimal('1')
        >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
        Decimal('7')
        >>> ExtendedContext.max(1, 2)
        Decimal('2')
        >>> ExtendedContext.max(Decimal(1), 2)
        Decimal('2')
        >>> ExtendedContext.max(1, Decimal(2))
        Decimal('2')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'max) b #:context self))))
	
    (define max_mag
      (lambda (self a b)
        "Compares the values numerically with their sign ignored.

        >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
        Decimal('7')
        >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
        Decimal('-10')
        >>> ExtendedContext.max_mag(1, -2)
        Decimal('-2')
        >>> ExtendedContext.max_mag(Decimal(1), -2)
        Decimal('-2')
        >>> ExtendedContext.max_mag(1, Decimal(-2))
        Decimal('-2')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'max_mag) b #:context self))))
	
    (define min
      (lambda (self a b)
        "min compares two values numerically and returns the minimum.

        If either operand is a NaN then the general rules apply.
        Otherwise, the operands are compared as though by the compare
        operation.  If they are numerically equal then the left-hand operand
        is chosen as the result.  Otherwise the minimum (closer to negative
        infinity) of the two operands is chosen as the result.

        >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
        Decimal('2')
        >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
        Decimal('-10')
        >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
        Decimal('1.0')
        >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
        Decimal('7')
        >>> ExtendedContext.min(1, 2)
        Decimal('1')
        >>> ExtendedContext.min(Decimal(1), 2)
        Decimal('1')
        >>> ExtendedContext.min(1, Decimal(29))
        Decimal('1')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'min) b #:context self))))

    (define min_mag
      (lambda (self a b)
        "Compares the values numerically with their sign ignored.

        >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
        Decimal('-2')
        >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
        Decimal('-3')
        >>> ExtendedContext.min_mag(1, -2)
        Decimal('1')
        >>> ExtendedContext.min_mag(Decimal(1), -2)
        Decimal('1')
        >>> ExtendedContext.min_mag(1, Decimal(-2))
        Decimal('1')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'min_mag) b #:context self))))

    (define minus
      (lambda (self a)
        "Minus corresponds to unary prefix minus in Python.

        The operation is evaluated using the same rules as subtract; the
        operation minus(a) is calculated as subtract('0', a) where the '0'
        has the same exponent as the operand.

        >>> ExtendedContext.minus(Decimal('1.3'))
        Decimal('-1.3')
        >>> ExtendedContext.minus(Decimal('-1.3'))
        Decimal('1.3')
        >>> ExtendedContext.minus(1)
        Decimal('-1')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a '__neg__) #:context self))))

    (define multiply
      (lambda (self a b)
        "multiply multiplies two operands.

        If either operand is a special value then the general rules apply.
        Otherwise, the operands are multiplied together
        ('long multiplication'), resulting in a number which may be as long as
        the sum of the lengths of the two operands.

        >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
        Decimal('3.60')
        >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
        Decimal('21')
        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
        Decimal('0.72')
        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
        Decimal('-0.0')
        >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
        Decimal('4.28135971E+11')
        >>> ExtendedContext.multiply(7, 7)
        Decimal('49')
        >>> ExtendedContext.multiply(Decimal(7), 7)
        Decimal('49')
        >>> ExtendedContext.multiply(7, Decimal(7))
        Decimal('49')
        "
	(let* ((a (_convert_other a #:raiseit #t))
	       (r ((ref a '__mul__) b #:context self)))
	  (if (equal? r NotImplemented)
	      (raise (TypeError (format #t "Unable to convert ~a to Decimal" b)))
	      r))))

    (define next_minus
      (lambda (self a)
        "Returns the largest representable number smaller than a.

        >>> c = ExtendedContext.copy()
        >>> c.Emin = -999
        >>> c.Emax = 999
        >>> ExtendedContext.next_minus(Decimal('1'))
        Decimal('0.999999999')
        >>> c.next_minus(Decimal('1E-1007'))
        Decimal('0E-1007')
        >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
        Decimal('-1.00000004')
        >>> c.next_minus(Decimal('Infinity'))
        Decimal('9.99999999E+999')
        >>> c.next_minus(1)
        Decimal('0.999999999')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'next_minus) #:context self))))

    (define next_plus
      (lambda (self a)
        "Returns the smallest representable number larger than a.

        >>> c = ExtendedContext.copy()
        >>> c.Emin = -999
        >>> c.Emax = 999
        >>> ExtendedContext.next_plus(Decimal('1'))
        Decimal('1.00000001')
        >>> c.next_plus(Decimal('-1E-1007'))
        Decimal('-0E-1007')
        >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
        Decimal('-1.00000002')
        >>> c.next_plus(Decimal('-Infinity'))
        Decimal('-9.99999999E+999')
        >>> c.next_plus(1)
        Decimal('1.00000001')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'next_plus) #:context self))))
    
    (define next_toward
      (lambda (self a b)
        "Returns the number closest to a, in direction towards b.

        The result is the closest representable number from the first
        operand (but not the first operand) that is in the direction
        towards the second operand, unless the operands have the same
        value.

        >>> c = ExtendedContext.copy()
        >>> c.Emin = -999
        >>> c.Emax = 999
        >>> c.next_toward(Decimal('1'), Decimal('2'))
        Decimal('1.00000001')
        >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
        Decimal('-0E-1007')
        >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
        Decimal('-1.00000002')
        >>> c.next_toward(Decimal('1'), Decimal('0'))
        Decimal('0.999999999')
        >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
        Decimal('0E-1007')
        >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
        Decimal('-1.00000004')
        >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
        Decimal('-0.00')
        >>> c.next_toward(0, 1)
        Decimal('1E-1007')
        >>> c.next_toward(Decimal(0), 1)
        Decimal('1E-1007')
        >>> c.next_toward(0, Decimal(1))
        Decimal('1E-1007')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'next_toward) b #:context self))))

    (define normalize
      (lambda (self a)
        "normalize reduces an operand to its simplest form.

        Essentially a plus operation with all trailing zeros removed from the
        result.

        >>> ExtendedContext.normalize(Decimal('2.1'))
        Decimal('2.1')
        >>> ExtendedContext.normalize(Decimal('-2.0'))
        Decimal('-2')
        >>> ExtendedContext.normalize(Decimal('1.200'))
        Decimal('1.2')
        >>> ExtendedContext.normalize(Decimal('-120'))
        Decimal('-1.2E+2')
        >>> ExtendedContext.normalize(Decimal('120.00'))
        Decimal('1.2E+2')
        >>> ExtendedContext.normalize(Decimal('0.00'))
        Decimal('0')
        >>> ExtendedContext.normalize(6)
        Decimal('6')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'normalize) #:context self))))

    (define number_class
      (lambda (self a)
        "Returns an indication of the class of the operand.

        The class is one of the following strings:
          -sNaN
          -NaN
          -Infinity
          -Normal
          -Subnormal
          -Zero
          +Zero
          +Subnormal
          +Normal
          +Infinity

        >>> c = ExtendedContext.copy()
        >>> c.Emin = -999
        >>> c.Emax = 999
        >>> c.number_class(Decimal('Infinity'))
        '+Infinity'
        >>> c.number_class(Decimal('1E-10'))
        '+Normal'
        >>> c.number_class(Decimal('2.50'))
        '+Normal'
        >>> c.number_class(Decimal('0.1E-999'))
        '+Subnormal'
        >>> c.number_class(Decimal('0'))
        '+Zero'
        >>> c.number_class(Decimal('-0'))
        '-Zero'
        >>> c.number_class(Decimal('-0.1E-999'))
        '-Subnormal'
        >>> c.number_class(Decimal('-1E-10'))
        '-Normal'
        >>> c.number_class(Decimal('-2.50'))
        '-Normal'
        >>> c.number_class(Decimal('-Infinity'))
        '-Infinity'
        >>> c.number_class(Decimal('NaN'))
        'NaN'
        >>> c.number_class(Decimal('-NaN'))
        'NaN'
        >>> c.number_class(Decimal('sNaN'))
        'sNaN'
        >>> c.number_class(123)
        '+Normal'
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'number_class) #:context self))))

    (define plus
      (lambda (self a)
        "Plus corresponds to unary prefix plus in Python.

        The operation is evaluated using the same rules as add; the
        operation plus(a) is calculated as add('0', a) where the '0'
        has the same exponent as the operand.

        >>> ExtendedContext.plus(Decimal('1.3'))
        Decimal('1.3')
        >>> ExtendedContext.plus(Decimal('-1.3'))
        Decimal('-1.3')
        >>> ExtendedContext.plus(-1)
        Decimal('-1')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a '__pos__) #:context self))))

    (define power
      (lam (self a b (= modulo None))
        "Raises a to the power of b, to modulo if given.

        With two arguments, compute a**b.  If a is negative then b
        must be integral.  The result will be inexact unless b is
        integral and the result is finite and can be expressed exactly
        in 'precision' digits.

        With three arguments, compute (a**b) % modulo.  For the
        three argument form, the following restrictions on the
        arguments hold:

         - all three arguments must be integral
         - b must be nonnegative
         - at least one of a or b must be nonzero
         - modulo must be nonzero and have at most 'precision' digits

        The result of pow(a, b, modulo) is identical to the result
        that would be obtained by computing (a**b) % modulo with
        unbounded precision, but is computed more efficiently.  It is
        always exact.

        >>> c = ExtendedContext.copy()
        >>> c.Emin = -999
        >>> c.Emax = 999
        >>> c.power(Decimal('2'), Decimal('3'))
        Decimal('8')
        >>> c.power(Decimal('-2'), Decimal('3'))
        Decimal('-8')
        >>> c.power(Decimal('2'), Decimal('-3'))
        Decimal('0.125')
        >>> c.power(Decimal('1.7'), Decimal('8'))
        Decimal('69.7575744')
        >>> c.power(Decimal('10'), Decimal('0.301029996'))
        Decimal('2.00000000')
        >>> c.power(Decimal('Infinity'), Decimal('-1'))
        Decimal('0')
        >>> c.power(Decimal('Infinity'), Decimal('0'))
        Decimal('1')
        >>> c.power(Decimal('Infinity'), Decimal('1'))
        Decimal('Infinity')
        >>> c.power(Decimal('-Infinity'), Decimal('-1'))
        Decimal('-0')
        >>> c.power(Decimal('-Infinity'), Decimal('0'))
        Decimal('1')
        >>> c.power(Decimal('-Infinity'), Decimal('1'))
        Decimal('-Infinity')
        >>> c.power(Decimal('-Infinity'), Decimal('2'))
        Decimal('Infinity')
        >>> c.power(Decimal('0'), Decimal('0'))
        Decimal('NaN')

        >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
        Decimal('11')
        >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
        Decimal('-11')
        >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
        Decimal('1')
        >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
        Decimal('11')
        >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
        Decimal('11729830')
        >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
        Decimal('-0')
        >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
        Decimal('1')
        >>> ExtendedContext.power(7, 7)
        Decimal('823543')
        >>> ExtendedContext.power(Decimal(7), 7)
        Decimal('823543')
        >>> ExtendedContext.power(7, Decimal(7), 2)
        Decimal('1')
        "
	(let* ((a (_convert_other a #:raiseit #t))
	       (r ((ref a '__pow__) b modulo #:context self)))
	  (if (equal? r NotImplemented)
	      (raise (TypeError (format #t "Unable to convert ~a to Decimal" b)))
	      r))))

    (define quantize
      (lambda (self a b)
        "Returns a value equal to 'a' (rounded), having the exponent of 'b'.

        The coefficient of the result is derived from that of the left-hand
        operand.  It may be rounded using the current rounding setting (if the
        exponent is being increased), multiplied by a positive power of ten (if
        the exponent is being decreased), or is unchanged (if the exponent is
        already equal to that of the right-hand operand).

        Unlike other operations, if the length of the coefficient after the
        quantize operation would be greater than precision then an Invalid
        operation condition is raised.  This guarantees that, unless there is
        an error condition, the exponent of the result of a quantize is always
        equal to that of the right-hand operand.

        Also unlike other operations, quantize will never raise Underflow, even
        if the result is subnormal and inexact.

        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
        Decimal('2.170')
        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
        Decimal('2.17')
        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
        Decimal('2.2')
        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
        Decimal('2')
        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
        Decimal('0E+1')
        >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
        Decimal('-Infinity')
        >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
        Decimal('NaN')
        >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
        Decimal('-0')
        >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
        Decimal('-0E+5')
        >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
        Decimal('NaN')
        >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
        Decimal('NaN')
        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
        Decimal('217.0')
        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
        Decimal('217')
        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
        Decimal('2.2E+2')
        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
        Decimal('2E+2')
        >>> ExtendedContext.quantize(1, 2)
        Decimal('1')
        >>> ExtendedContext.quantize(Decimal(1), 2)
        Decimal('1')
        >>> ExtendedContext.quantize(1, Decimal(2))
        Decimal('1')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'quantize) b #:context self))))

    (define radix
      (lambda (self)
        "Just returns 10, as this is Decimal, :)

        >>> ExtendedContext.radix()
        Decimal('10')
        "
        (Decimal 10)))

    (define remainder
      (lambda (self a b)
        "Returns the remainder from integer division.

        The result is the residue of the dividend after the operation of
        calculating integer division as described for divide-integer, rounded
        to precision digits if necessary.  The sign of the result, if
        non-zero, is the same as that of the original dividend.

        This operation will fail under the same conditions as integer division
        (that is, if integer division on the same two operands would fail, the
        remainder cannot be calculated).

        >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
        Decimal('2.1')
        >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
        Decimal('1')
        >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
        Decimal('-1')
        >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
        Decimal('0.2')
        >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
        Decimal('0.1')
        >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
        Decimal('1.0')
        >>> ExtendedContext.remainder(22, 6)
        Decimal('4')
        >>> ExtendedContext.remainder(Decimal(22), 6)
        Decimal('4')
        >>> ExtendedContext.remainder(22, Decimal(6))
        Decimal('4')
        "
	(let* ((a (_convert_other a #:raiseit #t))
	       (r ((ref a '__mod__) b #:context self)))
	  (if (equal? r NotImplemented)
	      (raise (TypeError (format #t "Unable to convert ~a to Decimal" b)))
	      r))))

    (define remainder_near
      (lambda (self a b)
        "Returns to be 'a - b * n', where n is the integer nearest the exact
        value of "x / b" (if two integers are equally near then the even one
        is chosen).  If the result is equal to 0 then its sign will be the
        sign of a.

        This operation will fail under the same conditions as integer division
        (that is, if integer division on the same two operands would fail, the
        remainder cannot be calculated).

        >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
        Decimal('-0.9')
        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
        Decimal('-2')
        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
        Decimal('1')
        >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
        Decimal('-1')
        >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
        Decimal('0.2')
        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
        Decimal('0.1')
        >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
        Decimal('-0.3')
        >>> ExtendedContext.remainder_near(3, 11)
        Decimal('3')
        >>> ExtendedContext.remainder_near(Decimal(3), 11)
        Decimal('3')
        >>> ExtendedContext.remainder_near(3, Decimal(11))
        Decimal('3')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'remainder_near) b #:context self))))

    (define rotate
      (lambda (self a b)
        "Returns a rotated copy of a, b times.

        The coefficient of the result is a rotated copy of the digits in
        the coefficient of the first operand.  The number of places of
        rotation is taken from the absolute value of the second operand,
        with the rotation being to the left if the second operand is
        positive or to the right otherwise.

        >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
        Decimal('400000003')
        >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
        Decimal('12')
        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
        Decimal('891234567')
        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
        Decimal('123456789')
        >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
        Decimal('345678912')
        >>> ExtendedContext.rotate(1333333, 1)
        Decimal('13333330')
        >>> ExtendedContext.rotate(Decimal(1333333), 1)
        Decimal('13333330')
        >>> ExtendedContext.rotate(1333333, Decimal(1))
        Decimal('13333330')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'rotate) b #:context self))))

    (define same_quantum
      (lambda (self a b)
        "Returns True if the two operands have the same exponent.

        The result is never affected by either the sign or the coefficient of
        either operand.

        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
        False
        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
        True
        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
        False
        >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
        True
        >>> ExtendedContext.same_quantum(10000, -1)
        True
        >>> ExtendedContext.same_quantum(Decimal(10000), -1)
        True
        >>> ExtendedContext.same_quantum(10000, Decimal(-1))
        True
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'same_quantum) b #:context self))))

    (define scaleb
      (lambda (self a b)
        "Returns the first operand after adding the second value its exp.

        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
        Decimal('0.0750')
        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
        Decimal('7.50')
        >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
        Decimal('7.50E+3')
        >>> ExtendedContext.scaleb(1, 4)
        Decimal('1E+4')
        >>> ExtendedContext.scaleb(Decimal(1), 4)
        Decimal('1E+4')
        >>> ExtendedContext.scaleb(1, Decimal(4))
        Decimal('1E+4')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'scaleb) b #:context self))))

    (define shift
      (lambda (self a b)
        "Returns a shifted copy of a, b times.

        The coefficient of the result is a shifted copy of the digits
        in the coefficient of the first operand.  The number of places
        to shift is taken from the absolute value of the second operand,
        with the shift being to the left if the second operand is
        positive or to the right otherwise.  Digits shifted into the
        coefficient are zeros.

        >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
        Decimal('400000000')
        >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
        Decimal('0')
        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
        Decimal('1234567')
        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
        Decimal('123456789')
        >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
        Decimal('345678900')
        >>> ExtendedContext.shift(88888888, 2)
        Decimal('888888800')
        >>> ExtendedContext.shift(Decimal(88888888), 2)
        Decimal('888888800')
        >>> ExtendedContext.shift(88888888, Decimal(2))
        Decimal('888888800')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'shift) b #:context self))))

    (define sqrt
      (lambda (self a)
        "Square root of a non-negative number to context precision.

        If the result must be inexact, it is rounded using the round-half-even
        algorithm.

        >>> ExtendedContext.sqrt(Decimal('0'))
        Decimal('0')
        >>> ExtendedContext.sqrt(Decimal('-0'))
        Decimal('-0')
        >>> ExtendedContext.sqrt(Decimal('0.39'))
        Decimal('0.624499800')
        >>> ExtendedContext.sqrt(Decimal('100'))
        Decimal('10')
        >>> ExtendedContext.sqrt(Decimal('1'))
        Decimal('1')
        >>> ExtendedContext.sqrt(Decimal('1.0'))
        Decimal('1.0')
        >>> ExtendedContext.sqrt(Decimal('1.00'))
        Decimal('1.0')
        >>> ExtendedContext.sqrt(Decimal('7'))
        Decimal('2.64575131')
        >>> ExtendedContext.sqrt(Decimal('10'))
        Decimal('3.16227766')
        >>> ExtendedContext.sqrt(2)
        Decimal('1.41421356')
        >>> ExtendedContext.prec
        9
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'sqrt) #:context self))))

    (define subtract
      (lambda (self a b)
        "Return the difference between the two operands.

        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
        Decimal('0.23')
        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
        Decimal('0.00')
        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
        Decimal('-0.77')
        >>> ExtendedContext.subtract(8, 5)
        Decimal('3')
        >>> ExtendedContext.subtract(Decimal(8), 5)
        Decimal('3')
        >>> ExtendedContext.subtract(8, Decimal(5))
        Decimal('3')
        "
	(let* ((a (_convert_other a #:raiseit #t))
	       (r ((ref a '__sub__) b #:context self)))
	  (if (equal? r NotImplemented)
	      (raise (TypeError (format #t "Unable to convert ~a to Decimal" b)))
	      r))))

    (define to_eng_string
      (lambda (self a)
        "Convert to a string, using engineering notation if an exponent is needed.

        Engineering notation has an exponent which is a multiple of 3.  This
        can leave up to 3 digits to the left of the decimal place and may
        require the addition of either one or two trailing zeros.

        The operation is not affected by the context.

        >>> ExtendedContext.to_eng_string(Decimal('123E+1'))
        '1.23E+3'
        >>> ExtendedContext.to_eng_string(Decimal('123E+3'))
        '123E+3'
        >>> ExtendedContext.to_eng_string(Decimal('123E-10'))
        '12.3E-9'
        >>> ExtendedContext.to_eng_string(Decimal('-123E-12'))
        '-123E-12'
        >>> ExtendedContext.to_eng_string(Decimal('7E-7'))
        '700E-9'
        >>> ExtendedContext.to_eng_string(Decimal('7E+1'))
        '70'
        >>> ExtendedContext.to_eng_string(Decimal('0E+1'))
        '0.00E+3'

        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'to_eng_string) #:context self))))

    (define to_sci_string
      (lambda (self a)
        "Converts a number to a string, using scientific notation.

        The operation is not affected by the context.
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a '__str__) #:context self))))

    (define to_integral_exact
      (lambda (self a)
        "Rounds to an integer.

        When the operand has a negative exponent, the result is the same
        as using the quantize() operation using the given operand as the
        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
        of the operand as the precision setting; Inexact and Rounded flags
        are allowed in this operation.  The rounding mode is taken from the
        context.

        >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
        Decimal('2')
        >>> ExtendedContext.to_integral_exact(Decimal('100'))
        Decimal('100')
        >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
        Decimal('100')
        >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
        Decimal('102')
        >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
        Decimal('-102')
        >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
        Decimal('1.0E+6')
        >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
        Decimal('7.89E+77')
        >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
        Decimal('-Infinity')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'to_integral_exact) #:context self))))

    (define to_integral_value
      (lambda (self a)
        "Rounds to an integer.

        When the operand has a negative exponent, the result is the same
        as using the quantize() operation using the given operand as the
        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
        of the operand as the precision setting, except that no flags will
        be set.  The rounding mode is taken from the context.

        >>> ExtendedContext.to_integral_value(Decimal('2.1'))
        Decimal('2')
        >>> ExtendedContext.to_integral_value(Decimal('100'))
        Decimal('100')
        >>> ExtendedContext.to_integral_value(Decimal('100.0'))
        Decimal('100')
        >>> ExtendedContext.to_integral_value(Decimal('101.5'))
        Decimal('102')
        >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
        Decimal('-102')
        >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
        Decimal('1.0E+6')
        >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
        Decimal('7.89E+77')
        >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
        Decimal('-Infinity')
        "
	(let* ((a (_convert_other a #:raiseit #t)))
	  ((ref a 'to_integral_value) #:context self))))

    ;; the method name changed, but we provide also the old one, for compatibility
    (define to_integral to_integral_value))

(define-python-class _WorkRep ()
  (define __init__
    (lam (self (= value None))
	 (cond
	  ((eq? value None)
	   (set self 'sign None)
	   (set self 'int  0)
	   (set self 'exp  None))
	  ((isinstance value Decimal)
	   (set self 'sign  (ref value '_sign))
	   (set self 'int   (int (ref value '_int)))
	   (set self 'exp   (ref value '_exp)))
	  (else
	   ;; assert isinstance(value, tuple)
	   (set self 'sign (pylist-ref value 0))
	   (set self 'int  (pylist-ref value 1))
	   (set self 'exp  (pylist-ref value 2))))))
  
  (define __repr__
    (lambda (self)
        (format "(~a, ~a, ~a)" (ref self 'sign) (ref self 'int) (ref self 'exp))))

  (define __str__  __repr__))



(define _normalize
  (lam (op1 op2 (= prec 0))
    "Normalizes op1, op2 to have the same exp and length of coefficient.

    Done during addition.
    "
    (call-with-values
	(lambda ()
	  (if (< (ref op1 'exp) (ref op2 'exp))
	      (values op2 op1)
	      (values op1 op2)))
      (lambda (tmp other)
	;; Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
	;; Then adding 10**exp to tmp has the same effect (after rounding)
	;; as adding any positive quantity smaller than 10**exp; similarly
	;; for subtraction.  So if other is smaller than 10**exp we replace
	;; it with 10**exp.  This avoids tmp.exp - other.exp getting too large.
	(let* ((tmp_len   (len (str (ref tmp   'int))))
	       (other_len (len (str (ref other 'int))))
	       (exp       (+ (ref tmp 'exp)
			     (min -1  (- tmp_len prec 2)))))
	  (when (< (+ other_len (ref other 'exp) -1) exp)
	    (set other 'int 1)
	    (set other 'exp exp))

	  (set tmp 'int (* (ref tmp 'int) (expt 10 (- (ref tmp 'exp) (ref other 'exp)))))
	  (set tmp 'exp (ref other 'exp))
	  (values op1 op2))))))


;;##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####

(define _nbits (ref int 'bit_length))

(define _decimal_lshift_exact
  (lambda (n e)
    " Given integers n and e, return n * 10**e if it's an integer, else None.

    The computation is designed to avoid computing large powers of 10
    unnecessarily.

    >>> _decimal_lshift_exact(3, 4)
    30000
    >>> _decimal_lshift_exact(300, -999999999)  # returns None

    "
    (cond
     ((= n 0)
      0)
     ((>= e 0)
      (* n (expt 10 e)))
     (else
      ;; val_n = largest power of 10 dividing n.
      (let* ((str_n (str (abs n)))
	     (val_n (- (len str_n) (len ((ref str_n 'rstrip) "0")))))
	(if (< val_n (- e))
	    None
	    (floor-quotient n (expt 10 (- e)))))))))

(define _sqrt_nearest
  (lambda (n a)
    "Closest integer to the square root of the positive integer n.  a is
    an initial approximation to the square root.  Any positive integer
    will do for a, but the closer a is to the square root of n the
    faster convergence will be.

    "
    (if (or (<= n 0) (<= a 0))
        (raise (ValueError "Both arguments to _sqrt_nearest should be positive.")))

    (let lp ((b 0) (a a))
      (if (not (= a b))
	  (lp a (ash (- a (floor-quotient (- n) a)) -1))
	  a))))

(define _rshift_nearest
  (lambda (x shift)
    "Given an integer x and a nonnegative integer shift, return closest
    integer to x / 2**shift; use round-to-even in case of a tie.

    "
    (let ((b (ash 1 shift))
	  (q (ash x (- shift))))
      (+ q (if (> (+ (* 2 (logand x (- b 1))) (logand  q 1)) b) 1 0)))))

(define _div_nearest
  (lambda (a b)
    "Closest integer to a/b, a and b positive integers; rounds to even
    in the case of a tie.

    "
    (call-with-values (lambda () (py-divmod a b))
      (lambda (q r)
	(+ q  (if (> (+ (* 2 r) (logand q 1)) b) 1 0))))))

(define _ilog
  (lambda (x M (= L 8))
    "Integer approximation to M*log(x/M), with absolute error boundable
    in terms only of x/M.

    Given positive integers x and M, return an integer approximation to
    M * log(x/M).  For L = 8 and 0.1 <= x/M <= 10 the difference
    between the approximation and the exact result is at most 22.  For
    L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15.  In
    both cases these are upper bounds on the error; it will usually be
    much smaller."

    ;; The basic algorithm is the following: let log1p be the function
    ;; log1p(x) = log(1+x).  Then log(x/M) = log1p((x-M)/M).  We use
    ;; the reduction
    ;;
    ;;    log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
    ;;
    ;; repeatedly until the argument to log1p is small (< 2**-L in
    ;; absolute value).  For small y we can use the Taylor series
    ;; expansion
    ;;
    ;;    log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
    ;;
    ;; truncating at T such that y**T is small enough.  The whole
    ;; computation is carried out in a form of fixed-point arithmetic,
    ;; with a real number z being represented by an integer
    ;; approximation to z*M.  To avoid loss of precision, the y below
    ;; is actually an integer approximation to 2**R*y*M, where R is the
    ;; number of reductions performed so far.

    ;; argument reduction; R = number of reductions performed
    (call-with-values
	(lambda ()
	  (let lp ((y (- x M)) (R 0))
	    (if (>= (ash (abs y) (- L R)) M)
		(values
		 (_div_nearest (ash (* M y) 1)
			       (+ M (_sqrt_nearest (* M (+ M (_rshift_nearest y R))) M)))
		 (+ R 1))
		(values y R))))
      (lambda (y R)
	;; Taylor series with T terms
	(let* ((T      (- (int (* -10 (floor-quotient (len (str M)) (* 3 L))))))
	       (yshift (_rshift_nearest y R))
	       (w      (_div_nearest M T)))
	  (for ((k : (range (- T 1) 0 -1))) ((w w))
	       (- (_div_nearest M k) (_div_nearest (* yshift w M)))
	       #:final
	       (_div_nearest (* w y) M)))))))

(define _dlog10
  (lambda (c e p)
    "Given integers c, e and p with c > 0, p >= 0, compute an integer
    approximation to 10**p * log10(c*10**e), with an absolute error of
    at most 1.  Assumes that c*10**e is not exactly 1."

    ;; increase precision by 2; compensate for this by dividing
    ;; final result by 100
    (set! p (+ p 2))

    ;; write c*10**e as d*10**f with either:
    ;;   f >= 0 and 1 <= d <= 10, or
    ;;   f <= 0 and 0.1 <= d <= 1.
    ;; Thus for c*10**e close to 1, f = 0
    (call-with-values
	(lambda ()
	  (let* ((l (len (str c)))
		 (f (- (+ e l) (if (>= (+ e l) 1) 1 0))))	    
	    (if (> p 0)
		(let* ((M      (expt 10 p))
		       (k      (- (+ e p) f))
		       (c      (if (>= k 0)
				   (* c (expt 10 k))
				   (_div_nearest c  (expt 10 (- k)))))
		       (log_d  (_ilog c M))        ;; error < 5 + 22 = 27
		       (log_10 (_log10_digits p))) ;; error < 1
		  (values (_div_nearest (* log_d M) log_10)
			  (* f M))) ;; exact
		(values 0  ;; error < 2.31
			(_div_nearest f  (expt 10 (- p))))))) ;; error < 0.5
      (lambda (log_d log_tenpower)
	(_div_nearest (+ log_tenpower log_d) 100)))))

(define _dlog
  (lambda (c e p)
    "Given integers c, e and p with c > 0, compute an integer
    approximation to 10**p * log(c*10**e), with an absolute error of
    at most 1.  Assumes that c*10**e is not exactly 1."

    ;; Increase precision by 2. The precision increase is compensated
    ;; for at the end with a division by 100.
    (set! p (+ p 2))

    ;; rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
    ;; or f <= 0 and 0.1 <= d <= 1.  Then we can compute 10**p * log(c*10**e)
    ;; as 10**p * log(d) + 10**p*f * log(10).
    (let* ((l (len (str c)))
	   (f (- (+ e l) (if (>= (+ e l) 1) 1 0))))

      ;; compute approximation to 10**p*log(d), with error < 27
      (call-with-values
	  (lambda ()
	    (if (> p 0)
		(let* ((k (- (+ e p) f))
		       (c (if (>= k 0)
			      (* c (expt 10 k))
			      (_div_nearest c (expt 10 (- k))))))  ; error of <= 0.5 in c

		  ;; _ilog magnifies existing error in c by a factor of at most 10
		  (_ilog c, (expt 10 p))) ; error < 5 + 22 = 27
		;; p <= 0: just approximate the whole thing by 0; error < 2.31
		0))
	(lambda (log_d)
	  (call-with-values
	      (lambda ()
		;; compute approximation to f*10**p*log(10), with error < 11.
		(if (not (= f 0))
		    (let ((extra (- (len (str (abs f))) 1)))
		      (if (>= (+ p extra) 0)
			  ;; error in f * _log10_digits(p+extra) < |f| * 1 = |f|
			  ;; after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
			  (_div_nearest (* f (_log10_digits (+ p extra))) (expt 10 extra))
			  0))
		    0))
	    (lambda (f_log_ten)
	      ;; error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
	      (_div_nearest (+ f_log_ten log_d) 100))))))))

(define-python-class _Log10Memoize ()
    "Class to compute, store, and allow retrieval of, digits of the
    constant log(10) = 2.302585....  This constant is needed by
    Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."
    
    (define __init__
      (lambda (self)
        (set self 'digits "23025850929940456840179914546843642076011014886")))

    (define getdigits
      (lambda (self p)
        "Given an integer p >= 0, return floor(10**p)*log(10).

        For example, self.getdigits(3) returns 2302.
        "
        ;; digits are stored as a string, for quick conversion to
        ;; integer in the case that we've already computed enough
        ;; digits; the stored digits should always be correct
        ;; (truncated, not rounded to nearest).
        (if (< p 0) (raise (ValueError "p should be nonnegative")))

        (if (>= p (len (ref self 'digits)))
            ;; compute p+3, p+6, p+9, ... digits; continue until at
            ;; least one of the extra digits is nonzero
	    (begin
	      (let lp ((extra 3))
		;; compute p+extra digits, correct to within 1ulp
		(let* ((M       (expt 10 (+ p extra 2)))
		       (digits  (str (_div_nearest (_ilog (* 10 M), M) 100))))
		  (if (not (equal? (pylist-slice digits (- extra) None None)
				   (* '0' extra)))
		      #t
		      (lp (+ extra  3))))))
	    ;; keep all reliable digits so far; remove trailing zeros
	    ;; and next nonzero digit
	    (set self 'digits (pylist-slice ((ref digits 'rstrip) "0") None -1 None)))
	
        (int (pylist-slice (ref self 'digits) None (+ p 1) None)))))

(define _log10_digits (ref (_Log10Memoize) 'getdigits))

(define _iexp
  (lam (x M (= L 8))
    "Given integers x and M, M > 0, such that x/M is small in absolute
    value, compute an integer approximation to M*exp(x/M).  For 0 <=
    x/M <= 2.4, the absolute error in the result is bounded by 60 (and
    is usually much smaller)."

    ;; Algorithm: to compute exp(z) for a real number z, first divide z
    ;; by a suitable power R of 2 so that |z/2**R| < 2**-L.  Then
    ;; compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
    ;; series
    ;;
    ;;     expm1(x) = x + x**2/2! + x**3/3! + ...
    ;;
    ;; Now use the identity
    ;;
    ;;     expm1(2x) = expm1(x)*(expm1(x)+2)
    ;;
    ;; R times to compute the sequence expm1(z/2**R),
    ;; expm1(z/2**(R-1)), ... , exp(z/2), exp(z).

    ;; Find R such that x/2**R/M <= 2**-L
    (let ((R (_nbits (floor-quotient (ash x L) M))))
      ;; Taylor series.  (2**L)**T > M
      (let* ((T  (- (int (floor-quotient (* -10 (len( strM))) (* 3 L)))))
	     (y1 (let ((Mshift (ash M R)))
		   (for ((i : (range (- T1) 0 -1))) ((y (_div_nearest x T)))
			(_div_nearest (* x (+ Mshift y)) (* Mshift i))
			#:final y)))
				   

	     ;; Expansion
	     (y2 (for ((k : (range (- R 1) -1 -1))) ((y y1))
		      (let ((Mshift (ash M (+ k 2))))
			(_div_nearest (* y (+ y Mshift)) Mshift))
		      #:final y)))

	(+ M y2)))))

(define _dexp
  (lambda (c e p)
    "Compute an approximation to exp(c*10**e), with p decimal places of
    precision.

    Returns integers d, f such that:

      10**(p-1) <= d <= 10**p, and
      (d-1)*10**f < exp(c*10**e) < (d+1)*10**f

    In other words, d*10**f is an approximation to exp(c*10**e) with p
    digits of precision, and with an error in d of at most 1.  This is
    almost, but not quite, the same as the error being < 1ulp: when d
    = 10**(p-1) the error could be up to 10 ulp."

    ;; we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
    (set! p (+ p 2))

    ;; compute log(10) with extra precision = adjusted exponent of c*10**e
    (let* ((extra (max 0 (+ e (len (str c)) -1)))
	   (q     (+ p extra)))

      ;; compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
      ;; rounding down
      (let* ((shift  (+ e q))
	     (cshift (if (>= shift 0)
			 (* c (expt 10 shift))
			 (floor-quotient c (expt 10 (- shift))))))
	(call-with-values
	    (lambda ()
	      (divmod cshift (_log10_digits q)))
	  (lambda (quot rem)
	    ;; reduce remainder back to original precision
	    (set! rem (_div_nearest rem (expt 10 extra)))

	    ;; error in result of _iexp < 120;  error after division < 0.62
	    (values (_div_nearest (_iexp rem (expt 10 p)) 1000)
		    (+ quot (- p) 3))))))))

(define _dpower
  (lambda (xc xe yc ye p)
    "Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
    y = yc*10**ye, compute x**y.  Returns a pair of integers (c, e) such that:

      10**(p-1) <= c <= 10**p, and
      (c-1)*10**e < x**y < (c+1)*10**e

    in other words, c*10**e is an approximation to x**y with p digits
    of precision, and with an error in c of at most 1.  (This is
    almost, but not quite, the same as the error being < 1ulp: when c
    == 10**(p-1) we can only guarantee error < 10ulp.)

    We assume that: x is positive and not equal to 1, and y is nonzero.
    "

    (let*
	;; Find b such that 10**(b-1) <= |y| <= 10**b
	((b   (+ (len (str (abs yc))) ye))

	 ;; log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
	 (lxc (_dlog xc xe (+ p b 1)))

	 ;; compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
	 (shift (- ye b))
	 (ps    (if (>= shift 0)
		    (* lxc yc (expt 10 shift))
		    (_div_nearest (* lxc yc) (expt 10 (- shift))))))

      (if (= pc 0)
	  ;; we prefer a result that isn't exactly 1; this makes it
	  ;; easier to compute a correctly rounded result in __pow__
	  (if (eq? (>= (+ (len (str xc)) xe) 1)
		   (>  yc 0)) ; if x**y > 1:
	      (values (+ (expt 10 (- p1)) 1) (- 1 p))
	      (values (- (expt 10 p) 1) (- p)))
	  (call-with-values
	      (lambda ()
		(_dexp pc (- (+ p1)) (+ p 1)))
	    (lambda (coeff exp)
	      (values (_div_nearest coeff 10)
		      (+ exp 1))))))))

(define _corr (dict '(("1" . 100) ("2" . 70) ("3" . 53) ("4" . 40) ("5" . 31)
		      ("6" . 23 ) ("7" . 16) ("8" . 10) ("9" . 5))))
(define _log10_lb
  (lam (c (= correction _corr))
       "Compute a lower bound for 100*log10(c) for a positive integer c."
    (if (<= c 0)
        (raise (ValueError "The argument to _log10_lb should be nonnegative.")))
    (let ((str_c (str c)))
      (- (* 100 (len str_c) (pylist-ref correction (pylist-ref str_c 0)))))))

;;#### Helper Functions ####################################################

(define _convert_other
  (lam (other (= raiseit #f) (= allow_float #f))
    "Convert other to Decimal.

    Verifies that it's ok to use in an implicit construction.
    If allow_float is true, allow conversion from float;  this
    is used in the comparison methods (__eq__ and friends).

    "
    (cond
     ((isinstance other  Decimal)
      other)
     ((isinstance other int)
      (Decimal other))
     ((and allow_float (isinstance other float))
      ((ref Decimal 'from_float) other))
     (raiseit
      (raise (TypeError (format #f "Unable to convert  ~a to Decimal" other))))
     (else
      NotImplemented))))

(define _convert_for_comparison
  (lam (self other (= equality_op #f))
    "Given a Decimal instance self and a Python object other, return
    a pair (s, o) of Decimal instances such that 's op o' is
    equivalent to 'self op other' for any of the 6 comparison
    operators 'op'.

    "
    (cond
     ((isinstance other Decimal)
      (values self other))

     ;; Comparison with a Rational instance (also includes integers):
     ;; self op n/d <=> self*d op n (for n and d integers, d positive).
     ;; A NaN or infinity can be left unchanged without affecting the
     ;; comparison result.
     ((isinstance other (ref _numbers Rational))
      (if (not (bool (ref self '_is_special)))
          (values
	   (_dec_from_triple (ref self '_sign)
			     (* (str int (ref self '_int)) (ref other 'denominator))
			     (ref self '_exp))
	   (Decimal (ref other 'numerator)))
	  (values NotImplemented NotImplemented)))
	  
     ;; Comparisons with float and complex types.  == and != comparisons
     ;; with complex numbers should succeed, returning either True or False
     ;; as appropriate.  Other comparisons return NotImplemented.
     (else
      (let ((other (if (and equality_op
			    (isinstance other  (ref_numbers 'Complex))
			    (= (ref other 'imag) 0))
		       (ref other 'real)
		       other)))
	(if (isinstance other float)
	    (let ((context (getcontext)))
	      (if equality_op
		  (pylist-set! (ref context 'flags) FloatOperation 1)
		  (ctx-error context FloatOperation
			     "strict semantics for mixing floats and Decimals are enabled"))
	      (values self ((ref Decimal 'from_float) other)))
	    (values NotImplemented NotImplemented)))))))


;;##### Setup Specific Contexts ############################################

;; The default context prototype used by Context()
;; Is mutable, so that new contexts can have different default values

(define DefaultContext
  (Context
   #:prec     28
   #:rounding ROUND_HALF_EVEN
   #:traps    (list DivisionByZero Overflow InvalidOperation)
   #:flags    '()
   #:Emax     999999
   #:Emin    -999999
   #:capitals 1
   #:clamp    0))

;; Pre-made alternate contexts offered by the specification
;; Don't change these; the user should be able to select these
;; contexts and be able to reproduce results from other implementations
;; of the spec.

(define BasicContext
  (Context
   #:prec     9
   #:rounding ROUND_HALF_UP
   #:traps    (list DivisionByZero Overflow InvalidOperation Clamped Underflow)
   #:flags    '()))

(define ExtendedContext
  (Context
   #:prec     9
   #:rounding ROUND_HALF_EVEN
   #:traps    '()
   #:flags    '()))

;;##### crud for parsing strings #############################################
;;#
;;# Regular expression used for parsing numeric strings.  Additional
;;# comments:
;;#
;;# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
;;# whitespace.  But note that the specification disallows whitespace in
;;# a numeric string.
;;#
;;# 2. For finite numbers (not infinities and NaNs) the body of the
;;# number between the optional sign and the optional exponent must have
;;# at least one decimal digit, possibly after the decimal point.  The
;;# lookahead expression '(?=\d|\.\d)' checks this.

(define _parser
  (ref
   (compile "        # A numeric string consists of:
#    \\s*
    (?P<sign>[-+])?              # an optional sign, followed by either...
    (
        (?=\\d|\\.\\d)           # ...a number (with at least one digit)
        (?P<int>\\d*)            # having a (possibly empty) integer part
        (\\.(?P<frac>\\d*))?      # followed by an optional fractional part
        (E(?P<exp>[-+]?\\d+))?   # followed by an optional exponent, or...
    |
        Inf(inity)?              # ...an infinity, or...
    |
        (?P<signal>s)?           # ...an (optionally signaling)
        NaN                      # NaN
        (?P<diag>\\d*)           # with (possibly empty) diagnostic info.
    )
#    \\s*
    \\Z
" (logior VERBOSE IGNORECASE))
   'match))

(define _all_zeros  (ref (compile "0*$" ) 'match))
(define _exact_half (ref (compile "50*$") 'match))

;;##### PEP3101 support functions ##############################################
;;# The functions in this section have little to do with the Decimal
;;# class, and could potentially be reused or adapted for other pure
;;# Python numeric classes that want to implement __format__
;;#
;;# A format specifier for Decimal looks like:
;;#
;;#   [[fill]align][sign][#][0][minimumwidth][,][.precision][type]

(define _parse_format_specifier_regex
  (compile "\\A
(?:
   (?P<fill>.)?
   (?P<align>[<>=^])
)?
(?P<sign>[-+ ])?
(?P<alt>\\#)?
(?P<zeropad>0)?
(?P<minimumwidth>(?!0)\\d+)?
(?P<thousands_sep>,)?
(?:\\.(?P<precision>0|(?!0)\\d+))?
(?P<type>[eEfFgGn%])?
\\Z
" (logior VERBOSE DOTALL)))

;; The locale module is only needed for the 'n' format specifier.  The
;; rest of the PEP 3101 code functions quite happily without it, so we
;; don't care too much if locale isn't present.
(define _locale (try-module "locale"))

(define _parse_format_specifier
  (lam (format_spec (=_localeconv None))
    "Parse and validate a format specifier.

    Turns a standard numeric format specifier into a dict, with the
    following entries:

      fill: fill character to pad field to minimum width
      align: alignment type, either '<', '>', '=' or '^'
      sign: either '+', '-' or ' '
      minimumwidth: nonnegative integer giving minimum width
      zeropad: boolean, indicating whether to pad with zeros
      thousands_sep: string to use as thousands separator, or ''
      grouping: grouping for thousands separators, in format
        used by localeconv
      decimal_point: string to use for decimal point
      precision: nonnegative integer giving precision, or None
      type: one of the characters 'eEfFgG%', or None

    "
    (let* ((m (let ((m ((ref _parse_format_specifier_regex 'match) format_spec)))
		(if (eq? m None)
		    (raise (ValueError (+ "Invalid format specifier: " format_spec))))
		m))

	   ;; get the dictionary
	   (format_dict = ((ref m 'groupdict)))

	   ;; zeropad; defaults for fill and alignment.  If zero padding
	   ;; is requested, the fill and align fields should be absent.
	   (fill  (pylist-ref format_dict "fill"))
	   (minw  (pylist-ref format_dict "minimumwidth"))
	   (sign  (pylist-ref format_dict "sign"))
	   (prec  (pylist-ref format_dict "precition"))
	   (sepM  (pylist-ref format_dict "thousands_sep"))
	   (type  (pylist-ref format_dict "type"))
	   (align (pylist-ref format_dict "align")))

      (pylist-set! format_dict "zeropad" (not (eq? (pylist-ref format_dict "zeropad") None)))
      (when (pylist-ref format_dict "zeropad")
	 (if (not (eq? fill  None))
	     (raise (ValueError (+ "Fill character conflicts with '0'"
				   " in format specifier: " format_spec))))
	 (if (not (eq? align  None))
	     (raise (ValueError (+ "Alignment conflicts with '0' in "
				   "format specifier: " format_spec)))))

      (pylist-set! format_dict "fill" (or (bool fill) " "))
      
      ;; PEP 3101 originally specified that the default alignment should
      ;; be left;  it was later agreed that right-aligned makes more sense
      ;; for numeric types.  See http://bugs.python.org/issue6857.

      (pylist-set! format_dict "align" (or (bool align) ">"))

      ;; default sign handling: '-' for negative, '' for positive
      (pylist-set! format_dict "sign" (or (bool sign) "-"))
      
      ;; minimumwidth defaults to 0; precision remains None if not given
      (pylist-set! format_dict "minimumwidth" (int (if (eq? minw None) "0" minw)))
      (if (not (eq? prec None))
	  (pylist-set! format_dict "precision" (let ((w (int prec))) (set! prec w) w)))

      ;; if format type is 'g' or 'G' then a precision of 0 makes little
      ;; sense; convert it to 1.  Same if format type is unspecified.
      (if (equal? prec 0)
	  (if (or (eq? type None) (in type "gGn"))
	      (pylist-set! format_dict "precision" 1)))

      ;; determine thousands separator, grouping, and decimal separator, and
      ;; add appropriate entries to format_dict
      (if (equal? type "n")
	  (begin
	    ;; apart from separators, 'n' behaves just like 'g'
	    (pylist-set! format_dict "type" "g")
	    (if _(eq? _localeconv None)
		(set! _localeconv ((ref _locale 'localeconv))))
	    (if (not (eq? sepM None))
		(raise (ValueError (+ "Explicit thousands separator conflicts with "
				      "'n' type in format specifier: " format_spec))))
            (pylist-set! format_dict "thousands_sep" (pylist-ref _localeconv "thousands_sep"))
	    (pylist-set! format_dict "grouping"      (pylist-ref _localeconv "grouping"))
	    (pylist-set! format_dict "decimal_point" (pylist-ref _localeconv "decimal_point")))
	  (begin
	    (if (eq? sepM None)
		(pylist-set! format_dict "thousands_sep" ""))
	    (pylist-set! format_dict "grouping"      (list 3 0))
	    (pylist-set! format_dict "decimal_point" ".")))

      format_dict)))

(define _format_align
  (lambda (sign body spec)
    "Given an unpadded, non-aligned numeric string 'body' and sign
    string 'sign', add padding and alignment conforming to the given
    format specifier dictionary 'spec' (as produced by
    parse_format_specifier).

    "
    ;; how much extra space do we have to play with?
    (let ((minimumwidth (pylist-ref spec "minimumwidth"))
	  (fill         (pylist-ref spec "fill"))
	  (padding      (* fill (- minimumwidth (len sign) (len body))))
	  (align        (pylist-ref spec "align")))
      (cond
       ((equal? align "<")
        (+ sign body padding))
       ((equal? align ">")
        (+ padding sign body))
       ((equal? align "=")
        (+ sign padding body))
       ((equal? align "^")
        (let* ((half (floor-quotient (len padding) 2))
	       (pad1  (pylist-slice padding None half None))
	       (pad2  (pylist-slice padding half None None)))
	  (+ pad1 sign  body pad2)))
       (else
        (raise (ValueError "Unrecognised alignment field")))))))

(define _group_lengths
  (lambda (grouping)
    "Convert a localeconv-style grouping into a (possibly infinite)
    iterable of integers representing group lengths.

    "
    ;; The result from localeconv()['grouping'], and the input to this
    ;; function, should be a list of integers in one of the
    ;; following three forms:
    ;;
    ;;   (1) an empty list, or
    ;;   (2) nonempty list of positive integers + [0]
    ;;   (3) list of positive integers + [locale.CHAR_MAX], or

    (cond
     ((not (bool grouping))
      '())
     ((and (= (pylist-ref grouping -1) 0) (>= (len grouping) 2))
      (chain (pylist-slice grouping None -1 None) (repeat (pylist-ref grouping -2))))
     ((= (pylist-ref grouping -1) (ref _locale 'CHAR_MAX))
      (pylist-slice grouping None -1 None))
     (else
      (raise (ValueError "unrecognised format for grouping"))))))

(define _insert_thousands_sep
  (lam (digits spec (= min_width 1))
    "Insert thousands separators into a digit string.

    spec is a dictionary whose keys should include 'thousands_sep' and
    'grouping'; typically it's the result of parsing the format
    specifier using _parse_format_specifier.

    The min_width keyword argument gives the minimum length of the
    result, which will be padded on the left with zeros if necessary.

    If necessary, the zero padding adds an extra '0' on the left to
    avoid a leading thousands separator.  For example, inserting
    commas every three digits in '123456', with min_width=8, gives
    '0,123,456', even though that has length 9.

    "

    (let ((sep       (pylist-ref spec "thousands_sep"))
	  (grouping  (pylist-ref spec "grouping"))
	  (groups    (pylist)))

      (for ((l :: (_group_lengths grouping))) ()
	   (if (<= l 0)
	       (raise (ValueError "group length should be positive")))
	   ;; max(..., 1) forces at least 1 digit to the left of a separator
	   (let ((l (min (max (len digits) min_width 1) l)))
	     ((ref groups 'append) (+ (* '0' (- l (len digits)))
				      (pylist-slice digits (- l) None None)))
	     (set! digits (pylist-slice digits None (- l) None))
	     (set! min_width (- min_width l))
	     (if (and (= 0 digits) (<= min_width  0))
		 (break))
	     (set! min_width (- min_width (len sep))))
	   #:final
	   (let ((l (max (len digits) min_width 1)))
	     ((ref groups 'append) (+ (* "0" (- l (len digits)))
				      (pylist-slice digits (- l) None None)))))
      ((ref sep 'join) (reversed groups)))))

(define _format_sign
  (lam (is_negative spec)
    "Determine sign character."

    (cond
     ((bool is_negative)
      "-")
     ((in (pylist-ref spec "sign") " +")
      (pylist-ref spec "sign"))
     (else
      ""))))

(define typed (dict '(("E" .  "E") ("e" . "e") ("G" . "E") ("g" . "e"))))

(define _format_number
  (lambda (is_negative intpart fracpart exp spec)
    "Format a number, given the following data:

    is_negative: true if the number is negative, else false
    intpart: string of digits that must appear before the decimal point
    fracpart: string of digits that must come after the point
    exp: exponent, as an integer
    spec: dictionary resulting from parsing the format specifier

    This function uses the information in spec to:
      insert separators (decimal separator and thousands separators)
      format the sign
      format the exponent
      add trailing '%' for the '%' type
      zero-pad if necessary
      fill and align if necessary
    "

    (let ((sign  (_format_sign is_negative  spec)))

      (if (or (bool fracpart) (bool (pylist-ref spec "alt")))
	  (set! fracpart (+ (pylist-ref spec "decimal_point") fracpart)))

      (if (or (not (= exp 0)) (in (pylist-ref spec "type") "eEgG"))
	  (let ((echar (pylist-ref typed /pylist-ref spec "type"))) 
	    (set! fracpart (+ fracpart (str-format "{0}{1:+}" echar exp)))))
    
      (if (equal? (pylist-ref spec "type") "%")
	  (set! fracpart (+ fracpart "%")))

      (let* ((min_width
	      (if (bool (pylist.ref spec "zeropad"))
		  (- (pylist-ref spec "minimumwidth") (len fracpart) (len sign))
		  0))
	     (intpart (_insert_thousands_sep intpart spec min_width)))


	(_format_align sign  (+ intpart fracpart) spec)))))


;;##### Useful Constants (internal use only) ################################

;; Reusable defaults
(define _Infinity         (Decimal "Inf"))
(define _NegativeInfinity (Decimal "-Inf"))
(define _NaN              (Decimal "NaN"))
(define _Zero             (Decimal 0))
(define _One              (Decimal 1))
(define _NegativeOne      (Decimal -1))

;; _SignedInfinity[sign] is infinity w/ that sign
(define _SignedInfinity  (list _Infinity _NegativeInfinity))

;; Constants related to the hash implementation;  hash(x) is based
;; on the reduction of x modulo _PyHASH_MODULUS
(define _PyHASH_MODULUS (ref hash_info 'modulus))

;; hash values to use for positive and negative infinities, and nans
(define _PyHASH_INF (ref hash_info 'inf))
(define _PyHASH_NAN (ref hash_info 'nan))

;; _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
(define _PyHASH_10INV (py-pow 10 (- _PyHASH_MODULUS 2) _PyHASH_MODULUS))

|#