File: recode.c

package info (click to toggle)
recode 3.4.1-11
  • links: PTS
  • area: main
  • in suites: slink
  • size: 1,560 kB
  • ctags: 622
  • sloc: ansic: 10,572; perl: 339; makefile: 317; lisp: 243; sh: 173; lex: 165; awk: 127; sed: 10
file content (2860 lines) | stat: -rw-r--r-- 77,742 bytes parent folder | download | duplicates (2)
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
/* Conversion of files between different charsets and usages.
   Copyright (C) 1990, 1992, 1993, 1994 Free Software Foundation, Inc.
   Francois Pinard <pinard@iro.umontreal.ca>, 1990.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "recode.h"

/* Maximum number of single step methods.  */
#define MAX_SINGLE_STEPS 300

/* Maximum length of a conversion sequence.  */
#define MAX_SEQUENCE 12

/* Global declarations and definitions.  */

#include <ctype.h>

#include <sys/types.h>
#include <sys/stat.h>

#include <setjmp.h>
#include <signal.h>
#ifndef RETSIGTYPE
# define RETSIGTYPE void
#endif

#if HAVE_STRING_H
# include <string.h>
#else
# include <strings.h>
# define strchr index
# define strrchr rindex
#endif

#if MSDOS
# define MSDOS_or_OS2 1
# include <dir.h>
# define unlink dummy1
# include <io.h>
# undef unlink
# include <fcntl.h>
#endif

#if OS2
# define MSDOS_or_OS2 1
# include <io.h>
# include <fcntl.h>
#endif

#include <errno.h>
#ifndef errno
extern int errno;
#endif

#include "getopt.h"

/* tmpnam/tmpname/mktemp/tmpfile and the associate logic has been the
   main portability headache of GNU recode :-(.
   
   People reported that tmpname does not exist everywhere.  On OS/2,
   recode aborts if the prefix has more than five characters.
   
   tmpnam seems to exist everywhere so far.  But NeXT's tmpnam() is such
   that, if called many times in succession, it will always return the
   same value.  One has to really open a file with the returned name
   first, for the next call to tmpnam() to return a different value.  I
   can manage it for a single invocation of recode, but using two recode
   invocations connected with a shell pipe, on the NeXT, creates a race
   by which both copies may call tmpnam() in parallel, then getting the
   same value, and will consequently open the same temporary file.
   
   Noah Friedman <friedman@gnu.ai.mit.edu> suggests opening the file with
   O_EXCL, and when the open presumably fails, call tmpnam again, or try
   the mktemp routine in the GNU C library: maybe that will work better.
   
   Michael I Bushnell <mib@gnu.ai.mit.edu> suggests always using tmpfile,
   which opens the file too, using the O_EXCL option to open.
   
   I'm trying this last suggestion, rewinding instead of closing.
   Someone reported, a long while ago, that rewind did not work on his
   system, so I reverted to opening and closing the temporary files all
   the time.  I lost the precise references for this problem.  In any
   case, I'm reusing rewind with tmpfile, now.  Hopefully, someone will
   tell me if this creates a problem somewhere!  */

/* The previous round used tmpnam(3).  This one tries tmpfile(3).  */
#undef USE_TMPNAM
#define USE_TMPFILE 1

/* Guarantee some value for L_tmpnam.  */
#if USE_TMPNAM
# if MSDOS
#  define L_tmpnam 13
# else
char *tmpnam ();
#  ifndef L_tmpnam
#   include "pathmax.h"
#   define L_tmpnam PATH_MAX
#  endif
# endif
#endif

#if USE_TMPFILE
FILE *tmpfile __P ((void));
#endif

#if WITH_DMALLOC
# include <dmalloc.h>
#endif

#if MSDOS
/* Increase stack size, so init_recode_rfc1345 works.  */
extern unsigned _stklen = 10000U;
#endif

/* Variables.  */

/* The name this program was run with. */
const char *program_name;

/* If non-zero, display usage information and exit.  */
static int show_help = 0;

/* If non-zero, print the version on standard output and exit.  */
static int show_version = 0;

/* If non-zero, show a list of one or all known charsets, then exit.  */
static int show_charsets = 0;

/* If non-zero, show a restricted list of charsets.  */
static int show_restricted_charsets = 0;

/* Indicates the format for showing only one charset.  */
enum list_format list_format = NO_FORMAT;

/* If non-zero, merely explore all recoding paths, report and exit.  */
static int auto_check_mode = 0;

/* If non-zero, produce C code for initializing the conversion and exit.  */
static int make_header_mode = 0;

/* Table name in generated C code.  */
static const char *header_name = NULL;

/* If the recoding yields some problems in reversibility in some file,
   this file replacement is denied and it is left unrecoded or, if recode
   is used as a mere filter, the recoding is interrupted.  The following
   option forces the recoding to run to completion and the replacement to
   be done even if the recoding is not reversible.  */
int force_option = 0;

/* This option prevents recode from automatically completing charsets.  */
int strict_mapping = 0;

/* This option merely inhibits messages about non-reversible recodings, but
   it does not prevent recodings to be aborted or exit status to be set.  */
static int quiet_mode = 0;

/* By selecting the following option, the program will echo to stderr the
   sequence of elementary recoding steps which will be taken to effect
   the requested recoding.  */
int verbose_option = 0;

/* When a file is recoded over itself, precautions are taken to move the
   timestamps of the original file into the recoded file, so to make the
   recoding the most transparent possible to make, and other tools.
   However, selecting the following option inhibit the timestamps handling,
   thus effectively `touching' the file.  */
int touch_option = 0;

/* In `texte' charset, some countries use double quotes to mark diaeresis,
   while other countries prefer colons.  The following variable contains the
   diaeresis character for `texte' charset.  Nominally set to a double
   quote, it can be forced to a colon by an option on recode command.  */
char diaeresis_char = '"';

/* For `latex' charset, it is often convenient to recode the diacritics
   only, while letting other LaTeX code using backslashes unrecoded.
   In the other charset, one can edit text as well as LaTeX directives.  */
int diacritics_only = 0;

/* For `ibmpc' charset, characters 176 to 223 are use to draw boxes.
   If this variable is set, while getting out of `ibmpc', ASCII
   characters are selected so to approximate these boxes.  */
int ascii_graphics = 0;

/* The following charset name will be ignored, if given.  */
static const char *ignored_name = NULL;

/* Unabridged names of BEFORE and AFTER charsets, even if still aliases.
   These are used for naming the array in produced C code.  */
static const char *before_full_name;
static const char *after_full_name;

/* Ordinals of list, BEFORE and AFTER charset.  */
static CHARSET *list_charset;
static CHARSET *before_charset;
static CHARSET *after_charset;

/* Flag telling usage that we are decoding charsets.  */
int decoding_charset_flag = 0;

/* Tells how various passes will be interconnected.  */
enum sequence_strategy
  {
    STRATEGY_UNDECIDED,		/* sequencing strategy is undecided yet */
    SEQUENCE_WITH_FILES,	/* do not fork, use intermediate files */
    SEQUENCE_WITH_POPEN,	/* use `popen(3)' to fork processes */
    SEQUENCE_WITH_PIPE		/* fork processes connected with `pipe(2)' */
  };
enum sequence_strategy sequence_strategy = STRATEGY_UNDECIDED;

/* Known single steps.  */

STEP single_step_array[MAX_SINGLE_STEPS];
int number_of_single_steps;	/* number of announced single steps */

const unsigned char *one_to_same; /* identity recoding */

CHARSET *rfc1345;		/* special RFC 1345 charset value */

/* Array stating the sequence of conversions.  */
const STEP *sequence[MAX_SEQUENCE];
int length_of_sequence;

/* Error handling.  */

/*---------------------------------------------------------------------.
| Print the source location of error when PERROR or PERROR1 are used.  |
`---------------------------------------------------------------------*/

static const char *error_file_reference = NULL;
static int error_line_reference = 0;

static void
error_print_prefix (void)
{
  fflush (stdout);
  if (error_file_reference)
    fprintf (stderr, "%s:%d: ", error_file_reference, error_line_reference);
  else
    fprintf (stderr, "%s: ", program_name);
}

#define PERROR(Message) \
  error ((error_file_reference = __FILE__,				\
	  error_line_reference = __LINE__,				\
	  EXIT_FAILURE),						\
	 errno, "%s", (Message))

#define PERROR1(Format, Argument) \
  error ((error_file_reference = __FILE__,				\
	  error_line_reference = __LINE__,				\
	  EXIT_FAILURE),						\
	 errno, (Format), (Argument))

#define PERROR2(Format, Argument1, Argument2) \
  error ((error_file_reference = __FILE__,				\
	  error_line_reference = __LINE__,				\
	  EXIT_FAILURE),						\
	 errno, (Format), (Argument1), (Argument2))

/*-----------------.
| Signal handler.  |
`-----------------*/

static jmp_buf signal_label;	/* where to jump when signal received */
static int interrupted = 0;	/* set when some signal has been received */

static RETSIGTYPE
signal_handler (int number)
{
  interrupted = 1;
  signal (number, signal_handler);
}

/*------------------------------------------------------------------------.
| Prepare to handle signals, intercept willingful requests for stopping.  |
`------------------------------------------------------------------------*/

static void
setup_signals (void)
{
#ifdef SIGPIPE
  signal (SIGPIPE, signal_handler);
#endif
#if 0
  signal (SIGINT, signal_handler);
  signal (SIGTERM, signal_handler);
#endif
}

/* Quality handling.  */

/*---------------------------------------.
| Return a string describing a quality.	 |
`---------------------------------------*/

const char *
quality_to_string (QUALITY quality)
{
  switch (quality)
    {
    default:
      abort ();

    case REVERSIBLE:
      return _("reversible");

    case ONE_TO_ONE:
      return _("one to one");

    case MANY_TO_ONE:
      return _("many to one");

    case ONE_TO_MANY:
      return _("one to many");

    case MANY_TO_MANY:
      return _("many to many");
    }
}

/*-------------------------------------------------------------------------.
| Return the quality of a step obtained by merging two others steps, given |
| their respective qualities FIRST and SECOND.				   |
`-------------------------------------------------------------------------*/

QUALITY 
merge_qualities (QUALITY first, QUALITY second)
{
  switch (first)
    {
    default:
      abort ();
      
    case REVERSIBLE:
      return second;

    case ONE_TO_ONE:
      switch (second)
	{
	case REVERSIBLE:
	case ONE_TO_ONE:
	  return ONE_TO_ONE;

	case MANY_TO_ONE:
	case ONE_TO_MANY:
	case MANY_TO_MANY:
	  return second;
	}

    case MANY_TO_ONE:
      switch (second)
	{
	case REVERSIBLE:
	case ONE_TO_ONE:
	case MANY_TO_ONE:
	  return MANY_TO_ONE;

	case ONE_TO_MANY:
	case MANY_TO_MANY:
	  return MANY_TO_MANY;
	}

    case ONE_TO_MANY:
      switch (second)
	{
	case REVERSIBLE:
	case ONE_TO_ONE:
	case ONE_TO_MANY:
	  return ONE_TO_MANY;

	case MANY_TO_ONE:
	case MANY_TO_MANY:
	  return MANY_TO_MANY;
	}

    case MANY_TO_MANY:
      return MANY_TO_MANY;
    }
}

/* Charset handling.  */

/*----------------------------------------------------.
| Decode the BEFORE:AFTER argument, given in STRING.  |
`----------------------------------------------------*/

static void
decode_before_after (const char *string)
{
  char *before;
  char *after;
  char *in;
  char *out;

  /* Split the BEFORE:AFTER keyword at the colon.  A backslash can escape
     a colon in both charsets.  */

  before = xstrdup (string);
  after = NULL;
  out = before;

  for (in = before; *in; in++)
    if (*in == ':' && !after)
      {
	*out++ = '\0';
	after = out;
      }
    else
      {
	if (*in == '\\' && *(in + 1))
	  in++;
	*out++ = *in;
      }
  *out = '\0';

  if (!after)
    usage (EXIT_FAILURE);

  /* Decode both charsets.  */

  before_full_name = clean_charset_name (before);
  before_charset = find_charset (before_full_name);

  after_full_name = clean_charset_name (after);
  after_charset = find_charset (after_full_name);

  /* Free the work area.  */

  free (before);
}

/* Single step handling.  */

/*-------------------------------------------------------------------------.
| Allocate and initialize a new single step, save for the before and after |
| charsets and quality.							   |
`-------------------------------------------------------------------------*/

static STEP *
new_single_step (void)
{
  STEP *step;

  if (number_of_single_steps == MAX_SINGLE_STEPS)
    error (EXIT_FAILURE, 0, _("MAX_SINGLE_STEPS is too small"));

  step = single_step_array + number_of_single_steps++;
  step->init_recode = NULL;
  step->file_recode = NULL;
  step->one_to_one = NULL;
  step->one_to_many = NULL;

  return step;
}
  
/*------------------------------------------------------------------------.
| Create and initialize a new single step for recoding between START_NAME |
| and GOAL_NAME, which are given as strings, give it a recoding QUALITY,  |
| also saving an INIT_RECODE and a FILE_RECODE functions.		  |
`------------------------------------------------------------------------*/

/* If not __STDC__, do not write prototypes for functionnal parameters,
   because ansi2knr does not clean them.  */

#if __STDC__
void
declare_step (const char *before_name, const char *after_name, QUALITY quality,
	      void (*init_recode) (STEP *),
	      int (*file_recode) (const STEP *, FILE *, FILE *))
#else
void
declare_step (const char *before_name, const char *after_name, QUALITY quality,
	      void (*init_recode) (),
	      int (*file_recode) ())
#endif
{
  STEP *step;

  step = new_single_step ();
  step->before = find_charset (before_name);
  step->after = find_charset (after_name);
  step->quality = quality;
  step->init_recode = init_recode;
  step->file_recode = file_recode;
}

/*------------------------------------------------------------------.
| Create a one to one table which is the inverse of the given one.  |
`------------------------------------------------------------------*/

unsigned char *
invert_table (const unsigned char *table)
{
  unsigned char flag[256];
  unsigned char *result;
  int table_error;
  int counter;

  result = (unsigned char *) xmalloc (256);
  memset (flag, 0, 256);
  table_error = 0;

  for (counter = 0; counter < 256; counter++)
    {
      if (flag[table[counter]])
	{
	  error (0, 0, _("Codes %3d and %3d both recode to %3d"),
		 result[table[counter]], counter, table[counter]);
	  table_error = 1;
	}
      else
	{
	  result[table[counter]] = counter;
	  flag[table[counter]] = 1;
	}
    }
  if (table_error)
    {
      for (counter = 0; counter < 256; counter++)
	if (!flag[counter])
	  error (0, 0, _("No character recodes to %3d"), counter);
      error (EXIT_FAILURE, 0, _("Cannot invert given one-to-one table"));
    }
  return result;
}

/*-------------------------------------------------------------------------.
| Complete a STEP descriptor by a constructed recoding array for 256 chars |
| and the adequate recoding routine.  If FIRST_HALF_IMPLIED is not zero,   |
| default the unconstrained characters of the first 128 to the identity	   |
| mapping.  Use an KNOWN_PAIRS array of NUMBER_OF_PAIRS constraints.  If   |
| REVERSE is not zero, use right_table instead of left_table.		   |
`-------------------------------------------------------------------------*/

void
complete_pairs (STEP *step, int first_half_implied,
		const KNOWN_PAIR *known_pairs, int number_of_pairs,
		int reverse)
{
  unsigned char left_flag[256];
  unsigned char right_flag[256];
  unsigned char left_table[256];
  unsigned char right_table[256];
  int table_error;

  unsigned char *flag;
  unsigned char *table;
  const char **table2;
  char *cursor;
  unsigned char left;
  unsigned char right;
  unsigned char search;
  int counter;
  int used;

  /* Init tables with zeroes.  */

  memset (left_flag, 0, 256);
  memset (right_flag, 0, 256);
  table_error = 0;

  /* Establish known data.  */

  for (counter = 0; counter < number_of_pairs; counter++)
    {
      left = known_pairs[counter].left;
      right = known_pairs[counter].right;

      /* Set one known correspondance.  */

      if (left_flag[left])
	{
	  if (!table_error)
	    {
	      error (0, 0, _("Following diagnostics for `%s' to `%s'"),
		     step->before->name, step->after->name);
	      table_error = 1;
	    }
	  error (0, 0,
		 _("Pair no. %d: { %3d, %3d } conflicts with { %3d, %3d }"),
		 counter, left, right, left, left_table[left]);
	}
      else if (right_flag[right])
	{
	  if (!table_error)
	    {
	      error (0, 0, _("Following diagnostics for `%s' to `%s'"),
		     step->before->name, step->after->name);
	      table_error = 1;
	    }
	  error (0, 0,
		 _("Pair no. %d: { %3d, %3d } conflicts with { %3d, %3d }"),
		 counter, left, right, right_table[right], right);
	}
      else
	{
	  left_flag[left] = 1;
	  left_table[left] = right;
	  right_flag[right] = 1;
	  right_table[right] = left;
	}
    }

  /* Set all the implied correspondances.  */

  if (first_half_implied)
    for (counter = 0; counter < 128; counter++)
      if (!left_flag[counter] && !right_flag[counter])
	{
	  left_flag[counter] = 1;
	  left_table[counter] = counter;
	  right_flag[counter] = 1;
	  right_table[counter] = counter;
	}

  if (strict_mapping)
    {

      /* If the recoding is strict, prepare a one to many table, each
	 entry being NULL or a string of a single character.  */

      /* Select the proper table.  */

      if (reverse)
	{
	  flag = right_flag;
	  table = right_table;
	}
      else
	{
	  flag = left_flag;
	  table = left_table;
	}

      /* Allocate everything in one blow, so it will be freed likewise.  */

      used = 0;
      for (counter = 0; counter < 256; counter++)
	if (flag[counter])
	  used++;

      table2 = (const char **) xmalloc (256 * sizeof (char *) + 2 * used);
      cursor = (char *) (table2 + 256);

      /* Construct the table and the strings in parallel.  */

      for (counter = 0; counter < 256; counter++)
	if (flag[counter])
	  {
	    table2[counter] = cursor;
	    *cursor++ = table[counter];
	    *cursor++ = '\0';
	  }
	else
	  table2[counter] = NULL;

      /* Save a one to many recoding table.  */

      step->file_recode = file_one_to_many;
      step->one_to_many = table2;
    }
  else
    {

      /* If the recoding is not strict, compute a reversible one to one
	 table.  */

      if (table_error)
	error (EXIT_FAILURE, 0,
	       _("Cannot complete table from set of known pairs"));

      /* Close the table with small permutation cycles.  */

      for (counter = 0; counter < 256; counter++)
	if (!right_flag[counter])
	  {
	    search = counter;
	    while (left_flag[search])
	      search = left_table[search];
	    left_flag[search] = 1;
	    left_table[search] = counter;
	    right_flag[counter] = 1;
	    right_table[counter] = search;
	  }

      /* Save a copy of the proper table.  */

      step->file_recode = file_one_to_one;
      table = (unsigned char *) xmalloc (256);
      memcpy (table, reverse ? right_table : left_table, 256);
      step->one_to_one = table;
    }
}

/*----------------------------------------.
| Initialize all collected single steps.  |
`----------------------------------------*/

void
register_all_modules (void)
{
  STEP *step;
  int counter;
  unsigned char *table;

  table = (unsigned char *) xmalloc (256);
  for (counter = 0; counter < 256; counter++)
    table[counter] = counter;
  one_to_same = table;

  prepare_charset_initialization ();
  number_of_single_steps = 0;

  rfc1345 = find_charset ("RFC 1345");
  declare_alias (".", "RFC 1345");
  declare_alias ("ASCII", "ANSI_X3.4-1968");
  declare_alias ("BS", "ASCII-BS");
  declare_alias ("Latin-1", "ISO_8859-1:1987");

  /* Needed for compatibility with recode version 3.2.  */
  declare_alias ("lat1", "Latin-1");

#include "initstep.h"

  for (step = single_step_array;
       step < single_step_array + number_of_single_steps;
       step++)

    if (step->file_recode == file_one_to_one
	&& step->one_to_one == one_to_same)

      step->conversion_cost = 0;

    else
      switch (step->quality)
	{
	case REVERSIBLE:
	  step->conversion_cost = 2;
	  break;

	case ONE_TO_ONE:
	  step->conversion_cost = 30;
	  break;

	case MANY_TO_ONE:
	  step->conversion_cost = 10;
	  break;

	case ONE_TO_MANY:
	  step->conversion_cost = 40;
	  break;

	case MANY_TO_MANY:
	  step->conversion_cost = 50;
	  break;
	}

  /* For all RFC 1345 participating steps, halve the cost since they
     come in pair.  */

  for (counter = 0; counter < number_of_single_steps; counter++)
    if (single_step_array[counter].before == rfc1345
	|| single_step_array[counter].after == rfc1345)
      single_step_array[counter].conversion_cost /= 2;
}

/*-------------------------------------------------------------------------.
| Produce a C include file representing the recoding, on standard output.  |
`-------------------------------------------------------------------------*/

static void
output_header_file (void)
{
  const STEP *step;		/* step being analysed */
  int column;			/* column counter */
  char *name;			/* constructed name */
  char *cursor;			/* cursor in constructed name */
  const char *cursor2;		/* cursor to study strings */
  int counter;			/* general purpose counter */

  /* This function is called only when the recoding sequence contains a
     single step, so it is safe to use sequence[0] for the step.  */

  step = sequence[0];

  /* Print the header of the header file.  */

  printf (_("/* Conversion table from `%s' charset to `%s' charset.\n"),
	  before_full_name, after_full_name);
  printf (_("   Generated mechanically by GNU %s %s.\n"), PACKAGE, VERSION);
  printf ("\n");
  switch (sequence[0]->quality)
    {
    case REVERSIBLE:
      printf (_("   The recoding should be reversible.\n"));
      break;

    case ONE_TO_ONE:
      printf (_("   The recoding might not be reversible.\n"));
      break;

    case MANY_TO_ONE:
      printf (_("   Programming is needed to handle multichar input.\n"));
      break;

    case ONE_TO_MANY:
      printf (_("   Each input char transforms into an output string.\n"));
      break;

    case MANY_TO_MANY:
      printf (_("   Each input char transforms into an output string,\n"));
      printf (_("   programming is needed to handle multichar input.\n"));
      break;
    }
  printf ("*/\n");
  printf ("\n");

  /* Construct the name of the resulting table.  */

  if (header_name)
    name = xstrdup (header_name);
  else
    {
      name = (char *) xmalloc (strlen (before_full_name) + sizeof "_to_"
			       + strlen (after_full_name));
      strcpy (name, before_full_name);
      strcat (name, "_to_");
      strcat (name, after_full_name);
    }

  /* Ensure the table name contains only valid characters for a C
     identifier.  */

  for (cursor = name; *cursor; cursor++)
    if (*cursor != '_'
	&& (*cursor < 'a' || *cursor > 'z')
	&& (*cursor < 'A' || *cursor > 'Z')
	&& (*cursor < '0' || *cursor > '9'))
      *cursor = '_';

  /* Produce the recoding table in the correct format.  */

  if (step->one_to_one)
    {

      /* Produce a one to one recoding table.  */

      printf ("unsigned char const %s[256] =\n", name);
      printf ("  {\n");
      for (counter = 0; counter < 256; counter++)
	{
	  printf ("%s%3d,", counter % 8 == 0 ? "    " : " ",
		   step->one_to_one[counter]);
	  if (counter % 8 == 7)
	    printf ("\t/* %3d - %3d */\n", counter - 7, counter);
	}
      printf ("  };\n");
    }

  else if (step->one_to_many)
    {

      /* Produce a one to many recoding table.  */

      printf ("const char *%s[256] =\n", name);
      printf ("  {\n");
      for (counter = 0; counter < 256; counter++)
	{
	  printf ("    ");
	  column = 4;
	  if (step->one_to_many[counter])
	    {
	      printf ("\"");
	      column++;
	      for (cursor2 = step->one_to_many[counter]; *cursor2; cursor2++)
		switch (*cursor2)
		  {
		  case ' ':
		    printf (" ");
		    column++;
		    break;

		  case '\b':
		    printf ("\\b");
		    column += 2;
		    break;

		  case '\t':
		    printf ("\\t");
		    column += 2;
		    break;

		  case '\n':
		    printf ("\\n");
		    column += 2;
		    break;

		  case '"':
		    printf ("\\\"");
		    column += 2;
		    break;

		  case '\\':
		    printf ("\\\\");
		    column += 2;
		    break;

		  default:
		    if (isprint (*cursor2))
		      {
			printf ("%c", *cursor2);
			column++;
		      }
		    else
		      {
			printf ("\\%0.3o", *(const unsigned char *) cursor2);
			column += 4;
		      }
		  }
	      printf ("\"");
	      column++;
	    }
	  else
	    {
	      printf ("0");
	      column++;
	    }
	  printf (",");
	  column++;
	  while (column < 32)
	    {
	      printf ("\t");
	      column += 8 - column % 8;
	    }
	  printf ("/* %3d */\n", counter);
	}
      printf ("  };\n");
    }

  else
    error (EXIT_FAILURE, 0, _("No table to print"));

  free (name);
}

/* Double step handling (for RFC 1345).  */

/*-----------------------------------------------------------------------.
| Associate a double TABLE with charset NAME, part of the RFC 1345 fully |
| connected set.  Each entry in table uses SIZE characters.		 |
`-----------------------------------------------------------------------*/

void
declare_double_step (DOUBLE_TABLE *table, const char *name, int size)
{
  CHARSET *charset;
  STEP *step;

  charset = find_charset (name);
  charset->table = table;
  charset->size = size;

  step = new_single_step ();
  step->before = charset;
  step->after = rfc1345;
  step->quality = strict_mapping ? ONE_TO_MANY : REVERSIBLE;
  step->init_recode = NULL;
  step->file_recode = NULL;

  step = new_single_step ();
  step->before = rfc1345;
  step->after = charset;
  step->quality = strict_mapping ? ONE_TO_MANY : REVERSIBLE;
  step->init_recode = NULL;
  step->file_recode = NULL;
}

/*---------------------------------------------------------------.
| Order two struct item's lexicographically of their key value.	 |
`---------------------------------------------------------------*/

struct item
  {
    const char *key;		/* RFC 1345 short mnemonic name */
    int code;			/* corresponding charset code (0..255) */
  };

static int
compare_struct_item (const void *void_first, const void *void_second)
{
  return strcmp (((const struct item *) void_first)->key,
		 ((const struct item *) void_second)->key);
}

/*------------------------------------------------------------------------.
| Complete the initialization of a double step which just has been merged |
| into a single STEP.  Establish known pairings by comparing keys between |
| the before and after charsets.					  |
`------------------------------------------------------------------------*/

void
init_recode_rfc1345 (STEP *step)
{
  struct side
    {
      CHARSET *charset;		/* charset */
      struct item item[256];	/* array of binding items */
      int number_of_items;	/* number of binding items in array */
    };

  char pool[2 * 256 * 6];	/* character pool */
  DOUBLE_TABLE *table;		/* RFC 1345 table */
  struct side side_array[2];	/* information for each side */
  struct side *side;		/* cursor into side_array */
  int reversed;			/* if both sides reversed */
  const char *in;		/* cursor in double table strings */
  char *out;			/* cursor in character pool */
  int code;			/* character code */
  int row_counter;		/* double table row counter */
  int position_counter;		/* double table column counter */
  int counter;			/* counter for characters */
  struct item *item_cursor;	/* cursor in arrays of binding items */
  struct item *left;		/* left binding items cursor */
  struct item *left_limit;	/* limit value for left */
  struct item *right;		/* right binding items cursor */
  struct item *right_limit;	/* limit value for right */
  KNOWN_PAIR pair_array[256];	/* obtained pairings */
  KNOWN_PAIR *pair_cursor;	/* cursor in array of pairings */
  int value;			/* result of lexicographical comparison */

  /* For ensuring reversibility, known pairs should be computed the same
     way regardless of the direction of recoding.  This canonalization is
     ensured through the charset values, which are increasing along the
     initialization order.  This should also reflect the charset order in
     rfc1345.txt.  */

  if (step->before < step->after)
    {
      side_array[0].charset = step->before;
      side_array[1].charset = step->after;
      reversed = 0;
    }
  else
    {
      side_array[0].charset = step->after;
      side_array[1].charset = step->before;
      reversed = 1;
    }

  out = pool;
  for (side = side_array; side < side_array + 2; side++)
    {

      /* Move the string values out of the double table, while constructing
	 the array of binding items for the charset.  */

      table = side->charset->table;
      item_cursor = side->item;
      code = 0;

      for (row_counter = 0; row_counter < 8; row_counter++)
	if (in = (*table)[row_counter], in)
	  for (position_counter = 0; position_counter < 32; position_counter++)
	    {
	      if (*in == ' ')
		in += side->charset->size;
	      else
		{

		  /* Establish a new binding item.  */

		  item_cursor->code = code;
		  item_cursor->key = out;
		  item_cursor++;

		  /* Copy out the value to the character pool, and terminate it
		     with a NULL.  */

		  for (counter = 0; counter < side->charset->size; counter++)
		    if (*in == ' ')
		      in++;
		    else
		      *out++ = *in++;
		  *out++ = '\0';
		}
	      code++;
	    }
	else
	  code += 32;

      side->number_of_items = item_cursor - side->item;
    }

  /* Sort both arrays of binding items into lexicographical order.  The
     taken time, which is O(n.log(n)), is gained back when the further
     pairing is completed in a time which is linear instead of quadratic.  */

  qsort (side_array[0].item, side_array[0].number_of_items,
	 sizeof (struct item), compare_struct_item);
  qsort (side_array[1].item, side_array[1].number_of_items,
	 sizeof (struct item), compare_struct_item);

  /* Scan both arrays of binding items simultaneously, saving as pairs
     those codes having the same key.  */

  left = side_array[0].item;
  left_limit = left + side_array[0].number_of_items;
  right = side_array[1].item;
  right_limit = right + side_array[1].number_of_items;
  pair_cursor = pair_array;

  while (left < left_limit && right < right_limit)
    {
      value = strcmp (left->key, right->key);
      if (value < 0)
	left++;
      else if (value > 0)
	right++;
      else
	{
	  pair_cursor->left = (left++)->code;
	  pair_cursor->right = (right++)->code;
	  pair_cursor++;
	}
    }

  /* Complete the recoding table out of this.  */

  complete_pairs (step, 0, pair_array, pair_cursor - pair_array, reversed);
}

/* Step sequence handling.  */

#define UNREACHABLE	30000		/* No way for this conversion */

/*-------------------------------------------------------.
| Explain what recoding step sequence has been planned.	 |
`-------------------------------------------------------*/

static void
echo_sequence (void)
{
  const char *last;		/* last name printed */
  const char *name;		/* name being printed */
  QUALITY quality;		/* cumulative quality */
  int counter;			/* index into sequence */

  if (length_of_sequence < 0)
    fprintf (stderr, _("UNACHIEVABLE recoding!\n"));
  else if (length_of_sequence == 0)
    fprintf (stderr, _("Mere copy for the trivial recoding\n"));
  else
    {
      quality = REVERSIBLE;
      last = NULL;
      for (counter = 0; counter < length_of_sequence; counter++)
	{
	  name = sequence[counter]->before->name;
	  if (counter == 0)
	    fprintf (stderr, "%s", name);
	  else if (name != last)
	    fprintf (stderr, "/%s", name);

	  name = sequence[counter]->after->name;
	  fprintf (stderr, " -> %s", name);

	  quality = merge_qualities (quality, sequence[counter]->quality);
	  last = name;
	}
      fprintf (stderr, " (%s)\n", quality_to_string (quality));
    }
}

/*----------------------------------------------------------.
| Find a sequence of single steps to achieve a conversion.  |
`----------------------------------------------------------*/

static void
find_sequence (CHARSET *before, CHARSET *after)
{
  struct search
    {
      STEP *step;		/* step who will bring us nearer to after */
      int cost;			/* cost from here through after */
    };
  struct search *search_array;	/* critical path search tree */
  struct search *search;	/* item in search_array for charset */
  STEP *step;			/* cursor in possible single_steps */
  int cost;			/* cost under consideration */
  int modified;			/* != 0 if modified since last iteration */
  CHARSET *charset;		/* charset while reconstructing sequence */

  search_array
    = (struct search *) xmalloc (number_of_charsets * sizeof (struct search));

  /* Initialize the search for an economical route, looking our way
     backward from the after towards the before.  */

  for (search = search_array;
       search < search_array + number_of_charsets;
       search++)
    {
      search->step = NULL;
      search->cost = UNREACHABLE;
    }
  search_array[after - charset_array].cost = 0;

  modified = 1;
  while (modified)
    {
      modified = 0;
      for (step = single_step_array;
	   step < single_step_array + number_of_single_steps;
	   step++)
	if (!step->before->ignore)
	  {
	    cost = search_array[step->after - charset_array].cost;
	    if (cost != UNREACHABLE)
	      {
		cost += step->conversion_cost;
		search = search_array + (step->before - charset_array);
		if (cost < search->cost)
		  {
		    search->step = step;
		    search->cost = cost;
		    modified = 1;
		  }
	      }
	  }
    }

  if (search_array[before - charset_array].cost == UNREACHABLE)
    {
      
      /* If no path has been found, return with a negative length.  */

      length_of_sequence = -1;
    }
  else
    {

      /* Save the retained best path in the sequence array.  While doing so,
	 simplify out any single step which merely copies.  Also execute the
	 delayed initialization for those steps which registered one.  */

      length_of_sequence = 0;
      for (charset = before; charset != after; charset = step->after)
	{
	  step = search_array[charset - charset_array].step;
	  if (step->file_recode != file_one_to_one
	      || step->one_to_one != one_to_same)
	    {
	      if (length_of_sequence == MAX_SEQUENCE)
		error (EXIT_FAILURE, 0, _("MAX_SEQUENCE is too small"));
	      sequence[length_of_sequence++] = step;
	      if (step->init_recode)
		{
		  (*step->init_recode) (step);
		  step->init_recode = NULL;
		}
	    }
	}
    }

  /* Tell what has been decided, for the user.  */

  if (verbose_option)
    echo_sequence ();

  free (search_array);
}

/*-------------------------------------------------------------------------.
| Return 0 if STEP cannot be easily simplified.  Return 1 if it is an all  |
| table driven ONE_TO_ONE recoding.  Return 2 if it is an all table driven |
| ONE_TO_MANY recoding.  If making headers, accept more easily that a step |
| is simplifyable, just looking at tables and ignoring preset functions.   |
`-------------------------------------------------------------------------*/

static int
simplify_type (const STEP *step)
{
  if (step->one_to_one
      && (make_header_mode || step->file_recode == file_one_to_one))
    return 1;

  if (step->one_to_many
      && (make_header_mode || step->file_recode == file_one_to_many))
    return 2;

  return 0;
}

/*---------------------------------------------------------------------.
| Optimize a sequence of single steps by creating new single steps, if |
| this can be done by merging adjacent steps which are simple enough.  |
`---------------------------------------------------------------------*/

static void
simplify_sequence (void)
{
  int saved_steps;		/* number of saved steps */
  int in;			/* ordinal of next studied sequence step */
  int out;			/* ordinal of next output sequence step */
  STEP *step;			/* new single step being constructed */
  unsigned char *accum;		/* one_to_one accumulated recoding */
  const char **string;		/* one_to_many recoding */
  unsigned char temp[256];	/* temporary value for accum array */
  int counter;			/* all purpose counter */

  saved_steps = 0;

  /* See if there are some RFC 1345 double steps to merge.  */

  in = 0;
  out = 0;

  while (in < length_of_sequence)
    if (in < length_of_sequence - 1
	&& sequence[in]->after == rfc1345
	&& sequence[in+1]->before == rfc1345)
      {

	/* Produce a new single step for the double step.  */

	step = new_single_step ();
	step->before = sequence[in]->before;
	step->after = sequence[in+1]->after;
	step->quality = merge_qualities (sequence[in]->quality,
					 sequence[in+1]->quality);
	step->init_recode = init_recode_rfc1345;
	step->file_recode = file_one_to_one;

	in += 2;
	saved_steps++;

	/* Initialize the new single step, so it can be later merged with
	   others.  */

	(*step->init_recode) (step);
	step->init_recode = NULL;

	sequence[out++] = step;
      }
    else if (sequence[in]->before == rfc1345)
      error (EXIT_FAILURE, 0,
	     _("You may not explicitely recode from RFC 1345"));
    else if (sequence[in]->after == rfc1345)
      {

	/* Produce a new single step for the double step.  */

	step = new_single_step ();
	step->before = sequence[in]->before;
	step->after = sequence[in]->after;
	step->quality = ONE_TO_MANY;

	in++;

	/* Initialize the new single step, so it can be later merged with
	   others.  */

	init_table_for_rfc1345 (step);
	step->file_recode = file_one_to_many;

	sequence[out++] = step;
      }
    else
      sequence[out++] = sequence[in++];

  length_of_sequence = out;

  /* Recopy the sequence array over itself, while merging subsequences of
     one or more consecutive one-to-one recodings, including an optional
     final one-to-many recoding.  */

  in = 0;
  out = 0;
  while (in < length_of_sequence)
    if (in < length_of_sequence - 1
	&& simplify_type (sequence[in]) == 1
	&& simplify_type (sequence[in+1]) > 0)
      {

	/* Construct a new single step, and initialize a cumulative
	   one-to-one recoding with the identity permutation.  */

	accum = (unsigned char *) xmalloc (256);
	for (counter = 0; counter < 256; counter++)
	  accum[counter] = counter;

	step = new_single_step ();
	step->before = sequence[in]->before;
	step->quality = REVERSIBLE;

	/* Merge in all consecutive one-to-one recodings.  */

	while (in < length_of_sequence && simplify_type (sequence[in]) == 1)
	  {
	    for (counter = 0; counter < 256; counter++)
	      temp[counter] = sequence[in]->one_to_one[accum[counter]];
	    for (counter = 0; counter < 256; counter++)
	      accum[counter] = temp[counter];
	    step->after = sequence[in]->after;
	    step->quality
	      = merge_qualities (step->quality, sequence[in]->quality);
	    in++;
	    saved_steps++;
	  }

	/* Check for a possible one-to-many recoding.  */

	if (in < length_of_sequence && simplify_type (sequence[in]) == 2)
	  {

	    /* Merge in the one-to-many recoding, and make the new single
	       step be a one-to-many recoding.  */

	    string = (const char **) xmalloc (256 * sizeof (char *));
	    for (counter = 0; counter < 256; counter++)
	      string[counter] = sequence[in]->one_to_many[accum[counter]];
	    free (accum);
	    step->one_to_many = string;
	    step->file_recode = file_one_to_many;
	    step->after = sequence[in]->after;
	    step->quality
	      = merge_qualities (step->quality, sequence[in]->quality);
	    in++;
	    saved_steps++;
	  }
	else
	  {

	    /* Make the new single step be a one-to-one recoding.  */

	    step->one_to_one = accum;
	    step->file_recode = file_one_to_one;
	  }

	/* Save the newly created step.  */

	sequence[out++] = step;
      }
    else
      sequence[out++] = sequence[in++];

  length_of_sequence = out;

  /* Delete a remaining single step, if it happens to be the identity
     one-to-one recoding.  */

  if (length_of_sequence == 1 && simplify_type (sequence[0]) == 1
      && memcmp (sequence[0]->one_to_one, one_to_same, 256) == 0)
    {
      length_of_sequence = 0;
      saved_steps++;
    }

  /* Save the resulting sequence length, and tell the user if something
     changed.  */

  if (saved_steps > 0 && verbose_option)
    {
      fprintf (stderr, _("Simplified to: "));
      echo_sequence ();
    }
}

/* Recoding execution control.  */

/*--------------.
| Copy a file.  |
`--------------*/

/* This should be rewritten to be a lot faster.  */

static void
file_copy (FILE *input_file, FILE *output_file)
{
  int input_char;		/* current character */

  while (input_char = getc (input_file), input_char != EOF)
    putc (input_char, output_file);
}

/*----------------------------------------------------------------------.
| Recode a file using a one-to-one recoding table.  Returns zero if the |
| recoding has been interrupted because of a reversibility problem.     |
`----------------------------------------------------------------------*/

int
file_one_to_one (const STEP *step, FILE *input_file, FILE *output_file)
{
  const unsigned char *table;	/* conversion table */
  int input_char;		/* current character */

  table = step->one_to_one;
  while (input_char = getc (input_file), input_char != EOF)
    putc (table[input_char], output_file);

  return 1;
}

/*-----------------------------------------------------------------------.
| Recode a file using a one-to-many recoding table.  Returns zero if the |
| recoding has been found to be non reversible.				 |
`-----------------------------------------------------------------------*/

int
file_one_to_many (const STEP *step, FILE *input_file, FILE *output_file)
{
  int reversible;		/* reversibility of recoding */
  const char *const *table;	/* conversion table */
  int input_char;		/* current character */
  const char *output_string;	/* translated characters */

  /* Copy the file through the one to many recoding table.  */

  reversible = 1;
  table = step->one_to_many;
  while (input_char = getc (input_file), input_char != EOF)
    if (output_string = table[input_char], output_string)
      while (*output_string)
	{
	  putc (*output_string, output_file);
	  output_string++;
	}
    else
      reversible = 0;

  return reversible;
}

/*-------------------------------------------------------------------------.
| Execute the conversion sequence, using several passes with two	   |
| alternating intermediate files.  This routine assumes at least one	   |
| needed recoding step.  Returns zero if the recoding has been found to be |
| non-reversible.							   |
`-------------------------------------------------------------------------*/

static int
execute_pass_sequence (const char *input_name, const char *output_name)
{
  int sequence_index;		/* index into sequence */
  const STEP *step;		/* pointer to step */
  FILE *input_file;		/* input file to recoding step */
  FILE *output_file;		/* output file from recoding step */
  int reversible;		/* reversibility of recoding */
#if USE_TMPNAM
  char *temp_input_name;	/* step input file name */
  char *temp_output_name;	/* step output file name */
  char temp_name_1[L_tmpnam];	/* one temporary file name */
  char temp_name_2[L_tmpnam];	/* another temporary file name */
  char *exchange_temp;		/* for exchanging temporary names */
#endif

#if USE_TMPNAM

  /* Choose names for intermediate files.  Use "" for delaying them.  */

#if MSDOS_or_OS2
  strcpy (temp_name_1, "recodex1.tmp");
  strcpy (temp_name_2, "recodex2.tmp");
#else
  temp_name_1[0] = '\0';
  temp_name_2[0] = '\0';
#endif
  temp_input_name = temp_name_1;
  temp_output_name = temp_name_2;

#endif /* USE_TMPNAM */

  /* Execute one pass for each step of the sequence.  */

  reversible = 1;
  for (sequence_index = 0;
       sequence_index < length_of_sequence;
       sequence_index++)
    {

      /* Select the input file for this step.  */

      if (sequence_index == 0)
	{
	  if (!input_name)
	    input_file = stdin;
	  else if (input_file = fopen (input_name, "r"), input_file == NULL)
	    PERROR1 ("fopen (%s)", input_name);
	}
      else
	{
#if USE_TMPNAM
	  if (input_file = fopen (temp_input_name, "r"), input_file == NULL)
	    PERROR1 ("fopen (%s)", temp_input_name);
#endif

#if USE_TMPFILE
	  rewind (input_file);
#endif
	}

      /* Select the output file for this step.  */

      if (sequence_index == length_of_sequence - 1)
	{
	  if (!output_name)
	    output_file = stdout;
	  else if (output_file = fopen (output_name, "w"), output_file == NULL)
	    PERROR1 ("fopen (%s)", output_name);
	}
      else
	{
#if USE_TMPNAM
# if MSDOS_or_OS2
	  if (*temp_output_name == '\0')
	    tmpnam (temp_output_name);
# endif
	  if (output_file = fopen (temp_output_name, "w"), output_file == NULL)
	    PERROR1 ("fopen (%s)", temp_output_name);
#endif

#if USE_TMPFILE
	  if (output_file = tmpfile (), output_file == NULL)
	    PERROR ("tmpfile ()");
#endif
	}

      /* Execute one recoding step.  */

      step = sequence[sequence_index];
      if (!(*step->file_recode) (step, input_file, output_file))
	reversible = 0;

      /* Close the input file, unlink it if it was temporary.  */

      if (sequence_index == 0)
	{
	  if (input_name)
	    fclose (input_file);
	}
      else
	{
	  fclose (input_file);
#if USE_TMPNAM
	  unlink (temp_input_name);
#endif
	}

      /* Close the output file and prepare for subsequent step.  */

      if (sequence_index == length_of_sequence - 1)
	{
	  if (output_name)
	    fclose (output_file);
	}
      else
	{
#if USE_TMPNAM
	  fclose (output_file);

	  exchange_temp = temp_input_name;
	  temp_input_name = temp_output_name;
	  temp_output_name = exchange_temp;
#endif

#if USE_TMPFILE
	  input_file = output_file;
#endif
	}
    }
  return reversible;
}

/*-------------------------------------------------------------------------.
| Execute the conversion sequence, using a chain of invocations of the	   |
| program through popen.  This routine assumes that more than one recoding |
| step is needed.  Returns zero if the recoding has been found to be	   |
| non-reversible.							   |
`-------------------------------------------------------------------------*/

#if HAVE_POPEN

static int
execute_popen_sequence (const char *input_name, const char *output_name)
{
  const STEP *step;		/* current step */
  FILE *input_file;		/* input file to recoding step */
  FILE *output_file;		/* output file from recoding step */
  char popen_command[80];	/* to receive command string */
  int reversible;		/* reversibility of recoding */

  /* Construct a `recode' command for all recoding steps but the first.  */

  strcpy (popen_command, program_name);
  if (diaeresis_char)
    strcat (popen_command, " -c");
  if (diacritics_only)
    strcat (popen_command, " -d");
  if (force_option)
    strcat (popen_command, " -f");
  strcat (popen_command, " -o -q ");
  strcat (popen_command, clean_charset_name (sequence[1]->before->name));
  strcat (popen_command, ":");
  strcat (popen_command,
	  clean_charset_name (sequence[length_of_sequence-1]->after->name));
  if (output_name)
    {
      strcat (popen_command, " >");
      strcat (popen_command, output_name);
    }

  /* Execute the first recoding step.  */

  if (!input_name)
    input_file = stdin;
  else if (input_file = fopen (input_name, "r"), input_file == NULL)
    PERROR1 ("fopen (%s)", input_name);

  if (output_file = popen (popen_command, "w"), output_file == NULL)
    PERROR1 ("popen (%s)", popen_command);

  step = sequence[0];
  reversible = (*step->file_recode) (step, input_file, output_file);

  if (input_name)
    fclose (input_file);

  /* Return the proper status.  */

  if (pclose (output_file) != 0)
    reversible = 0;

  return reversible;
}

#endif /* HAVE_POPEN */

#if HAVE_PIPE

#if !HAVE_DUP2

/*------------------------------------------------------------------------.
| Duplicate the OLD_FD file descriptor into NEW_FD, closing NEW_FD first  |
| if it is used.  This implementation presumes both OLD_FD and NEW_FD are |
| valid file descriptors.						  |
`------------------------------------------------------------------------*/

/* Overall idea taken from GNU Emacs 18.55 dup2 (), in src/sysdep.c.  */

#include <sys/fcntl.h>

#ifndef F_DUPFD

static int
dup2_recursive (int old_fd, int new_fd)
{
  int fd;

  /* Attempt to dup OLD_FD to NEW_FD.  If not successful, call dup2
     recursively, filling the file descriptor table until NEW_FD is
     reached.  Then close all the spurious file descriptors we created.  */

  if (fd = dup (old_fd) && fd != new_fd)
    if (fd < 0 || dup2_recursive (old_fd, new_fd) < 0 || close (fd) < 0)
      return 0;

  return 1;
}

#endif /* not F_DUPFD */

static int
dup2 (int old_fd, int new_fd)
{

  /* If OLD_FD or NEW_FD were not valid file descriptors, dup2 should
     ideally return -1 with errno set to EBADF.  This is not checked.  */

  if (old_fd != new_fd)
    {
      close (new_fd);

#ifdef F_DUPFD
      if (fcntl (old_fd, F_DUPFD, new_fd) != new_fd)
	return -1;
#else
      if (!dup2_recursive (old_fd, new_fd))
	return -1;
#endif
    }
  return new_fd;
}

#endif /* not HAVE_DUP2 */

/*-------------------------------------------------------------------------.
| Execute the conversion sequence, forking the program many times for all  |
| elementary steps, interconnecting them with pipes.  This routine assumes |
| that more than one recoding step is needed.  Returns zero if the	   |
| recoding has been found to be non-reversible.				   |
`-------------------------------------------------------------------------*/

#if 1

/* This is no good.  The main process might open too many files for one
   thing.  All of it should work almost the same way
   execute_popen_sequence does, creating children from left to right,
   instead of all children to a single parent right to left.  */

static int
execute_pipe_sequence (const char *input_name, const char *output_name)
{
  int sequence_index;		/* index into sequence */
  const STEP *step;		/* pointer into single_steps */

  FILE *input_file;		/* input file to recoding step */
  FILE *output_file;		/* output file from recoding step */
  int pipe_pair[2];		/* pair of file descriptors for a pipe */
  int child_process;		/* child process number, zero if child */
  int wait_status;		/* status returned by wait() */
  int reversible;		/* reversibility of recoding */

  /* Prepare the final output file.  */

  if (!output_name)
    output_file = stdout;
  else if (output_file = fopen (output_name, "w"), output_file == NULL)
    PERROR1 ("fopen (%s)", output_name);

  /* Create all subprocesses, from the last to the first, and
     interconnect them.  */

  reversible = 1;
  for (sequence_index = length_of_sequence - 1;
       sequence_index > 0;
       sequence_index--)
    {
      if (pipe (pipe_pair) < 0)
	PERROR ("pipe ()");
      if (child_process = fork (), child_process < 0)
	PERROR ("fork ()");
      if (child_process == 0)
	{

          /* The child executes its recoding step, reading from the pipe
             and writing to the current output file; then it exits.  */

	  if (close (pipe_pair[1]) < 0)
	    PERROR ("close ()");
	  if (input_file = fdopen (pipe_pair[0], "r"), input_file == NULL)
	    PERROR ("fdopen ()");

	  step = sequence[sequence_index];
	  if (!(*step->file_recode) (step, input_file, output_file))
	    reversible = 0;

	  fclose (input_file);
	  if (sequence_index < length_of_sequence - 1 || output_name)
	    fclose (output_file);

	  exit (reversible ? EXIT_SUCCESS : EXIT_FAILURE);
	}
      else
	{

          /* The parent redirects the current output file to the pipe.  */

	  if (dup2 (pipe_pair[1], fileno (output_file)) < 0)
	    PERROR ("dup2 ()");
	  if (close (pipe_pair[0]) < 0)
	    PERROR ("close ()");
	  if (close (pipe_pair[1]) < 0)
	    PERROR ("close ()");
	}
    }

  /* All the children are created, blocked on read.  Now, feed the whole
     chain of processes with the output of the first recoding step.  */

  if (!input_name)
    input_file = stdin;
  else if (input_file = fopen (input_name, "r"), input_file == NULL)
    PERROR1 ("fopen (%s)", input_name);

  step = sequence[0];
  if (!(*step->file_recode) (step, input_file, output_file))
    reversible = 0;

  if (input_name)
    fclose (input_file);

  fclose (output_file);

  /* Wait on all children, mainly to avoid synchronisation problems on
     output file contents, but also to reduce the number of zombie
     processes in case the user recodes many files at once.  */

  while (wait (&wait_status) > 0)
    {

      /* Diagnose and abort on any abnormally terminating child.  */

      if ((wait_status & ~(~0 << 8)) != 0
	  && (wait_status & ~(~0 << 8)) != SIGPIPE)
	error (0, 0, _("Child process wait status is 0x%0.2x"),
	       wait_status);

      /* Check for a non-zero exit from the terminating child.  */

      if (wait_status & ~(~0 << 16))
	reversible = 0;
    }

  if (interrupted)
    reversible = 0;

  return reversible;
}

#else

static int
execute_pipe_sequence (const char *input_name, const char *output_name)
{
  int sequence_index;		/* index into sequence */
  const STEP *step;		/* pointer into single_steps */

  FILE *input_file;		/* input file to recoding step */
  FILE *output_file;		/* output file from recoding step */
  int pipe_pair[2];		/* pair of file descriptors for a pipe */
  int child_process;		/* child process number, zero if child */
  int wait_status;		/* status returned by wait() */
  int reversible;		/* reversibility of recoding */

  /* Prepare the final files.  */

  if (!input_name)
    input_file = stdin;
  else if (input_file = fopen (input_name, "r"), input_file == NULL)
    PERROR1 ("fopen (%s)", input_name);

  if (!output_name)
    output_file = stdout;
  else if (output_file = fopen (output_name, "w"), output_file == NULL)
    PERROR1 ("fopen (%s)", output_name);

  /* Create all subprocesses, from the first to the last, and
     interconnect them.  */

  reversible = 1;
  for (sequence_index = 0;
       sequence_index < length_of_sequence - 1;
       sequence_index++)
    {
      if (pipe (pipe_pair) < 0)
	PERROR ("pipe ()");
      if (child_process = fork (), child_process < 0)
	PERROR ("fork ()");
      if (child_process == 0)
	{
          /* The child executes its recoding step, reading from the pipe
             and writing to the current output file; then it exits.  */

	  if (close (pipe_pair[1]) < 0)
	    PERROR ("close ()");
	  if (input_file = fdopen (pipe_pair[0], "r"), input_file == NULL)
	    PERROR ("fdopen ()");

	  step = sequence[sequence_index];
	  if (!(*step->file_recode) (step, input_file, output_file))
	    reversible = 0;

	  fclose (input_file);
	  if (sequence_index < length_of_sequence - 1 || output_name)
	    fclose (output_file);

	  exit (reversible ? EXIT_SUCCESS : EXIT_FAILURE);
	}
      else
	{

          /* The parent redirects the current output file to the pipe.  */

	  if (dup2 (pipe_pair[1], fileno (output_file)) < 0)
	    PERROR ("dup2 ()");
	  if (close (pipe_pair[0]) < 0)
	    PERROR ("close ()");
	  if (close (pipe_pair[1]) < 0)
	    PERROR ("close ()");
	}
      else
	{
	  break;
	}
    }

  /* All processes execute the following common code, each with its proper
     value for SEQUENCE_INDEX, CHILD_PROCESS, etc.  */

  /* All the children are created, blocked on read.  Now, feed the whole
     chain of processes with the output of the first recoding step.  */

  if (!input_name)
    input_file = stdin;
  else if (input_file = fopen (input_name, "r"), input_file == NULL)
    PERROR1 ("fopen (%s)", input_name);

  step = sequence[0];
  if (!(*step->file_recode) (step, input_file, output_file))
    reversible = 0;

  if (input_name)
    fclose (input_file);

  fclose (output_file);

  /* Wait on all children, mainly to avoid synchronisation problems on
     output file contents, but also to reduce the number of zombie
     processes in case the user recodes many files at once.  */

  while (wait (&wait_status) > 0)
    {

      /* Diagnose and abort on any abnormally terminating child.  */

      if ((wait_status & ~(~0 << 8)) != 0
	  && (wait_status & ~(~0 << 8)) != SIGPIPE)
	error (0, 0, _("Child process wait status is 0x%0.2x"),
	       wait_status);

      /* Check for a non-zero exit from the terminating child.  */

      if (wait_status & ~(~0 << 16))
	reversible = 0;
    }

  if (interrupted)
    reversible = 0;

  return reversible;
}

#endif

#endif /* HAVE_PIPE */

/*-------------------------------------------------------------------------.
| Execute the conversion sequence, using the selected strategy whenever	   |
| more than one conversion step is needed.  If no conversion are needed,   |
| merely copy the input onto the output.  Returns zero if the recoding has |
| been found to be non-reversible.					   |
`-------------------------------------------------------------------------*/

/* If some sequencing strategies are missing, this routine automatically
   uses fallback strategies.  */

static int
execute_sequence (const char *input_name, const char *output_name)
{
  FILE *input_file;		/* input file to recoding step */
  FILE *output_file;		/* output file from recoding step */
  const STEP *step;		/* current step */
  int reversible;		/* reversibility of recoding */

#if MSDOS_or_OS2
  if (!input_name)
    setmode (fileno (stdin), O_BINARY);
  if (!output_name)
    setmode (fileno (stdout), O_BINARY);
# ifdef __EMX__
  {
    extern int _fmode_bin;
    _fmode_bin = 1;
  }
# else
  _fmode = O_BINARY;
# endif
#endif

  if (verbose_option && input_name)
    {
      fprintf (stderr, _("Recoding %s..."), input_name);
      fflush (stderr);
    }

  if (length_of_sequence > 1)
    switch (sequence_strategy)
      {
      case STRATEGY_UNDECIDED:
	error (EXIT_FAILURE, 0, _("Internal error - strategy undecided"));

      case SEQUENCE_WITH_PIPE:
#if HAVE_PIPE
	reversible = execute_pipe_sequence (input_name, output_name);
	break;
#endif

      case SEQUENCE_WITH_POPEN:
#if HAVE_POPEN
	reversible = execute_popen_sequence (input_name, output_name);
	break;
#endif

      case SEQUENCE_WITH_FILES:
	reversible = execute_pass_sequence (input_name, output_name);
	break;
      }
  else
    {

      /* This is a single-step recoding a mere copy.  Do it.  */

      if (!input_name)
	input_file = stdin;
      else if (input_file = fopen (input_name, "r"), input_file == NULL)
	PERROR1 ("fopen (%s)", input_name);

      if (!output_name)
	output_file = stdout;
      else if (output_file = fopen (output_name, "w"), output_file == NULL)
	PERROR1 ("fopen (%s)", output_name);

      if (length_of_sequence == 1)
	{
	  step = sequence[0];
	  reversible = (*step->file_recode) (step, input_file, output_file);
	}
      else
	{
	  file_copy (input_file, output_file);
	  reversible = 1;
	}

      if (input_name)
	fclose (input_file);
      if (output_name)
	fclose (output_file);
    }

  if (verbose_option && input_name)
    {
      fprintf (stderr, _(" done\n"));
      fflush (stderr);
    }
  return reversible;
}

/* Some special option handling.  */

/*-----------------------------------------------------------------.
| Print a truncated charset name, with a guaranteed space at end.  |
`-----------------------------------------------------------------*/

static void
print_truncated_charset_name (const char *name)
{
  char copy[15];

  if ((int) strlen (name) > 14)
    {
      memcpy (copy, name, 14);
      copy[14] = '\0';
      name = copy;
    }
  printf ("%-14s ", name);
}

/*----------------------------------------------------------------------.
| Find all possible sequences and report about them.  If CHARSET is not |
| NULL, limit the study to those recoding starting or ending with the   |
| given charset.						        |
`----------------------------------------------------------------------*/

static void
perform_auto_check_one (CHARSET *before, CHARSET *after)
{
  int saved_length_of_sequence;
  int saved_number_of_single_steps;
  QUALITY quality;
  const char *quality_string;
  int counter;
  STEP *step;

  /* Study what we can do.  */

  find_sequence (before, after);
  if (length_of_sequence < 0)
    {
      if (!ignored_name)
	{
	  print_truncated_charset_name (before->name);
	  print_truncated_charset_name (after->name);
	  printf (_("  UNACHIEVABLE\n"));
	}
    }
  else
    {

      /* Compute the recoding quality.  */

      quality = REVERSIBLE;
      for (counter = 0; counter < length_of_sequence; counter++)
	quality = merge_qualities (quality,
				   sequence[counter]->quality);
      quality_string = quality_to_string (quality);

      /* Study what optimization can do.  */

      saved_length_of_sequence = length_of_sequence;
      saved_number_of_single_steps = number_of_single_steps;

      simplify_sequence ();

      /* Check and report codes which should be aliases.  */

      if (length_of_sequence == 0)
	quality_string = _("ONE to SAME");

      /* Make the report.  */

      print_truncated_charset_name (before->name);
      print_truncated_charset_name (after->name);
      printf ("  %-16s", quality_string);
      printf (_("steps: %d"), saved_length_of_sequence);

      if (length_of_sequence != saved_length_of_sequence)
	printf (_(", %d saved by merging"),
		saved_length_of_sequence - length_of_sequence);
      printf ("\n");

      /* Unregister and clean up the merged steps.  */

      while (number_of_single_steps > saved_number_of_single_steps)
	{
	  number_of_single_steps--;
	  step = single_step_array + number_of_single_steps;
	  if (step->one_to_one)
	    free ((void *) step->one_to_one);
	  if (step->one_to_many)
	    free ((void *) step->one_to_many);
	}
    }
}

static void
perform_auto_check (CHARSET *charset)
{
  CHARSET *before;
  CHARSET *after;

  if (charset)
    {
      if (charset->ignore)
	error (EXIT_FAILURE, 0, _("Cannot auto check the ignored charset"));
      if (charset == rfc1345)
	error (EXIT_FAILURE, 0, _("Cannot auto check on %s"), charset->name);

      for (before = charset_array;
	   before < charset_array + number_of_charsets;
	   before++)
	if (!before->ignore && before != charset && before != rfc1345)

	    perform_auto_check_one (before, charset);

      for (after = charset_array;
	   after < charset_array + number_of_charsets;
	   after++)
	if (!after->ignore && after != charset && after != rfc1345)

	    perform_auto_check_one (charset, after);
    }
  else
    for (before = charset_array;
	 before < charset_array + number_of_charsets;
	 before++)
      if (!before->ignore && before != rfc1345)

	for (after = charset_array;
	     after < charset_array + number_of_charsets;
	     after++)
	  if (!after->ignore && after != before && after != rfc1345)

	    perform_auto_check_one (before, after);
}

/* Main program.  */

/*-----------------------------------------------.
| Explain how to use the program, then get out.	 |
`-----------------------------------------------*/

void
usage (int status)
{
  if (status != EXIT_SUCCESS)
    fprintf (stderr, _("Try `%s %s' for more information.\n"), program_name,
	     decoding_charset_flag ? "--list" : "--help");
  else
    {
      printf ("GNU %s %s\n", PACKAGE, VERSION);
      printf (_("\
\n\
Usage: %s [OPTION]... [CHARSET]\n"), program_name);
      fputs (_("\
Mandatory or optional arguments to long options are mandatory or optional\n\
for short options too.\n\
\n\
  -C, --copyright       display Copyright and copying conditions\n\
  -a, --auto-check      report about some or all recoding paths, then exit\n\
  -l, --list[=FORMAT]   list one or all known charsets\n\
  -k, --known=PAIRS     restrict charsets according to known PAIRS list\n\
      --help            display this help and exit\n\
      --version         output version information and exit\n\
\n\
FORMAT is a word among decimal, octal, hexadecimal or full (which may be\n\
abbreviated to one of `dohf'), it defaults to just the canonical name.\n\
With -k, possible before charsets are listed for the given after CHARSET,\n\
both being RFC1345 charsets, with PAIRS of the form `BEF1:AFT1,BEF2:AFT2,...\n\
and BEFs and AFTs being codes.  All codes are given as decimal numbers.\n"),
	      stdout);
      fputs (_("\
Option -l with no FORMAT nor CHARSET list all charsets, also see the Texinfo\n\
documentation.  My preferred charsets are (each user has preferences):\n\
\n\
  ascii-bs   ASCII (7-bit), using backspace to apply diacritics\n\
  ibmpc      IBM-PC 8-bit characters, with proper newlines\n\
  latex      LaTeX coding of foreign and diacriticized characters\n\
  latin1     ISO Latin-1 8-bit extension of ASCII\n\
  texte      Easy French convention for transmitting email messages\n"),
	     stdout);
      printf (_("\
\n\
Usage: %s [OPTION]... [BEFORE]:[AFTER] [FILE]...\n"), program_name);
      fputs (_("\
\n\
  -c, --colons            use colons instead of double quotes for diaeresis\n\
  -d, --diacritics        limit conversion to diacritics or alike for LaTeX\n\
  -f, --force             force recodings even if they are not reversible\n\
                          (BEWARE: in this version, -f is always selected)\n\
  -g, --graphics          approximate IBMPC rulers by ASCII graphics\n\
  -h, --header[=NAME]     write C code with table NAME on stdout, then exit\n\
  -i, --sequence=files    use intermediate files for sequencing passes\n"),
	     stdout);

#if HAVE_POPEN
      fputs (_("\
  -o, --sequence=popen    use popen machinery for sequencing passes\n"),
	     stdout);
#else
      fputs (_("\
  -o, --sequence=popen    same as -i (on this system)\n"),
	     stdout);
#endif

#if HAVE_PIPE
      fputs (_("\
  -p, --sequence=pipe     use pipe machinery for sequencing passes\n"),
	     stdout);
#else
      fputs (_("\
  -p, --sequence=pipe     same as -o (on this system)\n"),
	     stdout);
#endif

      fputs (_("\
  -q, --quiet, --silent   inhibit messages about irreversible recodings\n\
  -s, --strict            use strict mappings, even loose characters\n\
  -t, --touch             touch the recoded files after replacement\n\
  -v, --verbose           explain sequence of steps and report progress\n\
  -x, --ignore=CHARSET    ignore CHARSET while choosing a recoding path\n\
\n\
If none of -i, -o and -p are given, presume -p if no FILE, else -i.\n\
Each FILE is recoded over itself, destroying the original.  If no\n\
FILE is specified, then act as a filter and recode stdin to stdout.\n"),
	     stdout);
      printf (_("\
BEFORE and AFTER both default to `%s' when needed.\n"), DEFAULT_CHARSET);
    }
  exit (status);
}

/*----------------------------------------------------------------------.
| Main program.  Decode ARGC arguments passed through the ARGV array of |
| strings, then launch execution.				        |
`----------------------------------------------------------------------*/

/* Long options equivalences.  */
static const struct option long_options[] =
{
  {"auto-check", no_argument, NULL, 'a'},
  {"colons", no_argument, NULL, 'c'},
  {"copyright", no_argument, NULL, 'C'},
  {"diacritics", no_argument, NULL, 'd'},
  {"force", no_argument, NULL, 'f'},
  {"header", optional_argument, NULL, 'h'},
  {"help", no_argument, &show_help, 1},
  {"ignore", required_argument, NULL, 'x'},
  {"list", optional_argument, NULL, 'l'},
  {"quiet", no_argument, NULL, 'q'},
  {"sequence", required_argument, NULL, '\n'},
  {"silent", no_argument, NULL, 'q'},
  {"strict", no_argument, NULL, 's'},
  {"touch", no_argument, NULL, 't'},
  {"verbose", no_argument, NULL, 'v'},
  {"version", no_argument, &show_version, 1},
  {0, 0, 0, 0},
};

static const char *const format_strings[] =
  {
    "decimal",
    "octal",
    "hexadecimal",
    "full",
    NULL,
  };

static const char *const sequence_strings[] =
  {
    "files",
    "popen",
    "pipe",
    NULL,
  };

int
main (int argc, char *const *argv)
{
  extern int optind;		/* index of argument */
  int option_char;		/* option character */
  int reversible;		/* reversibility of all recodings */
  const char *input_name;	/* input file name */
  char output_name[200];	/* output file name */
  FILE *file;			/* file to check or stat */
#if MSDOS
  struct ftime stamp_stat;	/* input file time stamps */
#else
  struct stat stamp_stat;	/* input file time stamps */
  time_t stamp_utime[2];	/* recoded file time stamps */
#endif
  char *cursor;			/* all purpose cursor */

  /* Decode command options.  */

  program_name = argv[0];
  setlocale (LC_ALL, "");

  error_print_progname = error_print_prefix;

  if (argc == 1)
    usage (EXIT_SUCCESS);

  while (option_char = getopt_long (argc, argv, "aCcdfgh::ik:l::opqstvx:",
				    long_options, NULL),
	 option_char != EOF)
    switch (option_char)
      {
      default:
	usage (EXIT_FAILURE);

      case '\0':
	break;

      case '\n':
	switch (argmatch (optarg, sequence_strings))
	  {
	  case -2:
	    error (0, 0, _("Ambiguous sequence `%s'"), optarg);
	    usage (EXIT_FAILURE);

	  case -1:
	    error (0, 0, _("Unknown sequence `%s'"), optarg);
	    usage (EXIT_FAILURE);

	  case 0:
	    sequence_strategy = SEQUENCE_WITH_FILES;
	    break;

	  case 1:
	    sequence_strategy = SEQUENCE_WITH_POPEN;
	    break;

	  case 2:
	    sequence_strategy = SEQUENCE_WITH_PIPE;
	    break;
	  }
	break;

      case 'a':
	auto_check_mode = 1;
	break;

      case 'C':
	fprintf (stderr, "%s", _("\
This program is free software; you can redistribute it and/or modify\n\
it under the terms of the GNU General Public License as published by\n\
the Free Software Foundation; either version 2, or (at your option)\n\
any later version.\n\
\n\
This program is distributed in the hope that it will be useful,\n\
but WITHOUT ANY WARRANTY; without even the implied warranty of\n\
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\
GNU General Public License for more details.\n\
\n\
You should have received a copy of the GNU General Public License\n\
along with this program; if not, write to the Free Software\n\
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n"));

	exit (EXIT_SUCCESS);

      case 'c':
	diaeresis_char = ':';
	break;

      case 'd':
	diacritics_only = 1;
	break;

      case 'f':
	force_option = 1;
	break;

      case 'g':
	ascii_graphics = 1;
	break;

      case 'h':
	make_header_mode = 1;
	header_name = optarg;
	break;

      case 'i':
	sequence_strategy = SEQUENCE_WITH_FILES;
	break;

      case 'k':
	decode_known_pairs (optarg);
	show_restricted_charsets = 1;
	break;

      case 'l':
	show_charsets = 1;
	if (optarg)
	  switch (argmatch (optarg, format_strings))
	    {
	    case -2:
	      error (0, 0, _("Ambiguous format `%s'"), optarg);
	      usage (EXIT_FAILURE);

	    case -1:
	      error (0, 0, _("Unknown format `%s'"), optarg);
	      usage (EXIT_FAILURE);

	    case 0:
	      list_format = DECIMAL_FORMAT;
	      break;

	    case 1:
	      list_format = OCTAL_FORMAT;
	      break;

	    case 2:
	      list_format = HEXADECIMAL_FORMAT;
	      break;

	    case 3:
	      list_format = FULL_FORMAT;
	      break;
	    }
	break;

      case 'o':
	sequence_strategy = SEQUENCE_WITH_POPEN;
	break;

      case 'p':
	sequence_strategy = SEQUENCE_WITH_PIPE;
	break;

      case 'q':
	quiet_mode = 1;
	break;

      case 's':
	strict_mapping = 1;
	break;

      case 't':
	touch_option = 1;
	break;

      case 'v':
	verbose_option = 1;
	break;

      case 'x':
	ignored_name = optarg;
	break;
      }

  if (ascii_graphics && strict_mapping)
    {
      error (0, 0, _("Currently, -s is ignored when -g is selected"));
      strict_mapping = 0;
    }

  if (ascii_graphics || strict_mapping)
    force_option = 1;

  /* Process trivial options.  */

  if (show_version)
    {
      printf ("GNU %s %s\n", PACKAGE, VERSION);
      exit (EXIT_SUCCESS);
    }

  if (show_help)
    usage (EXIT_SUCCESS);

  /* Register all modules, then set the ignored charset.  */

  register_all_modules ();
  make_argmatch_array ();

  if (ignored_name)
    find_charset (clean_charset_name (ignored_name))->ignore = 1;

  /* Process auto check option.  */

  if (auto_check_mode)
    {
      if (optind + 1 < argc)
	usage (EXIT_FAILURE);

      /* Accept a possible charset.  */

      if (optind < argc)
	perform_auto_check (find_charset (clean_charset_name (argv[optind])));
      else
	perform_auto_check (NULL);
      exit (EXIT_SUCCESS);
    }

  /* Process charset listing options.  */

  if (show_charsets || show_restricted_charsets)
    {
      if (optind + 1 < argc)
	usage (EXIT_FAILURE);

      /* Select a possible charset and a default format.  */

      if (optind < argc)
	list_charset = find_charset (clean_charset_name (argv[optind]));
      else if (list_format != NO_FORMAT || show_restricted_charsets)
	list_charset = find_charset (clean_charset_name (NULL));
      else
	list_charset = NULL;

      /* List the charset(s) appropriately.  */
      
      if (show_restricted_charsets)
	list_all_charsets (list_charset);
      else if (list_charset)
	if (list_format == FULL_FORMAT)
	  list_full_charset (list_charset);
	else
	  list_concise_charset (list_charset);
      else
	list_all_charsets (NULL);

      /* Then get out.  */

      exit (EXIT_SUCCESS);
    }

  /* Decode the BEFORE:AFTER argument.  */

  if (optind + 1 > argc)
    usage (EXIT_FAILURE);

  decode_before_after (argv[optind++]);

  /* Establish the sequence of recoding steps.  */

  length_of_sequence = 0;
  find_sequence (before_charset, after_charset);
  if (length_of_sequence < 0)
    error (EXIT_FAILURE, 0, _("No way to recode from %s to %s"),
	   before_charset->name, after_charset->name);

  simplify_sequence ();

  /* If we merely want C code, do it and get out.  */

  if (make_header_mode)
    {
      if (length_of_sequence == 0)
	error (EXIT_FAILURE, 0, _("Recoding is trivial, not worth a table"));
      if (length_of_sequence > 1
	  || !(sequence[0]->one_to_one || sequence[0]->one_to_many))
	error (EXIT_FAILURE, 0, _("Recoding is too complex for a mere table"));

      output_header_file ();
      exit (EXIT_SUCCESS);
    }

  /* If the recoding might be not reversible, do not proceed further without
     --force option.  */

  /* DO IT!  */

  /* If there is no input file, act as a filter.  Else, recode all files
     over themselves.  */

  setup_signals ();

  if (optind < argc)
    {

      /* When reading and writing files, unless the user selected otherwise,
	 avoid forking and use intermediate files.  */

      if (sequence_strategy == STRATEGY_UNDECIDED)
	sequence_strategy = SEQUENCE_WITH_FILES;

      /* In case files are recoded over themselves and there is no
         recoding step at all, do not even try to touch the files.  */

      reversible = 1;
      if (length_of_sequence > 0)

	/* Process files, one at a time.  */

	for (; optind < argc; optind++)
	  {
	    input_name = argv[optind];

	    /* Check if the file can be read and rewritten.  */

	    if (file = fopen (input_name, "r+"), file == NULL)
	      PERROR1 ("fopen (%s)", input_name);

	    /* Save the input file time stamp.  */

	    if (!touch_option)
	      {
#if MSDOS
		getftime (fileno (file), &stamp_stat);
#else
		fstat (fileno (file), &stamp_stat);
#endif
	      }

	    fclose (file);

	    /* Choose an output file in the same directory.  */

#if MSDOS_or_OS2

	    strcpy (output_name, input_name);
	    for (cursor = output_name + strlen (output_name);
		 cursor > output_name && cursor[-1] != '/'
		 && cursor[-1] != '\\' && cursor[-1] != ':';
		 cursor--)
	      ;
	    strcpy (cursor, "recodeXX.TMP");

#else /* not MSDOS_or_OS2 */

	    strcpy (output_name, input_name);
	    for (cursor = output_name + strlen (output_name);
		 cursor > output_name && cursor[-1] != '/';
		 cursor--)
	      ;
	    sprintf (cursor, "rec%d.tmp", getpid ());

#endif /* not MSDOS_or_OS2 */

	    /* Recode the file.  */

	    if (!execute_sequence (input_name, output_name))
	      {
		reversible = 0;
		if (!quiet_mode)
		  error (0, 0, _("%s: Recoding is not reversible"),
			 input_name);
	      }

	    /* Move the new file over the original.  */

	    if (unlink (input_name) < 0)
	      PERROR1 ("unlink (%s)", input_name);
#if HAVE_RENAME
	    if (rename (output_name, input_name) < 0)
	      PERROR2 ("rename (%s, %s)", output_name, input_name);
#else
	    if (link (output_name, input_name) < 0)
	      PERROR2 ("link (%s, %s)", output_name, input_name);
	    if (unlink (output_name) < 0)
	      PERROR1 ("unlink (%s)", output_name);
#endif

	    /* Adjust the time stamp for the new file.  */

	    if (!touch_option)
	      {
#if MSDOS
		file = fopen (input_name, "r");
		if (file == NULL)
		  PERROR1 ("fopen (%s)", input_name);
		setftime (fileno (file), &stamp_stat);
		fclose (file);
#else
		stamp_utime[0] = stamp_stat.st_atime;
		stamp_utime[1] = stamp_stat.st_mtime;
		utime (input_name, stamp_utime);
#endif
	      }
	  }
    }
  else
    {

      /* When reading stdin and writing stdout, unless the user selected
         otherwise, fork processes interconnected with pipes.  */

      if (sequence_strategy == STRATEGY_UNDECIDED)
	sequence_strategy = SEQUENCE_WITH_PIPE;

      if (!execute_sequence (NULL, NULL))
	{
	  reversible = 0;
	  if (!quiet_mode)
	    error (0, 0, _("Recoding is not reversible"));
	}
    }

  /* Exit with an appropriate status.  */

  exit ((force_option || reversible) ? EXIT_SUCCESS : EXIT_FAILURE);
}