File: efax.c

package info (click to toggle)
efax-gtk 3.0.17-1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 4,672 kB
  • ctags: 2,278
  • sloc: cpp: 18,493; ansic: 5,586; sh: 4,548; makefile: 132; sed: 16
file content (2836 lines) | stat: -rw-r--r-- 80,604 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
#define Copyright         "Copyright 1999 Ed Casas"

#define Version		  "efax v 0.9a-001114"

/*
    Copyright (C) 1999  Ed Casas

    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 of the License, 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    Please contact the author if you wish to use efax or efix in
    ways not covered by the GNU GPL.

    You may contact the author by e-mail at: edc@cce.com.

*/

/* 
    Internationalisation support added by Chris Vine September 2005,
    including addition of the -n and -u options.

    The following patches from http://shino.pos.to/linux/efax/ also
    applied:

      efax-0.9-nullptr.patch
      efax-0.9a-frlen.patch

    The patch efax-0.9-misc.patch from Fedora 2 has been applied.
*/

const char *Usage =
  "Usage:\n"
  "  %s [ option ]... [ -t num [ file... ] ]\n"
  "Options:\n"
  "  -a str  use command ATstr to answer\n"
  "  -c cap  set modem and receive capabilites to cap\n"
  "  -d dev  use modem on device dev\n"
  "  -e cmd  exec \"/bin/sh -c cmd\" for voice calls\n"
  "  -f fnt  use (PBM) font file fnt for headers\n"
  "  -g cmd  exec \"/bin/sh -c cmd\" for data calls\n"
  "  -h hdr  use page header hdr (use %%d's for current page/total pages)\n"
  "  -i str  send modem command ATstr at start\n"
  "  -j str  send modem command ATstr after set fax mode\n"
  "  -k str  send modem command ATstr when done\n"
  "  -l id   set local identification to id\n"
  "  -n      force line buffering of stdout instead of block buffering (necessary\n"
  "          if outputting UTF-8 to a terminal with translated text via NLS)\n"
  "  -o opt  use protocol option opt:\n"
  "      0     use class 2.0 instead of class 2 modem commands\n"
  "      1     use class 1 modem commands\n"
  "      2     use class 2 modem commands\n"
  "      a     if first [data mode] answer attempt fails retry as fax\n"
  "      e     ignore errors in modem initialization commands\n"
  "      f     use virtual flow control\n"
  "      h     use hardware flow control\n"
  "      l     halve lock file polling interval\n"
  "      n     ignore page retransmission requests\n"
  "      r     do not reverse received bit order for Class 2 modems\n"  
  "      x     use XON instead of DC2 to trigger reception\n"
  "      z     add 100 ms to pause before each modem comand (cumulative)\n"
  "  -q ne   ask for retransmission if more than ne errors per page\n"
  "  -r pat  save received pages into files pat.001, pat.002, ... \n"
  "  -s      share (unlock) modem device while waiting for call\n"
  "  -u      use UTF-8 and not locale codeset (if different) for messages to\n"
  "          stderr and stdout (see also -n option)\n"
  "  -v lvl  print messages of type in string lvl (ewinchamr)\n"
  "  -w      don't answer phone, wait for OK or CONNECT instead\n"
  "  -x fil  use uucp-style lock file fil\n"
  "Commands:\n"
  "  -t      dial num and send fax image files file... \n"
  ;

#include <ctype.h>		/* ANSI C */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include <config.h>             /* For NLS */
#ifdef ENABLE_NLS
#include <locale.h>
#include <libintl.h>
#include <glib/gconvert.h>
#include <glib/gunicode.h>
#include <glib/gmem.h>
#endif

#include "efaxio.h"		/* EFAX */
#include "efaxlib.h"
#include "efaxmsg.h"
#include "efaxos.h"

/* constants... */

			    /* delays and timeouts (t/o), in deciseconds */
#define T1 350		    /* T.30 T1 - waiting for DIS/DCS before Phase B */
#define T2 60		    /* T.30 T2 - waiting for frame in Phase B */
#define T3S 30		    /* T.30 response timeout (not T3) */
#define T4 30		    /* T.30 T4 - between [re]transmissions of DIS */

#define TCFSECS 1.5	    /* TCF duration (seconds, nominally 1.5) */

#define TMOD 55             /* T.30 pause between v.21&v.29, 75-20 ms */
#define MODDLY "5"	    /* same as above, a string */

#define TO_A     1200	    /* dial/answer (Phase A) - modem may t/o first */
#define TO_ABRT  20	    /* max delay after sending abort sequence */
#define TO_CHAR  51	    /* per data character (max FILL length) */
#define TO_DATAF 80	    /* software adaptive answer data connect t/o */
#define TO_DRAIN_H 136	    /* minimum HDLC buffer drain time (4k/300cps) */
#define TO_DRAIN_D 300	    /* minimum data buffer drain time */
#define TO_FT    31	    /* max delay after +F[TR][MH] command */
#define TO_RTCMD 20	    /* return to command mode after DLE-ETX (rx) */

#define TO_C2B    450	    /* Class 2 DIS to CONNECT:(DCS+TCF+CFR)xretries */
#define TO_C2X    20	    /* Class 2 wait for XON: 2/5 of 5s timeout */
#define TO_C2PP   200	    /* Class 2 wait for ppr: (ppm+ppr)x3retries + 2 */
#define TO_C2R    600	    /* Class 2 receive: (TCF+FTT)x11 retrains + 5 */
#define TO_C2EOR  160	    /* Class 2 end of data rx (4 retrans x 4 s) */

#define ANSCMD  "A"	    /* default modem command to answer calls */
#define DCSLEN 3	    /* length of FIF for DCS commands sent */
#define DEFDISLEN 3	    /* length of DIS initially transmitted */
#define DEFCAP 1,3,0,2,0,0,0,0	/* default local capabilities */
#define DEFID "                    " /* default local ID */
#define DEFPAT "%m%d%H%M%S" /* default received file name pattern */
#define HDRSHFT 54	    /* shift header right 6.7mm into image area */
#define HDRSPCE 20	    /* number of scan lines inserted before image */
#define HDRSTRT  4	    /* scan line where header is placed on image */
#define HDRCHRH 24 	    /* header character height (pels, at 196lpi) */
#define HDRCHRW 12	    /* header character width (pels) */
#define IDLEN 20	    /* length of T.30 ID strings, must be 20 */
#define MAXDIS 8	    /* maximum DIS frames sent without response (T1) */
#define MAXERRPRT 32	    /* maximum number of reception errors to report */
#define MAXFIFLEN 125	    /* max FIF len = MAXFRLEN - (adx+ctl+FCF) - FCS */
#define MAXFRLEN 130        /* max frame length = 3.45s x 300 bps / 8 */
#define MAXGETTY 512        /* maximum length of exec'ed (-g, -e) commands */
#define MAXICMD  100        /* maximum # of modem setup/reset commands */
#define MAXLKFILE 16	    /* maximum number of lock files */
#define MAXNULLS 2	    /* maximum consecutive received nulls saved */
#define MAXPGERR 10         /* maximum received errors allowed per page */
#define MAXTRAIN 2	    /* maximum training retries at lowest speed */
#define MAXRETRY 3	    /* maximum retries of unacknowledged commands */
#define NCAP 8              /* number of fields in a capability string */
#define NTXRETRY 3	    /* maximum re-sends per page */

typedef int cap [ NCAP ] ;		/* remote/local capabilities */

                                        /* capability fields... */
enum  captype {	         VR, BR, WD, LN, DF, EC, BF, ST } ;
int capmax [ NCAP ] = {   1,  7,  2,  2,  3,  2,  1,  7 } ;
					/* & maximum values */

                                        /* vertical resolution, dpi */
int vresolution [ 2 ] = { 98, 196 } ;

					/* characters per second for br */
int cps [ 8 ] = { 300, 600, 900, 1200, 1500, 1800, 900, 1200 } ;

					/* next br = fallback [ br ] */
                    /* 0, 1, 2, 3, 4, 5, 6, 7 */
int fallback [ 8 ] = {-1, 0, 1, 2, 7, 4, 3, 6 } ;

					/* negotiation speed index */
                         /* 0, 1, 2, 3, 4, 5, 6, 7 */
int brindex [ 8 ] = { 0, 1, 2, 3, 4, 7, 5, 6 } ;

					/* minimum scan time in ms  */
int mst [ 8 ] = { 0 , 5, 10, 10, 20, 20, 40, 40 } ;

					/* page width in pixels */
int pagewidth [ 5 ] = { 1728, 2048, 2432, 1216, 864 } ;

/* Table to convert between T.30 DIS/DCS/DTC FIF and Class 2-like
   capability codes. Uses br=6, 7 for V.17 at 7200, 9600. */

typedef struct t30tabstruct
{ 
  char *name ; 
  uchar byte, shift, mask ; 
  uchar safeval ;
  uchar captodis[8], distocap[16], captodcs[8], dcstocap[16] ; 
} t30tabst ;

#define X 0xff				/* invalid values */

t30tabst t30tab [ NCAP ] = {
  { "vr", 1, 1, 0x01, 0, { 0, 1 } , { 0, 1 } , { 0, 1 } , { 0, 1 } },	 
  { "br", 1, 2, 0x0f, 0,
      { 0, 4, 12, 12, 13, 13 } ,
      { 0, X, X, X, 1, X, X, X, 3, X, X, X, 3, 5, 3, X } ,
      { 0, 4, 12, 8, 5, 1 } ,
      { 0, 5, 5, X, 1, 4, 4, X, 3, 7, X, X, 2, 6, X, X } } ,
  { "wd", 2, 6, 0x03, 0, { 0, 2, 1 } , { 0, 2, 1, 2 } ,
      { 0, 2, 1 } , { 0, 2, 1, 2 } },
  { "ln", 2, 4, 0x03, 0, { 0, 2, 1 } , { 0, 2, 1, X } ,
      { 0, 2, 1 } , { 0, 2, 1, X } },
  { "df", 1, 0, 0x01, 0, { 0, 1 } , { 0, 1 } , { 0, 1 } , { 0, 1 } },
  { "ec", 3, 4, 0x03, 0, { 0, 2, 2 } , { 0, X, 2, X } , 
      { 0, 3, 2 } , { 0, 0, 2, 1 } }, 
  { "bf", 5, 5, 0x01, 0, { 0, 1 } , { 0, 1 } , { 0, 1 } , { 0, 1 } },
  { "st", 2, 1, 0x07, 7,
      { 7, 4, 3, 2, 6, 0, 5, 1 } , { 5, 7, 3, 2, 1, 6, 4, 0 } ,
      { 7, 4, X, 2, X, 0, X, 1 } , { 5, 7, 3, 1, X, X, X, 0 } } 
} ;

					/* values of capability fields */
char *capvaluestr [ NCAP ] [8] = {
  { " 98lpi", "196lpi" } , 
  { " 2400bps", " 4800bps", " 7200bps", " 9600bps", "  12kbps", "14.4kbps",
    "7200V.17", "9600V.17" } ,
  { "8.5\"/215mm", " 10\"/255mm", " 12\"/303mm",
    "  6\"/151mm", "4.2\"/107mm" } ,
  { "11\"/A4", "14\"/B4", " any  " } ,
  { "1D" , "2D" }, { "   -   ", "ECM-256", "ECM-64 " }, { " - ", "BFT" },
  { "0ms", "5ms", "10/5ms", "10ms", "20/10ms", "20ms", "40/20ms", "40ms" }
} ;

/* T.30 control frames */

enum frametype {	    
 DIS=0x01, CSI,	NSF=0x04,
 CFR=0x21, FTT,
 MCF=0x31, RTN, RTP, PIN, PIP,
 DCS=0x41, TSI,	NSS=0x44,
 CRP=0x58, DCN=0x5f,
 EOM=0x71, MPS, EOP=0x74, PRI_EOM=0x79, PRI_MPS, PRI_EOP=0x7c,
 DTC=0x81, CIG, NSC=0x84
 } ;

enum commanddtype { RCV=0, SND=1, DTA=0, TRN=1 } ;

/* Class 1 commands to [receive=0/transmit=1] [data=0/training=1] for
   [baud rate=BR]. */

char *c1cmd [ 2 ]  [ 2 ] [ 8 ] = { 
{ { "+FRM=24", "+FRM=48", "+FRM=72", "+FRM=96", "+FRM=122", "+FRM=146" ,
    "+FRM=74", "+FRM=98" } ,
  { "+FRM=24", "+FRM=48", "+FRM=72", "+FRM=96", "+FRM=121", "+FRM=145" ,
    "+FRM=73", "+FRM=97" } } ,
{ { "+FTM=24", "+FTM=48", "+FTM=72", "+FTM=96", "+FTM=122", "+FTM=146" ,
    "+FTM=74", "+FTM=98", } ,
  { "+FTM=24", "+FTM=48", "+FTM=72", "+FTM=96", "+FTM=121", "+FTM=145" ,
    "+FTM=73", "+FTM=97" } }
} ;

struct c2msgstruct
{ 
  int min, max ;
  char *msg ;
} c2msg [] = {
  {   0,   9, "Call Placement and Termination:" },
  {   0,   0, "  Normal and proper end of connection" },
  {   1,   1, "  Ring Detect without successful handshake" },
  {   2,   2, "  Call aborted, from +FK[S] or CAN" },
  {   3,   3, "  No Loop Current" },
  {   4,   4, "  Ringback Detected, no answer" },
  {   5,   5, "  Ringback Detected, answer without CED" },

  {  10,  19, "Transmit Phase A & Miscellaneous Errors:" },
  {  10,  10, "  Unspecified Phase A error" },
  {  11,  11, "  No Answer (T.30 T1 timeout)" },
  {  20,  39, "Transmit Phase B Hangup Codes:" },
  {  20,  20, "  Unspecified Transmit Phase B error" },
  {  21,  21, "  Remote cannot receive or send" },
  {  22,  22, "  COMREC error in transmit Phase B" },
  {  23,  23, "  COMREC invalid command received" },
  {  24,  24, "  RSPREC error" },
  {  25,  25, "  DCS sent three times without response" },
  {  26,  26, "  DIS/DTC received 3 times; DCS not recognized" },
  {  27,  27, "  Failure to train at 2400 bps or +FMINSP value" },
  {  28,  28, "  RSPREC invalid response received" },
  {  40,  49, "Transmit Phase C Hangup Codes:" },
  {  40,  40, "  Unspecified Transmit Phase C error" },
  {  41,  41, "  Unspecified image format error"  },
  {  42,  42, "  Image conversion error" },
  {  43,  43, "  DTE to DCE data underflow" },
  {  44,  44, "  Unrecognized transparent data command" },
  {  45,  45, "  Image error, line length wrong" },
  {  46,  46, "  Image error, page length wrong" },
  {  47,  47, "  Image error, wrong compression code" },
  {  50,  69, "Transmit Phase D Hangup Codes:" },
  {  50,  50, "  Unspecified Transmit Phase D error" },
  {  51,  51, "  RSPREC error" },
  {  52,  52, "  No response to MPS repeated 3 times" },
  {  53,  53, "  Invalid response to MPS" },
  {  54,  54, "  No response to EOP repeated 3 times" },
  {  55,  55, "  Invalid response to EOP" },
  {  56,  56, "  No response to EOM repeated 3 times" },
  {  57,  57, "  Invalid response to EOM" },
  {  58,  58, "  Unable to continue after PIN or PIP" },

  {  70,  89, "Receive Phase B Hangup Codes:" },
  {  70,  70, "  Unspecified Receive Phase B error" },
  {  71,  71, "  RSPREC error" },
  {  72,  72, "  COMREC error" },
  {  73,  73, "  T.30 T2 timeout, expected page not received" },
  {  74,  74, "  T.30 T1 timeout, after EOM received" },
  {  90,  99, "Receive Phase C Hangup Codes:" },
  {  90,  90, "  Unspecified Receive Phase C error" },
  {  91,  91, "  Missing EOL after 5 seconds" },
  {  92,  92, "  Unused code" },
  {  93,  93, "  DCE to DTE buffer overflow" },
  {  94,  94, "  Bad CRC or frame (ECM or BFT modes)" },
  { 100, 119, "Receive Phase D Hangup Codes:" },
  { 100, 100, "  Unspecified Receive Phase D errors" },
  { 101, 101, "  RSPREC invalid response received" },
  { 102, 102, "  COMREC invalid response received" },
  { 103, 103, "  Unable to continue after PIN or PIP" },
  { 120, 255, "Reserved Codes" },
  {  -1,  -1, "" }
} ;

/* array for efax return codes */

char *errormsg [7] ;

/* array for frame names */

static struct framenamestruct {  int code ;  char *name ; } 
  framenames [] = {

    {NSC,0}, /* these 3 frames must be first */
    {CIG,0}, 
    {DTC,0},
    {NSF,0},
    {CSI,0},
    {DIS,0},
    {NSS,0},
    {TSI,0},
    {DCS,0},

    {CFR,0},
    {FTT,0},

    {MPS,0},
    {EOM,0},
    {EOP,0},

    {PRI_MPS,0},
    {PRI_EOM,0},
    {PRI_EOP,0},

    {MCF,0},
    {RTP,0},
    {PIP,0},
    {RTN,0},
    {PIN,0},

    {CRP,0},
    {DCN,0},
    {0,0}
  } ;

/* Functions... */

/* Provide dummy gettext() function if there is no internationalisation support */

#ifndef ENABLE_NLS
static const char *gettext ( const char *text )
{
  return text;
}
#endif

/* Initialize errormsg array - meaning of efax return codes */

void init_errormsg ( void )
{
  errormsg[0] = strdup ( gettext ( "success" ) );
  errormsg[1] = strdup ( gettext ( "number busy or modem in use" ) );
  errormsg[2] = strdup ( gettext ( "unrecoverable error" ) );
  errormsg[3] = strdup ( gettext ( "invalid modem response" ) );
  errormsg[4] = strdup ( gettext ( "no response from modem" ) );
  errormsg[5] = strdup ( gettext ( "terminated by signal" ) );
  errormsg[6] = strdup ( gettext ( "internal error" ) );
}

/* Initialize the framenames array */

void init_framenames ( void )
{

  /* Translator: this reports frame progress during reception/transmission
     - leave "NSC" untranslated, but translate the remainder */
  framenames[0].name =  strdup ( gettext ( "NSC - poller features" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "CIG" untranslated, but translate the remainder */
  framenames[1].name =  strdup ( gettext ( "CIG - poller ID" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "DTC" untranslated, but translate the remainder */
  framenames[2].name =  strdup ( gettext ( "DTC - poller capabilities" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "NSF" untranslated, but translate the remainder */
  framenames[3].name =  strdup ( gettext ( "NSF - answering features" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "CSI" untranslated, but translate the remainder */
  framenames[4].name =  strdup ( gettext ( "CSI - answering ID" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "DIS" untranslated, but translate the remainder */
  framenames[5].name =  strdup ( gettext ( "DIS - answering capabilities" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "NSS" untranslated, but translate the remainder */
  framenames[6].name =  strdup ( gettext ( "NSS - caller features" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "TSI" untranslated, but translate the remainder */
  framenames[7].name =  strdup ( gettext ( "TSI - caller ID" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "DCS" untranslated, but translate the remainder */
  framenames[8].name =  strdup ( gettext ( "DCS - session format" ) );

  /* Translator: this reports frame progress during reception/transmission
     - leave "CFR" untranslated, but translate the remainder */
  framenames[9].name =  strdup ( gettext ( "CFR - channel OK" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "FTT" untranslated, but translate the remainder */
  framenames[10].name = strdup ( gettext ( "FTT - channel not OK" ) );

  /* Translator: this reports frame progress during reception/transmission
     - leave "MPS" untranslated, but translate the remainder */
  framenames[11].name = strdup ( gettext ( "MPS - not done" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "EOM" untranslated, but translate the remainder */
  framenames[12].name = strdup ( gettext ( "EOM - not done, new format" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "EOP" untranslated, but translate the remainder */
  framenames[13].name = strdup ( gettext ( "EOP - done" ) );

  /* Translator: this reports frame progress during reception/transmission
     - leave "PRI-MPS" untranslated, but translate the remainder */
  framenames[14].name = strdup ( gettext ( "PRI-MPS - not done, call operator" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "PRI-EOM" untranslated, but translate the remainder */
  framenames[15].name = strdup ( gettext ( "PRI-EOM - not done, new format, call operator" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "PRI-EOP" untranslated, but translate the remainder */
  framenames[16].name = strdup ( gettext ( "PRI-EOP - done, call operator" ) );

  /* Translator: this reports frame progress during reception/transmission
     - leave "MCF" untranslated, but translate the remainder */
  framenames[17].name = strdup ( gettext ( "MCF - page OK" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "RTP" untranslated, but translate the remainder */
  framenames[18].name = strdup ( gettext ( "RTP - page OK, check channel" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "PIP" untranslated, but translate the remainder */
  framenames[19].name = strdup ( gettext ( "PIP - page OK, call operator" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "RTN" untranslated, but translate the remainder */
  framenames[20].name = strdup ( gettext ( "RTN - page not OK, check channel" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "PIN" untranslated, but translate the remainder */
  framenames[21].name = strdup ( gettext ( "PIN - page not OK, call operator" ) );

  /* Translator: this reports frame progress during reception/transmission
     - leave "CRP" untranslated, but translate the remainder */
  framenames[22].name = strdup ( gettext ( "CRP - repeat command" ) );
  /* Translator: this reports frame progress during reception/transmission
     - leave "DCN" untranslated, but translate the remainder */
  framenames[23].name = strdup ( gettext ( "DCN - disconnect" ) );

  /* Translator: this reports an unknown frame type during reception/transmission */
  framenames[24].name = strdup ( gettext ( "UNKNOWN" ) );

}

/* Return name of frame of type 'fr'. */

char *frname ( int fr )
{
  struct framenamestruct *p ;
  static int is_framenames_init = 0 ;

  if ( !is_framenames_init ) {
    is_framenames_init = 1;
    init_framenames();
  }

  for ( p=framenames ; p->code ; p++ )   /* framenames[24].code == 0 */
    if ( fr == p->code || ( fr & 0x7f ) == p->code) break ;
  return p->name ;
}

/* Range-check capability. */

int checkcap ( cap c )
{
  int err=0, i ;

  for ( i=0 ; i<NCAP ; i++ )
    if ( c[i] > capmax[i] || c[i] < 0 ) {
      err = msg ( "E3%s = %d out of range, set to 0", t30tab[i].name, c[i] ) ;
      c[i]=0 ;
    }
  return err ;
}


/* Print cap[ability] c using text values and prefix s. */

void printcap ( char *s , cap c )
{
  int i ;
  msg ( "N-+ %s" , s ) ;
  checkcap ( c ) ;
  for ( i=0 ; i<NCAP ; i++ ) 
    msg ( "N-+  %s" , capvaluestr [ i ] [ c[i] ] ) ;
  msg ( "N-" ) ;
}


/* Convert capability string to cap struct. Returns 0 or 2 on errors. */

int str2cap ( char *s, cap c )
{
  int err=0, n ;

  n = sscanf ( s, "%d,%d,%d,%d,%d,%d,%d,%d", 
	      c+0, c+1, c+2, c+3,  c+4, c+5, c+6, c+7 ) ;

  if ( n < NCAP ) msg ( "Wmissing value(s) in \"%s\"", s ) ;

  checkcap ( c ) ;

  return err ;
}


/* Convert a cap[ability] 'c' to a DIS/DCS/DTC FIF 'fif' of 'len'
   bytes.  Converts into DIS format if 'isdis' is true, else into
   DCS/DTC format. */

void mkdis ( cap c, uchar *fif, int len, int isdis, int t4tx ) 
{
  int i, k ;
  t30tabst *p ;

  len = len > DCSLEN ? DCSLEN : len ;

  fif[0] = 0 ;
  fif[1] = ( isdis && t4tx ? 0x80 : 0 ) | 0x40 ;
  for ( i=2 ; i<len-1 ; i++ ) fif[i] = 0x01 ;       /* add extension bits */
  fif[i] = 0 ;

  checkcap ( c ) ;

  for ( i=0 ; i<NCAP ; i++ ) {
    p = t30tab + i ;
    if ( ( k = ( isdis ? p->captodis : p->captodcs ) [ c [ i ] ] ) == X )
      msg ( "E3mkdis: can't happen (invalid %s)", p->name ), k=0 ;
    if ( p->byte < len ) fif [ p->byte ] |= k << p->shift ;
  }
}


/* Return length of DIS/DTC FIF (counts extension bits). */

int dislen ( uchar *fif )
{
  int n ;
  for ( n=3 ; fif [ n-1 ] & 0x01 && n < MAXFIFLEN ; n++ ) ;
  return n ;
}


/* Convert received DIS/DCS/DTC FIF to cap. Returns 0 or 3 if bad DIS/DCS
   field. */

int mkcap ( uchar *fif, cap c, int dis ) 
{
  int err=0, i, j, k, len ;
  t30tabst *p ;

  len = dislen ( fif ) ;

  for ( i=0 ; i<NCAP ; i++ ) {
    p=t30tab+i ;
    if ( p->byte >= len ) {
      c [ i ] = 0 ;
    } else {
      j = ( fif [ p->byte ] >> p->shift ) & p->mask ;
      k = ( dis ? p->distocap : p->dcstocap ) [ j ] ;
      if ( k == X ) {
	c [ i ] = p->safeval ;
	err = msg("E3mkcap: bad %s field (%d) set to %d", 
		  p->name, j, c [ i ] ) ;
      } else { 
	c [ i ] = k ;
      }
    }
  }
  return err ;
}


/* Compute compatible local/remote capabilities. Used by the
   sending station only and only for Class 1. Returns 0 if OK or
   3 if no compatible settings possible. */

int mincap ( cap local, cap remote, cap session )
{
  int err=0, i ;
  int msttab[2][8] = { { 0,1,3,3,5,5,7,7 } , { 0,1,1,3,3,5,5,7 } } ;

  printcap ( "local  ", local ) ;
  printcap ( "remote ", remote ) ;

  for ( i=0 ; i<NCAP && i!=ST && i !=BR ; i++ )
    session[i] = remote[i] < local[i] ? remote[i] : local[i] ;

  session[BR] = brindex[ remote[BR] ] < brindex[ local[BR] ] ?
    remote[BR] : local[BR] ;

  session[ST] = msttab [ session[VR] ] [ remote[ST] ] ;

  printcap ( "session", session ) ;

  if ( local[WD] != session[WD] || local[LN] > session[LN] || 
      local[DF] != session[DF] ) 
    err = msg ("W3 %s", gettext ( "incompatible local and remote capabilities" ) );

  return err ;
}


/* Skip to start of first/next page (or to start of previous page
   if dp is 0).  If ppm in not null, it is then set to EOP if
   there are no pages following this one, MPS if the next page
   has the same format as `local' (assumed to be the format of
   the previous page), EOM if the page has a different format.
   If local is non-NULL its format fields are set according to
   the format of the new page.  Currently only considers the
   file's y-resolution.

   This function is called before send_data() and obtains the ppm
   for that page.  It can be called again with dp=0 if a PIN or
   RTN is received to restart the page.  Returns 0 or 2 on
   errors. */

int rdpage ( IFILE *f, int dp, int *ppm, cap local, int *changed )
{
  int err=0, m=EOP, yres, fVR, nVR  ;

  if ( nextipage ( f, dp ) )
    err = msg ( "E2 can't happen (rdpage: can't go to %s page)", 
	       dp ? "next" : "same" ) ;
  
  if ( ! err ) {

    yres = f->page->yres ;
    fVR = ( yres > (196+98)/2 ) ? 1 : 0 ;

    if ( local && yres ) {
      if ( local [ VR ] != fVR ) {
	local [ VR ] = fVR ;
	if ( changed ) *changed = 1 ;
      } else {
	if ( changed ) *changed = 0 ;
      }
    }

    if ( lastpage ( f ) ) {
      m = EOP ;
    } else {
      PAGE *p = f->page + 1 ;
      nVR = ( p->yres > (196+98)/2 ) ? 1 : 0  ;
      m = ( nVR != fVR ) ? EOM : MPS ;
    }

  }

  if ( ppm ) {
    *ppm = err ? EOP : m ;
  }

  return err ;
}


/* Terminate previous page if page number is non-zero and start
   next output page if page number is non-negative. If page is -1
   removes the most recently opened file. Returns 0 if OK, 2 on
   errors. */

int wrpage ( OFILE *f, int page )
{
  int err=0 ;
  char *message = NULL ;

#ifdef ENABLE_NLS
  gsize written = 0 ;
  char *conv_cfname ;
#endif

  err = nextopage ( f, page ) ;
#ifdef ENABLE_NLS
  if ( ! err && page == -1 ) {
    if ( use_utf8 && !g_utf8_validate ( f->cfname, -1, NULL ) ) {
      conv_cfname = g_filename_to_utf8 ( f->cfname, -1, NULL, &written, NULL ) ;
      if ( remove ( f->cfname ) ) {
	message = strdup2 ( "ES2 ", gettext ( "can't delete file %s:" ) ) ;
	if ( message && conv_cfname ) err = msg ( message, conv_cfname ) ; 
      } else {
	message = strdup2 ( "F ", gettext ( "removed file: %s" ) ) ; 
	if ( message && conv_cfname ) msg ( message, conv_cfname ) ; 
      }
      g_free ( conv_cfname ) ;

    } else {
      if ( remove ( f->cfname ) ) {
	message = strdup2 ( "ES2 ", gettext ( "can't delete file %s:" ) ) ;
	if ( message ) err = msg ( message, f->cfname ) ; 
      } else {
	message = strdup2 ( "F ", gettext ( "removed file: %s" ) ) ; 
	if ( message ) msg ( message, f->cfname ) ; 
      }
    }
    free ( message ) ;
  }
#else
  if ( ! err && page == -1 ) {
    if ( remove ( f->cfname ) ) {
      message = strdup2 ( "ES2 ", gettext ( "can't delete file %s:" ) ) ;
      if ( message ) err = msg ( message, f->cfname ) ; 
    } else {
      message = strdup2 ( "F ", gettext ( "removed file: %s" ) ) ; 
      if ( message ) msg ( message, f->cfname ) ; 
    }
    free ( message ) ;
  }
#endif
  
  return err ;
}


/* Send data for one page.  Figures out required padding and 196->98 lpi
   decimation based on local and session capabilitites, substitutes page
   numbers in header string and enables serial port flow control.  Inserts
   the page header before the input file data.  Converts each scan line to
   T.4 codes and adds padding (FILL) and EOL codes before writing out.
   Sends RTC when done.  Sends DLE-ETX and returns serial port to command
   mode when done. Returns 0 if OK, non-0 on errors. */

int send_data ( TFILE *mf, IFILE *f, int page, int pages,
	       cap local, cap session, char *header, faxfont *font )
{
  int done=0, err=0, noise=0, nr=0, lastnr=0, line, pixels ;
  int i, decimate, pwidth, minlen, dcecps, inheader, skip=0 ;
  uchar buf [ MAXCODES + 2*EOLBITS/8 + 1 ], *p ;
  short runs [ MAXRUNS ], lastruns [ MAXRUNS ] ;
  char headerbuf [ MAXLINELEN ] ;
  ENCODER e ;

  newENCODER ( &e ) ;

  dcecps = cps[session[BR]] ;
  minlen = ( (long)dcecps * mst[session[ST]] - 1500 + 500 ) / 1000 ;
  pwidth = pagewidth [ session [ WD ] ] ;
  decimate = local[VR] > session[VR] ;

  msg ( "T padding to %d bytes/scan line.%s", minlen+1, 
       decimate ? " reducing 196->98 lpi." : "" ) ;

  if ( vfc ) 
    msg ( "T limiting output to %d bps for %d byte modem buffer", 
	 dcecps*8, MAXDCEBUF + MINWRITE  ) ;

  if ( ckfmt ( header, 6 ) )
    msg ( "W too many %%d escapes in header format string \"%s\"", header ) ;
  else
    sprintf ( headerbuf, header, page, pages, page, pages, page, pages ) ;

  /* Translator: "header" is a reference to the fax top header line */
  msg ("I %s[%s]", gettext ( "header:" ), headerbuf ) ;

  done = err = ttymode ( mf, SEND ) ; 

  mf->start = time(0) ;
  mf->mstart = proc_ms() ;
  mf->bytes = mf->pad = mf->lines = 0 ;

  /* start T.4 data with some FILL and an EOL */

  p = buf ;
  for ( i=0 ; i<32 ; i++ ) {
    p = putcode ( &e, 0, 8, p ) ;
  }
  p = putcode ( &e, EOLCODE, EOLBITS, p ) ;

  if ( ! f || ! f->f ) 
    err = msg ( "E2can't happen(send_data)" ) ; 

  mf->lines=0 ;
  for ( line=0 ; ! done && ! err ; line++ ) {

    if ( line < HDRSPCE ) {	/* insert blank lines at the top */
      runs[0] = pwidth ;
      pixels = pwidth ;
      nr = 1 ;
    } else {
      if ( ( nr = readline ( f, runs, &pixels ) ) < 0 ) {
	done = 1 ;
	continue ;
      }
    }
				/* generate and OR in header pixels */
    if ( line >= HDRSTRT && line < HDRSTRT + HDRCHRH ) {
      int hnr ;
      short hruns [ MAXRUNS ] ;
      hnr = texttorun ( (uchar*) headerbuf, font, line-HDRSTRT, 
		       HDRCHRW, HDRCHRH, HDRSHFT,
		       hruns, 0 ) ;
      nr = runor ( runs, nr, hruns, hnr, 0, &pixels ) ;
    }
    
    inheader = line < HDRSTRT + HDRCHRH ;

    if ( decimate || ( inheader && local[VR] == 0 ) ) {
      if ( ++skip & 1 ) {	/* save the first of every 2 lines */
   	memcpy ( lastruns, runs, nr * sizeof(short) ) ;
   	lastnr = nr ;
   	continue ;		/* get next line */
      } else {			/* OR previous line into current line */
   	nr = runor ( runs, nr, lastruns, lastnr, 0, &pixels ) ;
      }
    }

    if ( nr > 0 ) {
      if ( pixels ) {
				/* make line the right width */
	if ( pixels != pwidth ) nr = xpad ( runs, nr, pwidth - pixels ) ;
				/* convert to MH coding */
	p = runtocode ( &e, runs, nr, p ) ;
				/* zero pad to minimum scan time */
	while ( p - buf < minlen ) { 
	  p = putcode ( &e, 0, 8, p ) ;
	  mf->pad ++ ;
	}
				/* add EOL */
	p = putcode ( &e, EOLCODE, EOLBITS, p ) ;
	sendbuf ( mf, buf, p - buf, dcecps ) ;
	mf->bytes += p - buf ;
	mf->lines++ ;
      } else {
	/* probably read an EOL as part of RTC */
      }
      if ( tdata ( mf, 0 ) ) noise = 1 ;
      p = buf ;
    }
  }

  for ( i=0 ; i < RTCEOL ; i++ )
    p = putcode ( &e, EOLCODE, EOLBITS, p ) ;
  p = putcode ( &e, 0, 0, p ) ;
  sendbuf ( mf, buf, p - buf, dcecps ) ;
  mf->bytes += p - buf ;
  
  if ( noise ) msg ("W- %s", gettext ( "characters received while sending" ) ) ;

  return err ;
}


int end_data ( TFILE *mf, cap session, int ppm, int *good )
{
  int err=0, c ;
  uchar *p ;
  long dt, draintime ;
  char *message;
  
  if ( ! ppm ) p = (uchar*) DLE_ETX ;
  else if ( ppm == MPS ) p = (uchar*) "\020," ; 
  else if ( ppm == EOM ) p = (uchar*) "\020;" ; 
  else if ( ppm == EOP ) p = (uchar*) "\020." ; 
  else {
    p = (uchar*) "" ;
    err = msg ( "E2 can't happen (end_data)" ) ;
  }

  tput ( mf, p, 2 ) ;

  dt = time(0) - mf->start ;
				/* time to drain buffers + 100% + 4s */
  draintime = ( 2 * ( mf->bytes / cps[ session[BR] ] + 1 - dt ) + 4 ) * 10 ;
  draintime = draintime < TO_DRAIN_D ? TO_DRAIN_D : draintime ;

  c = ckcmd ( mf, 0, 0, (int) draintime, OK ) ;

  if ( good ) *good = ( c == OK ) ? 1 : 0 ;

  dt = time(0) - mf->start ;

  /* Translator: this is reporting the outcome of fax transmission.  It gives the
     number of lines sent, the number of bytes sent, the seconds taken and the
     bit rate (bps) - the translated text must contain 6 "%d" formatting items */
  message = strdup2 ( "I ",  gettext ( "sent %d+%d lines and %d+%d bytes, in %d secs at %d bps" ) );
  if ( message ) {
    msg ( message , 
	  HDRSPCE, mf->lines-HDRSPCE, 
	  mf->bytes-mf->pad, mf->pad, (int) dt, (mf->bytes*8)/dt ) ;
    free ( message ) ;
  }

  if ( mf->bytes / (dt+1) > cps[session[BR]] )
    msg ( "E %s", gettext ( "flow control did not work" ) );

  if ( ! err ) err = ttymode ( mf, COMMAND ) ;

  return err ;
}


/* Read one scan line from fax device. If pointer pels is not
   null it is used to save pixel count.  Returns number of runs
   stored, EOF on RTC, or -2 on EOF, DLE-ETX or other error. */

int readfaxruns ( TFILE *f, DECODER *d, short *runs, int *pels )
{
  int err=0, c=EOF, x, n ;
  dtab *tab, *t ;
  short shift ;
  short *p, *maxp, *q, len=0 ;
  uchar rd_state ;

  maxp = ( p = runs ) + MAXRUNS ;

  x = d->x ; shift = d->shift ; tab = d->tab ; /* restore decoder state */
  rd_state = f->rd_state ;

  do {
    do {
      while ( shift < 0 ) { 
	c = tgetd ( f, TO_CHAR ) ;

	rd_state = ( rd_state & rd_allowed[c] ) ?
	  ( ( rd_state & rd_nexts[c] ) ? rd_state << 1 : rd_state ) : 
	  RD_BEGIN ;

	if ( rd_state == RD_END ) {

	  /* Translator: I am not sure what this means - I think
	     that the modem has given an unexpected response while
	     receiving date */
	  msg ( "W+ %s", gettext ( "modem response in data" ) ) ;
	}

	if ( c < 0 )  {
	  x = ( x << 15 ) | 1 ; shift += 15 ;  /* EOL pad at EOF */
	} else {
	  x = ( x <<  8 ) | c ; shift +=  8 ; 
	}
      }
      t = tab + ( ( x >> shift ) & 0x1ff ) ;
      tab = t->next ;
      shift -= t->bits ;
    } while ( ! t->code ) ;
    if ( p < maxp ) *p++ = t->code ;
  } while ( t->code != -1 ) ;

  d->x = x ; d->shift = shift ; d->tab = tab ; /* save state */
  f->rd_state = rd_state ;

  if ( p >= maxp ) msg ( "W %s", gettext ( "run length buffer overflow" ) ) ;

  /* combine make-up and terminating codes and remove +1 offset
     in run lengths */

  n = p - runs - 1 ;
  for ( p = q = runs ; n-- > 0 ; )
    if ( *p > 64 && n-- > 0 ) {
      len += *q++ = p[0] + p[1] - 2 ;
      p+=2 ;
    } else {
      len += *q++ = *p++ - 1 ;
    }
  n = q - runs ;
  
  /* check for RTC and errors */

  if ( len )
    d->eolcnt = 0 ;
  else
    if ( ++(d->eolcnt) >= RTCEOL ) err = EOF ;

  if ( c < 0 ) err = - 2 ;

  if ( pels ) *pels = len ;
  
  return err ? err : n ;
}


/* Receive data. Reads scan lines from modem and writes to output
   file.  Checks for errors by comparing received line width and
   session line width.  Check that the output file is still OK
   and if not, send one CANcel character and wait for protocol to
   complete. Returns 0 if OK, 1 on DLE-ETX without RTC, or 2 if
   there was a file write error. */

int receive_data ( TFILE *mf, OFILE *f, cap session, int *nerr )
{
  int err=0, line, lines, nr, len ;
  int pwidth = pagewidth [ session [ WD ] ] ;
  short runs [ MAXRUNS ] ;
  DECODER d ;
  char *message ;

  if ( ! f || ! f->f ) {
    msg ( "E2 can't happen (writeline)" ) ;
  } 
  
  newDECODER ( &d ) ;

  lines=0 ; 
  for ( line=0 ; ( nr = readfaxruns ( mf, &d, runs, &len ) ) >= 0 ; line++ ) {
    if ( nr > 0 && len > 0 && line ) { /* skip first line+EOL and RTC */
      if ( len != pwidth ) { 
	(*nerr)++ ;
	if ( *nerr <= MAXERRPRT ) msg ("R-+ (%d:%d)", line, len ) ;
	nr = xpad ( runs, nr, pwidth - len ) ;
      } 
      writeline ( f, runs, nr, 1 ) ;
      lines++ ;
    }
    if ( ferror ( f->f ) ) {
      err = msg ( "ES2 %s", gettext ( "file write:" ) ) ;
      tput ( mf, (uchar*) CAN_STR, 1 ) ;
      msg ("W %s", gettext ( "CAN: data reception cancelled" ) ) ;
    }
  }
  
  if ( *nerr ) {
    if ( *nerr > MAXERRPRT ) msg ("R-+ ....." ) ;
    msg ("R-  : %s", gettext ( "reception errors" ) ) ;
    msg ("W- %d %s", *nerr , gettext ( "reception errors" ) ) ;
  }

  if ( nr == EOF ) { 
    while ( tgetd ( mf, TO_CHAR ) >= 0 ) ; /* got RTC, wait for DLE-ETX */
  } else {
    err = 1 ;			/* DLE-ETX without RTC - should try again */
  }

  /* Translator: this must have two "%d" formatting items in the translated string */
  message = strdup2 ( "I- ", gettext ( "received %d lines with %d errors" ) ) ;
  if ( message ) {
    msg ( message, lines, *nerr ) ;
    free ( message ) ;
  }

  return err ;
}


/* Send training check sequence of n zeroes.  Returns 0 or 2 on error. */

int puttrain ( TFILE *f, char *s, int n  )
{
  int i, m, err=0 ;
  uchar buf [ MINWRITE ] = { 0 } ;
  char *message ;

#ifdef ADDTCFRTC
  ENCODER e ;
  uchar *p ;
#endif

  ckcmd ( f, &err, s, TO_FT, CONNECT ) ;
  
  if ( ! err ) {
    ttymode ( f, SEND ) ;

    /* send n bytes of zeros */

    for ( i=0 ; i < n ; i += m ) {
      m = n-i < MINWRITE ? n-i : MINWRITE ;
      sendbuf ( f, buf, m, 0 ) ;
    }

#ifdef ADDTCFRTC
    /* append RTC in case modem is looking for it */

    newENCODER ( &e ) ;

    p = buf ;
    for ( i=0 ; i < RTCEOL ; i++ )
      p = putcode ( &e, EOLCODE, EOLBITS, p ) ;
    p = putcode ( &e, 0, 0, p ) ;
    sendbuf ( f, buf, p - buf, 0 ) ;
#endif

    tput ( f, (uchar*) DLE_ETX, 2 ) ; 


    ckcmd ( f, &err, 0, TO_DRAIN_D, OK ) ;

    message = strdup2 ( "I- ", gettext ( "sent TCF - channel check of %d bytes" ) ) ;
    if ( message ) {
      msg ( message, n ) ;
      free ( message ) ;
    }

    ttymode ( f, COMMAND ) ;
  }
  
  return err ;
}


/* Checks for an error-free run of at least n bytes in the
   received training check sequence. Sets good if it's not null,
   the run was long enough and there were no errors. Returns 0 or
   3 on other errors.  */

int gettrain ( TFILE *f, char *s, int n, int *good ) 
{ 
  int err=0, c, i=0, maxrunl=0, runl=0 ;
  char * message ;
  
  ckcmd ( f, &err, s, T2, CONNECT ) ;
  
  if ( ! err ) {

    for ( i=0 ; ( c = tgetd ( f, T3S ) ) >= 0 ; i++ )
      if ( c ) {
   	if ( runl > maxrunl ) maxrunl = runl ;
   	runl = 0 ;
      } else {
   	runl ++ ;
      }
    
    if ( c == EOF )
      err = msg ( "E3 %s", gettext ( "timed out during training check data" ) ) ;
    else
      ckcmd ( f, &err, 0, TO_RTCMD, NO ) ;
    
  }
     
  if ( runl > maxrunl ) maxrunl = runl ;
     
  if ( good ) *good = !err && maxrunl > n ;

  if ( !err ) {
    if ( maxrunl > n ) {
      message = strdup2 ( "I- ",
			  gettext ( "received TCF - channel check (OK: run of %d in %d)" ) ) ;
    } else {
      message = strdup2 ( "I- ",
			  gettext ( "received TCF - channel check (not OK: run of %d in %d)" ) ) ;
    }
    if ( message ) {
      msg ( message, maxrunl, i ) ;
      free ( message ) ;
    }
  }

  return err ;
}


/* Log a sent/received HDLC frame.  Display of these messages is delayed to
   avoid possible timing problems. */

void logfr ( char *s , char *nm , uchar *p , int n )
{
  int i=0 ;
  msg ( n > 10 ? "H- %s %d bytes:" : "H-+ %s %d bytes:" , s, n ) ;
  for ( i=0 ; i<n ; i++ ) {
    msg ( "H-+  %02x" , p[i] & 0xff ) ;
    if ( ( i&0xf ) == 0xf && i != n-1 ) msg ( "H-" ) ;
  }
  msg ( "H-" ) ;
  msg ( "I- %s %s", s, nm ) ;
}


/* Send HDLC control frame of type type.  Extra bits can be OR'ed
   into the frame type (FCF) to indicate that this frame follows
   a previous one (no +FTH required) and/or that more frames will
   follow.  Sets up flag, address, and fax control field bytes in
   `buf'.  Sends these plus `len` additional bytes.  Terminates
   with DLE-ETX and checks response.  Returns 0 if OK, 2 or 3 on
   error. */

#define MORE_FR  0x100 
#define SUB_FR   0x200 

int nframes = 0 ;		/* counts frames sent/received */

int putframe ( int type, uchar *buf, int len, TFILE *f, int t )
{
  int err=0 ;

  buf [ 0 ] = 0xff ;
  buf [ 1 ] = type & MORE_FR ? 0xc0 : 0xc8 ;
  buf [ 2 ] = type & 0xff ;

  if ( nframes++ && ! ( type & SUB_FR ) )
    ckcmd ( f, &err, "+FTH=3" , TO_FT, CONNECT ) ;
  
  if ( ! err ) {

    if ( ! buf[len+2] ) {
      msg ( "W %s", gettext ( "last byte of frame is NULL" ) ) ;
    }

    /* ttymode ( f, SEND ) ; */
    sendbuf ( f, buf, len+3, 0 ) ;
    tput ( f, (uchar*) DLE_ETX, 2 ) ; 
    /* ttymode ( f, COMMAND ) ; */

    logfr ( gettext ( "sent" ), frname ( buf [ 2 ] ), buf, len+3 ) ;

    ckcmd ( f, &err, 0, TO_DRAIN_H, ( type & MORE_FR ) ? CONNECT : OK ) ;
  }

  return err ;
}


/* Reverse bit and byte order of ID strings as per T.30 5.3.6.2.4-6 */

void revcpy ( uchar *from , uchar *to )
{
  int i, j ;
  for ( i=0, j=IDLEN-1 ; i<IDLEN ; i++, j-- ) 
    to [ i ] = normalbits [ from [ j ] & 0xff ] ;
}


/* Check for missing initial 0xFF in HDLC frame and insert it if
   missing.  Ugly fix for a still-hidden bug.  Also do bit
   inversion if required. */

int fixframe ( uchar *buf, int n, TFILE *f )
{
  int i;

  if ( *buf == 0xc0 || *buf == 0xc8 ) {
    for ( i=n; i >= 1 ; i-- ) 
      buf[i]=buf[i-1] ;
    buf[i] = 0xff ;
    msg ("W %s", gettext ( "HDLC frame missing initial 0xff" ) ) ;
    n++ ;
  }

  if ( buf[1] == 0x03 || buf[1] == 0x13 ) {
    for ( i=0 ; i < n ; i++ ) 
      buf[i]=normalbits[buf[i]] ;
    msg ("W %s", gettext ( "bit-reversed HDLC frame, reversing bit order" ) ) ;
    f->ibitorder = f->ibitorder == normalbits ? reversebits : normalbits ;
  }

  return n ;
}


/* Read HDLC frame data.  Returns 0 if OK, 1 on frame error, 3 on
   timeout, invalid response or too-long frame. */

int receive_frame_data ( TFILE *f, uchar *buf, int n, int *len )
{
  int err=0, c, i ;
  char *message;

  for ( i=0 ; ( c = tgetd ( f, T3S ) ) >= 0  ; i++ )
    if ( i < n ) buf[ i ] = c ;
  
  if ( c == EOF ) {

    err = msg ( "E3 %s", gettext ( "timed out reading frame data" ) ) ;

  } else {
    
    switch ( cmd ( f, 0, TO_RTCMD ) ) {
    case OK:
    case CONNECT:
      break ;
    case ERROR:
    case NO:
      err = msg ( "W1 %s", gettext ( "frame error" ) ) ;
      break ;
    case EOF:
      err = msg ( "E3 %s", gettext ( "no response after frame data" ) ) ;
      break ;
    default:
      err = msg ( "E3 %s", gettext ( "wrong response after frame data" ) );
      break ;
    }

  }

  if ( i >= n ) {
    message = strdup2 ( "E3 ", gettext ( "frame too long (%d, > %d max bytes)" ) ) ;
    if ( message ) {
      err = msg ( message, i, n ) ;
      free ( message ) ;
    }
  }

  if ( len ) *len = i ;

  return err ;
}


/* Get a Class 1 command or response frame.  An attempt to match
   and combine T.30 "Response Received?" and "Command Received?"
   protocol flowcharts.

   When receiving commands returns after first correct
   non-optional frame or after the time given by getcmd has
   elapsed.  This is instead of looping through main flowchart.

   When receiving responses returns on the first detected
   non-optional frame, after timeout T4, or on errors.

   Returns immediately if gets a +FCERROR response so can retry
   as data carrier.  Returns DCN as a valid frame instead of
   hanging up.

   Returns the command/response received, or EOF on timeout or
   error.
 
*/

int getfr ( TFILE *mf, uchar *buf, int getcmd )
{
  /* frlen should be initialized to be zero */
  /* informed from Steven Doerfler <steven@lugaru.com> */
  int err=0, frame=0, frlen=0, c, t ;
  char remoteid [ IDLEN + 1 ] ;
  time_t start ;
  uchar *fif=buf+3 ;
  char *message ;
  
  start = 10*time(0) ;
  
  t = getcmd ? ( getcmd > 1 ? getcmd : T2 ) : T4 ;

 Enter:

  err = 0 ;

  if ( nframes++ ) {
    c = cmd ( mf, "+FRH=3", t ) ;
  } else {
    c = CONNECT ;		/* implied by ATA or ATD */
  }
  
  switch ( c ) {
  case EOF:			/* time out */
    tput ( mf, (uchar*) CAN_STR, 1 ) ;
    ckcmd ( mf, 0, 0, TO_ABRT, OK ) ;
    err = 1 ;
    break ;
  case NO:			/* S7 time out */
    err = 1 ;
    break ;
  case MODULATION:		/* data carrier (or DHS) */
    return -msg ( "W-2 %s", gettext ( "wrong carrier" ) ) ;
    break ;
  case CONNECT:			/* frame */
    break ;
  default:			/* shouldn't happen */
    err = msg ( "E3 %s", gettext ( "wrong response to command to receive a frame" ) ) ;
    break ;
  }
  
  if ( ! err ) 
    err = receive_frame_data ( mf, buf, MAXFRLEN, &frlen ) ;
  
  if ( ! err && frlen < 3 ) {
    message = strdup2 ( "E3 ", gettext ( "received short frame (%d bytes)" ) ) ;
    if ( message ) {
      err = msg ( message, frlen ) ;
      free ( message ) ;
    }
  }

  logfr ( gettext ( "received" ), frname ( buf [ 2 ] ), buf, frlen ) ;

  if ( ! err ) {

    frlen = fixframe ( buf, frlen, mf ) ;
    frame = buf [ 2 ] & 0x7f ;

    switch ( frame ) {
    case CRP:
      err = 1 ;
    case NSF:
    case NSC:
    case NSS:
      goto Enter ;
    case CIG:
    case CSI:
    case TSI:
      revcpy ( fif , (uchar*) remoteid ) ;
      msg ( "I- %s %*.*s", gettext ( "The remote ID is" ), IDLEN, IDLEN, remoteid ) ;
      goto Enter ;
    }

  }
  
  if ( err && getcmd && ( t -= 10*time(0) - start ) > 0 ) 
    goto Enter ;

  return err ? EOF : frame ;
}


/* Class 1 send/receive.  

  The logic in this function is a mess because it's meant to
  mirror the flowchart in ITU-T recommendation T.30 which is the
  protocol specification.

  */

int c1sndrcv ( 
	      TFILE *mf, cap local, char *localid, 
	      OFILE *outf, IFILE *inf, 
	      int pages, char *header, faxfont *font, 
	      int maxpgerr, int noretry, int calling )
{ 
  int err=0, rxpage=0, page=1, t, disbit, good, frame, last, nerr ;
  int rxdislen, ppm, try=0, pagetry=0, retry=0, remtx=0, remrx=0 ;
  int writepending=0, dp=0 ;
  cap remote = { DEFCAP }, session = { DEFCAP } ;
  char *fname=0, *message ;
  uchar buf [ MAXFRLEN ], *fif=buf+3 ;

#ifdef ENABLE_NLS
  gsize written = 0 ;
  char *conv_fname ;
#endif

  if ( ! calling ) goto RX ;

  /* Class 1 Transmitter: */

 T:  /* Transmitter Phase B - wait for DIS or DTC */

  pagetry = 0 ;
  
  frame = getfr ( mf, buf, T1 ) ;
  
  if ( frame <= 0 ) {
    err = msg ( "E3 %s", gettext ( "no answer from remote fax" ) ) ;
    goto B ;
  }
  
  if ( frame != DIS && frame != DTC ) {
    msg ( "W2 %s", gettext ( "can't open page" ) ) ;
    goto C ;
  }

  disbit = ( frame == DIS ) ? 0x80 : 0x00 ;
  try = 0 ;

 A:				/* decide to send or receive after DIS/DTC */

  if ( frame == DIS || frame == DTC ) {
    rxdislen = dislen ( fif ) ;
    mkcap ( fif, remote, 1 ) ;
    remtx = fif[1] & 0x80 ;
    remrx = fif[1] & 0x40 ;
  }

  if ( remtx ) {
    if (remrx ) {
      msg ( "N %s", gettext ( "remote has one or more documents to send and can receive" ) ) ;
    } else {
      msg ( "N %s", gettext ( "remote has one or more documents to send and cannot receive" ) ) ;
    }
  } else {
    if (remrx ) {
      msg ( "N %s", gettext ( "remote has no documents to send and can receive" ) ) ;
    } else {
      msg ( "N %s", gettext ( "remote has no documents to send and cannot receive" ) ) ;
    }
  }

  if ( pages > 0 ) {
    if ( ! remrx ) msg ( "W %s", gettext ( "remote cannot receive, trying anyways" ) ) ;
    goto D ;
  } else {
    if ( ! remtx ) msg ( "W %s", gettext ( "remote has nothing to send, trying anyways" ) ) ;
    goto R ;
  }

 D:				/* send DCS */

  if ( rdpage ( inf, dp, &ppm, local, 0 ) ) {
    err = msg ( "E2 %s", gettext ( "can't open page" ) ) ;
    goto B ;
  }

 D_2:

  mincap ( local, remote, session ) ;

  revcpy ( (uchar*) localid, fif ) ;
  if ( ! err ) 
    err = putframe ( TSI | MORE_FR | disbit, buf, IDLEN, mf, -1 ) ;  

  mkdis ( session, fif, DCSLEN, 0, pages ) ;
  if ( ! err ) 
    err = putframe ( DCS | SUB_FR | disbit, buf, DCSLEN, mf, -1 ) ;

#ifdef USEFTS
  if ( cmd ( mf, "+FTS=" MODDLY, T3S ) != OK )
#endif
    msleep ( TMOD ) ;		/* if +FTS not supported */

  if ( ! err ) 
    err = puttrain ( mf, c1cmd[SND][TRN][session[BR]], 
		    TCFSECS*cps [ session[BR] ] ) ;
  try++ ;

  if ( ! err ) {
    cmd ( mf, "+FRS=1", T3S ) ; /* wait for TCF carrier to drop */
    frame = getfr ( mf, buf, 0 ) ;
  }

  if ( err || frame < 0 ) {
    if ( try >= 3 ) {
      goto C_timeout ;
    } else { 
      goto D_2 ;
    }
  }
  
  switch ( frame ) {

  case DIS:
  case DTC:
    if ( try >= 3 ) goto C_timeout ;
    else goto A ;

  case FTT:
    message = strdup2 ( "I ", gettext ( "channel not usable at %d bps" ) ) ;
    if ( message ) {
      msg ( message, 8*cps[session[BR]] ) ;
      free ( message ) ;
    }

    remote[BR] = fallback[session[BR]] ;
    if ( remote[BR] >= 0 ) goto D_2 ;
    else {
      err = msg ( "E2 %s", gettext ( "channel not usable at lowest speed" ) ) ;
      goto C ;
    }

  case CFR:
    goto I_2 ;

  default:
    err = msg ( "E3 %s", gettext ( "invalid response to DCS" ) ) ;
    goto C ;
  }    

 I:				/* send a page */

  if ( rdpage ( inf, dp, &ppm, local, 0 ) ) {
    err = msg ( "E2 %s", gettext ( "can't open page" ) ) ;
    goto B ;
  }

 I_2:

  ckcmd ( mf, &err, c1cmd [SND][DTA][session[BR]], TO_FT, CONNECT ) ;
  if ( !err ) {
    msleep ( 1000 ) ;
    err = send_data ( mf, inf, page, pages, local, session, header, font ) ;
  }

  pagetry++ ;

  if ( !err )
    err = end_data ( mf, session, 0, 0 ) ;
  
#ifdef USEFTS
  if ( cmd ( mf, "+FTS=" MODDLY, T3S ) != OK )
#endif
    msleep ( TMOD ) ;		/* if +FTS not supported */

				/* fix ppm if on last page of stdin */
  if ( lastpage ( inf ) ) ppm = EOP ;

  try = 0 ;
 sendppm:
  if ( !err ) err = putframe ( ppm | disbit, buf, 0, mf, -1 ) ;
  try++ ;
  
  frame = getfr ( mf, buf, 0 ) ;
  if ( frame < 0 ) {
    if ( try >= 3 ) {
      goto C_timeout ;
    } else { 
      goto sendppm ;
    }
  }

  fname = inf->page->fname ;

  switch ( noretry ? MCF : frame ) { /* common retry logic */
  case MCF:
  case RTP:
  case PIP:
    fname = inf->page->fname ;
    if ( fname ) {
      message = strdup2 ( "I ", gettext ( "sent page %s" ) ) ;
      if ( message ) {
#ifdef ENABLE_NLS
	if ( use_utf8 && !g_utf8_validate ( fname, -1, NULL ) ) {
	  conv_fname = g_filename_to_utf8 ( fname, -1, NULL, &written, NULL ) ;
	  if ( conv_fname ) {
	    msg ( message, conv_fname ) ;
	    g_free ( conv_fname ) ;
	  }
	} else {
	  msg ( message, fname ) ;
	}
#else
	msg ( message, fname ) ;
#endif
	free ( message ) ;
      }
    }
    pagetry=0 ;
    page++ ;
    dp = 1 ;
    break ;
  case PIN:
  case RTN:
    dp = 0 ;
    retry = pagetry < NTXRETRY ;
    break ;
  default:  
    err = msg ( "E3 %s", gettext ( "invalid post-page response" ) );
    goto C ;
  }
  
  switch ( ppm ) {
    
  case MPS:
    switch ( frame ) {
    case PIN: goto E ;
    case PIP: goto E ;
    case MCF: goto I ;
    case RTP: goto D ;
    case RTN: goto D ;
    }

  case EOP:
    switch ( frame ) {
    case PIN: goto E ;
    case PIP: goto E ;
    case MCF: 
    case RTP: 
      nextipage ( inf, 1 ) ;	/* skip ahead to mark all files done */
      if ( remtx ) goto R ;	/* poll after sending */
      else goto C ;
    case RTN: 
      if ( retry ) goto D ;
      else goto C ;
    }
    
  case EOM:
    switch ( frame ) {
    case PIN: goto E ;
    case PIP: goto E ;
    case MCF: 
    case RTP: 
    case RTN: 
      cmd ( mf, "+FRS=20", T3S ) ; /* wait for ppr carrier to drop */
      if ( retry ) goto T ;
      else goto T ;
    }
    
  }  

 E:				/* ignore PIN and PIP */
  msg ( "W %s", gettext ( "interrupt request ignored" ) ) ;
  try=0 ;
  goto A ;

  /* Class 1 Receiver */

 RX:

 R:  /* Receiver Phase B */

  if ( ! err ) err = wrpage ( outf, rxpage ) ;

  disbit=0x00 ;

  for ( t=0 ; !err && t<T1 ; t+=T2+10 ) {

    revcpy ( (uchar*) localid, fif ) ;
    if ( !err ) 
      err = putframe ( CSI | disbit | MORE_FR, buf, IDLEN, mf, -1 ) ;
    
    mkdis ( local, fif, DEFDISLEN, 1, pages ) ;
    if ( !err ) 
      err = putframe ( DIS | disbit | SUB_FR, buf, DEFDISLEN, mf, -1 ) ;

    frame = getfr ( mf, buf, 0 ) ;

    if ( frame > 0 ) {
      disbit = ( frame == DIS ) ? 0x80 : 0x00 ;
      goto F_2 ;
    }
  }
  if ( err ) goto C ;
  else goto C_timeout ;
  

 F:  /* get a command */

  last = frame ;
  frame = getfr ( mf, buf, 1 ) ;

  if ( writepending ) {		/* do postponed file close/open */
    writepending=0 ;
    err = wrpage ( outf, rxpage ) ;
    if ( err ) goto C ;
  }

  if ( frame < 0 ) {
    if ( frame == -2 ) goto getdata ; /* data carrier detected */
    if ( last == EOM ) goto R ; 
    else {
      err = msg ("E3 %s", gettext ( "timed out waiting for command" ) ) ;
      goto B ;
    }
  }
  
 F_2:

  switch ( frame ) {

  case DTC:
    goto D ;

  case DIS:
    try=0 ;
    goto A ;
    
  case DCS: 
    mkcap ( fif, session, 0 ) ;
    printcap ( "session", session ) ;
    
    cmd ( mf, "+FTS=1", T3S ) ;	/* make sure DCS is over */

    gettrain ( mf, c1cmd [RCV][TRN][session[BR]], cps[session[BR]], &good ) ;

    if ( putframe ( ( good ? CFR : FTT ) | disbit, buf, 0, mf, -1 ) ||
	! good ) goto F ;

  getdata:
    
    outf->w=pagewidth[session[WD]];
    outf->h=0;
    outf->xres=204.0;
    outf->yres=vresolution[session[VR]];
    nerr = 0 ;
    
  re_getdata:

    if ( cmd ( mf, c1cmd [RCV][DTA][session[BR]], TO_FT ) != CONNECT ) 
      goto F ;			/* +FCERROR -> DCS resent */
    
    switch ( receive_data ( mf, outf, session, &nerr ) ) {
    case 0:
      good = nerr < maxpgerr ;
      /* Translator: the %s formatting item refers to the file name to which
	 a received fax page has been saved */
      message = strdup2 ("I- ", gettext ( "page saved to %s" ) ) ;
      if (message) {
#ifdef ENABLE_NLS
	if ( use_utf8 && !g_utf8_validate ( outf->cfname, -1, NULL ) ) {
	  conv_fname = g_filename_to_utf8 ( outf->cfname, -1, NULL, &written, NULL ) ;
	  if ( conv_fname ) {
	    msg ( message, conv_fname ) ;
	    g_free ( conv_fname ) ;
	  }
	} else {
	  msg ( message, outf->cfname ) ;
	}
#else
	msg ( message, outf->cfname ) ;
#endif
	free ( message ) ;
      }
      writepending=1 ;		/* ppm follows immediately, don't write yet */
      rxpage++ ;
      break ;
    case 1:
      /* no RTC, re-issue +FRM command */
      goto re_getdata ;
    default:
      good = 0 ;
      break ;
    }
    ckcmd ( mf, 0, 0, TO_RTCMD, NO ) ;
    goto F ;

    /* III: */

  case PRI_EOM:
  case PRI_MPS:
  case PRI_EOP:
    frame &=0xf7 ;		/* ignore PRocedure Interrupt bit */
  case MPS:
  case EOP:
  case EOM:
    putframe ( ( good ? MCF : RTN ) | disbit, buf, 0, mf, -1 ) ;
    if ( good && frame == MPS ) goto getdata ;
    else goto F ;
    
  case DCN:
    goto B ;
    
  default:
    err = msg ( "E3 %s", gettext ( "unrecognized command" ) ) ;
    goto B ;

  }

 C_timeout:
  err = msg ( "E3 %s", gettext ( "no command or response from remote" ) ) ;

 C:
  putframe ( DCN, buf, 0, mf, -1 ) ;

 B:
  ckcmd ( mf, 0, "H", TO_RESET, OK ) ;	/* hang up */

  if ( rxpage > 0 ) 
    wrpage ( outf, -1 ) ;	/* remove last file */

  return err ;
}


/* Check for hangup message.  Assumes hsc is initialized to a
   negative value.  Returns 0 if no hangup message, 1 if there
   was one.  If perr is not null, sets it to 2 if the hsc was
   non-zero (error). */

int gethsc ( int *hsc, int *perr )
{
  int err=0, i ;
  char *message ;
  if ( sresponse ( "+FHNG:", hsc ) || sresponse ( "+FHS:", hsc ) ) {
    if ( hsc && *hsc > 0 ) {
      message = strdup2 ("E2 ", gettext ( "abnormal termination (code %d)" ) ) ;
      if ( message ) {
	err = msg ( message, *hsc ) ;
	free ( message ) ;
      }

      for ( i=0 ; c2msg[i].min >= 0 ; i++ ) {
	if ( *hsc >= c2msg[i].min && *hsc <= c2msg[i].max ) {
	  msg ( "E %s", c2msg[i].msg ) ;
	}
      }
      if ( perr && ! *perr ) {
	*perr = 2 ;
      }
    } else {
      err = 1 ;
    }
  }
  return err ;
}


/* Print remote ID and store DCS values in session as per
   responses since last command. */

void getc2dcs ( cap session )
{
  char *p ;
  if ( ( p = sresponse ( "+FTI:",  0 ) ) != 0 ||  
       ( p =  sresponse ( "+FTSI:", 0 ) ) != 0 ) {
    msg ( "I- remote ID -> %s", p ) ;
  }
  if ( ( p = sresponse ( "+FCS:", 0 ) ) != 0 || 
      ( p = sresponse ( "+FDCS:", 0 ) ) != 0 ) {
    str2cap ( p, session ) ;
    printcap ( "session", session ) ;
  }
}  

/* Wait for a starting character XON or DC2.  Display & ignore
   any other characters received. */

void getstartc ( TFILE *mf )
{
  int c, noise ;
  char *message ;
  
  for ( noise=0 ; ( c = tgetc ( mf, TO_C2X ) ) != XON && c != DC2 ; noise++ ) {
    if ( c == EOF ) {
      msg ( "W %s", gettext ( "no XON/DC2 received after CONNECT" ) ) ;
      break ;
    } else { 
      msg ( "W-+ %s", cname ( c ) ) ; 
      noise++ ; 
    }
  }
  
  if ( noise ) {
    message = strdup2 ( "W  : ", gettext ( "%d characters received while waiting to send" ) ) ;
    if ( message ) {
      msg ( message, noise ) ;
      free ( message ) ;
    }
  }
}  


/* Class 2 send and receive.  

   If calling, polls if no files to send, otherwise sends.  If
   not calling sends documents if files to send, else receives.

   When sending, issues +FDIS to change session parameters if
   file format changes, then sends +FDT followed by data and a
   post-page message determined by format of next page, if any.
   Retransmits each page up to NTXRETRY times.

   When receiving extracts file format from responses to +FDR or
   ATA and saves them in the file. Receives data to a file and
   sets page transfer status if too many errors.

   Returns 0 if OK or 2 on errors.  */


int c2sndrcv (
	      TFILE *mf, cap local, char *localid, 
	      OFILE *outf, IFILE *inf, 
	      int pages, char *header, faxfont *font, 
	      int maxpgerr, int noretry, int calling )
{
  int err=0, done=0, page, pagetry, nerr, c, dp=0 ;
  int ppm=0, good, hsc, changed ;
  int remtx=0 ;
  char *fname=0, *message ;
  cap session = { 0,0,0,0, 0,0,0,0 } ;
  char buf [ CMDBUFSIZE ] ;

#ifdef ENABLE_NLS
  gsize written = 0 ;
  char *conv_fname ;
#endif

  hsc=-1 ;			/* will be set >= 0 on hangup */

  if ( sresponse ( "+FPO", 0 ) ) {
    remtx = 1 ;
    msg ( "N %s", gettext ( "remote has one or more documents to send." ) ) ;
  }

  if ( calling ) {
    if ( pages ) goto send ;
    else goto poll ;
  } else {
    if ( pages ) goto pollserver ;
    else goto receive ;
  }

  /* Class 2 Send */

 pollserver:

  /* with +FLP[L]=1 the modem should accept +FDT. */

 send:
  
  page=1 ;
  
  pagetry=0 ;
  while ( ! err && ! done ) {

    err = rdpage ( inf, dp, &ppm, local, &changed ) ;

    if ( ! err && changed ) {
      sprintf ( buf, c20 ? "+FIS=%d,%d,%d,%d" : "+FDIS=%d,%d,%d,%d", 
	       local[0], local[1], local[2], local[3] ) ;
      ckcmd ( mf, 0, buf, TO_FT, OK ) ;
      if ( gethsc ( &hsc, &err ) ) {
	continue ;
      }
    }
    
    ckcmd ( mf, &err, "+FDT", -TO_C2B, CONNECT ) ;
    if ( err || gethsc ( &hsc, &err ) ) { 
      done=1 ; 
      continue ; 
    }

    getc2dcs ( session ) ; 

    if ( ! c20 ) getstartc ( mf ) ;

    send_data ( mf, inf, page, pages, local, session, header, font ) ;
    pagetry++ ;

    if ( c20 ) {
      end_data ( mf, session, ppm, &good ) ;
    } else {
      end_data ( mf, session, 0, 0 ) ;

      gethsc ( &hsc, &err ) ;

      if ( ! err && hsc < 0 ) {
	ckcmd ( mf, &err, ppm == EOP ? "+FET=2" : 
	       ppm == EOM ? "+FET=1" : "+FET=0" , TO_C2PP, OK ) ;
      }

      gethsc ( &hsc, &err ) ;

      if ( ! err && hsc < 0 ) {
	if ( sresponse ( "+FPTS:", &good ) ) {
	  good &= 1 ;		/* odd values mean received OK */
	} else {			/* no +FPTS and +FHNG probably NG */
	  good = gethsc ( 0, 0 ) ? 0 :  
	    msg ( "W1 %s",
		  gettext ("no +FPTS response obtained, it is assumed that fax was received" ) ) ;
	}
      }
    }
    
    if ( noretry ) good = 1;
    
    if ( good ) {
      fname = inf->page->fname ;
      if ( fname ) {
	message = strdup2 ( "I ", gettext ( "sent page %s" ) ) ;
	if ( message ) {
#ifdef ENABLE_NLS
	  if ( use_utf8 && !g_utf8_validate ( fname, -1, NULL ) ) {
	    conv_fname = g_filename_to_utf8 ( fname, -1, NULL, &written, NULL ) ;
	    if ( conv_fname ) {
	      msg ( message, conv_fname ) ;
	      g_free ( conv_fname ) ;
	    }
	  } else {
	    msg ( message, fname ) ;
	  }
#else
	  msg ( message, fname ) ;
#endif
	  free ( message ) ;
	}
      }
      pagetry=0 ;
      page++ ;
      dp = 1 ;
      if ( ppm == EOP ) {
	nextipage ( inf, 1 ) ;	/* skip ahead to mark all files done */
	done = 1 ;
      }
    } else {
      dp = 0 ;
      if ( pagetry >= NTXRETRY )
	err = msg ( "E2 %s", gettext ( "too many page send retries" ) ) ;
    }

    if ( gethsc ( &hsc, &err ) )  done=1 ;

    if ( good && lastpage ( inf ) ) {
      done = 1 ;
    }
  }

  goto done ;

  /* Class 2 Receive */

 poll:

  /* with +FSP[L]=1 and +FPO[LL]: the modem should now accept +FDR. */

 receive:

  getc2dcs ( session ) ;	/* get ATA responses */

  done=0 ;
  for ( page=0 ; ! err && ! done ; page++ ) {

    if ( ! ( err = wrpage ( outf, page ) ) ) {
      c = cmd ( mf, "+FDR", -TO_C2R ) ;

      switch ( c ) {

      case CONNECT:
   	getc2dcs ( session ) ; 

   	outf->w=pagewidth[session[WD]];
   	outf->h=0;
	outf->xres=204.0;
	outf->yres=vresolution[session[VR]];
	nerr = 0 ;
	
	tput ( mf, &startchar, 1 ) ;

	if ( receive_data ( mf, outf, session, &nerr ) == 0 ) {
	  good = nerr < maxpgerr ;
	  /* Translator: the %s formatting item refers to the file name to which
	     a received fax page has been saved */
	  message = strdup2 ( "I- ", gettext ( "page saved to %s" ) ) ;
	  if ( message ) {
#ifdef ENABLE_NLS
	    if ( use_utf8 && !g_utf8_validate ( outf->cfname, -1, NULL ) ) {
	      conv_fname = g_filename_to_utf8 ( outf->cfname, -1, NULL, &written, NULL ) ;
	      if ( conv_fname ) {
		msg ( message, conv_fname ) ;
		g_free ( conv_fname ) ;
	      }
	    } else {
	      msg ( message, outf->cfname ) ;
	    }
#else
	    msg ( message, outf->cfname ) ;
#endif
	    free ( message ) ;
	  }
	} else { 
	  good = 0 ;
	}
	
	ckcmd ( mf, &err, 0, TO_C2EOR, OK ) ;

	if ( err || gethsc ( &hsc, &err ) )  { 
	  wrpage ( outf, page+1 ) ;
	  wrpage ( outf, -1 ) ;
	  done=1 ; 
	  continue ; 
	}
	
	if ( ! good ) {
	  msg ( "W %s", gettext ( "reception errors" ) ) ;
	  ckcmd ( mf, 0, c20 ? "+FPS=2" : "+FPTS=2",  T3S, OK ) ;
	  if ( gethsc ( &hsc, &err ) ) continue ;
	}
	break ;

      case OK:
	wrpage ( outf, -1 ) ;	/* no more pages */
	done=1 ;
	if ( gethsc ( &hsc, &err ) ) continue ;
	break ;

      default:
	wrpage ( outf, -1 ) ;	/* oops */
	err = msg ( "E3 %s", gettext ( "receive (+FDR) command failed" ) ) ;
	break ;
      }
    }
  } 

  
 done:
  if ( hsc < 0 ) ckcmd ( mf, 0, c20 ? "+FKS" : "+FK", TO_RESET, OK ) ;

  return err ;
}


/* Dial the phone number given by string s.  If nowait is true
   adds a ';' to the dial string to avoid waiting for a
   CONNECTion (might allow ersatz polling).  Also resets the
   global "nframes" if appropriate so getfr() and putframe() know
   not to issue +FRH/+FTH. Returns 0 if dialed OK, 1 if busy, 2
   on errors.  */

int dial ( TFILE *f, char *s, int nowait )
{
  int err=0, hsc=-1 ;
  char c, dsbuf [ 128 ], *p, *message ;

  sprintf ( dsbuf, nowait ? "D%.126s;" : "D%.127s" , s ) ;
  message = strdup2 ( "I ", gettext ( "dialing %s" ) ) ;
  if ( message ) {
    msg ( message, dsbuf+1 ) ;
    free ( message ) ;
  }

  c = cmd ( f, dsbuf, TO_A ) ;

  if ( ( p = sresponse ( "+FCSI:", 0 ) ) != 0 ||
       ( p =  sresponse ( "+FCI:", 0 ) ) != 0 ) {
    message = strdup2 ( "I- ", gettext ( "The remote ID is %s" ) ) ;
    if ( message ) {
      msg ( message, p ) ;
      free ( message ) ;
    }
  }

  if ( nowait && c == OK ) {
    msg ( "I %s", gettext ( "called" ) ) ;
    nframes = 1 ;
  } else if ( c1 && c == CONNECT ) {
    msg ( "I %s", gettext ( "connected" ) ) ; 
    nframes = 0 ;
  } else if ( !c1 && c == OK ) {
    msg ( "I %s", gettext ( "connected" ) ); 
  } else if ( c ==  BUSY ) {
    err = msg ( "W1 %s", gettext ( "number is busy" ) ) ;
  } else {
    err = msg ( "E2 %s", gettext ( "dial command failed" ) ) ;
  }

  gethsc ( &hsc, err ? 0 : &err ) ;

  return err ;
}


/* Figure out which mode the modem answered in (fax, data, voice
   or none) based on modem class and responses to the previous
   command.  Sets crate (connect rate) for DATAMODE and hsc
   (hangup status code) if detects a class 2 hangup message. */

enum connectmode { NONE, DATAMODE, FAXMODE, VOICEMODE } ; 

enum connectmode ansmode ( int *crate, int *hsc )
{
  enum connectmode mode = NONE ;
  int x=0 ;

  if ( c1 && sresponse ( "CONNECT", &x ) ) {
    mode = x ? DATAMODE : FAXMODE ;
  }

  if ( !c1 && sresponse ( "OK", 0 ) ) {
    mode = FAXMODE ;
  } 

  if ( !c1 && ( sresponse ( "CONNECT", &x ) || sresponse ( "+FDM", 0 ) ) ) {
    mode = DATAMODE ;
  } 

  if ( sresponse ( "DATA", 0 ) || sresponse ( "CONNECT DATA", 0 ) ) {
    mode = DATAMODE ;
    sresponse ( "CONNECT", &x ) ;
  }

  if ( sresponse ( "FAX", 0 ) || sresponse ( "+FCO", 0 ) ) {
    mode = FAXMODE ;
  }

  if ( sresponse ( "VCON", 0 ) ) {
    mode = VOICEMODE ;
  }
  
  if ( gethsc ( hsc, 0 ) ) {
    mode = NONE ;
  }

  if ( DATAMODE && x ) *crate = x ;

  return mode ;
}


/* Answer the phone.  Remove our lock if sharing device with
   outgoing calls.  If waiting for call, wait for modem activity,
   else answer phone.  Figure out what mode we answered in and
   handle call appropriately.  Re-lock if necessary. Exec *getty
   or *vcmd for data or voice calls. */

int answer ( TFILE *f, char **lkfile, 
	    int wait, int share, int softaa, 
	    char *getty, char *vcmd, char *acmd )
{
  int err=0, c ;
  int crate=19200, hsc=-1, i ;
  enum connectmode mode=NONE ;
  char *message;

  if ( ! err && share ) {
    err = ttymode ( f, COMMAND ) ;
    if ( ! err ) 
      err = unlockall ( lkfile ) ;
  }
  
  if ( ! err && wait ) {
    msg ( "I %s", gettext ( "waiting for activity") ) ;
    tdata ( f, -1 ) ;
    msg ( "I %s", gettext ( "activity detected") ) ;
  }
  
  if ( ! err && share ) {
    msleep ( 500 ) ;		/* let other programs lock port  */
    err = lockall ( lkfile, 1 ) ;
    if ( err )
      err = msg ( "W1 %s", gettext ( "can't answer: can't lock device" ) );
    else
      err = ttymode ( f, COMMAND ) ; /* in case it was changed silently */
  }

  for ( i=0 ; ! err && mode == NONE && ( i==0 || ( i==1 && softaa ) ) ; i++ ) {

    c = cmd ( f, wait ? 0 : acmd, ( i==0 && softaa ) ? TO_DATAF : TO_A ) ;

    if ( c == DATA ) cmd ( f, c1 ? "O" : 0, TO_A ) ; /* +FAE=1 weirdness */

    mode = ansmode ( &crate, &hsc ) ;
    
    switch ( mode ) {
    case DATAMODE :
      msg ( "Idata call answered") ;
      if ( getty && *getty ) {
	char buf [ MAXGETTY ] ;
	if ( ckfmt ( getty, 6 ) ) {
	  message = strdup2 ( "E3 ", gettext ( "too many %%d escapes in command (%s)" ) ) ;
	  if ( message ) {
	    err = msg ( message, getty ) ;
	    free ( message ) ;
	  }
	} else {
	  sprintf ( buf, getty, crate, crate, crate, crate, crate, crate ) ;
	  message = strdup2 ( "I ", gettext ( "executing command /bin/sh -c %s" ) ) ;
	  if ( message ) {
	    msg ( message, buf ) ;
	    free ( message ) ;
	  }
	  execl ( "/bin/sh" , "sh" , "-c" , buf , (void*) 0 ) ; 
	  err = msg ( "ES2 %s", gettext ( "exec() call failed:" ) ) ;
	}
      } else {
	err = msg ( "E2 %s", gettext ( "no getty command defined for data call" ) ) ;
      }
      break ; 
    case FAXMODE :
      nframes = 0 ;
      msg ( "I %s", gettext ( "fax call answered") ) ;
      break ;
    case VOICEMODE :
      msg ( "I %s", gettext ( "voice call answered") );
      if ( vcmd && *vcmd ) {
	char buf [ MAXGETTY ] ;
	if ( ckfmt ( vcmd, 6 ) ) {
	} else {
	  sprintf ( buf, vcmd, f->fd, f->fd, f->fd, f->fd, f->fd, f->fd ) ;
	  message = strdup2 ( "I ", gettext ( "executing command /bin/sh -c %s" ) ) ;
	  if ( message ) {
	    msg ( message, buf ) ;
	    free ( message ) ;
	  }
	  execl ( "/bin/sh" , "sh" , "-c" , buf , (void*) 0 ) ; 
	  err = msg ( "ES2 %s", gettext ( "exec() call failed:" ) ) ;
	}
      } else {
	err = msg ( "E2 %s", gettext ( "no voice command defined for voice call" ) ) ;
      }
      break ; 
    case NONE:
      if ( i==0 && softaa && hsc < 0 && getty && *getty ) {
	int j ;			/* switch to fax for 2nd try */
	for ( j=0 ; j<3 ; j++ ) 
	  if ( cmd ( f, c1 ? "+FCLASS=1" : 
		    ( c20 ? "+FCLASS=2.0" : "+FCLASS=2" ), -TO_RESET ) 
	      == OK ) break ; 
	wait = 0 ;
	acmd = ANSCMD ;
      } else {
	err = msg ( "E3 %s", gettext ( "unable to answer call") ) ;
      }
      break ;
    default:
      err = msg ( "E3can't happen(answer)" ) ;
      break ;
    }
    
  }

  return err  ;
}


/* Initialize modem.  Determine class to use and issue
   class-specific fax initialization commands. If poll is true,
   issues commands to enable polling also.  Returns 0 or 3 if a
   mandatory setup command fails. */

int modem_init ( TFILE *mf, cap c, char *id, 
		 int calling, int poll, int capsset, int *preverse )
{
  int err=0, t=-TO_RESET ;
  char buf [ CMDBUFSIZE ], model [ CMDBUFSIZE ] = "" ;
  char **p, *q, *modelq [2][4] = { { "+FMFR?", "+FMDL?", 0 }, 
				   { "+FMI?", "+FMM?", "+FMR?", 0 } } ;
  char *message;


  /* diasable command echo and get firmware revision */

  cmd ( mf, "E0", t ) ;

  if ( cmd ( mf, "I3", t ) == OK ) {
    getresp ( "", model, CMDBUFSIZE ) ;
  }

  /* if not already chosen, pick safest class; set it */

  if ( ! err && ! c1 && !c2 && ! c20 ) {
    if ( cmd ( mf, "+FCLASS=?", t ) != OK ) {
      err = msg ("E3 %s", gettext ( "modem does not support fax" ) ) ;
    } else {
      if ( strinresp ( "2.0" ) ) c20 = 1 ;
      else if ( strinresp ( "2" ) ) ;
      else if ( strinresp ( "1" ) ) c1 = 1 ;
      else err = msg ("E3 %s", gettext ( "can't determine fax modem class support" ) ) ;
      if ( strstr ( model, "Sportster" ) ) { /* USR Sporsters are buggy */
	c1 = 1 ; 
	c2 = c20 = 0 ;
      }
    }
  }

  ckcmd ( mf, &err, c1 ? "+FCLASS=1" : 
       ( c20 ? "+FCLASS=2.0" : "+FCLASS=2" ), t, OK ) ;

  /* get make & model if using Class 2 or 2.0 */

  if ( ! c1 ) {
    for ( p = modelq [ c20 ] ; ! err && *p ; p++ ) {
      if ( cmd ( mf, *p, t ) == OK ) {
	getresp ( "", model, CMDBUFSIZE ) ;
      }
    }
  
    if ( ! c1 && strstr ( model, "Multi-Tech" ) ) {
      *preverse = 0 ;
      /* Translator: "Multi-Tech" is a make of modem */
      msg ("I %s", gettext ( "Multi-Tech bit order set" ) ) ;
    }
  }

  if ( ! err ) {
    /* Translator: the first string is the model of modem and the
       second is the fax modem class in which it operates */
    message = strdup2 ( "I ", gettext ( "using %s in class %s" ) ) ;
    if ( message ) {
      msg ( message, model, c1 ? "1" : c20 ? "2.0" : "2" ) ;
      free ( message ) ;
    }
  }
  /* get maximum modem speed if not already set (Class 1 only) */

  if ( ! err && c1 && ! capsset ) {
    int i ;
    char *c1spstr [6] = { "24", "48", "72", "96", "121", "145" } ;
    ckcmd ( mf, &err, calling ? "+FTM=?" : "+FRM=?", t, OK ) ;
    for ( i=0 ; i < 6 && strinresp ( c1spstr[i] ) ; i++ ) ;
    c[1]=i?i-1:0;
  }

  /* issue essential commands and set/get modem capabilities (Class 2 only) */

  if ( ! err && ! c1 ) {

    if ( c20 ) {
      ckcmd ( mf, 0, "+FIP", t, OK ) ;
      ckcmd ( mf, 0, "+FNR=1,1,1,0", t, OK ) ;

      ckcmd ( mf, 0, "+FLO=1", t, OK ) ;
      ckcmd ( mf, 0, "+FBO=0", t, OK ) ;
    }

    ckcmd ( mf, &err, "+FCR=1", t, OK ) ;

    if ( ! capsset ) {
      if ( cmd ( mf, c20 ? "+FIS?" : "+FDIS?", -t ) == OK &&
	   ( q = strinresp ( "," ) ) ) {
	str2cap ( q-1, c ) ;
      } else {
	msg ( "W can't get modem capabilities, set to default" ) ;
	capsset = 1 ;
      }
    }

    if ( capsset ) {
      sprintf ( buf, c20 ? "+FCC=%d,%d,%d,%d,%d,%d,%d,%d" : 
		"+FDCC=%d,%d,%d,%d,%d,%d,%d,%d", 
		c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7] ) ;
      ckcmd ( mf, 0, buf, -t, OK ) ;
    }
    
    sprintf ( buf, c20 ? "+FLI=\"%.*s\"" : "+FLID=\"%.*s\"" , 
	     CMDBUFSIZE-9, id ) ;
    ckcmd ( mf, 0, buf, -t, OK ) ;

    if ( ! err && poll ) {

      ckcmd ( mf, 0, c20 ? "+FSP=1" : "+FSPL=1", -t, OK ) ;

      sprintf ( buf, c20 ? "+FPI=\"%.*s\"" : "+FCIG=\"%.*s\"" , 
	       CMDBUFSIZE-9, id ) ;
      ckcmd ( mf, 0, buf, -t, OK ) ;

    }
  }

  return err ;
}


/* the following are global so can terminate properly on signal */

char *icmd[3][ MAXICMD+1 ] = {{0},{0},{0}} ; /* initialization commands */
TFILE faxdev = { -1, 0,0, {0}, 0, 0 } ;	/* modem */
char *lkfile [ MAXLKFILE+1 ] = {0} ; /* lock file names */
IFILE ifile = { 0 } ;		/* files being sent */
int locked = 0 ;		/* modem locked */


/* print names of files not sent and reset modem before
   exiting. */

int cleanup ( int err )
{
  char *message;
				/* log names of files not sent */

  /* Translator: this specifies a file (a fax page) the sending of which has failed
     (%s represents the file name of the page) */
  message = strdup2 ( "I ", gettext ( "failed page %s") ) ;
  if ( message ) {
    logifnames ( &ifile, message ) ;
    free ( message ) ;
  }

  if ( ! locked && faxdev.fd >= 0 )
    end_session ( &faxdev, icmd[2], lkfile, err != 4 ) ;

  /* Translator: %s represents a string reporting whether the
     fax operation failed or succeeded */
  message = strdup2 ( "I ", gettext ( "finished - %s" ) ) ;
  if ( message ) {
    msg ( message, errormsg [ err >= 0 && err <= 5 ? err : 6 ] ) ;
    free ( message ) ;
  }

  return err ;
}


/* signal handler */

void onsig ( int sig ) 
{ 
  msg ( "E terminating on signal %d", sig ) ; 
  exit ( cleanup ( 5 ) ) ;
}


/* Fax send/receive program for Class 1, 2 and 2.0 fax
   modems. Returns 0 on success, 1 if number busy or device
   locked, 2 for errors, 3 for protocol errors, 4 if no modem
   response, 5 on signal. */

int main( int argc, char **argv)
{
  int err=0, doneargs=0, c=0, i ;
  int testing=0, calling=0 ;

  int nicmd[3]={0,0,0}, nlkfile=0, nverb=0 ;

  char *faxfile = FAXFILE ;

  int softaa=0, share=0, wait=0, reverse=1, ignerr=0, noretry=0, hwfc=0 ;
  int capsset=0 ;
  char *getty = "", *vcmd = "", *acmd=ANSCMD ;

  cap local = { DEFCAP } ;
  char localid  [ IDLEN + 1 ] = DEFID ;

  int maxpgerr = MAXPGERR ;

  time_t now ;
  char *header = 0, headerbuf [ MAXLINELEN ] ; 
  char *fontname = 0 ;
  faxfont font ;

  OFILE ofile ;
  int pages = 0 ;
  char *phnum="", *ansfname = DEFPAT ;
  char fnamepat [ EFAX_PATH_MAX ] ;

  int index ;
  char *result, *message;

  /* As efax only accepts one option per argument, it is easy to test for '-u' and -n */
  for ( index = 0 ; index < argc ; index++ ) {
    if ( *( argv [ index ] ) == '-' ) {
      if ( *( argv [ index ] + 1 ) == 'u' ) use_utf8 = 1 ;
      else if ( *( argv [ index ] + 1 ) == 'n' ) line_buffered = 1 ;
    }
    if ( use_utf8 && line_buffered ) break ;
  }

  /* set up internationalization */
#ifdef ENABLE_NLS
  /* use the efax-gtk translation files */
  bindtextdomain( "efax-gtk", DATADIR "/locale" ) ;
  if ( use_utf8 ) {
    result = bind_textdomain_codeset ( "efax-gtk", "UTF-8" ) ;
    if ( ! result ) use_utf8 = 0 ;
  }
  textdomain ( "efax-gtk" ) ;

  setlocale ( LC_ALL, "" ) ;
  /* efax uses formatted text functions for floating point numbers,
     so restore the C locale for that  */
  setlocale ( LC_NUMERIC, "C" ) ;
#endif

  /* Initialize global/static variables */
  init_errormsg();

  /* print initial message to both stderr & stdout */
  argv0 = argv[0] ;
  memset((void *)lkfile, 0, sizeof(lkfile));  /* random effects on sparc linux */
  verb[1] = "ewia" ;
  msg ( "I " Version " " Copyright ) ;
  argv0 = efaxbasename ( argv0 ) ;
  msg ( "A compiled "__DATE__ " " __TIME__ ) ;
  verb[1] = "" ;

  while ( ! err && ! doneargs &&
	 ( c = nextopt ( argc,argv,
			"a:c:d:e:f:g:h:i:j:k:l:no:p:q:r:st:uv:wx:T" ) ) != -1 ) {

    switch (c) {
    case 'a': 
      acmd = nxtoptarg ;
      break ;
    case 'c': 
      err = str2cap ( nxtoptarg, local ) ;
      capsset = 1 ;
      break ;
    case 'l': 
      if ( strlen ( nxtoptarg ) > IDLEN ) {
	message = strdup2 ( "W ", gettext ( "local ID (%s) truncated to %d characters" ) ) ;
	if ( message ) {
	  msg ( message, nxtoptarg, IDLEN ) ;
	  free ( message ) ;
	}
      }
      if ( strspn ( nxtoptarg, " +0123456789" ) != strlen ( nxtoptarg ) ) {
	message = strdup2 ( "W ", gettext ( "local ID (%s) has non-standard characters" ) ) ;
	if ( message ) {
	  msg ( message, nxtoptarg ) ;
	  free ( message ) ;
	}
      }
      sprintf ( localid, "%*.*s", IDLEN, IDLEN, nxtoptarg ) ;
      break ;
    case 'i': 
      if ( nicmd[0] < MAXICMD ) icmd[0][ nicmd[0]++ ] = nxtoptarg ;
      else err = msg ( "E2too many '-i' options"); 
      break ;
    case 'j': 
      if ( nicmd[1] < MAXICMD ) icmd[1][ nicmd[1]++ ] = nxtoptarg ;
      else err = msg ( "E2too many '-j' options"); 
      break ;
    case 'k': 
      if ( nicmd[2] < MAXICMD ) icmd[2][ nicmd[2]++ ] = nxtoptarg ;
      else err = msg ( "E2too many '-k' options"); 
      break ;
    case 'h': 
      header = nxtoptarg ; 
      break ;
    case 'f': 
      fontname = nxtoptarg ; 
      break ;
    case 'd': 
      faxfile = nxtoptarg ; 
      break ;
    case 'e': 
      vcmd = nxtoptarg ; 
      break ;
    case 'g': 
      getty = nxtoptarg ; 
      break ;
    case 'n': 
      msg ( "I %s", gettext ( "using line buffering of stdout" ) ) ; 
      break ;
    case 'o':			/* most protocol options are globals */
      for ( ; *nxtoptarg ; nxtoptarg++ ) 
	switch ( *nxtoptarg ) {
	case '0' : c20 = 1 ; break ;
	case '1' : c1 = 1 ; break ;
	case '2' : c2 = 1 ; break ;
	case 'a' : softaa = 1 ;  break ;
	case 'e' : ignerr = 1 ;  break ;
	case 'f' : vfc = 1 ;  break ;
	case 'h' : hwfc = 1 ;  break ;
	case 'l' : lockpolldelay /= 2 ;  break ;
	case 'n' : noretry = 1 ;  break ;
	case 'r' : reverse = 0 ; break ;
	case 'x' : startchar = XON ; break ;
	case 'z' : cmdpause += T_CMD ; break ;
	 default : msg ( "Wunrecognized protocol option (%c)", *nxtoptarg ) ; 
	}
      break ;
    case 'q':
      if ( sscanf ( nxtoptarg , "%d", &maxpgerr ) != 1 || maxpgerr < 0 ) {
	message = strdup2 ( "E2 ", gettext ( "incorrect quality (-q) argument (%s)" ) ) ;
	if ( message ) {
	  err=msg ( message, nxtoptarg ) ;
	  free ( message ) ;
	}
      }
      break;
    case 'r': 
      ansfname = nxtoptarg ;
      break;
    case 's': 
      share = 1 ; 
      break;
    case 't': 
      calling=1;
      /* fall through */
    case 'p':
      if ( argv [ argc ] ) err = msg ("E2can't happen(unterminated argv)") ;
      if ( ! err ) err = newIFILE ( &ifile, argv + nxtoptind ) ;
      pages = argc - nxtoptind - ( c == 'p' ? 1 : 0 )  ;
      pages = pages < 0 ? 0 : pages ;
      phnum = nxtoptarg ;
      doneargs=1 ; 
      break;
    case 'u': 
      if ( ! use_utf8 ) msg ( "E error in binding textdomain to UTF-8 codeset" ) ;
      /* else msg ( "I using UTF-8 codeset" ) ; */
      break ;
    case 'v': 
      verb[nverb] = nxtoptarg ; 
      nverb=1;
      break ;
    case 'w': 
      wait = 1 ; 
      break ;
    case 'x': 
      if ( nlkfile < MAXLKFILE ) lkfile[ nlkfile++ ] = nxtoptarg ;
      else err = msg ( "E2too many lock files" ) ; 
      break ;
    case 'T':			/* test: begin+end session */
      testing=1;
      doneargs=1 ; 
      break ;
    default : fprintf ( stderr, Usage, argv0 ) ; err = 2 ; break ;
    }
  }

  for ( i=0 ; i<argc ; i++ ) 
    msg ( "Aargv[%d]=%s", i, argv[i]) ; 

  if ( ! nicmd[2] ) icmd[2][nicmd[2]++] = "H" ;	/* default -k command */

  readfont ( fontname, &font ) ;

  if ( ! header ) {
    char tmp [ MAXLINELEN ] ;
    now = time ( 0 ) ;
    /* we do not want to convert from the locale to UTF-8 here if the -u
       flag has been used, as this goes on the fax top header */
    strftime ( tmp, MAXLINELEN, "%c %%s   P. %%%%d", localtime ( &now ) ) ;
    sprintf ( header = headerbuf, tmp, localid ) ;
  }

  if ( ! err ) {
    err = begin_session ( &faxdev, faxfile, 
			 !c1 && !c20 && reverse, /* Class 2 rx bit reversal */
			 hwfc, lkfile, COMMAND, onsig ) ;
    if ( ! err ) err = setup ( &faxdev, icmd[0], ignerr ) ;
    if ( ! err ) err = modem_init ( &faxdev, local, localid, 
				    calling, calling && !pages, capsset,
				    &reverse ) ;
    if ( ! err ) err = setup ( &faxdev, icmd[1], ignerr ) ;
    if ( err == 1 ) locked = 1 ;
  }

  if ( ! err && ! testing ) {

    if ( calling ) {
      err = dial ( &faxdev, phnum, 0 ) ;
    } else {
      err = answer ( &faxdev, lkfile, wait, share, softaa, 
		    getty, vcmd, acmd ) ;
      if ( err == 1 ) locked = 1 ;
    }

    now = time(0) ;		/* do it here so use reception time */

    /* we do not want to convert from the locale to UTF-8 here if the -u
       flag has been used, as this creates a filename for the file system */
    strftime ( fnamepat, EFAX_PATH_MAX, ansfname, localtime ( &now ) ) ;
    strncat ( fnamepat, ".%03d", EFAX_PATH_MAX - strlen ( fnamepat ) ) ;
    newOFILE ( &ofile, O_TIFF_FAX, fnamepat, 0, 0, 0, 0 ) ;
    
    if ( ! err ) {
      if ( c1 ) {
	err = c1sndrcv ( &faxdev, local, localid,
			&ofile, &ifile, pages, header, &font,
			maxpgerr, noretry, calling ) ;
      } else {
	err = c2sndrcv ( &faxdev, local, localid,
			&ofile, &ifile, pages, header, &font,
			maxpgerr, noretry, calling ) ;
      }
    }
  }

  return cleanup ( err ) ;
}