aboutsummaryrefslogtreecommitdiffstats
path: root/erts/emulator/beam/erl_unicode.c
blob: f8e1431a539c63b3bfb4f83ff4e6f61ffe7811e8 (plain) (blame)
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
/*
 * %CopyrightBegin%
 *
 * Copyright Ericsson AB 2008-2013. All Rights Reserved.
 *
 * The contents of this file are subject to the Erlang Public License,
 * Version 1.1, (the "License"); you may not use this file except in
 * compliance with the License. You should have received a copy of the
 * Erlang Public License along with this software. If not, it can be
 * retrieved online at http://www.erlang.org/.
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
 * the License for the specific language governing rights and limitations
 * under the License.
 *
 * %CopyrightEnd%
 */

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif
#include "sys.h"
#include "erl_vm.h"
#include "global.h"
#include "erl_process.h"
#include "error.h"
#include "bif.h"
#include "erl_binary.h"
#include "big.h"

#include "erl_unicode.h"
#include "erl_unicode_normalize.h"


typedef struct _restart_context {
    byte *bytes;
    Uint num_processed_bytes;
    Uint num_bytes_to_process;
    Uint num_resulting_chars;
    int state;
} RestartContext;


#define LOOP_FACTOR 10
#define LOOP_FACTOR_SIMPLE 50 /* When just counting */

static Uint max_loop_limit;

static BIF_RETTYPE utf8_to_list(Process *p, Eterm arg1);
static BIF_RETTYPE finalize_list_to_list(Process *p, 
					 byte *bytes,
					 Eterm rest,
					 Uint num_processed_bytes,
					 Uint num_bytes_to_process, 
					 Uint num_resulting_chars, 
					 int state, int left,
					 Eterm tail);
static BIF_RETTYPE characters_to_utf8_trap(BIF_ALIST_3);
static BIF_RETTYPE characters_to_list_trap_1(BIF_ALIST_3);
static BIF_RETTYPE characters_to_list_trap_2(BIF_ALIST_3);

static BIF_RETTYPE characters_to_list_trap_3(BIF_ALIST_3);
static BIF_RETTYPE characters_to_list_trap_4(BIF_ALIST_1);

static Export characters_to_utf8_trap_exp;
static Export characters_to_list_trap_1_exp;
static Export characters_to_list_trap_2_exp;

static Export characters_to_list_trap_3_exp;
static Export characters_to_list_trap_4_exp;

static Export *c_to_b_int_trap_exportp = NULL;
static Export *c_to_l_int_trap_exportp = NULL;

void erts_init_unicode(void)
{
    max_loop_limit = CONTEXT_REDS * LOOP_FACTOR;
    /* Non visual BIFs to trap to. */
    erts_init_trap_export(&characters_to_utf8_trap_exp,
			  am_erlang, am_atom_put("characters_to_utf8_trap",23), 3,
			  &characters_to_utf8_trap);

    erts_init_trap_export(&characters_to_list_trap_1_exp,
			  am_erlang, am_atom_put("characters_to_list_trap_1",25), 3,
			  &characters_to_list_trap_1);

    erts_init_trap_export(&characters_to_list_trap_2_exp,
			  am_erlang, am_atom_put("characters_to_list_trap_2",25), 3,
			  &characters_to_list_trap_2);

    erts_init_trap_export(&characters_to_list_trap_3_exp,
			  am_erlang, am_atom_put("characters_to_list_trap_3",25), 3,
			  &characters_to_list_trap_3);

    erts_init_trap_export(&characters_to_list_trap_4_exp,
			  am_erlang, am_atom_put("characters_to_list_trap_4",25), 1,
			  &characters_to_list_trap_4);

    c_to_b_int_trap_exportp =  erts_export_put(am_unicode,am_characters_to_binary_int,2);
    c_to_l_int_trap_exportp =  erts_export_put(am_unicode,am_characters_to_list_int,2);
    

}


static ERTS_INLINE void *alloc_restart(size_t size)
{
    return erts_alloc(ERTS_ALC_T_UNICODE_BUFFER,size);
}

static ERTS_INLINE void free_restart(void *ptr)
{
    erts_free(ERTS_ALC_T_UNICODE_BUFFER, ptr);
}

static void cleanup_restart_context(RestartContext *rc)
{
    if (rc->bytes != NULL) {
	free_restart(rc->bytes);
	rc->bytes = NULL;
    }
}

static void cleanup_restart_context_bin(Binary *bp)
{
    RestartContext *rc = ERTS_MAGIC_BIN_DATA(bp);
    cleanup_restart_context(rc);
}

static RestartContext *get_rc_from_bin(Eterm bin)
{
    Binary *mbp;
    ASSERT(ERTS_TERM_IS_MAGIC_BINARY(bin));

    mbp = ((ProcBin *) binary_val(bin))->val;

    ASSERT(ERTS_MAGIC_BIN_DESTRUCTOR(mbp)
	   == cleanup_restart_context_bin);
    return (RestartContext *) ERTS_MAGIC_BIN_DATA(mbp);    
}

static Eterm make_magic_bin_for_restart(Process *p, RestartContext *rc)
{
    Binary *mbp = erts_create_magic_binary(sizeof(RestartContext),
					   cleanup_restart_context_bin);
    RestartContext *restartp = ERTS_MAGIC_BIN_DATA(mbp);
    Eterm *hp;
    memcpy(restartp,rc,sizeof(RestartContext));
    hp = HAlloc(p, PROC_BIN_SIZE);
    return erts_mk_magic_binary_term(&hp, &MSO(p), mbp);
}

	
Sint erts_unicode_set_loop_limit(Sint limit) 
{
    Sint save = (Sint) max_loop_limit;
    if (limit <= 0) {
	max_loop_limit = CONTEXT_REDS * LOOP_FACTOR;
    } else {
	max_loop_limit = (Uint) limit;
    }
    return save;
}

static ERTS_INLINE int allowed_iterations(Process *p)
{
    int tmp = ERTS_BIF_REDS_LEFT(p) * LOOP_FACTOR;
    int tmp2 = max_loop_limit;
    if (tmp2 < tmp)
	return tmp2;
    else
	return tmp;
}
static ERTS_INLINE int cost_to_proc(Process *p, int cost)
{
    int x = (cost / LOOP_FACTOR);
    BUMP_REDS(p,x);
    return x;
}
static ERTS_INLINE int simple_loops_to_common(int cost)
{
    int factor = (LOOP_FACTOR_SIMPLE / LOOP_FACTOR);
    return (cost / factor);
}

static Sint aligned_binary_size(Eterm binary)
{
    ERTS_DECLARE_DUMMY(unsigned char *bytes);
    ERTS_DECLARE_DUMMY(Uint bitoffs);
    Uint bitsize;
    
    ERTS_GET_BINARY_BYTES(binary, bytes, bitoffs, bitsize);
    if (bitsize != 0) {
	return (Sint) -1;
    }
    return binary_size(binary);
}

static Sint latin1_binary_need(Eterm binary)
{
    unsigned char *bytes;
    byte *temp_alloc = NULL;
    Uint bitoffs;
    Uint bitsize;
    Uint size;
    Sint need = 0;
    Sint i;
    
    ERTS_GET_BINARY_BYTES(binary, bytes, bitoffs, bitsize);
    if (bitsize != 0) {
	return (Sint) -1;
    }
    if (bitoffs != 0) {
	bytes = erts_get_aligned_binary_bytes(binary, &temp_alloc);
	/* The call to erts_get_aligned_binary_bytes cannot fail as 
	   we'we already checked bitsize and that this is a binary */
    }
    size = binary_size(binary);
    for(i = 0; i < size; ++i) {
	if (bytes[i] & ((byte) 0x80)) {
	    need += 2;
	} else {
	    need += 1;
	}
    }
    erts_free_aligned_binary_bytes(temp_alloc);
    return need;
}

static int utf8_len(byte first) 
{
    if ((first & ((byte) 0x80)) == 0) {
	return 1;
    } else if ((first & ((byte) 0xE0)) == 0xC0) {
	return 2;
    } else if ((first & ((byte) 0xF0)) == 0xE0) {
	return 3;
    } else if ((first & ((byte) 0xF8)) == 0xF0) {
	return 4;
    } 
    return -1;
}

static int copy_utf8_bin(byte *target, byte *source, Uint size, 
			 byte *leftover, int *num_leftovers, 
			 byte **err_pos, Uint *characters) {
    int copied = 0;
    if (leftover != NULL && *num_leftovers) {
	int need = utf8_len(leftover[0]);
	int from_source = need - (*num_leftovers);
	int c;
	byte *tmp_err_pos = NULL;
	ASSERT(need > 0);
	ASSERT(from_source > 0);
	if (size < from_source) {
	    memcpy(leftover + (*num_leftovers), source, size);
	    *num_leftovers += size;
	    return 0;
	}
	/* leftover has room for four bytes (see bif) */
	memcpy(leftover + (*num_leftovers),source,from_source);
	c = copy_utf8_bin(target, leftover, need, NULL, NULL, &tmp_err_pos, characters);
	if (tmp_err_pos != 0) {
	    *err_pos = source;
	    return 0;
	}
	copied += c;
	*num_leftovers = 0;
	size -= from_source;
	target += c;
	source += from_source;
    }
    while (size) {
	if (((*source) & ((byte) 0x80)) == 0) {
	    *(target++) = *(source++);
	    --size; ++copied;
	} else if (((*source) & ((byte) 0xE0)) == 0xC0) {
	    if (leftover && size < 2) {
		*leftover = *source;
		*num_leftovers = 1;
		break;
	    }
	    if (size < 2 || ((source[1] & ((byte) 0xC0)) != 0x80) ||
		((*source) < 0xC2) /* overlong */) {
		*err_pos = source;
		return copied;
	    }
	    *(target++) = *(source++);
	    *(target++) = *(source++);
	    size -= 2; copied += 2;
	} else if (((*source) & ((byte) 0xF0)) == 0xE0) {
	    if (leftover && size < 3) {
		memcpy(leftover, source, (int) size);
		*num_leftovers = (int) size;
		break;
	    }
	    if (size < 3 || ((source[1] & ((byte) 0xC0)) != 0x80) ||
		((source[2] & ((byte) 0xC0)) != 0x80) ||
		(((*source) == 0xE0) && (source[1] < 0xA0)) /* overlong */ ) {
		*err_pos = source;
		return copied;
	    }
	    if ((((*source) & ((byte) 0xF)) == 0xD) && 
		((source[1] & 0x20) != 0)) {
		*err_pos = source;
		return copied;
	    }

	    *(target++) = *(source++);
	    *(target++) = *(source++);
	    *(target++) = *(source++);
	    size -= 3; copied += 3;
	} else if (((*source) & ((byte) 0xF8)) == 0xF0) {
	    if (leftover && size < 4) {
		memcpy(leftover, source, (int) size);
		*num_leftovers = (int) size;
		break;
	    }
	    if (size < 4 || ((source[1] & ((byte) 0xC0)) != 0x80) ||
		((source[2] & ((byte) 0xC0)) != 0x80) ||
		((source[3] & ((byte) 0xC0)) != 0x80) ||
		(((*source) == 0xF0) && (source[1] < 0x90)) /* overlong */) {
		*err_pos = source;
		return copied;
	    }
	    if ((((*source) & ((byte)0x7)) > 0x4U) ||
		((((*source) & ((byte)0x7)) == 0x4U) && 
		 ((source[1] & ((byte)0x3F)) > 0xFU))) {
		*err_pos = source;
		return copied;
	    }
	    *(target++) = *(source++);
	    *(target++) = *(source++);
	    *(target++) = *(source++);
	    *(target++) = *(source++);
	    size -= 4; copied +=4;
	} else {
	    *err_pos = source;
	    return copied;
	}
	++(*characters);
    }
    return copied;
}
	    
	    
    
static Sint utf8_need(Eterm ioterm, int latin1, Uint *costp) 
{
    Eterm *objp;
    Eterm obj;
    DECLARE_ESTACK(stack);
    Sint need = 0;
    Uint cost = 0;

    if (is_nil(ioterm)) {
	DESTROY_ESTACK(stack);
	*costp = 0;
	return need;
    }
    if(is_binary(ioterm)) {
	DESTROY_ESTACK(stack);
	if (latin1) {
	    Sint x = latin1_binary_need(ioterm);
	    *costp = x;
	    return x;
	} else {
	    *costp = 1;
	    return aligned_binary_size(ioterm);
	}
    }
    
    if (!is_list(ioterm)) {
	DESTROY_ESTACK(stack);
	*costp = 0;
	return (Sint) -1;
    }
    /* OK a list, needs to be processed in order, handling each flat list-level
       as they occur, just like io_list_to_binary would */
    ESTACK_PUSH(stack,ioterm);
    while (!ESTACK_ISEMPTY(stack)) {
	ioterm = ESTACK_POP(stack);
	if (is_nil(ioterm)) {
	    /* ignore empty lists */
	    continue;
	}
	if(is_list(ioterm)) {
L_Again:   /* Restart with sublist, old listend was pushed on stack */
	    objp = list_val(ioterm);
	    obj = CAR(objp);
	    for(;;) { /* loop over one flat list of bytes and binaries
		         until sublist or list end is encountered */
		if (is_small(obj)) { /* Always small */
		    for(;;) {
			Uint x = unsigned_val(obj);
			if (x < 0x80)
			    need +=1;
			else if (x < 0x800)
			    need += 2;
			else if (x < 0x10000) 
			    need += 3;
			else 
			    need += 4; 
			/* everything else will give badarg later 
			   in the process, so we dont check */
			++cost;
			ioterm = CDR(objp);
			if (!is_list(ioterm)) {
			    break;
			}
			objp = list_val(ioterm);
			obj = CAR(objp);
			if (!is_small(obj))
			    break;
		    }
		} else if (is_nil(obj)) {
		    ioterm = CDR(objp);
		    if (!is_list(ioterm)) {
			break;
		    }
		    objp = list_val(ioterm);
		    obj = CAR(objp);
		} else if (is_list(obj)) {
		    /* push rest of list for later processing, start 
		       again with sublist */
		    ESTACK_PUSH(stack,CDR(objp));
		    ioterm = obj;
		    goto L_Again;
		} else if (is_binary(obj)) {
		    Sint x;

		    if (latin1) { 
			x = latin1_binary_need(obj);
			if (x < 0) {
			    DESTROY_ESTACK(stack);
			    *costp = cost;
			    return x;
			} 
			cost += x;
		    } else {
			x = aligned_binary_size(obj);
			if (x < 0) {
			    DESTROY_ESTACK(stack);
			    *costp = cost;
			    return x;
			} 
			++cost;
		    }
		    need += x;
		    ioterm = CDR(objp);
		    if (is_list(ioterm)) {
			/* objp and obj need to be updated if 
			   loop is to continue */
			objp = list_val(ioterm);
			obj = CAR(objp);
		    }
		} else {
		    DESTROY_ESTACK(stack);
		    *costp = cost;
		    return ((Sint) -1);
		} 
		if (is_nil(ioterm) || !is_list(ioterm)) {
		    break;
		}
	    } /* for(;;) */
	} /* is_list(ioterm) */
	
	if (!is_list(ioterm) && !is_nil(ioterm)) {
	    /* inproper list end */
	    if (is_binary(ioterm)) {
		Sint x; 
		if (latin1) {
		    x = latin1_binary_need(ioterm);
		    if (x < 0) {
			DESTROY_ESTACK(stack);
			*costp = cost;
			return x;
		    } 
		    cost += x;
		} else {
		    x = aligned_binary_size(ioterm);
		    if (x < 0) {
			DESTROY_ESTACK(stack);
			*costp = cost;
			return x;
		    } 
		    ++cost;
		}
		need += x;
	    } else {
		DESTROY_ESTACK(stack);
		*costp = cost;
		return ((Sint) -1);
	    }
	}
    } /* while  not estack empty */
    DESTROY_ESTACK(stack);
    *costp = cost;
    return need;
}
    
    
static Eterm do_build_utf8(Process *p, Eterm ioterm, int *left, int latin1,
			   byte *target, int *pos, Uint *characters, int *err, 
			   byte *leftover, int *num_leftovers)
{
    int c;
    Eterm *objp;
    Eterm obj;
    DECLARE_ESTACK(stack);

    *err = 0;
    if ((*left) <= 0 || is_nil(ioterm)) {
	DESTROY_ESTACK(stack);
	return ioterm;
    }
    if(is_binary(ioterm)) {
	Uint bitoffs;
	Uint bitsize;
	Uint size;
	Uint i;
	Eterm res_term = NIL;
	unsigned char *bytes;
	byte *temp_alloc = NULL;
	Uint orig_size;
	
	ERTS_GET_BINARY_BYTES(ioterm, bytes, bitoffs, bitsize);
	if (bitsize != 0) {
	    *err = 1;
	    DESTROY_ESTACK(stack);
	    return ioterm;
	}
	if (bitoffs != 0) {
	    bytes = erts_get_aligned_binary_bytes(ioterm, &temp_alloc);
	    /* The call to erts_get_aligned_binary_bytes cannot fail as 
	       we'we already checked bitsize and that this is a binary */
	}

	orig_size = size = binary_size(ioterm);

	/* This is done to avoid splitting binaries in two 
	   and then create an unnecessary rest that eventually gives an error.
	   For cases where errors are not returned this is unnecessary */
	if (!latin1) { 
	    /* Find a valid character boundary */
	    while (size > (*left) && 
		   (((byte) bytes[(*left)]) & ((byte) 0xC0)) == ((byte) 0x80)) {
		++(*left);
	    }
	}

	if (size > (*left)) {
	    Eterm *hp;
	    ErlSubBin *sb;
	    Eterm orig;
	    Uint offset;
	    /* Split the binary in two parts, of which we 
	       only process the first */
	    hp = HAlloc(p, ERL_SUB_BIN_SIZE);
	    sb = (ErlSubBin *) hp;
	    ERTS_GET_REAL_BIN(ioterm, orig, offset, bitoffs, bitsize);
	    sb->thing_word = HEADER_SUB_BIN;
	    sb->size = size - (*left);
	    sb->offs = offset + (*left);
	    sb->orig = orig;
	    sb->bitoffs = bitoffs;
	    sb->bitsize = bitsize;
	    sb->is_writable = 0;
	    res_term = make_binary(sb);
	    size = (*left);
	}

	if (!latin1) {
	    int num;
	    byte *err_pos = NULL;
	    num = copy_utf8_bin(target + (*pos), bytes, 
				size, leftover, num_leftovers,&err_pos,characters);
	    *pos += num;
	    if (err_pos != NULL) {
		int rest_bin_offset;
		int rest_bin_size;
		Eterm *hp;
		ErlSubBin *sb;
		Eterm orig;
		Uint offset;

		*err = 1;
		/* we have no real stack, just build a list of the binaries
		   we have not decoded... */
		DESTROY_ESTACK(stack);

		rest_bin_offset = (err_pos - bytes);
		rest_bin_size = orig_size - rest_bin_offset;
		
		hp = HAlloc(p, ERL_SUB_BIN_SIZE);
		sb = (ErlSubBin *) hp;
		ERTS_GET_REAL_BIN(ioterm, orig, offset, bitoffs, bitsize);
		sb->thing_word = HEADER_SUB_BIN;
		sb->size = rest_bin_size;
		sb->offs = offset + rest_bin_offset;
		sb->orig = orig;
		sb->bitoffs = bitoffs;
		sb->bitsize = bitsize;
		sb->is_writable = 0;
		res_term = make_binary(sb);
		erts_free_aligned_binary_bytes(temp_alloc);
		return res_term;
	    }
	} else {
	    i = 0;
	    while(i < size) {
		if (bytes[i] < 0x80) {
		    target[(*pos)++] = bytes[i++];
		} else {
		    target[(*pos)++] = ((bytes[i] >> 6) | ((byte) 0xC0));
		    target[(*pos)++] = ((bytes[i] & 0x3F) | ((byte) 0x80));
		    ++i;
		}
		++(*characters);
	    }
	}
	*left -= size;
	DESTROY_ESTACK(stack);
	erts_free_aligned_binary_bytes(temp_alloc);
	return res_term;
    }
	
    if (!is_list(ioterm)) {
	*err = 1;
	goto done;
    }

    /* OK a list, needs to be processed in order, handling each flat list-level
       as they occur, just like io_list_to_binary would */
    ESTACK_PUSH(stack,ioterm);
    while (!ESTACK_ISEMPTY(stack) && (*left)) {
	ioterm = ESTACK_POP(stack);
	if (is_nil(ioterm)) {
	    /* ignore empty lists */
	    continue;
	}
	if(is_list(ioterm)) {
L_Again:   /* Restart with sublist, old listend was pushed on stack */
	    objp = list_val(ioterm);
	    obj = CAR(objp);
	    for(;;) { /* loop over one flat list of bytes and binaries
		         until sublist or list end is encountered */
		if (is_small(obj)) { /* Always small in unicode*/
		    if (*num_leftovers) {
			/* Have rest from previous bin and this is an integer, not allowed */
			*err = 1;
			goto done;
		    }
		    for(;;) {
			Uint x = unsigned_val(obj);
			if (latin1 && x > 255) {
			    *err = 1;
			    goto done;
			}
			if (x < 0x80) {
			    target[(*pos)++] = (byte) x;
			}
			else if (x < 0x800) {
			    target[(*pos)++] = (((byte) (x >> 6)) | 
						 ((byte) 0xC0));
			    target[(*pos)++] = (((byte) (x & 0x3F)) | 
						((byte) 0x80));
			} else if (x < 0x10000) {
			    if (x >= 0xD800 && x <= 0xDFFF) {
				/* Invalid unicode range */
				*err = 1;
				goto done;
			    }
			    target[(*pos)++] = (((byte) (x >> 12)) | 
						((byte) 0xE0));
			    target[(*pos)++] = ((((byte) (x >> 6)) & 0x3F)  | 
						((byte) 0x80));
			    target[(*pos)++] = (((byte) (x & 0x3F)) | 
						((byte) 0x80));
			} else if (x < 0x110000) { /* Standard imposed max */
			    target[(*pos)++] = (((byte) (x >> 18)) | 
						((byte) 0xF0));
			    target[(*pos)++] = ((((byte) (x >> 12)) & 0x3F)  | 
						((byte) 0x80));
			    target[(*pos)++] = ((((byte) (x >> 6)) & 0x3F)  | 
						((byte) 0x80));
			    target[(*pos)++] = (((byte) (x & 0x3F)) | 
						((byte) 0x80));
			} else {
				*err = 1;
				goto done;
			}
			++(*characters);
			--(*left);
			ioterm = CDR(objp);
			if (!is_list(ioterm) || !(*left)) {
			    break;
			}
			objp = list_val(ioterm);
			obj = CAR(objp);
			if (!is_small(obj))
			    break;
		    }
		} else if (is_nil(obj)) {
		    ioterm = CDR(objp);
		    if (!is_list(ioterm)) {
			break;
		    }
		    objp = list_val(ioterm);
		    obj = CAR(objp);
		} else if (is_list(obj)) {
		    /* push rest of list for later processing, start 
		       again with sublist */
		    ESTACK_PUSH(stack,CDR(objp));
		    ioterm = obj;
		    goto L_Again;
		} else if (is_binary(obj)) {
		    Eterm rest_term;
		    rest_term = do_build_utf8(p,obj,left,latin1,target,pos, characters, err, 
					      leftover, num_leftovers);
		    if ((*err) != 0) {
			Eterm *hp;
			hp = HAlloc(p, 2);
			obj = CDR(objp);
			ioterm = CONS(hp, rest_term, obj);
			/* (*left) = 0; */
			goto done;
		    }
		    if (rest_term != NIL) {
			Eterm *hp;
			hp = HAlloc(p, 2);
			obj = CDR(objp);
			ioterm = CONS(hp, rest_term, obj);
			(*left) = 0;
			break;
		    }
		    ioterm = CDR(objp);
		    if (is_list(ioterm)) {
			/* objp and obj need to be updated if 
			   loop is to continue */
			objp = list_val(ioterm);
			obj = CAR(objp);
		    }
		} else {
		    *err = 1;
		    goto done;
		} 
		if (!(*left) || is_nil(ioterm) || !is_list(ioterm)) {
		    break;
		}
	    } /* for(;;) */
	} /* is_list(ioterm) */

	if ((*left) && !is_list(ioterm) && !is_nil(ioterm)) {
	    /* inproper list end */
	    if (is_binary(ioterm)) {
		ioterm = do_build_utf8(p,ioterm,left,latin1,target,pos,characters,err,leftover,num_leftovers);
		if ((*err) != 0) {
		    goto done;
		}
	    } else {
		*err = 1;
		goto done;
	    }
	}
    } /* while left and not estack empty */
 done:
    c = ESTACK_COUNT(stack);
    if (c > 0) {
	Eterm *hp = HAlloc(p,2*c);
	while(!ESTACK_ISEMPTY(stack)) {
	    Eterm st = ESTACK_POP(stack);
	    ioterm = CONS(hp, ioterm, st);
	    hp += 2;
	}
    }
    DESTROY_ESTACK(stack);
    return ioterm;

}

static int check_leftovers(byte *source, int size) 
{
    if (((*source) & ((byte) 0xE0)) == 0xC0) {
	return 0;
    } else if (((*source) & ((byte) 0xF0)) == 0xE0) {
	if (size < 2 || 
	    (size < 3 && ((source[1] & ((byte) 0xC0)) == 0x80))) { 
	    return 0;
	}
    } else if (((*source) & ((byte) 0xF8)) == 0xF0) {
	if (size < 2 ||
	    (size < 3 && ((source[1] & ((byte) 0xC0)) == 0x80)) ||
	    (size < 4 && 
	     ((source[1] & ((byte) 0xC0)) == 0x80) &&
	     ((source[2] & ((byte) 0xC0)) == 0x80))) {
	    return 0;
	}
    }
    return -1;
}
	
	 

static BIF_RETTYPE build_utf8_return(Process *p,Eterm bin,int pos,
			       Eterm rest_term,int err,
			       byte *leftover,int num_leftovers,Eterm latin1)
{
    Eterm *hp;
    Eterm ret;

    binary_size(bin) = pos;
    if (err) {
	if (num_leftovers > 0) {
	    Eterm leftover_bin = new_binary(p, leftover, num_leftovers);
	    hp = HAlloc(p,8);
	    rest_term = CONS(hp,rest_term,NIL);
	    hp += 2;
	    rest_term = CONS(hp,leftover_bin,rest_term);
	    hp += 2;
	} else {
	   hp = HAlloc(p,4);
	} 
	ret = TUPLE3(hp,am_error,bin,rest_term);
    } else if (rest_term == NIL && num_leftovers != 0) {
	Eterm leftover_bin = new_binary(p, leftover, num_leftovers);
	if (check_leftovers(leftover,num_leftovers) != 0) {
	    hp = HAlloc(p,4);
	    ret = TUPLE3(hp,am_error,bin,leftover_bin);
	} else {
	    hp = HAlloc(p,4);
	    ret = TUPLE3(hp,am_incomplete,bin,leftover_bin);
	}
    } else { /* All OK */	    
	if (rest_term != NIL) { /* Trap */
	    if (num_leftovers > 0) {
		Eterm rest_bin = new_binary(p, leftover, num_leftovers);
		hp = HAlloc(p,2);
		rest_term = CONS(hp,rest_bin,rest_term);
	    }
	    BUMP_ALL_REDS(p);
	    BIF_TRAP3(&characters_to_utf8_trap_exp, p, bin, rest_term, latin1);
	} else { /* Success */
	    /*hp = HAlloc(p,5);
	      ret = TUPLE4(hp,bin,rest_term,make_small(pos),make_small(err));*/
	    ret = bin;
	}
    }
    BIF_RET(ret);
}


static BIF_RETTYPE characters_to_utf8_trap(BIF_ALIST_3)
{
#ifdef DEBUG
    Eterm *real_bin;
#endif
    byte* bytes;
    Eterm rest_term;
    int left, sleft;
    int pos;
    int err;
    byte leftover[4]; /* used for temp buffer too, 
			 otherwise 3 bytes would have been enough */
    int num_leftovers = 0;
    int latin1 = 0;
    Uint characters = 0;
    
    /*erts_printf("Trap %T!\r\n",BIF_ARG_2);*/
    ASSERT(is_binary(BIF_ARG_1));
#ifdef DEBUG
    real_bin = binary_val(BIF_ARG_1);
    ASSERT(*real_bin == HEADER_PROC_BIN);
#endif
    pos = (int) binary_size(BIF_ARG_1);
    bytes = binary_bytes(BIF_ARG_1);
    sleft = left = allowed_iterations(BIF_P);
    err = 0;
    if (BIF_ARG_3 == am_latin1) {
	latin1 = 1;
    } 
    rest_term = do_build_utf8(BIF_P, BIF_ARG_2, &left, latin1,
			      bytes, &pos, &characters, &err, leftover, &num_leftovers); 
    cost_to_proc(BIF_P, sleft - left);
    return build_utf8_return(BIF_P,BIF_ARG_1,pos,rest_term,err,
			      leftover,num_leftovers,BIF_ARG_3);
}

BIF_RETTYPE unicode_bin_is_7bit_1(BIF_ALIST_1)
{
    Sint need;
    if(!is_binary(BIF_ARG_1)) {
	BIF_RET(am_false);
    }
    need = latin1_binary_need(BIF_ARG_1);
    if(need >= 0 && aligned_binary_size(BIF_ARG_1) == need) {
	BIF_RET(am_true);
    }
    BIF_RET(am_false);
}

static int is_valid_utf8(Eterm orig_bin)
{
    Uint bitoffs;
    Uint bitsize;
    Uint size;
    byte *temp_alloc = NULL;
    byte *endpos;
    Uint numchar;
    byte *bytes;
    int ret;

    ERTS_GET_BINARY_BYTES(orig_bin, bytes, bitoffs, bitsize);
    if (bitsize != 0) {
	return 0;
    }
    if (bitoffs != 0) {
	bytes = erts_get_aligned_binary_bytes(orig_bin, &temp_alloc);
    }
    size = binary_size(orig_bin);
    ret = erts_analyze_utf8(bytes,
		       size,
		       &endpos,&numchar,NULL);
    erts_free_aligned_binary_bytes(temp_alloc);
    return (ret == ERTS_UTF8_OK);
}

BIF_RETTYPE unicode_characters_to_binary_2(BIF_ALIST_2)
{
    Sint need;
    Uint characters;
    int latin1;
    Eterm bin;
    byte *bytes;
    int pos;
    int err;
    int left, sleft;
    Eterm rest_term, subject;
    byte leftover[4]; /* used for temp buffer too, o
			 therwise 3 bytes would have been enough */
    int num_leftovers = 0;
    Uint cost_of_utf8_need;


    if (BIF_ARG_2 == am_latin1) {
	latin1 = 1;
    } else if (BIF_ARG_2 == am_unicode || BIF_ARG_2 == am_utf8) {
	latin1 = 0;
    } else {
	BIF_TRAP2(c_to_b_int_trap_exportp, BIF_P, BIF_ARG_1, BIF_ARG_2);
    }	
    if (is_list(BIF_ARG_1) && is_binary(CAR(list_val(BIF_ARG_1))) && 
	is_nil(CDR(list_val(BIF_ARG_1)))) {
	subject = CAR(list_val(BIF_ARG_1));
    } else {
	subject = BIF_ARG_1;
    }

    need = utf8_need(subject,latin1,&cost_of_utf8_need);
    if (need < 0) {
	BIF_ERROR(BIF_P,BADARG);
    }
    if (is_binary(subject) && need >= 0 && aligned_binary_size(subject) == need
	&& (latin1 || is_valid_utf8(subject))) {
	cost_to_proc(BIF_P, simple_loops_to_common(cost_of_utf8_need)); 
	    BIF_RET(subject);
    }
	

    bin = erts_new_mso_binary(BIF_P, (byte *)NULL, need);
    bytes = binary_bytes(bin);
    cost_to_proc(BIF_P, simple_loops_to_common(cost_of_utf8_need)); 
    left = allowed_iterations(BIF_P) - 
	simple_loops_to_common(cost_of_utf8_need);
    if (left <= 0) {
	/* simplified - let everything be setup by setting left to 1 */
	left = 1;
    }
    sleft = left;
    pos = 0;
    err = 0;


    rest_term = do_build_utf8(BIF_P, subject, &left, latin1,
			      bytes, &pos, &characters, &err, leftover, &num_leftovers); 
#ifdef HARDDEBUG
    if (left == 0) {
	Eterm bin;
	if (is_binary(subject)) {
	    bin = subject;
	} else if(is_list(subject) && is_binary(CAR(list_val(subject)))) {
	    bin = CAR(list_val(subject));
	} else {
	    bin = NIL;
	}
	if (is_binary(bin)) {
	    byte *t = NULL;
	    Uint sz = binary_size(bin);
	    byte *by = erts_get_aligned_binary_bytes(bin,&t);
	    int i;
	    erts_printf("<<");
	    for (i = 0;i < sz; ++i) {
		erts_printf((i == sz -1) ? "0x%X" : "0x%X, ", (unsigned) by[i]);
	    }
	    erts_printf(">>: ");
	    erts_free_aligned_binary_bytes(t);
	}
	erts_printf("%d - %d = %d\n",sleft,left,sleft - left);
    }
#endif
    cost_to_proc(BIF_P, sleft - left); 
    return build_utf8_return(BIF_P,bin,pos,rest_term,err,
			     leftover,num_leftovers,BIF_ARG_2);
}

static BIF_RETTYPE build_list_return(Process *p, byte *bytes, int pos, Uint characters,
				     Eterm rest_term, int err,
				     byte *leftover, int num_leftovers,
				     Eterm latin1, int left)
{
    Eterm *hp;
    
    if (left <= 0) {
	left = 1;
    }
    
    if (err) {
	if (num_leftovers > 0) {
	    Eterm leftover_bin = new_binary(p, leftover, num_leftovers);
	    hp = HAlloc(p,4);
	    rest_term = CONS(hp,rest_term,NIL);
	    hp += 2;
	    rest_term = CONS(hp,leftover_bin,rest_term);
	}
	BIF_RET(finalize_list_to_list(p, bytes, rest_term, 0U, pos, characters, ERTS_UTF8_ERROR, left, NIL));
    } else if (rest_term == NIL && num_leftovers != 0) {
	Eterm leftover_bin = new_binary(p, leftover, num_leftovers);
	if (check_leftovers(leftover,num_leftovers) != 0) {
	    BIF_RET(finalize_list_to_list(p, bytes, leftover_bin, 0U, pos, characters, ERTS_UTF8_ERROR, 
					  left, NIL));
	} else {
	    BIF_RET(finalize_list_to_list(p, bytes, leftover_bin, 0U, pos, characters, ERTS_UTF8_INCOMPLETE, 
					  left, NIL));
	}
    } else { /* All OK */	    
	if (rest_term != NIL) { /* Trap */
	    RestartContext rc;
	    if (num_leftovers > 0) {
		Eterm rest_bin = new_binary(p, leftover, num_leftovers);
		hp = HAlloc(p,2);
		rest_term = CONS(hp,rest_bin,rest_term);
	    }
	    BUMP_ALL_REDS(p);
	    rc.bytes = bytes;
	    rc.num_processed_bytes = 0; /* not used */
	    rc.num_bytes_to_process = pos;
	    rc.num_resulting_chars = characters;
	    rc.state = ERTS_UTF8_OK; /* not used */
	    BIF_TRAP3(&characters_to_list_trap_1_exp, p, make_magic_bin_for_restart(p,&rc), 
		      rest_term, latin1);
	} else { /* Success */
	    BIF_RET(finalize_list_to_list(p, bytes, NIL, 0U, pos, characters, ERTS_UTF8_OK, left, NIL));
	}
    }
}

static BIF_RETTYPE characters_to_list_trap_1(BIF_ALIST_3)
{
    RestartContext *rc;
    byte* bytes;
    int pos;
    Uint characters;
    int err;
    Eterm rest_term;
    int left, sleft;

    int latin1 = 0;
    byte leftover[4]; /* used for temp buffer too, 
			 otherwise 3 bytes would have been enough */
    int num_leftovers = 0;
    

    rc = get_rc_from_bin(BIF_ARG_1);

    bytes = rc->bytes;
    rc->bytes = NULL; /* to avoid free due to later GC */
    pos = rc->num_bytes_to_process;
    characters = rc->num_resulting_chars;

    sleft = left = allowed_iterations(BIF_P);
    err = 0;
    if (BIF_ARG_3 == am_latin1) {
	latin1 = 1;
    } 
    rest_term = do_build_utf8(BIF_P, BIF_ARG_2, &left, latin1,
			      bytes, &pos, &characters, &err, leftover, &num_leftovers); 
    cost_to_proc(BIF_P, sleft - left);
    return build_list_return(BIF_P,bytes,pos,characters,rest_term,err,
			      leftover,num_leftovers,BIF_ARG_3,left);
}

BIF_RETTYPE unicode_characters_to_list_2(BIF_ALIST_2)
{
    Sint need;
    int latin1;
    Uint characters = 0;
    byte *bytes;
    int pos;
    int err;
    int left, sleft;
    Eterm rest_term;
    byte leftover[4]; /* used for temp buffer too, o
			 therwise 3 bytes would have been enough */
    int num_leftovers = 0;
    Uint cost_of_utf8_need;

    if (BIF_ARG_2 == am_latin1) {
	latin1 = 1;
    } else if (BIF_ARG_2 == am_unicode || BIF_ARG_2 == am_utf8) {
	latin1 = 0;
    } else {
	BIF_TRAP2(c_to_l_int_trap_exportp, BIF_P, BIF_ARG_1, BIF_ARG_2);
    }	
    if (is_binary(BIF_ARG_1) && !latin1) { /* Optimized behaviour for this case */
	    return utf8_to_list(BIF_P,BIF_ARG_1);
    }
    need = utf8_need(BIF_ARG_1,latin1,&cost_of_utf8_need);
    if (need < 0) {
	BIF_ERROR(BIF_P,BADARG);
    }
    bytes = alloc_restart(need);
    cost_to_proc(BIF_P, simple_loops_to_common(cost_of_utf8_need)); 
    left = allowed_iterations(BIF_P) - 
	simple_loops_to_common(cost_of_utf8_need);
    if (left <= 0) {
	/* simplified - let everything be setup by setting left to 1 */
	left = 1;
    }
    sleft = left;
    pos = 0;
    err = 0;


    rest_term = do_build_utf8(BIF_P, BIF_ARG_1, &left, latin1,
			      bytes, &pos, &characters, &err, leftover, &num_leftovers); 
    cost_to_proc(BIF_P, sleft - left); 
    return build_list_return(BIF_P,bytes,pos,characters,rest_term,err,
			     leftover,num_leftovers,BIF_ARG_2,left);
}


/*
 * When input to characters_to_list is a plain binary and the format is 'unicode', we do
 * a faster analyze and size count with this function.
 */
static ERTS_INLINE int
analyze_utf8(byte *source, Uint size, byte **err_pos, Uint *num_chars, int *left,
	     Sint *num_latin1_chars, Uint max_chars)
{
    Uint latin1_count;
    int is_latin1;
    *err_pos = source;
    if (num_latin1_chars) {
	is_latin1 = 1;
	latin1_count = 0;
    }
    *num_chars = 0;
    while (size) {
	if (((*source) & ((byte) 0x80)) == 0) {
	    source++;
	    --size;
	    if (num_latin1_chars)
		latin1_count++;
	} else if (((*source) & ((byte) 0xE0)) == 0xC0) {
	    if (size < 2) {
		return ERTS_UTF8_INCOMPLETE;
	    }
	    if (((source[1] & ((byte) 0xC0)) != 0x80) ||
		((*source) < 0xC2) /* overlong */) {
		return ERTS_UTF8_ERROR;
	    }
	    if (num_latin1_chars) {
		latin1_count++;
		if ((source[0] & ((byte) 0xFC)) != ((byte) 0xC0))
		    is_latin1 = 0;
	    }
	    source += 2;
	    size -= 2;
	} else if (((*source) & ((byte) 0xF0)) == 0xE0) {
	    if (size < 3) {
		return ERTS_UTF8_INCOMPLETE;
	    }
	    if (((source[1] & ((byte) 0xC0)) != 0x80) ||
		((source[2] & ((byte) 0xC0)) != 0x80) ||
		(((*source) == 0xE0) && (source[1] < 0xA0)) /* overlong */ ) {
		return ERTS_UTF8_ERROR;
	    }
	    if ((((*source) & ((byte) 0xF)) == 0xD) && 
		((source[1] & 0x20) != 0)) {
		return ERTS_UTF8_ERROR;
	    }
	    source += 3;
	    size -= 3;
	    if (num_latin1_chars)
		is_latin1 = 0;
	} else if (((*source) & ((byte) 0xF8)) == 0xF0) {
	    if (size < 4) {
		return ERTS_UTF8_INCOMPLETE;
	    }
	    if (((source[1] & ((byte) 0xC0)) != 0x80) ||
		((source[2] & ((byte) 0xC0)) != 0x80) ||
		((source[3] & ((byte) 0xC0)) != 0x80) ||
		(((*source) == 0xF0) && (source[1] < 0x90)) /* overlong */) {
		return ERTS_UTF8_ERROR;
	    }
	    if ((((*source) & ((byte)0x7)) > 0x4U) ||
		((((*source) & ((byte)0x7)) == 0x4U) && 
		 ((source[1] & ((byte)0x3F)) > 0xFU))) {
		return ERTS_UTF8_ERROR;
	    }
	    source += 4;
	    size -= 4; 
	    if (num_latin1_chars)
		is_latin1 = 0;
	} else {
	    return ERTS_UTF8_ERROR;
	}
	++(*num_chars);
	*err_pos = source;
	if (max_chars && size > 0 && *num_chars == max_chars)
	    return ERTS_UTF8_OK_MAX_CHARS;
	if (left && --(*left) <= 0 && size) {
	    return ERTS_UTF8_ANALYZE_MORE;
	}
    }
    if (num_latin1_chars)
	*num_latin1_chars = is_latin1 ? latin1_count : -1;
    return ERTS_UTF8_OK;
}

int erts_analyze_utf8(byte *source, Uint size, 
		      byte **err_pos, Uint *num_chars, int *left)
{
    return analyze_utf8(source, size, err_pos, num_chars, left, NULL, 0);
}

int erts_analyze_utf8_x(byte *source, Uint size, 
			byte **err_pos, Uint *num_chars, int *left,
			Sint *num_latin1_chars, Uint max_chars)
{
    return analyze_utf8(source, size, err_pos, num_chars, left, num_latin1_chars, max_chars);
}

/*
 * No errors should be able to occur - no overlongs, no malformed, no nothing
 */
static Eterm do_utf8_to_list(Process *p, Uint num, byte *bytes, Uint sz, 
			     Uint left,
			     Uint *num_built, Uint *num_eaten, Eterm tail)
{
    Eterm *hp;
    Eterm ret;
    byte *source, *ssource;
    Uint unipoint;

    ASSERT(num > 0);
    if (left < num) {
	if (left > 0)
	    num = left;
	else
	    num = 1;
    }
    
    *num_built = num; /* Always */

    hp = HAlloc(p,num * 2);
    ret = tail;
    source = bytes + sz;
    ssource = source;
    while(--source >= bytes) {
	if (((*source) & ((byte) 0x80)) == 0) {
	    unipoint = (Uint) *source;
	} else if (((*source) & ((byte) 0xE0)) == 0xC0) {
	    unipoint = 
		(((Uint) ((*source) & ((byte) 0x1F))) << 6) |
		((Uint) (source[1] & ((byte) 0x3F)));
	} else if (((*source) & ((byte) 0xF0)) == 0xE0) {
	    unipoint = 
		(((Uint) ((*source) & ((byte) 0xF))) << 12) |
		(((Uint) (source[1] & ((byte) 0x3F))) << 6) |
		((Uint) (source[2] & ((byte) 0x3F))); 	 	
	} else if (((*source) & ((byte) 0xF8)) == 0xF0) {
	    unipoint = 
		(((Uint) ((*source) & ((byte) 0x7))) << 18) |
		(((Uint) (source[1] & ((byte) 0x3F))) << 12) |
		(((Uint) (source[2] & ((byte) 0x3F))) << 6) |
		((Uint) (source[3] & ((byte) 0x3F))); 	 	
	} else {
	    /* ignore 2#10XXXXXX */
	    continue;
	}
	ret = CONS(hp,make_small(unipoint),ret);
	hp += 2;
	if (--num <= 0) {
	    break;
	}
    }
    *num_eaten = (ssource - source);
    return ret;
}

Eterm erts_utf8_to_list(Process *p, Uint num, byte *bytes, Uint sz, Uint left,
			Uint *num_built, Uint *num_eaten, Eterm tail)
{
    return do_utf8_to_list(p, num, bytes, sz, left, num_built, num_eaten, tail);
}

static int is_candidate(Uint cp)
{
    int index,pos;
    if (cp < 768) return 0;
    if (cp > 4023) {
	if (cp == 12441 || cp == 12442) return 1;
	return 0;
    }
    index = cp / 32 - COMP_CANDIDATE_MAP_OFFSET;
    pos = cp % 32;
    return !!(comp_candidate_map[index] & (1UL << pos));
}

static int hashsearch(int *htab, int htab_size, CompEntry *cv, Uint16 c)
{
	int bucket = c % htab_size;
	while (htab[bucket] != -1 && cv[htab[bucket]].c != c)
	    bucket = (bucket + 1) % htab_size;
	return htab[bucket];
}

#define TRANSLATE_NO 0
#define TRANSLATE_MAYBE -1

/* The s array is reversed */
static int translate(Uint16 *s, int slen, Uint16 *res)
{
    /* Go backwards through buffer and match against tree */
    int pos = 0;
    CompEntry *cv = compose_tab;
    int *hc = hash_compose_tab;
    int cvs = compose_tab_size;
    int x;
    while (pos < slen) {
	x = hashsearch(hc,cvs*HASH_SIZE_FACTOR,cv,s[pos]);
	if (x < 0) {
	    return TRANSLATE_NO;
	} 
	if (cv[x].res) {
	    *res = cv[x].res;
	    return pos;
	}
	cvs = cv[x].num_subs;
	hc = cv[x].hash;
	cv = cv[x].subs;
	++pos;
    }
    return TRANSLATE_MAYBE;
}

static void handle_first_norm(Uint16 *savepoints, int *numpointsp, Uint unipoint)
{
    /*erts_fprintf(stderr,"CP = %d, numpoints = %d\n",(int) unipoint,(int) *numpointsp);*/
    *numpointsp = 1;
    savepoints[0] = (Uint16) unipoint;
}

static void cleanup_norm(Eterm **hpp, Uint16 *savepoints, int numpoints, Eterm *retp)
{
    Eterm *hp = *hpp;
    int res,i;
    Uint16 newpoint;
    Eterm ret = *retp;
    
    ret = CONS(hp,make_small((Uint) savepoints[0]),ret);
    hp += 2;
    
    for (i = 1;i < numpoints;) {
	if(!is_candidate(savepoints[i]) || 
	   ((res = translate(savepoints+i,numpoints - i, &newpoint)) <= 0)) {
	    ret = CONS(hp,make_small((Uint) savepoints[i]),ret);
	    hp += 2;
	    ++i;
	} else {
	    ret = CONS(hp,make_small((Uint) newpoint),ret);
	    hp += 2;
	    i += res;
	}
    }
    *retp = ret;
}
    
static void handle_potential_norm(Eterm **hpp, Uint16 *savepoints, int *numpointsp, Uint unipoint, Eterm *retp)
{
    Eterm *hp = *hpp;
    int numpoints = *numpointsp;
    int res,i;
    Uint16 newpoint;
    Eterm ret = *retp;

    /* erts_fprintf(stderr,"CP = %d, numpoints = %d\n",(int) unipoint,(int) numpoints);*/
    if ((unipoint >> 16) == 0) { /* otherwise we're done here */ 
	savepoints[numpoints++] = (Uint16) unipoint;
	res = translate(savepoints,numpoints,&newpoint);
	if (res == TRANSLATE_NO) {
	    ret = CONS(hp,make_small((Uint) savepoints[0]),ret);
	    hp += 2;
	    for (i = 1;i < numpoints;) {
		if(!is_candidate(savepoints[i]) ||
		   ((res = translate(savepoints+i,numpoints - i, &newpoint)) == 0)) {
		    ret = CONS(hp,make_small((Uint) savepoints[i]),ret);
		    hp += 2;
		    ++i;
		} else if (res > 0) {
		    ret = CONS(hp,make_small((Uint) newpoint),ret);
		    hp += 2;
		    i += res;
		} else { /* res < 0 */
		    /* A "maybe", means we are not done yet */
		    int j = 0;
		    while (i < numpoints) {
			savepoints[j++] = savepoints[i++];
		    }
		    numpoints = j;
		    goto breakaway;
		}
	    }
	    numpoints = 0;
	breakaway:
	    ;
	} else if (res > 0) {
	    numpoints = 0;
	    ret = CONS(hp,make_small((Uint) newpoint),ret);
	    hp += 2;
	} /* < 0 means go on */
    } else {
	/* Unconditional rollup, this character is larger than 16 bit */
	ret = CONS(hp,make_small((Uint) savepoints[0]),ret);
	hp += 2;
	
	for (i = 1;i < numpoints;) {
	    if(!is_candidate(savepoints[i]) || 
	       ((res = translate(savepoints+i,numpoints - i, &newpoint)) <= 0)) {
		ret = CONS(hp,make_small((Uint) savepoints[i]),ret);
		hp += 2;
		++i;
	    } else {
		ret = CONS(hp,make_small((Uint) newpoint),ret);
		hp += 2;
		i += res;
	    }
	}
	ret = CONS(hp,make_small(unipoint),ret);
	hp += 2;
	numpoints = 0;
    }	
    *hpp = hp;
    *numpointsp = numpoints;
    *retp = ret;
} 

static Eterm do_utf8_to_list_normalize(Process *p, Uint num, byte *bytes, Uint sz)
{
    Eterm *hp,*hp_end;
    Eterm ret;
    byte *source;
    Uint unipoint;
    Uint16 savepoints[4];
    int numpoints = 0;

    if (num == 0)
	return NIL;

    ASSERT(num > 0);

    hp = HAlloc(p,num * 2); /* May be to much */
    hp_end = hp + num * 2;
    ret = NIL;
    source = bytes + sz;
    while(--source >= bytes) {
	if (((*source) & ((byte) 0x80)) == 0) {
	    unipoint = (Uint) *source;
	} else if (((*source) & ((byte) 0xE0)) == 0xC0) {
	    unipoint = 
		(((Uint) ((*source) & ((byte) 0x1F))) << 6) |
		((Uint) (source[1] & ((byte) 0x3F))); 	
	} else if (((*source) & ((byte) 0xF0)) == 0xE0) {
	    unipoint = 
		(((Uint) ((*source) & ((byte) 0xF))) << 12) |
		(((Uint) (source[1] & ((byte) 0x3F))) << 6) |
		((Uint) (source[2] & ((byte) 0x3F))); 	 	
	} else if (((*source) & ((byte) 0xF8)) == 0xF0) {
	    unipoint = 
		(((Uint) ((*source) & ((byte) 0x7))) << 18) |
		(((Uint) (source[1] & ((byte) 0x3F))) << 12) |
		(((Uint) (source[2] & ((byte) 0x3F))) << 6) |
		((Uint) (source[3] & ((byte) 0x3F))); 	 	
	} else {
	    /* ignore 2#10XXXXXX */
	    continue;
	}
	if (numpoints) {
	    handle_potential_norm(&hp,savepoints,&numpoints,unipoint,&ret);
	    continue;
	}
	/* We are not building up any normalizations yet, look that we shouldn't start... */
	if (is_candidate(unipoint)) {
	    handle_first_norm(savepoints,&numpoints,unipoint);
	    continue;
	} 
	ret = CONS(hp,make_small(unipoint),ret);
	hp += 2;
    }
    /* so, we'we looped to the beginning, do we have anything saved? */
    if (numpoints) {
	cleanup_norm(&hp,savepoints,numpoints,&ret);
    }
    if (hp_end != hp) {
	HRelease(p,hp_end,hp);
    }
    return ret;
}

/*
 * The last step of characters_to_list, build a list from the buffer 'bytes' (created in the same way
 * as for characters_to_utf8). All sizes are known in advance and most data will be held in a 
 * "magic binary" during trapping.
 */
static BIF_RETTYPE finalize_list_to_list(Process *p, 
					 byte *bytes,
					 Eterm rest,
					 Uint num_processed_bytes,
					 Uint num_bytes_to_process, 
					 Uint num_resulting_chars, 
					 int state, int left,
					 Eterm tail) 
{
    Uint num_built; /* characters */
    Uint num_eaten; /* bytes */
    Eterm *hp;
    Eterm converted,ret;

    if (!num_bytes_to_process) {
	converted = tail;
    } else {
	num_built = 0;
	num_eaten = 0;
	converted = do_utf8_to_list(p, num_resulting_chars,
				    bytes, num_bytes_to_process,
				    left, &num_built, &num_eaten, tail);
	cost_to_proc(p,num_built);
	
	if (num_built != num_resulting_chars) { /* work left to do */
	    RestartContext rc;

	    rc.num_resulting_chars = num_resulting_chars - num_built;
	    rc.num_bytes_to_process = num_bytes_to_process - num_eaten;
	    rc.num_processed_bytes = num_processed_bytes + num_eaten;
	    rc.state = state;
	    rc.bytes = bytes;
	    BUMP_ALL_REDS(p);
	    BIF_TRAP3(&characters_to_list_trap_2_exp, p, 
		       make_magic_bin_for_restart(p, &rc), rest, converted); 
	}
    }

    /* 
     * OK, no more trapping, let's get rid of the temporary array...
     */

    free_restart(bytes);
    if (state == ERTS_UTF8_INCOMPLETE) {
	hp = HAlloc(p,4);
	ret = TUPLE3(hp,am_incomplete,converted,rest);
    } else if (state == ERTS_UTF8_ERROR) {
	hp = HAlloc(p,4);
	ret = TUPLE3(hp,am_error,converted,rest);
    } else {
	ret = converted;
    }

    BIF_RET(ret);
}
 
static BIF_RETTYPE characters_to_list_trap_2(BIF_ALIST_3)
{
    RestartContext *rc;
    byte *bytes;

    rc = get_rc_from_bin(BIF_ARG_1);

    bytes = rc->bytes;
    rc->bytes = NULL; /* Don't want this freed just yet... */
    return finalize_list_to_list(BIF_P, bytes, BIF_ARG_2, rc->num_processed_bytes,
				 rc->num_bytes_to_process, rc->num_resulting_chars,
				 rc->state, allowed_iterations(BIF_P), BIF_ARG_3);
}


/*
 * Hooks into the process of decoding a binary depending on state.
 * If last_state is ERTS_UTF8_ANALYZE_MORE, num_bytes_to_process 
 * and num_resulting_chars will grow
 * until we're done analyzing the binary. Then we'll eat 
 * the bytes to process, lowering num_bytes_to_process and num_resulting_chars,
 * while increasing num_processed_bytes until we're done. the state 
 * indicates how to return (error, incomplete or ok) in this stage.
 * note that num_processed_bytes and num_bytes_to_process will make up the 
 * length of the binary part to process, not necessarily the length of the 
 * whole binary (if there are errors or an incomplete tail).
 *
 * Analyzing happens from the beginning of the binary towards the end,
 * while result is built from the end of the analyzed/accepted part 
 * towards the beginning.
 *
 * Note that this routine is *only* called when original input was a plain utf8 binary,
 * otherwise the rest and the sizes are known in advance, so finalize_list_to_list is 
 * used to build the resulting list (no analyzing needed).
 */
static BIF_RETTYPE do_bif_utf8_to_list(Process *p, 
				       Eterm orig_bin,
				       Uint num_processed_bytes,
				       Uint num_bytes_to_process, 
				       Uint num_resulting_chars, 
				       int state,
				       Eterm tail) 
{
    int left;
    Uint bitoffs;
    Uint bitsize;
    Uint size;
    byte *bytes;
    Eterm converted = NIL;
    Eterm rest = NIL;
    Eterm *hp;
    Eterm ret;
    byte *temp_alloc = NULL;
    byte *endpos;
    Uint numchar;

    Uint b_sz; /* size of the non analyzed tail */
    Uint num_built; /* characters */
    Uint num_eaten; /* bytes */

    ERTS_GET_BINARY_BYTES(orig_bin, bytes, bitoffs, bitsize);
    if (bitsize != 0) {
	converted = NIL;
	rest = orig_bin;
	goto error_return;
    }
    if (bitoffs != 0) {
	bytes = erts_get_aligned_binary_bytes(orig_bin, &temp_alloc);
    }
    
    size = binary_size(orig_bin);

    left = allowed_iterations(p);
    
    if (state == ERTS_UTF8_ANALYZE_MORE) {
	state = erts_analyze_utf8(bytes + num_bytes_to_process,
			     size - num_bytes_to_process,
			     &endpos,&numchar,&left);
	cost_to_proc(p,numchar);
	num_resulting_chars += numchar;
	num_bytes_to_process = endpos - bytes;
	if (state == ERTS_UTF8_ANALYZE_MORE) {
	    Eterm epos = erts_make_integer(num_bytes_to_process,p);
	    Eterm enumchar = erts_make_integer(num_resulting_chars,p);
	    erts_free_aligned_binary_bytes(temp_alloc);
	    BUMP_ALL_REDS(p);
	    BIF_TRAP3(&characters_to_list_trap_3_exp, p, orig_bin, epos, 
		      enumchar);
	}
    } 

    /* 
     * If we're here, we have everything analyzed and are instead building 
     */


    if (!num_bytes_to_process) {
	converted = tail;
    } else {
	num_built = 0;
	num_eaten = 0;
	converted = do_utf8_to_list(p, num_resulting_chars,
				    bytes, num_bytes_to_process,
				    left, &num_built, &num_eaten, tail);
	cost_to_proc(p,num_built);
	
	if (num_built != num_resulting_chars) { /* work left to do */
	    Eterm newnum_resulting_chars = 
		erts_make_integer(num_resulting_chars - num_built,p);
	    Eterm newnum_bytes_to_process = 
		erts_make_integer(num_bytes_to_process - num_eaten,p);
	    Eterm newnum_processed_bytes = 
		erts_make_integer(num_processed_bytes + num_eaten,p);
	    Eterm traptuple;
	    hp = HAlloc(p,7);
	    traptuple = TUPLE6(hp,orig_bin,newnum_processed_bytes,
			       newnum_bytes_to_process, 
			       newnum_resulting_chars,
			       make_small(state),
			       converted);
	    BUMP_ALL_REDS(p);
	    erts_free_aligned_binary_bytes(temp_alloc);
	    BIF_TRAP1(&characters_to_list_trap_4_exp,p,traptuple);
	}
    }

    /* 
     * OK, no more trapping, let's build rest binary if there should
     * be one. 
     */

    b_sz = size - (num_bytes_to_process + num_processed_bytes);

    if (b_sz) {
	ErlSubBin *sb;
	Eterm orig;
	Uint offset;
	ASSERT(state != ERTS_UTF8_OK);
	hp = HAlloc(p, ERL_SUB_BIN_SIZE);
	sb = (ErlSubBin *) hp;
	ERTS_GET_REAL_BIN(orig_bin, orig, offset, bitoffs, bitsize);
	sb->thing_word = HEADER_SUB_BIN;
	sb->size = b_sz;
	sb->offs = offset + num_bytes_to_process + num_processed_bytes;
	sb->orig = orig;
	sb->bitoffs = bitoffs;
	sb->bitsize = bitsize;
	sb->is_writable = 0;
	rest = make_binary(sb);
    } 

    /* Done */

    if (state == ERTS_UTF8_INCOMPLETE) {
	if (check_leftovers(bytes + num_bytes_to_process + num_processed_bytes,
			    b_sz) != 0) {
	    goto error_return;
	}
	hp = HAlloc(p,4);
	ret = TUPLE3(hp,am_incomplete,converted,rest);
    } else if (state == ERTS_UTF8_ERROR) {
 error_return:
	hp = HAlloc(p,4);
	ret = TUPLE3(hp,am_error,converted,rest);
    } else {
	ret = converted;
    }

    erts_free_aligned_binary_bytes(temp_alloc);
    BIF_RET(ret);
}


/* 
 * This is called when there's still analyzing left to do,
 * we only reach this if original input was a binary.
 */

static BIF_RETTYPE characters_to_list_trap_3(BIF_ALIST_3)
{
    Uint num_bytes_to_process;
    Uint num_resulting_chars;

    term_to_Uint(BIF_ARG_2, &num_bytes_to_process); /* The number of already
						       analyzed and accepted 
						       bytes */
    term_to_Uint(BIF_ARG_3, &num_resulting_chars); /* The number of chars
						      procuced by the
						      already analyzed
						      part of the binary */

    /*erts_printf("Trap: %T, %T, %T\n",BIF_ARG_1, BIF_ARG_2, BIF_ARG_3);*/

    return do_bif_utf8_to_list(BIF_P, 
			       BIF_ARG_1, /* the binary */ 
			       0U, /* nothing processed yet */
			       num_bytes_to_process, 
			       num_resulting_chars,
			       ERTS_UTF8_ANALYZE_MORE, /* always this state here */
			       NIL); /* Nothing built -> no tail yet */
	
}

/*
 * This is called when analyzing is done and we are trapped during building,
 * we only reach this if original input was a binary.
 */
static BIF_RETTYPE characters_to_list_trap_4(BIF_ALIST_1)
{
    Uint num_processed_bytes;
    Uint num_bytes_to_process;
    Uint num_resulting_chars;
    Eterm orig_bin, tail;
    int last_state;
    Eterm *tplp = tuple_val(BIF_ARG_1);

    orig_bin = tplp[1];
    term_to_Uint(tplp[2], &num_processed_bytes);
    term_to_Uint(tplp[3], &num_bytes_to_process);
    term_to_Uint(tplp[4], &num_resulting_chars);
    last_state = (int) signed_val(tplp[5]);
    tail = tplp[6];

    /*erts_printf("Trap: {%T, %lu, %lu, %lu, %d, %T}\n",
      orig_bin, num_processed_bytes, num_bytes_to_process, 
      num_resulting_chars, last_state, tail);*/

    return do_bif_utf8_to_list(BIF_P, 
			       orig_bin, /* The whole binary */
			       num_processed_bytes,  /* Number of bytes 
							already processed */
			       num_bytes_to_process, /* Bytes left to proc. */
			       num_resulting_chars,  /* Num chars left to 
							build */
			       last_state,           /* The current state 
							(never ANALYZE_MORE)*/
			       tail);                /* The already built 
							tail */  
	
}
/*
 * This is only used when characters are a plain unicode (utf8) binary.
 * Instead of building an utf8 buffer, we analyze the binary given and use that.
 */

static BIF_RETTYPE utf8_to_list(Process* p, Eterm arg)
{
    if (!is_binary(arg) || aligned_binary_size(arg) < 0) {
	BIF_ERROR(p, BADARG);
    }
    return do_bif_utf8_to_list(p, arg, 0U, 0U, 0U,
			       ERTS_UTF8_ANALYZE_MORE, NIL);
}


BIF_RETTYPE atom_to_binary_2(BIF_ALIST_2)
{
    Atom* ap;

    if (is_not_atom(BIF_ARG_1)) {
	goto error;
    }

    ap = atom_tab(atom_val(BIF_ARG_1));

    if (BIF_ARG_2 == am_latin1) {
	Eterm bin_term;

	if (ap->latin1_chars < 0) {
	    goto error;
	}
	if (ap->latin1_chars == ap->len) {
	    bin_term = new_binary(BIF_P, ap->name, ap->len);
	}
	else {
	    byte* bin_p;
	    int dbg_sz;
	    bin_term = new_binary(BIF_P, 0, ap->latin1_chars);
	    bin_p = binary_bytes(bin_term);
	    dbg_sz = erts_utf8_to_latin1(bin_p, ap->name, ap->len);
	    ASSERT(dbg_sz == ap->latin1_chars); (void)dbg_sz; 
	}
	BIF_RET(bin_term);
    } else if (BIF_ARG_2 == am_utf8 || BIF_ARG_2 == am_unicode) {
	BIF_RET(new_binary(BIF_P, ap->name, ap->len));
    } else {
    error:
	BIF_ERROR(BIF_P, BADARG);
    }
}

static BIF_RETTYPE
binary_to_atom(Process* proc, Eterm bin, Eterm enc, int must_exist)
{
    byte* bytes;
    byte *temp_alloc = NULL;
    Uint bin_size;

    if ((bytes = erts_get_aligned_binary_bytes(bin, &temp_alloc)) == 0) {
	BIF_ERROR(proc, BADARG);
    }
    bin_size = binary_size(bin);
    if (enc == am_latin1) {
	Eterm a;
	if (bin_size > MAX_ATOM_CHARACTERS) {
	system_limit:
	    erts_free_aligned_binary_bytes(temp_alloc);
	    BIF_ERROR(proc, SYSTEM_LIMIT);
	}
	if (!must_exist) {
	    a = erts_atom_put((byte *) bytes,
			      bin_size,
			      ERTS_ATOM_ENC_LATIN1,
			      0);
    	    erts_free_aligned_binary_bytes(temp_alloc);
	    if (is_non_value(a))
		goto badarg;
	    BIF_RET(a);
	} else if (erts_atom_get((char *)bytes, bin_size, &a, ERTS_ATOM_ENC_LATIN1)) {
	    erts_free_aligned_binary_bytes(temp_alloc);
	    BIF_RET(a);
	} else {
	    goto badarg;
	}
    } else if (enc == am_utf8 || enc == am_unicode) {
	Eterm res;
	Uint num_chars = 0;
	const byte* p = bytes;
	Uint left = bin_size;

	while (left) {
	    if (++num_chars > MAX_ATOM_CHARACTERS) {
		goto system_limit;
	    }
	    if ((p[0] & 0x80) == 0) {
		++p;
		--left;
	    }
	    else if (left >= 2
		     && (p[0] & 0xFE) == 0xC2 /* only allow latin1 subset */
		     && (p[1] & 0xC0) == 0x80) {
		p += 2;
		left -= 2;
	    }
	    else goto badarg;
	}

	if (!must_exist) {
	    res = erts_atom_put((byte *) bytes,
				bin_size,
				ERTS_ATOM_ENC_UTF8,
				0);
	}
	else if (!erts_atom_get((char*)bytes, bin_size, &res, ERTS_ATOM_ENC_UTF8)) {
	    goto badarg;
	}
	erts_free_aligned_binary_bytes(temp_alloc);
	if (is_non_value(res))
	    goto badarg;
	BIF_RET(res);
    } else {
    badarg:
	erts_free_aligned_binary_bytes(temp_alloc);
	BIF_ERROR(proc, BADARG);
    }
}

BIF_RETTYPE binary_to_atom_2(BIF_ALIST_2)
{
    return binary_to_atom(BIF_P, BIF_ARG_1, BIF_ARG_2, 0);
}

BIF_RETTYPE binary_to_existing_atom_2(BIF_ALIST_2)
{
    return binary_to_atom(BIF_P, BIF_ARG_1, BIF_ARG_2, 1);
}

/**********************************************************
 * Simpler non-interruptable routines for UTF-8 and 
 * Windowish UTF-16 (restricted)
 **********************************************************/
/*
 * This function is the heart of the Unicode support for 
 * open_port - spawn_executable. It converts both the name
 * of the executable and the arguments according to the same rules
 * as for filename conversion. That means as if your arguments are
 * to be raw, you supply binaries, else unicode characters are allowed up to
 * the encoding maximum (256 of the unicode max).
 * Depending on the filename encoding standard, the vector is then
 * converted to whatever is used, which might mean win_utf16 if on windows.
 * Do not peek into the argument vector or filenam with ordinary
 * string routines, that will certainly fail on some OS.
 */

char *erts_convert_filename_to_native(Eterm name, char *statbuf, size_t statbuf_size,
				      ErtsAlcType_t alloc_type, int allow_empty,
				      int allow_atom, Sint *used)
{
    int encoding = erts_get_native_filename_encoding();
    return erts_convert_filename_to_encoding(name, statbuf, statbuf_size, alloc_type,
					     allow_empty, allow_atom, encoding,
					     used, 0);
}

char *erts_convert_filename_to_encoding(Eterm name, char *statbuf, size_t statbuf_size,
					ErtsAlcType_t alloc_type, int allow_empty,
					int allow_atom, int encoding, Sint *used,
					Uint extra)
{
    char* name_buf = NULL;

    if ((allow_atom && is_atom(name)) || 
	is_list(name) || 
	(allow_empty && is_nil(name))) {
	Sint need;
	if ((need = erts_native_filename_need(name,encoding)) < 0) {
	    return NULL;
	}
	if (encoding == ERL_FILENAME_WIN_WCHAR) {
	    need += 2;
	    extra *= 2;
	} else {
	    ++need;
	}
	if (used) 
	    *used = (Sint) need;
	if (need+extra > statbuf_size) {
	    name_buf = (char *) erts_alloc(alloc_type, need+extra);
	} else {
	    name_buf = statbuf;
	}
	erts_native_filename_put(name,encoding,(byte *)name_buf); 
	name_buf[need-1] = 0;
	if (encoding == ERL_FILENAME_WIN_WCHAR) {
	    name_buf[need-2] = 0;
	}
    } else if (is_binary(name)) {
	byte *temp_alloc = NULL;
	byte *bytes;
	Uint size;
	
	size = binary_size(name);
	bytes = erts_get_aligned_binary_bytes(name, &temp_alloc);

	if (encoding != ERL_FILENAME_WIN_WCHAR) {
	    /*Add 0 termination only*/
	    if (used) 
		*used = (Sint) size+1;
	    if (size+1+extra > statbuf_size) {
		name_buf = (char *) erts_alloc(alloc_type, size+1+extra);
	    } else {
		name_buf = statbuf;
	    }
	    memcpy(name_buf,bytes,size);
	    name_buf[size]=0;
	} else {
            name_buf = erts_convert_filename_to_wchar(bytes, size,
                                                      statbuf, statbuf_size,
                                                      alloc_type, used, extra);
        }
	erts_free_aligned_binary_bytes(temp_alloc);
    } else {
	return NULL;
    }
    return name_buf;
}

char* erts_convert_filename_to_wchar(byte* bytes, Uint size,
                                     char *statbuf, size_t statbuf_size,
                                     ErtsAlcType_t alloc_type, Sint* used,
                                     Uint extra_wchars)
{
    byte *err_pos;
    Uint num_chars;
    char* name_buf = NULL;
    Sint need;
    char *p;

    if (erts_analyze_utf8(bytes,size,&err_pos,&num_chars,NULL) != ERTS_UTF8_OK ||
        erts_get_user_requested_filename_encoding() ==  ERL_FILENAME_LATIN1) {

        /* What to do now? Maybe latin1, so just take byte for byte instead */
        need = (Sint) (size + extra_wchars + 1) * 2;
        if (need > statbuf_size) {
            name_buf = (char *) erts_alloc(alloc_type, need);
        } else {
            name_buf = statbuf;
        }
        p = name_buf;
        while (size--) {
            *p++ = *bytes++;
            *p++ = 0;
        }
    } else { /* WIN_WCHAR and valid UTF8 */
        need = (Sint) (num_chars + extra_wchars + 1) * 2;
        if (need > statbuf_size) {
            name_buf = (char *) erts_alloc(alloc_type, need);
        } else {
            name_buf = statbuf;
        }
        erts_copy_utf8_to_utf16_little((byte *) name_buf, bytes, num_chars);
        p = name_buf + num_chars*2;
    }
    *p++ = 0;
    *p++ = 0;
    if (used)
        *used = p - name_buf;
    return name_buf;
}


static int filename_len_16bit(byte *str) 
{
    byte *p = str;
    while(*p != '\0' || p[1] != '\0') {
	p += 2;
    }
    return (p - str);
}
Eterm erts_convert_native_to_filename(Process *p, byte *bytes)
{
    Uint size,num_chars;
    Eterm *hp;
    byte *err_pos;
    Uint num_built; /* characters */
    Uint num_eaten; /* bytes */
    Eterm ret;
    int mac = 0;

    switch (erts_get_native_filename_encoding()) {
    case ERL_FILENAME_LATIN1:
	goto noconvert;
    case ERL_FILENAME_UTF8_MAC:
	mac = 1;
    case ERL_FILENAME_UTF8:
	size = strlen((char *) bytes);
	if (size == 0)
	    return NIL;
	if (erts_analyze_utf8(bytes,size,&err_pos,&num_chars,NULL) != ERTS_UTF8_OK) {
	    goto noconvert;
	}
	num_built = 0;
	num_eaten = 0;
	if (mac) {
	    ret = do_utf8_to_list_normalize(p, num_chars, bytes, size);
	} else {
	    ret = do_utf8_to_list(p, num_chars, bytes, size, num_chars, &num_built, &num_eaten, NIL);
	} 
	return ret;
    case ERL_FILENAME_WIN_WCHAR:
	size=filename_len_16bit(bytes);
	if ((size % 2) != 0) { /* Panic fixup to avoid crashing the emulator */
	    size--;
	    hp = HAlloc(p, size+2);
	    ret = CONS(hp,make_small((Uint) bytes[size]),NIL);
	    hp += 2;
	} else {
	    hp = HAlloc(p, size);
	    ret = NIL;
	}
	bytes += size-1;
	while (size > 0) {
	    Uint x = ((Uint) *bytes--) << 8;
	    x |= ((Uint) *bytes--);
	    size -= 2;
	    ret = CONS(hp,make_small(x),ret);
	    hp += 2;
	}	    
	return ret;
    default:
	goto noconvert;
    }
 noconvert:
    size = strlen((char *) bytes);
    hp = HAlloc(p, 2 * size);
    return erts_bin_bytes_to_list(NIL, hp, bytes, size, 0);
}


Sint erts_native_filename_need(Eterm ioterm, int encoding) 
{
    Eterm *objp;
    Eterm obj;
    DECLARE_ESTACK(stack);
    Sint need = 0;

    if (is_atom(ioterm)) {
	Atom* ap;
	int i;
	ap = atom_tab(atom_val(ioterm));
	switch (encoding) {
	case ERL_FILENAME_LATIN1:
	    need = ap->latin1_chars;  /* May be -1 */
	    break;
	case ERL_FILENAME_UTF8_MAC:
	case ERL_FILENAME_UTF8:
	    need = ap->len;
	    break;
	case ERL_FILENAME_WIN_WCHAR:
            if (ap->latin1_chars >= 0) {
		need = 2* ap->latin1_chars;
            }
	    else {
		for (i = 0; i < ap->len; ) {
                    if (ap->name[i] < 0x80) {
			i++;
                    } else if (ap->name[i] < 0xE0) {
			i += 2;
                    } else if (ap->name[i] < 0xF0) {
			i += 3;
                    } else {
			need = -1;
			break;
		    }
		    need += 2;
		}
	    }
	    break;
	default:
	    need = -1;
	}
	DESTROY_ESTACK(stack);
	return need;
    }

    if (is_nil(ioterm)) {
	DESTROY_ESTACK(stack);
	return need;
    }
    if (!is_list(ioterm)) {
	DESTROY_ESTACK(stack);
	return (Sint) -1;
    }
    /* OK a list, needs to be processed in order, handling each flat list-level
       as they occur, just like io_list_to_binary would */
    ESTACK_PUSH(stack,ioterm);
    while (!ESTACK_ISEMPTY(stack)) {
	ioterm = ESTACK_POP(stack);	
	if (is_nil(ioterm)) {
	    /* ignore empty lists */
	    continue;
	}
	if(is_list(ioterm)) {
L_Again:   /* Restart with sublist, old listend was pushed on stack */
	    objp = list_val(ioterm);
	    obj = CAR(objp);
	    for(;;) { /* loop over one flat list of bytes and binaries
		         until sublist or list end is encountered */
		if (is_small(obj)) { /* Always small */
		    for(;;) {
			Uint x = unsigned_val(obj);
			switch (encoding) {
			case ERL_FILENAME_LATIN1:
			    if (x > 255) {
				DESTROY_ESTACK(stack);
				return ((Sint) -1);
			    }
			    need += 1;
			    break;
			case ERL_FILENAME_UTF8_MAC:
			case ERL_FILENAME_UTF8:
			    if (x < 0x80) {
				need +=1;
			    } else if (x < 0x800) {
				need += 2;
			    } else if (x < 0x10000) {
				if (x >= 0xD800 && x <= 0xDFFF) {
				    /* Invalid unicode range */
				    DESTROY_ESTACK(stack);
				    return ((Sint) -1);
				}
				need += 3;
			    } else  if (x < 0x110000) {
				need += 4; 
			    } else {
				DESTROY_ESTACK(stack);
				return ((Sint) -1);
			    }
			    break;
			case ERL_FILENAME_WIN_WCHAR:
			    if (x <= 0xffff) { 
				need += 2;
				break;
			    } /* else fall throug to error */
			default:
			    DESTROY_ESTACK(stack);
			    return ((Sint) -1);
			}
			    
			/* everything else will give badarg later 
			   in the process, so we dont check */
			ioterm = CDR(objp);
			if (!is_list(ioterm)) {
			    break;
			}
			objp = list_val(ioterm);
			obj = CAR(objp);
			if (!is_small(obj))
			    break;
		    }
		} else if (is_nil(obj)) {
		    ioterm = CDR(objp);
		    if (!is_list(ioterm)) {
			break;
		    }
		    objp = list_val(ioterm);
		    obj = CAR(objp);
		} else if (is_list(obj)) {
		    /* push rest of list for later processing, start 
		       again with sublist */
		    ESTACK_PUSH(stack,CDR(objp));
		    ioterm = obj;
		    goto L_Again;
		} else {
		    DESTROY_ESTACK(stack);
		    return ((Sint) -1);
		} 
		if (is_nil(ioterm) || !is_list(ioterm)) {
		    break;
		}
	    } /* for(;;) */
	} /* is_list(ioterm) */
	
	if (!is_list(ioterm) && !is_nil(ioterm)) {
	    /* inproper list end */
	    DESTROY_ESTACK(stack);
	    return ((Sint) -1);
	}
    } /* while  not estack empty */
    DESTROY_ESTACK(stack);
    return need;
}

void erts_native_filename_put(Eterm ioterm, int encoding, byte *p) 
{
    Eterm *objp;
    Eterm obj;
    DECLARE_ESTACK(stack);

    if (is_atom(ioterm)) {
	Atom* ap;
	int i;
	ap = atom_tab(atom_val(ioterm));
	switch (encoding) {
	case ERL_FILENAME_LATIN1:
	    for (i = 0; i < ap->len; i++) {
		if (ap->name[i] < 0x80) {
		    *p++ = ap->name[i];
		} else {
		    ASSERT(ap->name[i] < 0xC4);
		    *p++ = ((ap->name[i] & 3) << 6) | (ap->name[i+1] & 0x3F);
		    i++;
		}
	    }
	    break;
	case ERL_FILENAME_UTF8_MAC:
	case ERL_FILENAME_UTF8:
	    sys_memcpy(p, ap->name, ap->len);
	    break;
	case ERL_FILENAME_WIN_WCHAR:
	    for (i = 0; i < ap->len; i++) {
		/* Little endian */
                if (ap->name[i] < 0x80) {
		    *p++ = ap->name[i];
		    *p++ = 0;
                } else if (ap->name[i] < 0xE0) {
		    *p++ = ((ap->name[i] & 3) << 6) | (ap->name[i+1] & 0x3F);
		    *p++ = ((ap->name[i] & 0x1C) >> 2);
		    i++;
                } else {
		    ASSERT(ap->name[i] < 0xF0);
		    *p++ = ((ap->name[i+1] & 3) << 6) | (ap->name[i+2] & 0x3C);
		    *p++ = ((ap->name[i] & 0xF) << 4) | ((ap->name[i+1] & 0x3C) >> 2);
		    i += 2;
		}
            }
	    break;
	default:
	    ASSERT(0);
	}
	DESTROY_ESTACK(stack);
	return;
    }

    if (is_nil(ioterm)) {
	DESTROY_ESTACK(stack);
	return;
    }
    ASSERT(is_list(ioterm));
    /* OK a list, needs to be processed in order, handling each flat list-level
       as they occur, just like io_list_to_binary would */
    ESTACK_PUSH(stack,ioterm);
    while (!ESTACK_ISEMPTY(stack)) {
	ioterm = ESTACK_POP(stack);	
	if (is_nil(ioterm)) {
	    /* ignore empty lists */
	    continue;
	}
	if(is_list(ioterm)) {
L_Again:   /* Restart with sublist, old listend was pushed on stack */
	    objp = list_val(ioterm);
	    obj = CAR(objp);
	    for(;;) { /* loop over one flat list of bytes and binaries
		         until sublist or list end is encountered */
		if (is_small(obj)) { /* Always small */
		    for(;;) {
			Uint x = unsigned_val(obj);
			switch (encoding) {
			case ERL_FILENAME_LATIN1:
			    ASSERT( x < 256);
			    *p++ = (byte) x;
			    break;
			case ERL_FILENAME_UTF8_MAC:
			case ERL_FILENAME_UTF8:
			    if (x < 0x80) {
				*p++ = (byte) x;
			    }
			    else if (x < 0x800) {
				*p++ = (((byte) (x >> 6)) | 
					((byte) 0xC0));
				*p++ = (((byte) (x & 0x3F)) | 
					((byte) 0x80));
			    } else if (x < 0x10000) {
				ASSERT(!(x >= 0xD800 && x <= 0xDFFF));
				*p++ = (((byte) (x >> 12)) | 
					((byte) 0xE0));
				*p++ = ((((byte) (x >> 6)) & 0x3F)  | 
					((byte) 0x80));
				*p++ = (((byte) (x & 0x3F)) | 
					((byte) 0x80));
			    } else {
				ASSERT(x < 0x110000);
				*p++ = (((byte) (x >> 18)) | 
					((byte) 0xF0));
				*p++ = ((((byte) (x >> 12)) & 0x3F)  | 
					((byte) 0x80));
				*p++ = ((((byte) (x >> 6)) & 0x3F)  | 
					((byte) 0x80));
				*p++ = (((byte) (x & 0x3F)) | 
					((byte) 0x80));
			    }
			    break;
			case ERL_FILENAME_WIN_WCHAR:
			    ASSERT(x <= 0xFFFF); 
			    *p++ = (byte) (x & 0xFFU);
			    *p++ = (byte) ((x >> 8) & 0xFFU);
			    break;
			default:
			    ASSERT(0);
			}
			    
			/* everything else will give badarg later 
			   in the process, so we dont check */
			ioterm = CDR(objp);
			if (!is_list(ioterm)) {
			    break;
			}
			objp = list_val(ioterm);
			obj = CAR(objp);
			if (!is_small(obj))
			    break;
		    }
		} else if (is_nil(obj)) {
		    ioterm = CDR(objp);
		    if (!is_list(ioterm)) {
			break;
		    }
		    objp = list_val(ioterm);
		    obj = CAR(objp);
		} else if (is_list(obj)) {
		    /* push rest of list for later processing, start 
		       again with sublist */
		    ESTACK_PUSH(stack,CDR(objp));
		    ioterm = obj;
		    goto L_Again;
		} else {
		    ASSERT(0);
		} 
		if (is_nil(ioterm) || !is_list(ioterm)) {
		    break;
		}
	    } /* for(;;) */
	} /* is_list(ioterm) */
	
	ASSERT(is_list(ioterm) || is_nil(ioterm));
    } /* while  not estack empty */
    DESTROY_ESTACK(stack);
    return;
}
void erts_copy_utf8_to_utf16_little(byte *target, byte *bytes, int num_chars)
{
    Uint unipoint;
    
    while (num_chars--) {
	if (((*bytes) & ((byte) 0x80)) == 0) {
	    unipoint = (Uint) *bytes;
	    ++bytes;
	} else if (((*bytes) & ((byte) 0xE0)) == 0xC0) {
	    unipoint = 
		(((Uint) ((*bytes) & ((byte) 0x1F))) << 6) |
		((Uint) (bytes[1] & ((byte) 0x3F))); 	
	    bytes += 2;
	} else if (((*bytes) & ((byte) 0xF0)) == 0xE0) {
	    unipoint = 
		(((Uint) ((*bytes) & ((byte) 0xF))) << 12) |
		(((Uint) (bytes[1] & ((byte) 0x3F))) << 6) |
		((Uint) (bytes[2] & ((byte) 0x3F)));
	    bytes +=3;
	} else if (((*bytes) & ((byte) 0xF8)) == 0xF0) {
	    unipoint = 
		(((Uint) ((*bytes) & ((byte) 0x7))) << 18) |
		(((Uint) (bytes[1] & ((byte) 0x3F))) << 12) |
		(((Uint) (bytes[2] & ((byte) 0x3F))) << 6) |
		((Uint) (bytes[3] & ((byte) 0x3F)));
	    bytes += 4;
	} else {
	    erl_exit(1,"Internal unicode error in prim_file:internal_name2native/1");
	}
	*target++ = (byte) (unipoint & 0xFF);
	*target++ = (byte) ((unipoint >> 8) & 0xFF);
    }
}

/*
 * This internal bif converts a filename to whatever format is suitable for the file driver
 * It also adds zero termination so that prim_file needn't bother with the character encoding
 * of the file driver 
 */
BIF_RETTYPE prim_file_internal_name2native_1(BIF_ALIST_1)
{
    int encoding = erts_get_native_filename_encoding();
    Sint need;
    Eterm bin_term;
    byte* bin_p;
    /* Prim file explicitly does not allow atoms, although we could 
       very well cope with it. Instead of letting 'file' handle them,
       it would probably be more efficient to handle them here. Subject to 
       change in R15. */ 
    if (is_atom(BIF_ARG_1)) {
	BIF_ERROR(BIF_P,BADARG);
    }
    if (is_binary(BIF_ARG_1)) {
	byte *temp_alloc = NULL;
	byte *bytes;
	byte *err_pos;
	Uint size,num_chars;
	/* Uninterpreted encoding except if windows widechar, in case we convert from 
	   utf8 to win_wchar */
	size = binary_size(BIF_ARG_1);
	bytes = erts_get_aligned_binary_bytes(BIF_ARG_1, &temp_alloc);
	if (encoding != ERL_FILENAME_WIN_WCHAR) {
	    /*Add 0 termination only*/
	    bin_term = new_binary(BIF_P, NULL, size+1);
	    bin_p = binary_bytes(bin_term);
	    memcpy(bin_p,bytes,size);
	    bin_p[size]=0;
	    erts_free_aligned_binary_bytes(temp_alloc);
	    BIF_RET(bin_term);
	} 
	/* In a wchar world, the emulator flags only affect how
	   binaries are interpreted when sent from the user. */
	/* Determine real length and create a new binary */
	if (erts_analyze_utf8(bytes,size,&err_pos,&num_chars,NULL) != ERTS_UTF8_OK || 
	    erts_get_user_requested_filename_encoding() ==  ERL_FILENAME_LATIN1) {
	    /* What to do now? Maybe latin1, so just take byte for byte instead */
	    bin_term = new_binary(BIF_P, 0, (size+1)*2);
	    bin_p = binary_bytes(bin_term);
	    while (size--) {
		*bin_p++ = *bytes++;
		*bin_p++ = 0;
	    }
	    *bin_p++ = 0;
	    *bin_p++ = 0;
	    erts_free_aligned_binary_bytes(temp_alloc);
	    BIF_RET(bin_term);
	}
	/* OK, UTF8 ok, number of characters is in num_chars */
	bin_term = new_binary(BIF_P, 0, (num_chars+1)*2);
	bin_p = binary_bytes(bin_term);
	erts_copy_utf8_to_utf16_little(bin_p, bytes, num_chars);
	/* zero termination */
	bin_p[num_chars*2] = 0;
	bin_p[num_chars*2+1] = 0;
	erts_free_aligned_binary_bytes(temp_alloc);
	BIF_RET(bin_term);
    } /* binary */   
	    

    if ((need = erts_native_filename_need(BIF_ARG_1,encoding)) < 0) {
	BIF_ERROR(BIF_P,BADARG);
    }
    if (encoding == ERL_FILENAME_WIN_WCHAR) {
	need += 2;
    } else {
	++need;
    }
    
    bin_term = new_binary(BIF_P, 0, need);
    bin_p = binary_bytes(bin_term);
    erts_native_filename_put(BIF_ARG_1,encoding,bin_p); 
    bin_p[need-1] = 0;
    if (encoding == ERL_FILENAME_WIN_WCHAR) {
	bin_p[need-2] = 0;
    }
    BIF_RET(bin_term);
}

BIF_RETTYPE prim_file_internal_native2name_1(BIF_ALIST_1)
{
    Eterm real_bin;
    Uint offset;
    Uint size,num_chars;
    Uint bitsize;
    Uint bitoffs;
    Eterm *hp;
    byte *temp_alloc = NULL;
    byte *bytes;
    byte *err_pos;
    Uint num_built; /* characters */
    Uint num_eaten; /* bytes */
    Eterm ret;
    int mac = 0;

    if (is_not_binary(BIF_ARG_1)) {
	BIF_ERROR(BIF_P,BADARG);
    }
    size = binary_size(BIF_ARG_1);
    ERTS_GET_REAL_BIN(BIF_ARG_1, real_bin, offset, bitoffs, bitsize);
    if (bitsize != 0) {
	BIF_ERROR(BIF_P,BADARG);
    }
    if (size == 0) {
	BIF_RET(NIL);
    }
    switch (erts_get_native_filename_encoding()) {
    case ERL_FILENAME_LATIN1:
	hp = HAlloc(BIF_P, 2 * size);
	bytes = binary_bytes(real_bin)+offset;
    
	BIF_RET(erts_bin_bytes_to_list(NIL, hp, bytes, size, bitoffs));
    case ERL_FILENAME_UTF8_MAC:
	mac = 1;
    case ERL_FILENAME_UTF8:
	bytes = erts_get_aligned_binary_bytes(BIF_ARG_1, &temp_alloc);
	if (erts_analyze_utf8(bytes,size,&err_pos,&num_chars,NULL) != ERTS_UTF8_OK) {
	    Eterm *hp = HAlloc(BIF_P,3);
	    Eterm warn_type = NIL;
	    erts_free_aligned_binary_bytes(temp_alloc);
	    switch (erts_get_filename_warning_type()) {
	    case ERL_FILENAME_WARNING_IGNORE:
		warn_type = am_ignore;
		break;
	    case ERL_FILENAME_WARNING_ERROR:
		warn_type = am_error;
		break;
	    default:
		warn_type = am_warning;
	    }
	    BIF_RET(TUPLE2(hp,am_error,warn_type));
	}
	num_built = 0;
	num_eaten = 0;
	if (mac) {
	    ret = do_utf8_to_list_normalize(BIF_P, num_chars, bytes, size);
	} else {
	    ret = do_utf8_to_list(BIF_P, num_chars, bytes, size, num_chars, &num_built, &num_eaten, NIL);
	} 
	erts_free_aligned_binary_bytes(temp_alloc);
	BIF_RET(ret);
    case ERL_FILENAME_WIN_WCHAR:
	bytes = erts_get_aligned_binary_bytes(BIF_ARG_1, &temp_alloc);
	if ((size % 2) != 0) { /* Panic fixup to avoid crashing the emulator */
	    size--;
	    hp = HAlloc(BIF_P, size+2);
	    ret = CONS(hp,make_small((Uint) bytes[size]),NIL);
	    hp += 2;
	} else {
	    hp = HAlloc(BIF_P, size);
	    ret = NIL;
	}
	bytes += size-1;
	while (size > 0) {
	    Uint x = ((Uint) *bytes--) << 8;
	    x |= ((Uint) *bytes--);
	    size -= 2;
	    ret = CONS(hp,make_small(x),ret);
	    hp += 2;
	}	    
	erts_free_aligned_binary_bytes(temp_alloc);
	BIF_RET(ret);
    default:
	break;
    }
    BIF_RET(BIF_ARG_1);
}

BIF_RETTYPE prim_file_internal_normalize_utf8_1(BIF_ALIST_1)
{
    ERTS_DECLARE_DUMMY(Eterm real_bin);
    ERTS_DECLARE_DUMMY(Uint offset);
    Uint size,num_chars;
    Uint bitsize;
    ERTS_DECLARE_DUMMY(Uint bitoffs);
    Eterm ret;
    byte *temp_alloc = NULL;
    byte *bytes;
    byte *err_pos;

    if (is_not_binary(BIF_ARG_1)) {
	BIF_ERROR(BIF_P,BADARG);
    }
    size = binary_size(BIF_ARG_1);
    ERTS_GET_REAL_BIN(BIF_ARG_1, real_bin, offset, bitoffs, bitsize);
    if (bitsize != 0) {
	BIF_ERROR(BIF_P,BADARG);
    }
    if (size == 0) {
	BIF_RET(NIL);
    }
    bytes = erts_get_aligned_binary_bytes(BIF_ARG_1, &temp_alloc);
    if (erts_analyze_utf8(bytes,size,&err_pos,&num_chars,NULL) != ERTS_UTF8_OK) {
	erts_free_aligned_binary_bytes(temp_alloc);
	BIF_ERROR(BIF_P,BADARG);
    }
    ret = do_utf8_to_list_normalize(BIF_P, num_chars, bytes, size);
    erts_free_aligned_binary_bytes(temp_alloc);
    BIF_RET(ret);
}  

BIF_RETTYPE prim_file_is_translatable_1(BIF_ALIST_1)
{
    ERTS_DECLARE_DUMMY(Eterm real_bin);
    ERTS_DECLARE_DUMMY(Uint offset);
    Uint size;
    Uint num_chars;
    Uint bitsize;
    ERTS_DECLARE_DUMMY(Uint bitoffs);
    byte *temp_alloc = NULL;
    byte *bytes;
    byte *err_pos;
    int status;

    if (is_not_binary(BIF_ARG_1)) {
	BIF_ERROR(BIF_P,BADARG);
    }
    size = binary_size(BIF_ARG_1);
    ERTS_GET_REAL_BIN(BIF_ARG_1, real_bin, offset, bitoffs, bitsize);
    if (bitsize != 0) {
	BIF_ERROR(BIF_P,BADARG);
    }
    if (size == 0) {
	BIF_RET(am_true);
    }

    /*
     * If the encoding is latin1, the pathname is always translatable.
     */
    switch (erts_get_native_filename_encoding()) {
    case ERL_FILENAME_LATIN1:
	BIF_RET(am_true);
    case ERL_FILENAME_WIN_WCHAR:
	if (erts_get_user_requested_filename_encoding() == ERL_FILENAME_LATIN1) {
	    BIF_RET(am_true);
	}
    }

    /*
     * Check whether the binary contains legal UTF-8 sequences.
     */
    bytes = erts_get_aligned_binary_bytes(BIF_ARG_1, &temp_alloc);
    status = erts_analyze_utf8(bytes, size, &err_pos, &num_chars, NULL);
    erts_free_aligned_binary_bytes(temp_alloc);
    BIF_RET(status == ERTS_UTF8_OK ? am_true : am_false);
}  

BIF_RETTYPE file_native_name_encoding_0(BIF_ALIST_0)
{
    switch (erts_get_native_filename_encoding()) {
    case ERL_FILENAME_LATIN1:
	BIF_RET(am_latin1);
    case ERL_FILENAME_UTF8_MAC:
    case ERL_FILENAME_UTF8:
	BIF_RET(am_utf8);
    case ERL_FILENAME_WIN_WCHAR:
	if (erts_get_user_requested_filename_encoding() ==  ERL_FILENAME_LATIN1) {
	    BIF_RET(am_latin1);
	} else {
	    BIF_RET(am_utf8);
	}
    default:
	BIF_RET(am_undefined);
    }
}

int erts_utf8_to_latin1(byte* dest, const byte* source, int slen)
{
    /*
     * Assumes source contains valid utf8 that can be encoded as latin1,
     * and that dest has enough room.
     */
    byte* dp = dest;

    while (slen > 0) {
	if ((source[0] & 0x80) == 0) {
	    *dp++ = *source++;
	    --slen;
	}
	else {
	    ASSERT(slen > 1);
	    ASSERT((source[0] & 0xFE) == 0xC2);
	    ASSERT((source[1] & 0xC0) == 0x80);
	    *dp++ = (char) ((source[0] << 6) | (source[1] & 0x3F));
	    source += 2;
	    slen -= 2;
	}
    }
    return dp - dest;
}

BIF_RETTYPE io_printable_range_0(BIF_ALIST_0)
{
    if (erts_get_printable_characters() == ERL_PRINTABLE_CHARACTERS_UNICODE) {
	BIF_RET(am_unicode);
    } else {
	BIF_RET(am_latin1);
    }
}