summaryrefslogtreecommitdiff
path: root/backend/pie.c
blob: bfa68f041397ffc8897c06722955ee1b36960614 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
/* sane - Scanner Access Now Easy.

   pie.c

   Copyright (C) 2000 Simon Munton, based on the umax backend by Oliver Rauch

   This file is part of the SANE package.

   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, see <https://www.gnu.org/licenses/>.

   As a special exception, the authors of SANE give permission for
   additional uses of the libraries contained in this release of SANE.

   The exception is that, if you link a SANE library with other files
   to produce an executable, this does not by itself cause the
   resulting executable to be covered by the GNU General Public
   License.  Your use of that executable is in no way restricted on
   account of linking the SANE library code into it.

   This exception does not, however, invalidate any other reasons why
   the executable file might be covered by the GNU General Public
   License.

   If you submit changes to SANE to the maintainers to be included in
   a subsequent release, you agree by submitting the changes that
   those changes may be distributed with this exception intact.

   If you write modifications of your own for SANE, it is your choice
   whether to permit this exception to apply to your modifications.
   If you do not wish that, delete this exception notice.  */

/*
 * 22-2-2003 set devlist to NULL in sane_exit()
 *           set first_dev to NULL in sane_exit()
 *           eliminated num_devices
 *
 * 23-7-2002 added TL_X > BR_X, TL_Y > BR_Y check in sane_start
 *
 * 17-9-2001 changed ADLIB to AdLib as the comparison is case sensitive and
 * 	     the scanner returns AdLib
 *
 * 7-5-2001 removed removal of '\n' after sanei_config_read()
 *	    free devlist allocated in sane_get_devices() on sane_exit()
 *
 * 2-3-2001 improved the reordering of RGB data in pie_reader_process()
 *
 * 11-11-2000 eliminated some warnings about signed/unsigned comparisons
 *            removed #undef NDEBUG and C++ style comments
 *
 * 1-10-2000 force gamma table to one to one mapping if lineart or halftone selected
 *
 * 30-9-2000 added ADLIB devices to scanner_str[]
 *
 * 29-9-2000 wasn't setting 'background is halftone bit' (BGHT) in halftone mode
 *
 * 27-9-2000 went public with build 4
 */

#include "../include/sane/config.h"

#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include "../include/sane/sane.h"
#include "../include/sane/sanei.h"
#include "../include/sane/saneopts.h"
#include "../include/sane/sanei_scsi.h"
#include "../include/sane/sanei_debug.h"

#define BACKEND_NAME	pie
#include "../include/sane/sanei_backend.h"
#include "../include/sane/sanei_config.h"

# include "../include/sane/sanei_thread.h"

#include "pie-scsidef.h"

#define DBG_error0  0
#define DBG_error   1
#define DBG_sense   2
#define DBG_warning 3
#define DBG_inquiry 4

#define DBG_info    5
#define DBG_info2   6
#define DBG_proc    7
#define DBG_read    8
#define DBG_sane_init   10
#define DBG_sane_proc   11
#define DBG_sane_info   12
#define DBG_sane_option 13
#define DBG_dump	14

#define BUILD 9

#define PIE_CONFIG_FILE "pie.conf"

#define LINEART_STR         SANE_VALUE_SCAN_MODE_LINEART
#define HALFTONE_STR        SANE_VALUE_SCAN_MODE_HALFTONE
#define GRAY_STR            SANE_VALUE_SCAN_MODE_GRAY
#define COLOR_STR           SANE_VALUE_SCAN_MODE_COLOR

#define LINEART             1
#define HALFTONE            2
#define GRAYSCALE           3
#define RGB                 4

#define CAL_MODE_PREVIEW        (INQ_CAP_FAST_PREVIEW)
#define CAL_MODE_FLATBED        0x00
#define CAL_MODE_ADF            (INQ_OPT_DEV_ADF)
#define CAL_MODE_TRANPSARENCY   (INQ_OPT_DEV_TP)
#define CAL_MODE_TRANPSARENCY1  (INQ_OPT_DEV_TP1)

#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))


/* names of scanners that are supported because */
/* the inquiry_return_block is ok and driver is tested */

static char *scanner_str[] = {
  "DEVCOM", "9636PRO",
  "DEVCOM", "9636S",
  "DEVCOM", "9630S",
  "PIE", "ScanAce 1236S",
  "PIE", "ScanAce 1230S",
  "PIE", "ScanAce II",
  "PIE", "ScanAce III",
  "PIE", "ScanAce Plus",
  "PIE", "ScanAce II Plus",
  "PIE", "ScanAce III Plus",
  "PIE", "ScanAce V",
  "PIE", "ScanMedia",
  "PIE", "ScanMedia II",
  "PIE", "ScanAce 630S",
  "PIE", "ScanAce 636S",
  "AdLib", "JetScan 630",
  "AdLib", "JetScan 636PRO",
  "END_OF_LIST"
};

/* times (in us) to delay after certain commands. Scanner seems to lock up if it returns busy
 * status and commands are repeatedly reissued (by kernel error handler) */

#define DOWNLOAD_GAMMA_WAIT_TIME	(1000000)
#define SCAN_WAIT_TIME			(1000000)
#define SCAN_WARMUP_WAIT_TIME		(500000)
#define TUR_WAIT_TIME			(500000)


/* options supported by the scanner */

enum Pie_Option
{
  OPT_NUM_OPTS = 0,

  /* ------------------------------------------- */
  OPT_MODE_GROUP,
  OPT_MODE,
  OPT_RESOLUTION,


  /* ------------------------------------------- */

  OPT_GEOMETRY_GROUP,
  OPT_TL_X,			/* top-left x */
  OPT_TL_Y,			/* top-left y */
  OPT_BR_X,			/* bottom-right x */
  OPT_BR_Y,			/* bottom-right y */

  /* ------------------------------------------- */

  OPT_ENHANCEMENT_GROUP,

  OPT_HALFTONE_PATTERN,
  OPT_SPEED,
  OPT_THRESHOLD,

  OPT_GAMMA_VECTOR,
  OPT_GAMMA_VECTOR_R,
  OPT_GAMMA_VECTOR_G,
  OPT_GAMMA_VECTOR_B,

  /* ------------------------------------------- */

  OPT_ADVANCED_GROUP,
  OPT_PREVIEW,

  /* must come last: */
  NUM_OPTIONS
};




/* This defines the information needed during calibration */

struct Pie_cal_info
{
  int cal_type;
  int receive_bits;
  int send_bits;
  int num_lines;
  int pixels_per_line;
};


/* This structure holds the information about a physical scanner */

typedef struct Pie_Device
{
  struct Pie_Device *next;

  char *devicename;		/* name of the scanner device */

  char vendor[9];		/* will be xxxxx */
  char product[17];		/* e.g. "SuperVista_S12" or so */
  char version[5];		/* e.g. V1.3 */

  SANE_Device sane;
  SANE_Range dpi_range;
  SANE_Range x_range;
  SANE_Range y_range;

  SANE_Range exposure_range;
  SANE_Range shadow_range;
  SANE_Range highlight_range;

  int inquiry_len;		/* length of inquiry return block */

  int inquiry_x_res;		/* maximum x-resolution */
  int inquiry_y_res;		/* maximum y-resolution */
  int inquiry_pixel_resolution;
  double inquiry_fb_width;	/* flatbed width in inches */
  double inquiry_fb_length;	/* flatbed length in inches */

  int inquiry_trans_top_left_x;
  int inquiry_trans_top_left_y;
  double inquiry_trans_width;	/* transparency width in inches */
  double inquiry_trans_length;	/* transparency length in inches */

  int inquiry_halftones;	/* number of halftones supported */
  int inquiry_filters;		/* available colour filters */
  int inquiry_color_depths;	/* available colour depths */
  int inquiry_color_format;	/* colour format from scanner */
  int inquiry_image_format;	/* image data format */
  int inquiry_scan_capability;	/* additional scanner features, number of speeds */
  int inquiry_optional_devices;	/* optional devices */
  int inquiry_enhancements;	/* enhancements */
  int inquiry_gamma_bits;	/* no of bits used for gamma table */
  int inquiry_fast_preview_res;	/* fast preview resolution */
  int inquiry_min_highlight;	/* min highlight % that can be used */
  int inquiry_max_shadow;	/* max shadow % that can be used */
  int inquiry_cal_eqn;		/* which calibration equation to use */
  int inquiry_min_exp;		/* min exposure % */
  int inquiry_max_exp;		/* max exposure % */

  SANE_String scan_mode_list[7];	/* holds names of types of scan (color, ...) */

  SANE_String halftone_list[17];	/* holds the names of the halftone patterns from the scanner */

  SANE_String speed_list[9];	/* holds the names of available speeds */

  int cal_info_count;		/* number of calibration info sets */
  struct Pie_cal_info *cal_info;	/* points to the actual calibration information */
}
Pie_Device;

/* This structure holds information about an instance of an 'opened' scanner */

typedef struct Pie_Scanner
{
  struct Pie_Scanner *next;
  Pie_Device *device;		/* pointer to physical scanner */

  int sfd;			/* scanner file desc. */
  int bufsize;			/* max scsi buffer size */

  SANE_Option_Descriptor opt[NUM_OPTIONS];	/* option descriptions for this instance */
  Option_Value val[NUM_OPTIONS];	/* option settings for this instance */
  SANE_Int *gamma_table[4];	/* gamma tables for this instance */
  SANE_Range gamma_range;
  int gamma_length;		/* size of gamma table */

  int scanning;			/* true if actually doing a scan */
  SANE_Parameters params;

  SANE_Pid reader_pid;
  int pipe;
  int reader_fds;
  
  int colormode;		/* whether RGB, GRAY, LINEART, HALFTONE */
  int resolution;
  int cal_mode;			/* set to value to compare cal_info mode to */

  int cal_filter;		/* set to indicate which filters will provide data for cal */

  int filter_offset1;		/* offsets between colors in indexed scan mode */
  int filter_offset2;

  int bytes_per_line;		/* number of bytes per line */

}
Pie_Scanner;

static const SANE_Range percentage_range_100 = {
  0 << SANE_FIXED_SCALE_SHIFT,	/* minimum */
  100 << SANE_FIXED_SCALE_SHIFT,	/* maximum */
  0 << SANE_FIXED_SCALE_SHIFT	/* quantization */
};

static Pie_Device *first_dev = NULL;
static Pie_Scanner *first_handle = NULL;
static const SANE_Device **devlist = NULL;



static SANE_Status pie_wait_scanner (Pie_Scanner * scanner);


/* ---------------------------------- PIE DUMP_BUFFER ---------------------------------- */

#define DBG_DUMP(level, buf, n)	{ if (DBG_LEVEL >= (level)) pie_dump_buffer(level,buf,n); }


static void
pie_dump_buffer (int level, unsigned char *buf, int n)
{
  char s[80], *p = s;
  int a = 0;

  while (n--)
    {
      if ((a % 16) == 0)
	p += sprintf (p, "  %04X  ", a);

      p += sprintf (p, "%02X ", *buf++);

      if ((n == 0) || (a % 16) == 15)
	{
	  DBG (level, "%s\n", s);
	  p = s;
	}
      a++;
    }
}

/* ---------------------------------- PIE INIT ---------------------------------- */

static void
pie_init (Pie_Device * dev)	/* pie_init is called once while driver-initialization */
{
  DBG (DBG_proc, "init\n");

  dev->cal_info_count = 0;
  dev->cal_info = NULL;

  dev->devicename = NULL;
  dev->inquiry_len = 0;

#ifdef HAVE_SANEI_SCSI_OPEN_EXTENDED
  DBG (DBG_info,
       "variable scsi buffer size (usage of sanei_scsi_open_extended)\n");
#else
  DBG (DBG_info, "fixed scsi buffer size = %d bytes\n",
       sanei_scsi_max_request_size);
#endif
}


/* ---------------------------- SENSE_HANDLER ------------------------------ */


static SANE_Status
sense_handler (__sane_unused__ int scsi_fd, unsigned char *result, __sane_unused__ void *arg)	/* is called by sanei_scsi */
{
  unsigned char asc, ascq, sensekey;
  int asc_ascq, len;
  /* Pie_Device *dev = arg; */

  DBG (DBG_proc, "check condition sense handler\n");

  sensekey = get_RS_sense_key (result);
  asc = get_RS_ASC (result);
  ascq = get_RS_ASCQ (result);
  asc_ascq = (int) (256 * asc + ascq);
  len = 7 + get_RS_additional_length (result);

  if (get_RS_error_code (result) != 0x70)
    {
      DBG (DBG_proc, "invalid sense key => handled as DEVICE BUSY!\n");
      return SANE_STATUS_DEVICE_BUSY;	/* sense key invalid */
    }

  DBG (DBG_sense, "check condition sense: %s\n", sense_str[sensekey]);

  if (get_RS_ILI (result) != 0)
    {
      DBG (DBG_sense,
	   "-> ILI-ERROR: requested data length is larger than actual length\n");
    }

  switch (sensekey)
    {
    case 0x00:			/* no sense, could have been busy */
      return SANE_STATUS_IO_ERROR;
      break;

    case 0x02:
      if (asc_ascq == 0x0401)
	DBG (DBG_sense, "-> Not Ready - Warming Up\n");
      else if (asc_ascq == 0x0483)
	DBG (DBG_sense, "-> Not Ready - Need manual service\n");
      else if (asc_ascq == 0x0881)
	DBG (DBG_sense, "-> Not Ready - Communication time out\n");
      else
	DBG (DBG_sense, "-> unknown medium error: asc=%d, ascq=%d\n", asc,
	     ascq);
      break;

    case 0x03:			/* medium error */
      if (asc_ascq == 0x5300)
	DBG (DBG_sense, "-> Media load or eject failure\n");
      else if (asc_ascq == 0x3a00)
	DBG (DBG_sense, "-> Media not present\n");
      else if (asc_ascq == 0x3b05)
	DBG (DBG_sense, "-> Paper jam\n");
      else if (asc_ascq == 0x3a80)
	DBG (DBG_sense, "-> ADF paper out\n");
      else
	DBG (DBG_sense, "-> unknown medium error: asc=%d, ascq=%d\n", asc,
	     ascq);
      break;


    case 0x04:			/* hardware error */
      if (asc_ascq == 0x4081)
	DBG (DBG_sense, "-> CPU RAM failure\n");
      else if (asc_ascq == 0x4082)
	DBG (DBG_sense, "-> Scanning system RAM failure\n");
      else if (asc_ascq == 0x4083)
	DBG (DBG_sense, "-> Image buffer failure\n");
      else if (asc_ascq == 0x0403)
	DBG (DBG_sense, "-> Manual intervention required\n");
      else if (asc_ascq == 0x6200)
	DBG (DBG_sense, "-> Scan head position error\n");
      else if (asc_ascq == 0x6000)
	DBG (DBG_sense, "-> Lamp or CCD failure\n");
      else if (asc_ascq == 0x6081)
	DBG (DBG_sense, "-> Transparency lamp failure\n");
      else if (asc_ascq == 0x8180)
	DBG (DBG_sense, "-> DC offset or black level calibration failure\n");
      else if (asc_ascq == 0x8181)
	DBG (DBG_sense,
	     "-> Integration time adjustment failure (too light)\n");
      else if (asc_ascq == 0x8182)
	DBG (DBG_sense,
	     "-> Integration time adjustment failure (too dark)\n");
      else if (asc_ascq == 0x8183)
	DBG (DBG_sense, "-> Shading curve adjustment failure\n");
      else if (asc_ascq == 0x8184)
	DBG (DBG_sense, "-> Gain adjustment failure\n");
      else if (asc_ascq == 0x8185)
	DBG (DBG_sense, "-> Optical alignment failure\n");
      else if (asc_ascq == 0x8186)
	DBG (DBG_sense, "-> Optical locating failure\n");
      else if (asc_ascq == 0x8187)
	DBG (DBG_sense, "-> Scan pixel map less than 5100 pixels!\n");
      else if (asc_ascq == 0x4700)
	DBG (DBG_sense, "-> Parity error on SCSI bus\n");
      else if (asc_ascq == 0x4b00)
	DBG (DBG_sense, "-> Data phase error\n");
      else
	DBG (DBG_sense, "-> unknown hardware error: asc=%d, ascq=%d\n", asc,
	     ascq);
      return SANE_STATUS_IO_ERROR;
      break;


    case 0x05:			/* illegal request */
      if (asc_ascq == 0x1a00)
	DBG (DBG_sense, "-> Parameter list length error\n");
      else if (asc_ascq == 0x2c01)
	DBG (DBG_sense, "-> Too many windows specified\n");
      else if (asc_ascq == 0x2c02)
	DBG (DBG_sense, "-> Invalid combination of windows\n");
      else if (asc_ascq == 0x2c81)
	DBG (DBG_sense, "-> Illegal scanning frame\n");
      else if (asc_ascq == 0x2400)
	DBG (DBG_sense, "-> Invalid field in CDB\n");
      else if (asc_ascq == 0x2481)
	DBG (DBG_sense, "-> Request too many lines of data\n");
      else if (asc_ascq == 0x2000)
	DBG (DBG_sense, "-> Invalid command OP code\n");
      else if (asc_ascq == 0x2501)
	DBG (DBG_sense, "-> LUN not supported\n");
      else if (asc_ascq == 0x2601)
	DBG (DBG_sense, "-> Parameter not supported\n");
      else if (asc_ascq == 0x2602)
	DBG (DBG_sense,
	     "-> Parameter value invalid - Parameter not specified\n");
      else if (asc_ascq == 0x2603)
	DBG (DBG_sense, "-> Parameter value invalid - Invalid threshold\n");
      else if (asc_ascq == 0x2680)
	DBG (DBG_sense,
	     "-> Parameter value invalid - Control command sequence error\n");
      else if (asc_ascq == 0x2681)
	DBG (DBG_sense,
	     "-> Parameter value invalid - Grain setting (halftone pattern\n");
      else if (asc_ascq == 0x2682)
	DBG (DBG_sense,
	     "-> Parameter value invalid - Illegal resolution setting\n");
      else if (asc_ascq == 0x2683)
	DBG (DBG_sense,
	     "-> Parameter value invalid - Invalid filter assignment\n");
      else if (asc_ascq == 0x2684)
	DBG (DBG_sense,
	     "-> Parameter value invalid - Illegal gamma adjustment setting (look-up table)\n");
      else if (asc_ascq == 0x2685)
	DBG (DBG_sense,
	     "-> Parameter value invalid - Illegal offset setting (digital brightness)\n");
      else if (asc_ascq == 0x2686)
	DBG (DBG_sense,
	     "-> Parameter value invalid - Illegal bits per pixel setting\n");
      else if (asc_ascq == 0x2687)
	DBG (DBG_sense,
	     "-> Parameter value invalid - Illegal contrast setting\n");
      else if (asc_ascq == 0x2688)
	DBG (DBG_sense,
	     "-> Parameter value invalid - Illegal paper length setting\n");
      else if (asc_ascq == 0x2689)
	DBG (DBG_sense,
	     "-> Parameter value invalid - Illegal highlight/shadow setting\n");
      else if (asc_ascq == 0x268a)
	DBG (DBG_sense,
	     "-> Parameter value invalid - Illegal exposure time setting (analog brightness)\n");
      else if (asc_ascq == 0x268b)
	DBG (DBG_sense,
	     "-> Parameter value invalid - Invalid device select or device not exist\n");
      else if (asc_ascq == 0x268c)
	DBG (DBG_sense,
	     "-> Parameter value invalid - Illegal color packing\n");
      else if (asc_ascq == 0x3d00)
	DBG (DBG_sense, "-> Invalid bits in identify field\n");



      else if (asc_ascq == 0x4900)
	DBG (DBG_sense, "-> Invalid message\n");
      else if (asc_ascq == 0x8101)
	DBG (DBG_sense, "-> Not enough memory for color packing\n");

      if (len >= 0x11)
	{
	  if (get_RS_SKSV (result) != 0)
	    {
	      if (get_RS_CD (result) == 0)
		{

		  DBG (DBG_sense, "-> illegal parameter in CDB\n");
		}
	      else
		{
		  DBG (DBG_sense,
		       "-> illegal parameter is in the data parameters sent during data out phase\n");
		}

	      DBG (DBG_sense, "-> error detected in byte %d\n",
		   get_RS_field_pointer (result));
	    }
	}
      return SANE_STATUS_IO_ERROR;
      break;


    case 0x06:			/* unit attention */
      if (asc_ascq == 0x2900)
	DBG (DBG_sense, "-> power on, reset or bus device reset\n");
      if (asc_ascq == 0x8200)
	DBG (DBG_sense,
	     "-> unit attention - calibration disable not granted\n");
      if (asc_ascq == 0x8300)
	DBG (DBG_sense, "-> unit attention - calibration will be ignored\n");
      else
	DBG (DBG_sense, "-> unit attention: asc=%d, ascq=%d\n", asc, ascq);
      break;


    case 0x09:			/* vendor specific */
      DBG (DBG_sense, "-> vendor specific sense-code: asc=%d, ascq=%d\n", asc,
	   ascq);
      break;

    case 0x0b:
      if (asc_ascq == 0x0006)
	DBG (DBG_sense, "-> Received ABORT message from initiator\n");
      if (asc_ascq == 0x4800)
	DBG (DBG_sense, "-> Initiator detected error message received\n");
      if (asc_ascq == 0x4300)
	DBG (DBG_sense, "-> Message error\n");
      if (asc_ascq == 0x4500)
	DBG (DBG_sense, "-> Select or re-select error\n");
      else
	DBG (DBG_sense, "-> aborted command: asc=%d, ascq=%d\n", asc, ascq);
      break;

    }

  return SANE_STATUS_IO_ERROR;
}


/* -------------------------------- PIE PRINT INQUIRY ------------------------- */


static void
pie_print_inquiry (Pie_Device * dev)
{
  DBG (DBG_inquiry, "INQUIRY:\n");
  DBG (DBG_inquiry, "========\n");
  DBG (DBG_inquiry, "\n");
  DBG (DBG_inquiry, "vendor........................: '%s'\n", dev->vendor);
  DBG (DBG_inquiry, "product.......................: '%s'\n", dev->product);
  DBG (DBG_inquiry, "version.......................: '%s'\n", dev->version);

  DBG (DBG_inquiry, "X resolution..................: %d dpi\n",
       dev->inquiry_x_res);
  DBG (DBG_inquiry, "Y resolution..................: %d dpi\n",
       dev->inquiry_y_res);
  DBG (DBG_inquiry, "pixel resolution..............: %d dpi\n",
       dev->inquiry_pixel_resolution);
  DBG (DBG_inquiry, "fb width......................: %f in\n",
       dev->inquiry_fb_width);
  DBG (DBG_inquiry, "fb length.....................: %f in\n",
       dev->inquiry_fb_length);

  DBG (DBG_inquiry, "transparency width............: %f in\n",
       dev->inquiry_trans_width);
  DBG (DBG_inquiry, "transparency length...........: %f in\n",
       dev->inquiry_trans_length);
  DBG (DBG_inquiry, "transparency offset...........: %d,%d\n",
       dev->inquiry_trans_top_left_x, dev->inquiry_trans_top_left_y);

  DBG (DBG_inquiry, "# of halftones................: %d\n",
       dev->inquiry_halftones);

  DBG (DBG_inquiry, "One pass color................: %s\n",
       dev->inquiry_filters & INQ_ONE_PASS_COLOR ? "yes" : "no");

  DBG (DBG_inquiry, "Filters.......................: %s%s%s%s (%02x)\n",
       dev->inquiry_filters & INQ_FILTER_RED ? "Red " : "",
       dev->inquiry_filters & INQ_FILTER_GREEN ? "Green " : "",
       dev->inquiry_filters & INQ_FILTER_BLUE ? "Blue " : "",
       dev->inquiry_filters & INQ_FILTER_NEUTRAL ? "Neutral " : "",
       dev->inquiry_filters);

  DBG (DBG_inquiry, "Color depths..................: %s%s%s%s%s%s (%02x)\n",
       dev->inquiry_color_depths & INQ_COLOR_DEPTH_16 ? "16 bit " : "",
       dev->inquiry_color_depths & INQ_COLOR_DEPTH_12 ? "12 bit " : "",
       dev->inquiry_color_depths & INQ_COLOR_DEPTH_10 ? "10 bit " : "",
       dev->inquiry_color_depths & INQ_COLOR_DEPTH_8 ? "8 bit " : "",
       dev->inquiry_color_depths & INQ_COLOR_DEPTH_4 ? "4 bit " : "",
       dev->inquiry_color_depths & INQ_COLOR_DEPTH_1 ? "1 bit " : "",
       dev->inquiry_color_depths);

  DBG (DBG_inquiry, "Color Format..................: %s%s%s (%02x)\n",
       dev->inquiry_color_format & INQ_COLOR_FORMAT_INDEX ? "Indexed " : "",
       dev->inquiry_color_format & INQ_COLOR_FORMAT_LINE ? "Line " : "",
       dev->inquiry_color_format & INQ_COLOR_FORMAT_PIXEL ? "Pixel " : "",
       dev->inquiry_color_format);

  DBG (DBG_inquiry, "Image Format..................: %s%s%s%s (%02x)\n",
       dev->inquiry_image_format & INQ_IMG_FMT_OKLINE ? "OKLine " : "",
       dev->inquiry_image_format & INQ_IMG_FMT_BLK_ONE ? "BlackOne " : "",
       dev->inquiry_image_format & INQ_IMG_FMT_MOTOROLA ? "Motorola " : "",
       dev->inquiry_image_format & INQ_IMG_FMT_INTEL ? "Intel" : "",
       dev->inquiry_image_format);

  DBG (DBG_inquiry,
       "Scan Capability...............: %s%s%s%s%d speeds (%02x)\n",
       dev->inquiry_scan_capability & INQ_CAP_PWRSAV ? "PowerSave " : "",
       dev->inquiry_scan_capability & INQ_CAP_EXT_CAL ? "ExtCal " : "",
       dev->inquiry_scan_capability & INQ_CAP_FAST_PREVIEW ? "FastPreview" :
       "",
       dev->inquiry_scan_capability & INQ_CAP_DISABLE_CAL ? "DisCal " : "",
       dev->inquiry_scan_capability & INQ_CAP_SPEEDS,
       dev->inquiry_scan_capability);

  DBG (DBG_inquiry, "Optional Devices..............: %s%s%s%s (%02x)\n",
       dev->inquiry_optional_devices & INQ_OPT_DEV_MPCL ? "MultiPageLoad " :
       "",
       dev->inquiry_optional_devices & INQ_OPT_DEV_TP1 ? "TransModule1 " : "",
       dev->inquiry_optional_devices & INQ_OPT_DEV_TP ? "TransModule " : "",
       dev->inquiry_optional_devices & INQ_OPT_DEV_ADF ? "ADF " : "",
       dev->inquiry_optional_devices);

  DBG (DBG_inquiry, "Enhancement...................: %02x\n",
       dev->inquiry_enhancements);
  DBG (DBG_inquiry, "Gamma bits....................: %d\n",
       dev->inquiry_gamma_bits);

  DBG (DBG_inquiry, "Fast Preview Resolution.......: %d\n",
       dev->inquiry_fast_preview_res);
  DBG (DBG_inquiry, "Min Highlight.................: %d\n",
       dev->inquiry_min_highlight);
  DBG (DBG_inquiry, "Max Shadow....................: %d\n",
       dev->inquiry_max_shadow);
  DBG (DBG_inquiry, "Cal Eqn.......................: %d\n",
       dev->inquiry_cal_eqn);
  DBG (DBG_inquiry, "Min Exposure..................: %d\n",
       dev->inquiry_min_exp);
  DBG (DBG_inquiry, "Max Exposure..................: %d\n",
       dev->inquiry_max_exp);
}


/* ------------------------------ PIE GET INQUIRY VALUES -------------------- */


static void
pie_get_inquiry_values (Pie_Device * dev, unsigned char *buffer)
{
  DBG (DBG_proc, "get_inquiry_values\n");

  dev->inquiry_len = get_inquiry_additional_length (buffer) + 5;

  get_inquiry_vendor ((char *) buffer, dev->vendor);
  get_inquiry_product ((char *) buffer, dev->product);
  get_inquiry_version ((char *) buffer, dev->version);

  dev->inquiry_x_res = get_inquiry_max_x_res (buffer);
  dev->inquiry_y_res = get_inquiry_max_y_res (buffer);

  if (dev->inquiry_y_res < 256)
    {
      /* y res is a multiplier */
      dev->inquiry_pixel_resolution = dev->inquiry_x_res;
      dev->inquiry_x_res *= dev->inquiry_y_res;
      dev->inquiry_y_res = dev->inquiry_x_res;
    }
  else
    {
      /* y res really is resolution */
      dev->inquiry_pixel_resolution =
	min (dev->inquiry_x_res, dev->inquiry_y_res);
    }

  dev->inquiry_fb_width =
    (double) get_inquiry_fb_max_scan_width (buffer) /
    dev->inquiry_pixel_resolution;
  dev->inquiry_fb_length =
    (double) get_inquiry_fb_max_scan_length (buffer) /
    dev->inquiry_pixel_resolution;

  dev->inquiry_trans_top_left_x = get_inquiry_trans_x1 (buffer);
  dev->inquiry_trans_top_left_y = get_inquiry_trans_y1 (buffer);

  dev->inquiry_trans_width =
    (double) (get_inquiry_trans_x2 (buffer) -
	      get_inquiry_trans_x1 (buffer)) / dev->inquiry_pixel_resolution;
  dev->inquiry_trans_length =
    (double) (get_inquiry_trans_y2 (buffer) -
	      get_inquiry_trans_y1 (buffer)) / dev->inquiry_pixel_resolution;

  dev->inquiry_halftones = get_inquiry_halftones (buffer) & 0x0f;

  dev->inquiry_filters = get_inquiry_filters (buffer);
  dev->inquiry_color_depths = get_inquiry_color_depths (buffer);
  dev->inquiry_color_format = get_inquiry_color_format (buffer);
  dev->inquiry_image_format = get_inquiry_image_format (buffer);

  dev->inquiry_scan_capability = get_inquiry_scan_capability (buffer);
  dev->inquiry_optional_devices = get_inquiry_optional_devices (buffer);
  dev->inquiry_enhancements = get_inquiry_enhancements (buffer);
  dev->inquiry_gamma_bits = get_inquiry_gamma_bits (buffer);
  dev->inquiry_fast_preview_res = get_inquiry_fast_preview_res (buffer);
  dev->inquiry_min_highlight = get_inquiry_min_highlight (buffer);
  dev->inquiry_max_shadow = get_inquiry_max_shadow (buffer);
  dev->inquiry_cal_eqn = get_inquiry_cal_eqn (buffer);
  dev->inquiry_min_exp = get_inquiry_min_exp (buffer);
  dev->inquiry_max_exp = get_inquiry_max_exp (buffer);

  pie_print_inquiry (dev);

  return;
}

/* ----------------------------- PIE DO INQUIRY ---------------------------- */


static void
pie_do_inquiry (int sfd, unsigned char *buffer)
{
  size_t size;
  SANE_Status status;

  DBG (DBG_proc, "do_inquiry\n");
  memset (buffer, '\0', 256);	/* clear buffer */

  size = 5;

  set_inquiry_return_size (inquiry.cmd, size);	/* first get only 5 bytes to get size of inquiry_return_block */
  status = sanei_scsi_cmd (sfd, inquiry.cmd, inquiry.size, buffer, &size);
  if (status)
    {
      DBG (DBG_error, "pie_do_inquiry: command returned status %s\n",
	   sane_strstatus (status));
    }

  size = get_inquiry_additional_length (buffer) + 5;

  set_inquiry_return_size (inquiry.cmd, size);	/* then get inquiry with actual size */
  status = sanei_scsi_cmd (sfd, inquiry.cmd, inquiry.size, buffer, &size);
  if (status)
    {
      DBG (DBG_error, "pie_do_inquiry: command returned status %s\n",
	   sane_strstatus (status));
    }
}

/* ---------------------- PIE IDENTIFY SCANNER ---------------------- */


static int
pie_identify_scanner (Pie_Device * dev, int sfd)
{
  char vendor[9];
  char product[0x11];
  char version[5];
  char *pp;
  int i = 0;
  unsigned char inquiry_block[256];

  DBG (DBG_proc, "identify_scanner\n");

  pie_do_inquiry (sfd, inquiry_block);	/* get inquiry */

  if (get_inquiry_periph_devtype (inquiry_block) != IN_periph_devtype_scanner)
    {
      return 1;
    }				/* no scanner */

  get_inquiry_vendor ((char *) inquiry_block, vendor);
  get_inquiry_product ((char *) inquiry_block, product);
  get_inquiry_version ((char *) inquiry_block, version);

  pp = &vendor[8];
  vendor[8] = ' ';
  while (*pp == ' ')
    {
      *pp-- = '\0';
    }

  pp = &product[0x10];
  product[0x10] = ' ';
  while (*pp == ' ')
    {
      *pp-- = '\0';
    }

  pp = &version[4];

  version[4] = ' ';
  while (*pp == ' ')
    {
      *pp-- = '\0';
    }

  DBG (DBG_info, "Found %s scanner %s version %s on device %s\n", vendor,
       product, version, dev->devicename);

  while (strncmp ("END_OF_LIST", scanner_str[2 * i], 11) != 0)	/* Now identify full supported scanners */
    {
      if (!strncmp (vendor, scanner_str[2 * i], strlen (scanner_str[2 * i])))
	{
	  if (!strncmp
	      (product, scanner_str[2 * i + 1],
	       strlen (scanner_str[2 * i + 1])))
	    {
	      DBG (DBG_info, "found supported scanner\n");

	      pie_get_inquiry_values (dev, inquiry_block);
	      return 0;
	    }
	}
      i++;
    }

  return 1;			/* NO SUPPORTED SCANNER: short inquiry-block and unknown scanner */
}


/* ------------------------------- GET SPEEDS ----------------------------- */

static void
pie_get_speeds (Pie_Device * dev)
{
  int speeds = dev->inquiry_scan_capability & INQ_CAP_SPEEDS;

  DBG (DBG_proc, "get_speeds\n");

  if (speeds == 3)
    {
      dev->speed_list[0] = strdup ("Normal");
      dev->speed_list[1] = strdup ("Fine");
      dev->speed_list[2] = strdup ("Pro");
      dev->speed_list[3] = NULL;
    }
  else
    {
      int i;
      char buf[2];

      buf[1] = '\0';

      for (i = 0; i < speeds; i++)
	{
	  buf[0] = '1' + i;
	  dev->speed_list[i] = strdup (buf);
	}

      dev->speed_list[i] = NULL;
    }
}

/* ------------------------------- GET HALFTONES ----------------------------- */

static void
pie_get_halftones (Pie_Device * dev, int sfd)
{
  int i;
  size_t size;
  SANE_Status status;
  unsigned char *data;
  unsigned char buffer[128];

  DBG (DBG_proc, "get_halftones\n");

  for (i = 0; i < dev->inquiry_halftones; i++)
    {
      size = 6;

      set_write_length (swrite.cmd, size);

      memcpy (buffer, swrite.cmd, swrite.size);

      data = buffer + swrite.size;
      memset (data, 0, size);

      set_command (data, READ_HALFTONE);
      set_data_length (data, 2);
      data[4] = i;

      status = sanei_scsi_cmd (sfd, buffer, swrite.size + size, NULL, NULL);
      if (status)
	{
	  DBG (DBG_error,
	       "pie_get_halftones: write command returned status %s\n",
	       sane_strstatus (status));
	}
      else
	{
	  /* now read the halftone data */
	  memset (buffer, '\0', sizeof buffer);	/* clear buffer */

	  size = 128;
	  set_read_length (sread.cmd, size);

	  DBG (DBG_info, "doing read\n");
	  status = sanei_scsi_cmd (sfd, sread.cmd, sread.size, buffer, &size);
	  if (status)
	    {
	      DBG (DBG_error,
		   "pie_get_halftones: read command returned status %s\n",
		   sane_strstatus (status));
	    }
	  else
	    {
	      unsigned char *s;

	      s = buffer + 8 + buffer[6] * buffer[7];

	      DBG (DBG_info, "halftone %d: %s\n", i, s);

	      dev->halftone_list[i] = strdup ((char *)s);
	    }
	}
    }
  dev->halftone_list[i] = NULL;
}

/* ------------------------------- GET CAL DATA ----------------------------- */

static void
pie_get_cal_info (Pie_Device * dev, int sfd)
{
  size_t size;
  SANE_Status status;
  unsigned char *data;
  unsigned char buffer[280];

  DBG (DBG_proc, "get_cal_info\n");

  if (!(dev->inquiry_scan_capability & INQ_CAP_EXT_CAL))
    return;

  size = 6;

  set_write_length (swrite.cmd, size);

  memcpy (buffer, swrite.cmd, swrite.size);

  data = buffer + swrite.size;
  memset (data, 0, size);

  set_command (data, READ_CAL_INFO);

  status = sanei_scsi_cmd (sfd, buffer, swrite.size + size, NULL, NULL);
  if (status)
    {
      DBG (DBG_error, "pie_get_cal_info: write command returned status %s\n",
	   sane_strstatus (status));
    }
  else
    {
      /* now read the cal data */
      memset (buffer, '\0', sizeof buffer);	/* clear buffer */

      size = 128;
      set_read_length (sread.cmd, size);

      DBG (DBG_info, "doing read\n");
      status = sanei_scsi_cmd (sfd, sread.cmd, sread.size, buffer, &size);
      if (status)
	{
	  DBG (DBG_error,
	       "pie_get_cal_info: read command returned status %s\n",
	       sane_strstatus (status));
	}
      else
	{
	  int i;

	  dev->cal_info_count = buffer[4];
	  dev->cal_info =
	    malloc (sizeof (struct Pie_cal_info) * dev->cal_info_count);

	  for (i = 0; i < dev->cal_info_count; i++)
	    {
	      dev->cal_info[i].cal_type = buffer[8 + i * buffer[5]];
	      dev->cal_info[i].send_bits = buffer[9 + i * buffer[5]];
	      dev->cal_info[i].receive_bits = buffer[10 + i * buffer[5]];
	      dev->cal_info[i].num_lines = buffer[11 + i * buffer[5]];
	      dev->cal_info[i].pixels_per_line =
		(buffer[13 + i * buffer[5]] << 8) + buffer[12 +
							   i * buffer[5]];

	      DBG (DBG_info2, "%02x %2d %2d %2d %d\n",
		   dev->cal_info[i].cal_type, dev->cal_info[i].send_bits,
		   dev->cal_info[i].receive_bits, dev->cal_info[i].num_lines,
		   dev->cal_info[i].pixels_per_line);
	    }
	}
    }
}

/* ------------------------------- ATTACH SCANNER ----------------------------- */

static SANE_Status
attach_scanner (const char *devicename, Pie_Device ** devp)
{
  Pie_Device *dev;
  int sfd;
  int bufsize;

  DBG (DBG_sane_proc, "attach_scanner: %s\n", devicename);

  for (dev = first_dev; dev; dev = dev->next)
    {
      if (strcmp (dev->sane.name, devicename) == 0)
	{
	  if (devp)
	    {
	      *devp = dev;
	    }
	  return SANE_STATUS_GOOD;
	}
    }

  dev = malloc (sizeof (*dev));
  if (!dev)
    {
      return SANE_STATUS_NO_MEM;
    }

  DBG (DBG_info, "attach_scanner: opening %s\n", devicename);

#ifdef HAVE_SANEI_SCSI_OPEN_EXTENDED
  bufsize = 16384;		/* 16KB */

  if (sanei_scsi_open_extended
      (devicename, &sfd, sense_handler, dev, &bufsize) != 0)
    {
      DBG (DBG_error, "attach_scanner: open failed\n");
      free (dev);
      return SANE_STATUS_INVAL;
    }

  if (bufsize < 4096)		/* < 4KB */
    {
      DBG (DBG_error,
	   "attach_scanner: sanei_scsi_open_extended returned too small scsi buffer (%d)\n",
	   bufsize);
      sanei_scsi_close (sfd);
      free (dev);
      return SANE_STATUS_NO_MEM;
    }

  DBG (DBG_info,
       "attach_scanner: sanei_scsi_open_extended returned scsi buffer size = %d\n",
       bufsize);
#else
  bufsize = sanei_scsi_max_request_size;

  if (sanei_scsi_open (devicename, &sfd, sense_handler, dev) != 0)
    {
      DBG (DBG_error, "attach_scanner: open failed\n");
      free (dev);

      return SANE_STATUS_INVAL;

    }
#endif

  pie_init (dev);		/* preset values in structure dev */

  dev->devicename = strdup (devicename);

  if (pie_identify_scanner (dev, sfd) != 0)
    {
      DBG (DBG_error, "attach_scanner: scanner-identification failed\n");
      sanei_scsi_close (sfd);
      free (dev);
      return SANE_STATUS_INVAL;
    }

  pie_get_halftones (dev, sfd);
  pie_get_cal_info (dev, sfd);
  pie_get_speeds (dev);

  dev->scan_mode_list[0] = COLOR_STR;
  dev->scan_mode_list[1] = GRAY_STR;
  dev->scan_mode_list[2] = LINEART_STR;
  dev->scan_mode_list[3] = HALFTONE_STR;
  dev->scan_mode_list[4] = 0;

  sanei_scsi_close (sfd);

  dev->sane.name = dev->devicename;
  dev->sane.vendor = dev->vendor;
  dev->sane.model = dev->product;
  dev->sane.type = "flatbed scanner";

  dev->x_range.min = SANE_FIX (0);
  dev->x_range.quant = SANE_FIX (0);
  dev->x_range.max = SANE_FIX (dev->inquiry_fb_width * MM_PER_INCH);

  dev->y_range.min = SANE_FIX (0);
  dev->y_range.quant = SANE_FIX (0);
  dev->y_range.max = SANE_FIX (dev->inquiry_fb_length * MM_PER_INCH);

  dev->dpi_range.min = SANE_FIX (25);
  dev->dpi_range.quant = SANE_FIX (1);
  dev->dpi_range.max =
    SANE_FIX (max (dev->inquiry_x_res, dev->inquiry_y_res));

  dev->shadow_range.min = SANE_FIX (0);
  dev->shadow_range.quant = SANE_FIX (1);
  dev->shadow_range.max = SANE_FIX (dev->inquiry_max_shadow);

  dev->highlight_range.min = SANE_FIX (dev->inquiry_min_highlight);
  dev->highlight_range.quant = SANE_FIX (1);
  dev->highlight_range.max = SANE_FIX (100);

  dev->exposure_range.min = SANE_FIX (dev->inquiry_min_exp);
  dev->exposure_range.quant = SANE_FIX (1);
  dev->exposure_range.max = SANE_FIX (dev->inquiry_max_exp);

#if 0
  dev->analog_gamma_range.min = SANE_FIX (1.0);
  dev->analog_gamma_range.quant = SANE_FIX (0.01);
  dev->analog_gamma_range.max = SANE_FIX (2.0);

#endif

  dev->next = first_dev;
  first_dev = dev;

  if (devp)
    {
      *devp = dev;
    }

  return SANE_STATUS_GOOD;
}

/* --------------------------- MAX STRING SIZE ---------------------------- */


static size_t
max_string_size (SANE_String_Const strings[])
{
  size_t size, max_size = 0;
  int i;

  for (i = 0; strings[i]; ++i)
    {
      size = strlen (strings[i]) + 1;
      if (size > max_size)
	{
	  max_size = size;
	}
    }

  return max_size;
}


/* --------------------------- INIT OPTIONS ------------------------------- */


static SANE_Status
init_options (Pie_Scanner * scanner)
{
  int i;

  DBG (DBG_sane_proc, "init_options\n");

  memset (scanner->opt, 0, sizeof (scanner->opt));
  memset (scanner->val, 0, sizeof (scanner->val));

  for (i = 0; i < NUM_OPTIONS; ++i)
    {
      scanner->opt[i].size = sizeof (SANE_Word);
      scanner->opt[i].cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
    }

  scanner->opt[OPT_NUM_OPTS].title = SANE_TITLE_NUM_OPTIONS;
  scanner->opt[OPT_NUM_OPTS].desc = SANE_DESC_NUM_OPTIONS;
  scanner->opt[OPT_NUM_OPTS].type = SANE_TYPE_INT;
  scanner->opt[OPT_NUM_OPTS].cap = SANE_CAP_SOFT_DETECT;
  scanner->val[OPT_NUM_OPTS].w = NUM_OPTIONS;

  /* "Mode" group: */
  scanner->opt[OPT_MODE_GROUP].title = "Scan Mode";
  scanner->opt[OPT_MODE_GROUP].desc = "";
  scanner->opt[OPT_MODE_GROUP].type = SANE_TYPE_GROUP;
  scanner->opt[OPT_MODE_GROUP].cap = 0;
  scanner->opt[OPT_MODE_GROUP].constraint_type = SANE_CONSTRAINT_NONE;

  /* scan mode */
  scanner->opt[OPT_MODE].name = SANE_NAME_SCAN_MODE;
  scanner->opt[OPT_MODE].title = SANE_TITLE_SCAN_MODE;
  scanner->opt[OPT_MODE].desc = SANE_DESC_SCAN_MODE;
  scanner->opt[OPT_MODE].type = SANE_TYPE_STRING;
  scanner->opt[OPT_MODE].size =
    max_string_size ((SANE_String_Const *) scanner->device->scan_mode_list);
  scanner->opt[OPT_MODE].constraint_type = SANE_CONSTRAINT_STRING_LIST;
  scanner->opt[OPT_MODE].constraint.string_list =
    (SANE_String_Const *) scanner->device->scan_mode_list;
  scanner->val[OPT_MODE].s =
    (SANE_Char *) strdup (scanner->device->scan_mode_list[0]);

  /* x-resolution */
  scanner->opt[OPT_RESOLUTION].name = SANE_NAME_SCAN_RESOLUTION;
  scanner->opt[OPT_RESOLUTION].title = SANE_TITLE_SCAN_RESOLUTION;
  scanner->opt[OPT_RESOLUTION].desc = SANE_DESC_SCAN_RESOLUTION;
  scanner->opt[OPT_RESOLUTION].type = SANE_TYPE_FIXED;
  scanner->opt[OPT_RESOLUTION].unit = SANE_UNIT_DPI;
  scanner->opt[OPT_RESOLUTION].constraint_type = SANE_CONSTRAINT_RANGE;
  scanner->opt[OPT_RESOLUTION].constraint.range = &scanner->device->dpi_range;
  scanner->val[OPT_RESOLUTION].w = 100 << SANE_FIXED_SCALE_SHIFT;

  /* "Geometry" group: */

  scanner->opt[OPT_GEOMETRY_GROUP].title = "Geometry";
  scanner->opt[OPT_GEOMETRY_GROUP].desc = "";
  scanner->opt[OPT_GEOMETRY_GROUP].type = SANE_TYPE_GROUP;
  scanner->opt[OPT_GEOMETRY_GROUP].cap = SANE_CAP_ADVANCED;
  scanner->opt[OPT_GEOMETRY_GROUP].constraint_type = SANE_CONSTRAINT_NONE;

  /* top-left x */
  scanner->opt[OPT_TL_X].name = SANE_NAME_SCAN_TL_X;
  scanner->opt[OPT_TL_X].title = SANE_TITLE_SCAN_TL_X;
  scanner->opt[OPT_TL_X].desc = SANE_DESC_SCAN_TL_X;
  scanner->opt[OPT_TL_X].type = SANE_TYPE_FIXED;
  scanner->opt[OPT_TL_X].unit = SANE_UNIT_MM;
  scanner->opt[OPT_TL_X].constraint_type = SANE_CONSTRAINT_RANGE;
  scanner->opt[OPT_TL_X].constraint.range = &(scanner->device->x_range);
  scanner->val[OPT_TL_X].w = 0;

  /* top-left y */
  scanner->opt[OPT_TL_Y].name = SANE_NAME_SCAN_TL_Y;
  scanner->opt[OPT_TL_Y].title = SANE_TITLE_SCAN_TL_Y;
  scanner->opt[OPT_TL_Y].desc = SANE_DESC_SCAN_TL_Y;
  scanner->opt[OPT_TL_Y].type = SANE_TYPE_FIXED;
  scanner->opt[OPT_TL_Y].unit = SANE_UNIT_MM;
  scanner->opt[OPT_TL_Y].constraint_type = SANE_CONSTRAINT_RANGE;
  scanner->opt[OPT_TL_Y].constraint.range = &(scanner->device->y_range);
  scanner->val[OPT_TL_Y].w = 0;

  /* bottom-right x */
  scanner->opt[OPT_BR_X].name = SANE_NAME_SCAN_BR_X;
  scanner->opt[OPT_BR_X].title = SANE_TITLE_SCAN_BR_X;
  scanner->opt[OPT_BR_X].desc = SANE_DESC_SCAN_BR_X;
  scanner->opt[OPT_BR_X].type = SANE_TYPE_FIXED;
  scanner->opt[OPT_BR_X].unit = SANE_UNIT_MM;
  scanner->opt[OPT_BR_X].constraint_type = SANE_CONSTRAINT_RANGE;
  scanner->opt[OPT_BR_X].constraint.range = &(scanner->device->x_range);
  scanner->val[OPT_BR_X].w = scanner->device->x_range.max;

  /* bottom-right y */
  scanner->opt[OPT_BR_Y].name = SANE_NAME_SCAN_BR_Y;
  scanner->opt[OPT_BR_Y].title = SANE_TITLE_SCAN_BR_Y;
  scanner->opt[OPT_BR_Y].desc = SANE_DESC_SCAN_BR_Y;
  scanner->opt[OPT_BR_Y].type = SANE_TYPE_FIXED;
  scanner->opt[OPT_BR_Y].unit = SANE_UNIT_MM;
  scanner->opt[OPT_BR_Y].constraint_type = SANE_CONSTRAINT_RANGE;
  scanner->opt[OPT_BR_Y].constraint.range = &(scanner->device->y_range);
  scanner->val[OPT_BR_Y].w = scanner->device->y_range.max;

  /* "enhancement" group: */

  scanner->opt[OPT_ENHANCEMENT_GROUP].title = "Enhancement";
  scanner->opt[OPT_ENHANCEMENT_GROUP].desc = "";
  scanner->opt[OPT_ENHANCEMENT_GROUP].type = SANE_TYPE_GROUP;
  scanner->opt[OPT_ENHANCEMENT_GROUP].cap = 0;
  scanner->opt[OPT_ENHANCEMENT_GROUP].constraint_type = SANE_CONSTRAINT_NONE;

  /* grayscale gamma vector */
  scanner->opt[OPT_GAMMA_VECTOR].name = SANE_NAME_GAMMA_VECTOR;
  scanner->opt[OPT_GAMMA_VECTOR].title = SANE_TITLE_GAMMA_VECTOR;
  scanner->opt[OPT_GAMMA_VECTOR].desc = SANE_DESC_GAMMA_VECTOR;
  scanner->opt[OPT_GAMMA_VECTOR].type = SANE_TYPE_INT;
  scanner->opt[OPT_GAMMA_VECTOR].unit = SANE_UNIT_NONE;
  scanner->opt[OPT_GAMMA_VECTOR].constraint_type = SANE_CONSTRAINT_RANGE;
  scanner->val[OPT_GAMMA_VECTOR].wa = scanner->gamma_table[0];
  scanner->opt[OPT_GAMMA_VECTOR].constraint.range = &scanner->gamma_range;
  scanner->opt[OPT_GAMMA_VECTOR].size =
    scanner->gamma_length * sizeof (SANE_Word);
  scanner->opt[OPT_GAMMA_VECTOR].cap |= SANE_CAP_INACTIVE;

  /* red gamma vector */
  scanner->opt[OPT_GAMMA_VECTOR_R].name = SANE_NAME_GAMMA_VECTOR_R;
  scanner->opt[OPT_GAMMA_VECTOR_R].title = SANE_TITLE_GAMMA_VECTOR_R;
  scanner->opt[OPT_GAMMA_VECTOR_R].desc = SANE_DESC_GAMMA_VECTOR_R;
  scanner->opt[OPT_GAMMA_VECTOR_R].type = SANE_TYPE_INT;
  scanner->opt[OPT_GAMMA_VECTOR_R].unit = SANE_UNIT_NONE;
  scanner->opt[OPT_GAMMA_VECTOR_R].constraint_type = SANE_CONSTRAINT_RANGE;
  scanner->val[OPT_GAMMA_VECTOR_R].wa = scanner->gamma_table[1];
  scanner->opt[OPT_GAMMA_VECTOR_R].constraint.range = &(scanner->gamma_range);
  scanner->opt[OPT_GAMMA_VECTOR_R].size =
    scanner->gamma_length * sizeof (SANE_Word);

  /* green gamma vector */
  scanner->opt[OPT_GAMMA_VECTOR_G].name = SANE_NAME_GAMMA_VECTOR_G;
  scanner->opt[OPT_GAMMA_VECTOR_G].title = SANE_TITLE_GAMMA_VECTOR_G;
  scanner->opt[OPT_GAMMA_VECTOR_G].desc = SANE_DESC_GAMMA_VECTOR_G;
  scanner->opt[OPT_GAMMA_VECTOR_G].type = SANE_TYPE_INT;
  scanner->opt[OPT_GAMMA_VECTOR_G].unit = SANE_UNIT_NONE;
  scanner->opt[OPT_GAMMA_VECTOR_G].constraint_type = SANE_CONSTRAINT_RANGE;
  scanner->val[OPT_GAMMA_VECTOR_G].wa = scanner->gamma_table[2];
  scanner->opt[OPT_GAMMA_VECTOR_G].constraint.range = &(scanner->gamma_range);
  scanner->opt[OPT_GAMMA_VECTOR_G].size =
    scanner->gamma_length * sizeof (SANE_Word);


  /* blue gamma vector */
  scanner->opt[OPT_GAMMA_VECTOR_B].name = SANE_NAME_GAMMA_VECTOR_B;
  scanner->opt[OPT_GAMMA_VECTOR_B].title = SANE_TITLE_GAMMA_VECTOR_B;
  scanner->opt[OPT_GAMMA_VECTOR_B].desc = SANE_DESC_GAMMA_VECTOR_B;
  scanner->opt[OPT_GAMMA_VECTOR_B].type = SANE_TYPE_INT;
  scanner->opt[OPT_GAMMA_VECTOR_B].unit = SANE_UNIT_NONE;
  scanner->opt[OPT_GAMMA_VECTOR_B].constraint_type = SANE_CONSTRAINT_RANGE;
  scanner->val[OPT_GAMMA_VECTOR_B].wa = scanner->gamma_table[3];
  scanner->opt[OPT_GAMMA_VECTOR_B].constraint.range = &(scanner->gamma_range);
  scanner->opt[OPT_GAMMA_VECTOR_B].size =
    scanner->gamma_length * sizeof (SANE_Word);

  /* halftone pattern */
  scanner->opt[OPT_HALFTONE_PATTERN].name = SANE_NAME_HALFTONE_PATTERN;
  scanner->opt[OPT_HALFTONE_PATTERN].title = SANE_TITLE_HALFTONE_PATTERN;
  scanner->opt[OPT_HALFTONE_PATTERN].desc = SANE_DESC_HALFTONE_PATTERN;
  scanner->opt[OPT_HALFTONE_PATTERN].type = SANE_TYPE_STRING;
  scanner->opt[OPT_HALFTONE_PATTERN].size =
    max_string_size ((SANE_String_Const *) scanner->device->halftone_list);
  scanner->opt[OPT_HALFTONE_PATTERN].constraint_type =
    SANE_CONSTRAINT_STRING_LIST;
  scanner->opt[OPT_HALFTONE_PATTERN].constraint.string_list =
    (SANE_String_Const *) scanner->device->halftone_list;
  scanner->val[OPT_HALFTONE_PATTERN].s =
    (SANE_Char *) strdup (scanner->device->halftone_list[0]);
  scanner->opt[OPT_HALFTONE_PATTERN].cap |= SANE_CAP_INACTIVE;

  /* speed */
  scanner->opt[OPT_SPEED].name = SANE_NAME_SCAN_SPEED;
  scanner->opt[OPT_SPEED].title = SANE_TITLE_SCAN_SPEED;
  scanner->opt[OPT_SPEED].desc = SANE_DESC_SCAN_SPEED;
  scanner->opt[OPT_SPEED].type = SANE_TYPE_STRING;
  scanner->opt[OPT_SPEED].size =
    max_string_size ((SANE_String_Const *) scanner->device->speed_list);
  scanner->opt[OPT_SPEED].constraint_type = SANE_CONSTRAINT_STRING_LIST;
  scanner->opt[OPT_SPEED].constraint.string_list =
    (SANE_String_Const *) scanner->device->speed_list;
  scanner->val[OPT_SPEED].s =
    (SANE_Char *) strdup (scanner->device->speed_list[0]);

  /* lineart threshold */
  scanner->opt[OPT_THRESHOLD].name = SANE_NAME_THRESHOLD;
  scanner->opt[OPT_THRESHOLD].title = SANE_TITLE_THRESHOLD;
  scanner->opt[OPT_THRESHOLD].desc = SANE_DESC_THRESHOLD;
  scanner->opt[OPT_THRESHOLD].type = SANE_TYPE_FIXED;
  scanner->opt[OPT_THRESHOLD].unit = SANE_UNIT_PERCENT;
  scanner->opt[OPT_THRESHOLD].constraint_type = SANE_CONSTRAINT_RANGE;
  scanner->opt[OPT_THRESHOLD].constraint.range = &percentage_range_100;
  scanner->val[OPT_THRESHOLD].w = SANE_FIX (50);
  scanner->opt[OPT_THRESHOLD].cap |= SANE_CAP_INACTIVE;

  /* "advanced" group: */

  scanner->opt[OPT_ADVANCED_GROUP].title = "Advanced";
  scanner->opt[OPT_ADVANCED_GROUP].desc = "";
  scanner->opt[OPT_ADVANCED_GROUP].type = SANE_TYPE_GROUP;
  scanner->opt[OPT_ADVANCED_GROUP].cap = SANE_CAP_ADVANCED;
  scanner->opt[OPT_ADVANCED_GROUP].constraint_type = SANE_CONSTRAINT_NONE;

  /* preview */
  scanner->opt[OPT_PREVIEW].name = SANE_NAME_PREVIEW;
  scanner->opt[OPT_PREVIEW].title = SANE_TITLE_PREVIEW;
  scanner->opt[OPT_PREVIEW].desc = SANE_DESC_PREVIEW;
  scanner->opt[OPT_PREVIEW].type = SANE_TYPE_BOOL;
  scanner->val[OPT_PREVIEW].w = SANE_FALSE;



  return SANE_STATUS_GOOD;
}


/*------------------------- PIE POWER SAVE -----------------------------*/

static SANE_Status
pie_power_save (Pie_Scanner * scanner, int time)
{
  unsigned char buffer[128];
  size_t size;
  SANE_Status status;
  unsigned char *data;

  DBG (DBG_proc, "pie_power_save: %d min\n", time);

  size = 6;

  set_write_length (swrite.cmd, size);

  memcpy (buffer, swrite.cmd, swrite.size);

  data = buffer + swrite.size;
  memset (data, 0, size);

  set_command (data, SET_POWER_SAVE_CONTROL);
  set_data_length (data, size - 4);
  data[4] = time & 0x7f;

  status =
    sanei_scsi_cmd (scanner->sfd, buffer, swrite.size + size, NULL, NULL);
  if (status)
    {
      DBG (DBG_error, "pie_power_save: write command returned status %s\n",
	   sane_strstatus (status));
    }

  return status;
}

/*------------------------- PIE SEND EXPOSURE ONE -----------------------------*/


static SANE_Status
pie_send_exposure_one (Pie_Scanner * scanner, int filter, int value)
{
  unsigned char buffer[128];
  size_t size;
  SANE_Status status;
  unsigned char *data;

  DBG (DBG_proc, "pie_send_exposure_one\n");

  size = 8;

  set_write_length (swrite.cmd, size);

  memcpy (buffer, swrite.cmd, swrite.size);

  data = buffer + swrite.size;
  memset (data, 0, size);

  set_command (data, SET_EXP_TIME);
  set_data_length (data, size - 4);

  data[4] = filter;

  set_data (data, 6, (int) value, 2);

  status =
    sanei_scsi_cmd (scanner->sfd, buffer, swrite.size + size, NULL, NULL);
  if (status)
    {
      DBG (DBG_error,
	   "pie_send_exposure_one: write command returned status %s\n",
	   sane_strstatus (status));
    }

  return status;
}

/*------------------------- PIE SEND EXPOSURE -----------------------------*/

static SANE_Status
pie_send_exposure (Pie_Scanner * scanner)
{
  SANE_Status status;

  DBG (DBG_proc, "pie_send_exposure\n");

  status = pie_send_exposure_one (scanner, FILTER_RED, 100);
  if (status)
    return status;

  status = pie_send_exposure_one (scanner, FILTER_GREEN, 100);
  if (status)
    return status;

  status = pie_send_exposure_one (scanner, FILTER_BLUE, 100);
  if (status)
    return status;

  return SANE_STATUS_GOOD;
}


/*------------------------- PIE SEND HIGHLIGHT/SHADOW ONE -----------------------------*/

static SANE_Status
pie_send_highlight_shadow_one (Pie_Scanner * scanner, int filter,
			       int highlight, int shadow)
{
  unsigned char buffer[128];
  size_t size;
  SANE_Status status;
  unsigned char *data;

  DBG (DBG_proc, "pie_send_highlight_shadow_one\n");

  size = 8;

  set_write_length (swrite.cmd, size);

  memcpy (buffer, swrite.cmd, swrite.size);

  data = buffer + swrite.size;
  memset (data, 0, size);

  set_command (data, SET_EXP_TIME);
  set_data_length (data, size - 4);

  data[4] = filter;

  data[6] = highlight;
  data[7] = shadow;

  status =
    sanei_scsi_cmd (scanner->sfd, buffer, swrite.size + size, NULL, NULL);
  if (status)
    {
      DBG (DBG_error,
	   "pie_send_highlight_shadow_one: write command returned status %s\n",
	   sane_strstatus (status));
    }

  return status;
}

/*------------------------- PIE SEND HIGHLIGHT/SHADOW -----------------------------*/

static SANE_Status
pie_send_highlight_shadow (Pie_Scanner * scanner)
{
  SANE_Status status;

  DBG (DBG_proc, "pie_send_highlight_shadow\n");

  status = pie_send_highlight_shadow_one (scanner, FILTER_RED, 100, 0);
  if (status)
    return status;

  status = pie_send_highlight_shadow_one (scanner, FILTER_GREEN, 100, 0);
  if (status)
    return status;

  status = pie_send_highlight_shadow_one (scanner, FILTER_BLUE, 100, 0);
  if (status)
    return status;

  return SANE_STATUS_GOOD;
}

/*------------------------- PIE PERFORM CAL ----------------------------*/

static SANE_Status
pie_perform_cal (Pie_Scanner * scanner, int cal_index)
{
  long *red_result;
  long *green_result;
  long *blue_result;
  long *neutral_result;
  long *result = NULL;
  int rcv_length, send_length;
  int rcv_lines, rcv_bits, send_bits;
  int pixels_per_line;
  int i;
  unsigned char *rcv_buffer, *rcv_ptr;
  unsigned char *send_buffer, *send_ptr;
  size_t size;
  int fullscale;
  int cal_limit;
  int k;
  int filter;
  SANE_Status status;

  DBG (DBG_proc, "pie_perform_cal\n");

  pixels_per_line = scanner->device->cal_info[cal_index].pixels_per_line;
  rcv_length = pixels_per_line;
  send_length = pixels_per_line;

  rcv_bits = scanner->device->cal_info[cal_index].receive_bits;
  if (rcv_bits > 8)
    rcv_length *= 2;		/* 2 bytes / sample */

  send_bits = scanner->device->cal_info[cal_index].send_bits;
  if (send_bits > 8)
    send_length *= 2;		/* 2 bytes / sample */

  rcv_lines = scanner->device->cal_info[cal_index].num_lines;

  send_length += 2;		/* space for filter at start */

  if (scanner->colormode == RGB)
    {
      rcv_lines *= 3;
      send_length *= 3;
      rcv_length += 2;		/* 2 bytes for index at front of data (only in RGB??) */
    }

  send_length += 4;		/* space for header at start of data */

  /* allocate buffers for the receive data, the result buffers, and for the send data */
  rcv_buffer = (unsigned char *) malloc (rcv_length);

  red_result = (long *) calloc (pixels_per_line, sizeof (long));
  green_result = (long *) calloc (pixels_per_line, sizeof (long));
  blue_result = (long *) calloc (pixels_per_line, sizeof (long));
  neutral_result = (long *) calloc (pixels_per_line, sizeof (long));

  if (!rcv_buffer || !red_result || !green_result || !blue_result
      || !neutral_result)
    {
      /* at least one malloc failed, so free all buffers (free accepts NULL) */
      free (rcv_buffer);
      free (red_result);
      free (green_result);
      free (blue_result);
      free (neutral_result);
      return SANE_STATUS_NO_MEM;
    }

  /* read the cal data a line at a time, and accumulate into the result arrays */
  while (rcv_lines--)
    {
      /* TUR */
      status = pie_wait_scanner (scanner);
      if (status)
	{
	  free (rcv_buffer);
	  free (red_result);
	  free (green_result);
	  free (blue_result);
	  free (neutral_result);
	  return status;
	}

      set_read_length (sread.cmd, 1);
      size = rcv_length;

      DBG (DBG_info, "pie_perform_cal: reading 1 line (%lu bytes)\n", (u_long) size);

      status =
	sanei_scsi_cmd (scanner->sfd, sread.cmd, sread.size, rcv_buffer,
			&size);

      if (status)
	{
	  DBG (DBG_error,
	       "pie_perform_cal: read command returned status %s\n",
	       sane_strstatus (status));
	  free (rcv_buffer);
	  free (red_result);
	  free (green_result);
	  free (blue_result);
	  free (neutral_result);
	  return status;
	}

      DBG_DUMP (DBG_dump, rcv_buffer, 32);

      /* which result buffer does this line belong to? */
      if (scanner->colormode == RGB)
	{
	  if (*rcv_buffer == 'R')
	    result = red_result;
	  else if (*rcv_buffer == 'G')
	    result = green_result;
	  else if (*rcv_buffer == 'B')
	    result = blue_result;
	  else if (*rcv_buffer == 'N')
	    result = neutral_result;
	  else
	    {
	      DBG (DBG_error, "pie_perform_cal: invalid index byte (%02x)\n",
		   *rcv_buffer);
	      DBG_DUMP (DBG_error, rcv_buffer, 32);
	      free (rcv_buffer);
	      free (red_result);
	      free (green_result);
	      free (blue_result);
	      free (neutral_result);
	      return SANE_STATUS_INVAL;
	    }
	  rcv_ptr = rcv_buffer + 2;
	}
      else
	{
	  /* monochrome - no bytes indicating filter here */
	  result = neutral_result;
	  rcv_ptr = rcv_buffer;
	}

      /* now add the values in this line to the result array */
      for (i = 0; i < pixels_per_line; i++)
	{
	  result[i] += *rcv_ptr++;
	  if (rcv_bits > 8)
	    {
	      result[i] += (*rcv_ptr++) << 8;
	    }
	}
    }

  /* got all the cal data, now process it ready to send back */
  free (rcv_buffer);
  send_buffer = (unsigned char *) malloc (send_length + swrite.size);

  if (!send_buffer)
    {
      free (red_result);
      free (green_result);
      free (blue_result);
      free (neutral_result);
      return SANE_STATUS_NO_MEM;
    }

  rcv_lines = scanner->device->cal_info[cal_index].num_lines;
  fullscale = (1 << rcv_bits) - 1;
  cal_limit = fullscale / (1 << scanner->device->inquiry_cal_eqn);
  k = (1 << scanner->device->inquiry_cal_eqn) - 1;

  /* set up scsi command and data */
  size = send_length;

  memcpy (send_buffer, swrite.cmd, swrite.size);
  set_write_length (send_buffer, size);

  set_command (send_buffer + swrite.size, SEND_CAL_DATA);
  set_data_length (send_buffer + swrite.size, size - 4);

  send_ptr = send_buffer + swrite.size + 4;

  for (filter = FILTER_NEUTRAL; filter <= FILTER_BLUE; filter <<= 1)
    {

      /* only send data for filter we expect to send */
      if (!(filter & scanner->cal_filter))
	continue;

      set_data (send_ptr, 0, filter, 2);
      send_ptr += 2;

      if (scanner->colormode == RGB)
	{
	  switch (filter)
	    {
	    case FILTER_RED:
	      result = red_result;
	      break;

	    case FILTER_GREEN:
	      result = green_result;
	      break;

	    case FILTER_BLUE:
	      result = blue_result;
	      break;

	    case FILTER_NEUTRAL:
	      result = neutral_result;
	      break;
	    }
	}
      else
	result = neutral_result;

      /* for each pixel */
      for (i = 0; i < pixels_per_line; i++)
	{
	  long x;

	  /* make average */
	  x = result[i] / rcv_lines;

	  /* ensure not overflowed */
	  if (x > fullscale)
	    x = fullscale;

	  /* process according to required calibration equation */
	  if (scanner->device->inquiry_cal_eqn)
	    {
	      if (x <= cal_limit)
		x = fullscale;
	      else
		x = ((fullscale - x) * fullscale) / (x * k);
	    }

	  if (rcv_bits > send_bits)
	    x >>= (rcv_bits - send_bits);
	  else if (send_bits > rcv_bits)
	    x <<= (send_bits - rcv_bits);

	  /* put result into send buffer */
	  *send_ptr++ = x;
	  if (send_bits > 8)
	    *send_ptr++ = x >> 8;
	}
    }

  /* now send the data back to scanner */

  /* TUR */
  status = pie_wait_scanner (scanner);
  if (status)
    {
      free (red_result);
      free (green_result);
      free (blue_result);
      free (neutral_result);
      free (send_buffer);
      return status;
    }

  DBG (DBG_info, "pie_perform_cal: sending cal data (%lu bytes)\n", (u_long) size);
  DBG_DUMP (DBG_dump, send_buffer, 64);

  status =
    sanei_scsi_cmd (scanner->sfd, send_buffer, swrite.size + size, NULL,
		    NULL);
  if (status)
    {
      DBG (DBG_error, "pie_perform_cal: write command returned status %s\n",
	   sane_strstatus (status));
      free (red_result);
      free (green_result);
      free (blue_result);
      free (neutral_result);
      free (send_buffer);
      return status;
    }

  free (red_result);
  free (green_result);
  free (blue_result);
  free (neutral_result);
  free (send_buffer);

  return SANE_STATUS_GOOD;
}

/*------------------------- PIE DO CAL -----------------------------*/

static SANE_Status
pie_do_cal (Pie_Scanner * scanner)
{
  SANE_Status status;
  int cal_index;

  DBG (DBG_proc, "pie_do_cal\n");

  if (scanner->device->inquiry_scan_capability & INQ_CAP_EXT_CAL)
    {
      for (cal_index = 0; cal_index < scanner->device->cal_info_count;
	   cal_index++)
	if (scanner->device->cal_info[cal_index].cal_type ==
	    scanner->cal_mode)
	  {
	    status = pie_perform_cal (scanner, cal_index);
	    if (status != SANE_STATUS_GOOD)
	      return status;
	  }
    }

  return SANE_STATUS_GOOD;
}

/*------------------------- PIE DWNLD GAMMA ONE -----------------------------*/

static SANE_Status
pie_dwnld_gamma_one (Pie_Scanner * scanner, int filter, SANE_Int * table)
{
  unsigned char *buffer;
  size_t size;
  SANE_Status status;
  unsigned char *data;
  int i;

  DBG (DBG_proc, "pie_dwnld_gamma_one\n");

  /* TUR */
  status = pie_wait_scanner (scanner);
  if (status)
    {
      return status;
    }

  if (scanner->device->inquiry_gamma_bits > 8)
    size = scanner->gamma_length * 2 + 6;
  else
    size = scanner->gamma_length + 6;

  buffer = malloc (size + swrite.size);
  if (!buffer)
    return SANE_STATUS_NO_MEM;

  set_write_length (swrite.cmd, size);

  memcpy (buffer, swrite.cmd, swrite.size);

  data = buffer + swrite.size;
  memset (data, 0, size);

  set_command (data, DWNLD_GAMMA_TABLE);
  set_data_length (data, size - 4);

  data[4] = filter;

  for (i = 0; i < scanner->gamma_length; i++)
    {
      if (scanner->device->inquiry_gamma_bits > 8)
	{
	  set_data (data, 6 + 2 * i, table ? table[i] : i, 2);
	}
      else
	{
	  set_data (data, 6 + i, table ? table[i] : i, 1);
	}
    }

  DBG_DUMP (DBG_dump, data, 128);

  status =
    sanei_scsi_cmd (scanner->sfd, buffer, swrite.size + size, NULL, NULL);
  if (status)
    {
      DBG (DBG_error,
	   "pie_dwnld_gamma_one: write command returned status %s\n",
	   sane_strstatus (status));
    }

  free (buffer);

  return status;
}

/*------------------------- PIE DWNLD GAMMA -----------------------------*/

static SANE_Status
pie_dwnld_gamma (Pie_Scanner * scanner)
{
  SANE_Status status;

  DBG (DBG_proc, "pie_dwnld_gamma\n");

  if (scanner->colormode == RGB)
    {
      status =
	pie_dwnld_gamma_one (scanner, FILTER_RED, scanner->gamma_table[1]);
      if (status)
	return status;


      status =
	pie_dwnld_gamma_one (scanner, FILTER_GREEN, scanner->gamma_table[2]);
      if (status)
	return status;

      status =
	pie_dwnld_gamma_one (scanner, FILTER_BLUE, scanner->gamma_table[3]);
      if (status)
	return status;
    }
  else
    {
      SANE_Int *table;

      /* if lineart or half tone, force gamma to be one to one by passing NULL */
      if (scanner->colormode == GRAYSCALE)
	table = scanner->gamma_table[0];
      else
	table = NULL;

      status = pie_dwnld_gamma_one (scanner, FILTER_GREEN, table);
      if (status)
	return status;
    }

  usleep (DOWNLOAD_GAMMA_WAIT_TIME);

  return SANE_STATUS_GOOD;
}

/*------------------------- PIE SET WINDOW -----------------------------*/

static SANE_Status
pie_set_window (Pie_Scanner * scanner)
{
  unsigned char buffer[128];
  size_t size;
  SANE_Status status;
  unsigned char *data;
  double x, dpmm;

  DBG (DBG_proc, "pie_set_window\n");

  size = 14;

  set_write_length (swrite.cmd, size);

  memcpy (buffer, swrite.cmd, swrite.size);

  data = buffer + swrite.size;
  memset (data, 0, size);

  set_command (data, SET_SCAN_FRAME);
  set_data_length (data, size - 4);

  data[4] = 0x80;
  if (scanner->colormode == HALFTONE)
    data[4] |= 0x40;

  dpmm = (double) scanner->device->inquiry_pixel_resolution / MM_PER_INCH;

  x = SANE_UNFIX (scanner->val[OPT_TL_X].w) * dpmm;
  set_data (data, 6, (int) x, 2);
  DBG (DBG_info, "TL_X: %d\n", (int) x);

  x = SANE_UNFIX (scanner->val[OPT_TL_Y].w) * dpmm;
  set_data (data, 8, (int) x, 2);
  DBG (DBG_info, "TL_Y: %d\n", (int) x);

  x = SANE_UNFIX (scanner->val[OPT_BR_X].w) * dpmm;
  set_data (data, 10, (int) x, 2);
  DBG (DBG_info, "BR_X: %d\n", (int) x);

  x = SANE_UNFIX (scanner->val[OPT_BR_Y].w) * dpmm;
  set_data (data, 12, (int) x, 2);
  DBG (DBG_info, "BR_Y: %d\n", (int) x);

  status =
    sanei_scsi_cmd (scanner->sfd, buffer, swrite.size + size, NULL, NULL);
  if (status)
    {
      DBG (DBG_error, "pie_set_window: write command returned status %s\n",
	   sane_strstatus (status));
    }

  return status;
}


/*------------------------- PIE MODE SELECT -----------------------------*/

static SANE_Status
pie_mode_select (Pie_Scanner * scanner)
{

  SANE_Status status;
  unsigned char buffer[128];
  size_t size;
  unsigned char *data;
  int i;

  DBG (DBG_proc, "pie_mode_select\n");

  size = 14;

  set_mode_length (smode.cmd, size);

  memcpy (buffer, smode.cmd, smode.size);

  data = buffer + smode.size;
  memset (data, 0, size);

  /* size of data */
  data[1] = size - 2;

  /* set resolution required */
  set_data (data, 2, scanner->resolution, 2);

  /* set color filter and color depth */
  switch (scanner->colormode)
    {
    case RGB:
      if (scanner->device->inquiry_filters & INQ_ONE_PASS_COLOR)
	{
	  data[4] = INQ_ONE_PASS_COLOR;
	  scanner->cal_filter = FILTER_RED | FILTER_GREEN | FILTER_BLUE;
	}
      else
	{
	  DBG (DBG_error,
	       "pie_mode_select: support for multipass color not yet implemented\n");
	  return SANE_STATUS_UNSUPPORTED;
	}
      data[5] = INQ_COLOR_DEPTH_8;
      break;

    case GRAYSCALE:
    case LINEART:
    case HALFTONE:
      /* choose which filter to use for monochrome mode */
      if (scanner->device->inquiry_filters & INQ_FILTER_NEUTRAL)
	{
	  data[4] = FILTER_NEUTRAL;
	  scanner->cal_filter = FILTER_NEUTRAL;
	}
      else if (scanner->device->inquiry_filters & INQ_FILTER_GREEN)
	{
	  data[4] = FILTER_GREEN;
	  scanner->cal_filter = FILTER_GREEN;
	}
      else if (scanner->device->inquiry_filters & INQ_FILTER_RED)
	{
	  data[4] = FILTER_RED;
	  scanner->cal_filter = FILTER_RED;
	}
      else if (scanner->device->inquiry_filters & INQ_FILTER_BLUE)
	{
	  data[4] = FILTER_BLUE;
	  scanner->cal_filter = FILTER_BLUE;
	}
      else
	{
	  DBG (DBG_error,
	       "pie_mode_select: scanner doesn't appear to support monochrome\n");
	  return SANE_STATUS_UNSUPPORTED;
	}

      if (scanner->colormode == GRAYSCALE)
	data[5] = INQ_COLOR_DEPTH_8;
      else
	data[5] = INQ_COLOR_DEPTH_1;
      break;
    }

  /* choose color packing method */
  if (scanner->device->inquiry_color_format & INQ_COLOR_FORMAT_LINE)
    data[6] = INQ_COLOR_FORMAT_LINE;
  else if (scanner->device->inquiry_color_format & INQ_COLOR_FORMAT_INDEX)
    data[6] = INQ_COLOR_FORMAT_INDEX;
  else
    {
      DBG (DBG_error,
	   "pie_mode_select: support for pixel packing not yet implemented\n");
      return SANE_STATUS_UNSUPPORTED;
    }

  /* choose data format */
  if (scanner->device->inquiry_image_format & INQ_IMG_FMT_INTEL)
    data[8] = INQ_IMG_FMT_INTEL;
  else
    {
      DBG (DBG_error,
	   "pie_mode_select: support for Motorola format not yet implemented\n");
      return SANE_STATUS_UNSUPPORTED;
    }

  /* set required speed */
  i = 0;
  while (scanner->device->speed_list[i] != NULL)
    {
      if (strcmp (scanner->device->speed_list[i], scanner->val[OPT_SPEED].s)
	  == 0)
	break;
      i++;
    }

  if (scanner->device->speed_list[i] == NULL)
    data[9] = 0;
  else
    data[9] = i;

  scanner->cal_mode = CAL_MODE_FLATBED;

  /* if preview supported, ask for preview, limit resolution to max for fast preview */
  if (scanner->val[OPT_PREVIEW].w
      && (scanner->device->inquiry_scan_capability & INQ_CAP_FAST_PREVIEW))
    {
      DBG (DBG_info, "pie_mode_select: setting preview\n");
      scanner->cal_mode |= CAL_MODE_PREVIEW;
      data[9] |= INQ_CAP_FAST_PREVIEW;
      data[9] &= ~INQ_CAP_SPEEDS;
      if (scanner->resolution > scanner->device->inquiry_fast_preview_res)
	set_data (data, 2, scanner->device->inquiry_fast_preview_res, 2);
    }


  /* set required halftone pattern */
  i = 0;
  while (scanner->device->halftone_list[i] != NULL)
    {
      if (strcmp
	  (scanner->device->halftone_list[i],
	   scanner->val[OPT_HALFTONE_PATTERN].s) == 0)
	break;
      i++;
    }

  if (scanner->device->halftone_list[i] == NULL)
    data[12] = 0;		/* halftone pattern */
  else
    data[12] = i;

  data[13] = SANE_UNFIX (scanner->val[OPT_THRESHOLD].w) * 255 / 100;	/* lineart threshold */

  DBG (DBG_info, "pie_mode_select: speed %02x\n", data[9]);
  DBG (DBG_info, "pie_mode_select: halftone %d\n", data[12]);
  DBG (DBG_info, "pie_mode_select: threshold %02x\n", data[13]);

  status =
    sanei_scsi_cmd (scanner->sfd, buffer, smode.size + size, NULL, NULL);
  if (status)
    {
      DBG (DBG_error, "pie_mode_select: write command returned status %s\n",
	   sane_strstatus (status));
    }

  return status;
}


/*------------------------- PIE SCAN -----------------------------*/

static SANE_Status
pie_scan (Pie_Scanner * scanner, int start)
{
  SANE_Status status;

  DBG (DBG_proc, "pie_scan\n");

  /* TUR */
  status = pie_wait_scanner (scanner);
  if (status)
    {
      return status;
    }

  set_scan_cmd (scan.cmd, start);

  do
    {
      status = sanei_scsi_cmd (scanner->sfd, scan.cmd, scan.size, NULL, NULL);
      if (status)
	{
	  DBG (DBG_error, "pie_scan: write command returned status %s\n",
	       sane_strstatus (status));
	  usleep (SCAN_WARMUP_WAIT_TIME);
	}
    }
  while (start && status);

  usleep (SCAN_WAIT_TIME);

  return status;
}


/* --------------------------------------- PIE WAIT SCANNER -------------------------- */


static SANE_Status
pie_wait_scanner (Pie_Scanner * scanner)
{
  SANE_Status status;
  int cnt = 0;

  DBG (DBG_proc, "wait_scanner\n");

  do
    {
      if (cnt > 100)		/* maximal 100 * 0.5 sec = 50 sec */
	{
	  DBG (DBG_warning, "scanner does not get ready\n");
	  return -1;
	}
      /* test unit ready */
      status =
	sanei_scsi_cmd (scanner->sfd, test_unit_ready.cmd,
			test_unit_ready.size, NULL, NULL);
      cnt++;

      if (status)
	{
	  if (cnt == 1)
	    {
	      DBG (DBG_info2, "scanner reports %s, waiting ...\n",
		   sane_strstatus (status));
	    }

	  usleep (TUR_WAIT_TIME);
	}
    }
  while (status != SANE_STATUS_GOOD);

  DBG (DBG_info, "scanner ready\n");


  return status;
}


/* -------------------------------------- PIE GET PARAMS -------------------------- */


static SANE_Status
pie_get_params (Pie_Scanner * scanner)
{
  SANE_Status status;
  size_t size;
  unsigned char buffer[128];

  DBG (DBG_proc, "pie_get_params\n");

  status = pie_wait_scanner (scanner);
  if (status)
    return status;

  if (scanner->device->inquiry_image_format & INQ_IMG_FMT_OKLINE)
    size = 16;
  else

    size = 14;

  set_param_length (param.cmd, size);

  status =
    sanei_scsi_cmd (scanner->sfd, param.cmd, param.size, buffer, &size);

  if (status)
    {
      DBG (DBG_error, "pie_get_params: command returned status %s\n",
	   sane_strstatus (status));
    }
  else
    {
      DBG (DBG_info, "Scan Width:  %d\n", get_param_scan_width (buffer));
      DBG (DBG_info, "Scan Lines:  %d\n", get_param_scan_lines (buffer));
      DBG (DBG_info, "Scan bytes:  %d\n", get_param_scan_bytes (buffer));

      DBG (DBG_info, "Offset 1:    %d\n",
	   get_param_scan_filter_offset1 (buffer));
      DBG (DBG_info, "Offset 2:    %d\n",
	   get_param_scan_filter_offset2 (buffer));
      DBG (DBG_info, "Scan period: %d\n", get_param_scan_period (buffer));
      DBG (DBG_info, "Xfer rate:   %d\n", get_param_scsi_xfer_rate (buffer));
      if (scanner->device->inquiry_image_format & INQ_IMG_FMT_OKLINE)
	DBG (DBG_info, "Avail lines: %d\n",
	     get_param_scan_available_lines (buffer));

      scanner->filter_offset1 = get_param_scan_filter_offset1 (buffer);
      scanner->filter_offset2 = get_param_scan_filter_offset2 (buffer);
      scanner->bytes_per_line = get_param_scan_bytes (buffer);

      scanner->params.pixels_per_line = get_param_scan_width (buffer);
      scanner->params.lines = get_param_scan_lines (buffer);

      switch (scanner->colormode)
	{
	case RGB:
	  scanner->params.format = SANE_FRAME_RGB;
	  scanner->params.depth = 8;
	  scanner->params.bytes_per_line = 3 * get_param_scan_bytes (buffer);
	  break;

	case GRAYSCALE:
	  scanner->params.format = SANE_FRAME_GRAY;
	  scanner->params.depth = 8;
	  scanner->params.bytes_per_line = get_param_scan_bytes (buffer);
	  break;

	case HALFTONE:
	case LINEART:
	  scanner->params.format = SANE_FRAME_GRAY;
	  scanner->params.depth = 1;
	  scanner->params.bytes_per_line = get_param_scan_bytes (buffer);
	  break;
	}

      scanner->params.last_frame = 0;
    }

  return status;
}


/* -------------------------------------- PIE GRAB SCANNER -------------------------- */


static SANE_Status
pie_grab_scanner (Pie_Scanner * scanner)
{
  SANE_Status status;

  DBG (DBG_proc, "grab_scanner\n");


  status = pie_wait_scanner (scanner);
  if (status)
    return status;

  status =
    sanei_scsi_cmd (scanner->sfd, reserve_unit.cmd, reserve_unit.size, NULL,
		    NULL);


  if (status)
    {
      DBG (DBG_error, "pie_grab_scanner: command returned status %s\n",
	   sane_strstatus (status));
    }
  else
    {
      DBG (DBG_info, "scanner reserved\n");
    }

  return status;
}


/* ------------------------------------ PIE GIVE SCANNER -------------------------- */


static SANE_Status
pie_give_scanner (Pie_Scanner * scanner)
{
  SANE_Status status;

  DBG (DBG_info2, "trying to release scanner ...\n");

  status =
    sanei_scsi_cmd (scanner->sfd, release_unit.cmd, release_unit.size, NULL,
		    NULL);
  if (status)
    {
      DBG (DBG_error, "pie_give_scanner: command returned status %s\n",
	   sane_strstatus (status));
    }
  else
    {
      DBG (DBG_info, "scanner released\n");
    }
  return status;
}


/* ------------------- PIE READER PROCESS INDEXED ------------------- */

static int
pie_reader_process_indexed (Pie_Scanner * scanner, FILE * fp)
{
  int status;
  int lines;
  unsigned char *buffer, *reorder = NULL;
  unsigned char *red_buffer = NULL, *green_buffer = NULL;
  unsigned char *red_in = NULL, *red_out = NULL;
  unsigned char *green_in = NULL, *green_out = NULL;
  int red_size = 0, green_size = 0;
  int bytes_per_line;
  int red_count = 0, green_count = 0;

  size_t size;

  DBG (DBG_read, "reading %d lines of %d bytes/line (indexed)\n",
       scanner->params.lines, scanner->params.bytes_per_line);

  lines = scanner->params.lines;
  bytes_per_line = scanner->bytes_per_line;

  /* allocate receive buffer */
  buffer = malloc (bytes_per_line + 2);
  if (!buffer)
    {
      return SANE_STATUS_NO_MEM;
    }

  /* allocate deskew buffers for RGB mode */
  if (scanner->colormode == RGB)
    {
      lines *= 3;

      red_size = bytes_per_line * (scanner->filter_offset1 +
				   scanner->filter_offset2 + 2);
      green_size = bytes_per_line * (scanner->filter_offset2 + 2);

      DBG (DBG_info2,
	   "pie_reader_process_indexed: alloc %d lines (%d bytes) for red buffer\n",
	   red_size / bytes_per_line, red_size);
      DBG (DBG_info2,
	   "pie_reader_process_indexed: alloc %d lines (%d bytes) for green buffer\n",
	   green_size / bytes_per_line, green_size);

      reorder = malloc (scanner->params.bytes_per_line);
      red_buffer = malloc (red_size);
      green_buffer = malloc (green_size);

      if (!reorder || !red_buffer || !green_buffer)
	{
	  free (buffer);
	  free (reorder);
	  free (red_buffer);
	  free (green_buffer);
	  return SANE_STATUS_NO_MEM;
	}

      red_in = red_out = red_buffer;
      green_in = green_out = green_buffer;
    }

  while (lines--)
    {
      set_read_length (sread.cmd, 1);
      size = bytes_per_line + 2;

      do
	{
	  status =
	    sanei_scsi_cmd (scanner->sfd, sread.cmd, sread.size, buffer,
			    &size);
	}
      while (status);

      DBG_DUMP (DBG_dump, buffer, 64);

      if (scanner->colormode == RGB)
	{
	  /* we're assuming that we get red before green before blue here */
	  switch (*buffer)
	    {
	    case 'R':
	      /* copy to red buffer */
	      memcpy (red_in, buffer + 2, bytes_per_line);

	      /* advance in pointer, and check for wrap */
	      red_in += bytes_per_line;
	      if (red_in >= (red_buffer + red_size))
		red_in = red_buffer;

	      /* increment red line count */
	      red_count++;
	      DBG (DBG_info2,
		   "pie_reader_process_indexed: got a red line (%d)\n",
		   red_count);
	      break;

	    case 'G':
	      /* copy to green buffer */
	      memcpy (green_in, buffer + 2, bytes_per_line);

	      /* advance in pointer, and check for wrap */
	      green_in += bytes_per_line;
	      if (green_in >= (green_buffer + green_size))
		green_in = green_buffer;

	      /* increment green line count */
	      green_count++;
	      DBG (DBG_info2,
		   "pie_reader_process_indexed: got a green line (%d)\n",
		   green_count);
	      break;

	    case 'B':
	      /* check we actually have red and green data available */
	      if (!red_count || !green_count)
		{
		  DBG (DBG_error,
		       "pie_reader_process_indexed: deskew buffer empty (%d %d)\n",
		       red_count, green_count);
		  return SANE_STATUS_INVAL;
		}
	      red_count--;
	      green_count--;

	      DBG (DBG_info2,
		   "pie_reader_process_indexed: got a blue line\n");

	      {
		int i;
		unsigned char *red, *green, *blue, *dest;

		/* now pack the pixels lines into RGB format */
		dest = reorder;
		red = red_out;
		green = green_out;
		blue = buffer + 2;

		for (i = bytes_per_line; i > 0; i--)
		  {
		    *dest++ = *red++;
		    *dest++ = *green++;
		    *dest++ = *blue++;
		  }
		fwrite (reorder, 1, scanner->params.bytes_per_line, fp);

		/* advance out pointers, and check for wrap */
		red_out += bytes_per_line;
		if (red_out >= (red_buffer + red_size))
		  red_out = red_buffer;
		green_out += bytes_per_line;
		if (green_out >= (green_buffer + green_size))
		  green_out = green_buffer;
	      }
	      break;

	    default:
	      DBG (DBG_error,
		   "pie_reader_process_indexed: bad filter index\n");
	    }
	}
      else
	{
	  DBG (DBG_info2,
	       "pie_reader_process_indexed: got a line (%lu bytes)\n", (u_long) size);

	  /* just send the data on, assume filter bytes not present as per calibration case */
	  fwrite (buffer, 1, scanner->params.bytes_per_line, fp);
	}
    }

  free (buffer);
  free (reorder);
  free (red_buffer);
  free (green_buffer);
  return 0;
}

/* --------------------------------- PIE READER PROCESS ------------------------ */

static int
pie_reader_process (Pie_Scanner * scanner, FILE * fp)
{
  int status;
  int lines;
  unsigned char *buffer, *reorder;
  size_t size;

  DBG (DBG_read, "reading %d lines of %d bytes/line\n", scanner->params.lines,
       scanner->params.bytes_per_line);

  buffer = malloc (scanner->params.bytes_per_line);
  reorder = malloc (scanner->params.bytes_per_line);
  if (!buffer || !reorder)
    {
      free (buffer);
      free (reorder);
      return SANE_STATUS_NO_MEM;
    }

  lines = scanner->params.lines;

  while (lines--)
    {
      set_read_length (sread.cmd, 1);
      size = scanner->params.bytes_per_line;

      do
	{
	  status =
	    sanei_scsi_cmd (scanner->sfd, sread.cmd, sread.size, buffer,
			    &size);
	}
      while (status);

      DBG_DUMP (DBG_dump, buffer, 64);

      if (scanner->colormode == RGB)
	{
	  int i;
	  unsigned char *src, *dest;
	  int offset;

	  dest = reorder;
	  src = buffer;
	  offset = scanner->params.pixels_per_line;

	  for (i = scanner->params.pixels_per_line; i > 0; i--)
	    {
	      *dest++ = *src;
	      *dest++ = *(src + offset);
	      *dest++ = *(src + 2 * offset);
	      src++;
	    }
	  fwrite (reorder, 1, scanner->params.bytes_per_line, fp);
	}
      else
	{
	  fwrite (buffer, 1, scanner->params.bytes_per_line, fp);
	}

      fflush (fp);
    }

  free (buffer);
  free (reorder);

  return 0;
}



/* --------------------------------- READER PROCESS SIGTERM HANDLER  ------------ */


static void
reader_process_sigterm_handler (int signal)
{
  DBG (DBG_sane_info, "reader_process: terminated by signal %d\n", signal);

#ifdef HAVE_SANEI_SCSI_OPEN_EXTENDED
  sanei_scsi_req_flush_all ();	/* flush SCSI queue */
#else
  sanei_scsi_req_flush_all ();	/* flush SCSI queue */
#endif

  _exit (SANE_STATUS_GOOD);
}



/* ------------------------------ READER PROCESS ----------------------------- */


static int
reader_process ( void *data )	/* executed as a child process */
{
  int status;
  FILE *fp;
  Pie_Scanner * scanner;
  sigset_t ignore_set;
  struct SIGACTION act;

  scanner = (Pie_Scanner *)data;
  
  if (sanei_thread_is_forked ()) {

      close ( scanner->pipe );

      sigfillset (&ignore_set);
      sigdelset (&ignore_set, SIGTERM);
#if defined (__APPLE__) && defined (__MACH__)
      sigdelset (&ignore_set, SIGUSR2);
#endif
      sigprocmask (SIG_SETMASK, &ignore_set, 0);

      memset (&act, 0, sizeof (act));
      sigaction (SIGTERM, &act, 0);
  }
  
  DBG (DBG_sane_proc, "reader_process started\n");

  memset (&act, 0, sizeof (act));	/* define SIGTERM-handler */
  act.sa_handler = reader_process_sigterm_handler;
  sigaction (SIGTERM, &act, 0);

  fp = fdopen (scanner->reader_fds, "w");
  if (!fp)
    {
      return SANE_STATUS_IO_ERROR;
    }

  DBG (DBG_sane_info, "reader_process: starting to READ data\n");

  if (scanner->device->inquiry_color_format & INQ_COLOR_FORMAT_LINE)
    status = pie_reader_process (scanner, fp);
  else if (scanner->device->inquiry_color_format & INQ_COLOR_FORMAT_INDEX)
    status = pie_reader_process_indexed (scanner, fp);
  else
    status = SANE_STATUS_UNSUPPORTED;

  fclose (fp);

  DBG (DBG_sane_info, "reader_process: finished reading data\n");

  return status;
}


/* -------------------------------- ATTACH_ONE ---------------------------------- */


/* callback function for sanei_config_attach_matching_devices(dev_name, attach_one) */
static SANE_Status
attach_one (const char *name)
{
  attach_scanner (name, 0);
  return SANE_STATUS_GOOD;
}


/* ----------------------------- CLOSE PIPE ---------------------------------- */


static SANE_Status
close_pipe (Pie_Scanner * scanner)
{
  DBG (DBG_sane_proc, "close_pipe\n");

  if (scanner->pipe >= 0)
    {
      close (scanner->pipe);
      scanner->pipe = -1;
    }

  return SANE_STATUS_EOF;
}



/* ---------------------------- DO CANCEL ---------------------------------- */


static SANE_Status
do_cancel (Pie_Scanner * scanner)
{
  DBG (DBG_sane_proc, "do_cancel\n");

  scanner->scanning = SANE_FALSE;

  if (sanei_thread_is_valid (scanner->reader_pid))
    {
      DBG (DBG_sane_info, "killing reader_process\n");
      sanei_thread_kill (scanner->reader_pid);
      sanei_thread_waitpid (scanner->reader_pid, 0);
      sanei_thread_invalidate (scanner->reader_pid);
      DBG (DBG_sane_info, "reader_process killed\n");
    }

  if (scanner->sfd >= 0)
    {
      pie_scan (scanner, 0);

      pie_power_save (scanner, 15);

      pie_give_scanner (scanner);	/* reposition and release scanner */

      DBG (DBG_sane_info, "closing scannerdevice filedescriptor\n");
      sanei_scsi_close (scanner->sfd);
      scanner->sfd = -1;
    }

  return SANE_STATUS_CANCELLED;
}



/* --------------------------------------- SANE INIT ---------------------------------- */


SANE_Status
sane_init (SANE_Int * version_code, SANE_Auth_Callback __sane_unused__ authorize)
{
  char dev_name[PATH_MAX];
  size_t len;
  FILE *fp;

  DBG_INIT ();

  DBG (DBG_sane_init, "sane_init() build %d\n", BUILD);

  if (version_code)
    *version_code = SANE_VERSION_CODE (SANE_CURRENT_MAJOR, SANE_CURRENT_MINOR, BUILD);

  fp = sanei_config_open (PIE_CONFIG_FILE);
  if (!fp)
    {
      attach_scanner ("/dev/scanner", 0);	/* no config-file: /dev/scanner */
      return SANE_STATUS_GOOD;
    }

  while (sanei_config_read (dev_name, sizeof (dev_name), fp))
    {
      if (dev_name[0] == '#')
	{
	  continue;
	}			/* ignore line comments */

      len = strlen (dev_name);

      if (!len)			/* ignore empty lines */
	{
	  continue;
	}

      sanei_config_attach_matching_devices (dev_name, attach_one);
    }

  fclose (fp);

  return SANE_STATUS_GOOD;
}


/* ----------------------------------------- SANE EXIT ---------------------------------- */


void
sane_exit (void)
{
  Pie_Device *dev, *next;
  int i;

  DBG (DBG_sane_init, "sane_exit()\n");

  for (dev = first_dev; dev; dev = next)
    {
      next = dev->next;
      free (dev->devicename);
      free (dev->cal_info);
      i = 0;
      while (dev->halftone_list[i] != NULL)
	free (dev->halftone_list[i++]);
      i = 0;
      while (dev->speed_list[i] != NULL)
	free (dev->speed_list[i++]);

      free (dev);
    }

  first_dev = NULL;

  if (devlist)
    {
      free (devlist);
      devlist = NULL;
    }
}


/* ------------------------------------------ SANE GET DEVICES --------------------------- */


SANE_Status
sane_get_devices (const SANE_Device *** device_list, SANE_Bool __sane_unused__ local_only)
{
  Pie_Device *dev;
  int i;

  DBG (DBG_sane_init, "sane_get_devices\n");

  i = 0;
  for (dev = first_dev; dev; dev = dev->next)
    i++;

  if (devlist)
    {
      free (devlist);
    }

  devlist = malloc ((i + 1) * sizeof (devlist[0]));
  if (!devlist)
    {
      return SANE_STATUS_NO_MEM;
    }

  i = 0;

  for (dev = first_dev; dev; dev = dev->next)
    {
      devlist[i++] = &dev->sane;
    }

  devlist[i] = NULL;

  *device_list = devlist;

  return SANE_STATUS_GOOD;
}


/* --------------------------------------- SANE OPEN ---------------------------------- */

SANE_Status
sane_open (SANE_String_Const devicename, SANE_Handle * handle)
{
  Pie_Device *dev;
  SANE_Status status;
  Pie_Scanner *scanner;
  int i, j;

  DBG (DBG_sane_init, "sane_open(%s)\n", devicename);

  if (devicename[0])		/* search for devicename */
    {
      for (dev = first_dev; dev; dev = dev->next)
	{
	  if (strcmp (dev->sane.name, devicename) == 0)
	    {
	      break;
	    }
	}

      if (!dev)
	{
	  status = attach_scanner (devicename, &dev);
	  if (status != SANE_STATUS_GOOD)
	    {
	      return status;
	    }
	}
    }
  else
    {
      dev = first_dev;		/* empty devicename -> use first device */
    }


  if (!dev)
    {
      return SANE_STATUS_INVAL;
    }

  scanner = malloc (sizeof (*scanner));
  if (!scanner)

    {
      return SANE_STATUS_NO_MEM;
    }

  memset (scanner, 0, sizeof (*scanner));

  scanner->device = dev;
  scanner->sfd = -1;
  scanner->pipe = -1;

  scanner->gamma_length = 1 << (scanner->device->inquiry_gamma_bits);

  DBG (DBG_sane_info, "Using %d bits for gamma input\n",
       scanner->device->inquiry_gamma_bits);

  scanner->gamma_range.min = 0;
  scanner->gamma_range.max = scanner->gamma_length - 1;
  scanner->gamma_range.quant = 0;

  scanner->gamma_table[0] =
    (SANE_Int *) malloc (scanner->gamma_length * sizeof (SANE_Int));
  scanner->gamma_table[1] =
    (SANE_Int *) malloc (scanner->gamma_length * sizeof (SANE_Int));
  scanner->gamma_table[2] =
    (SANE_Int *) malloc (scanner->gamma_length * sizeof (SANE_Int));
  scanner->gamma_table[3] =
    (SANE_Int *) malloc (scanner->gamma_length * sizeof (SANE_Int));

  for (i = 0; i < 4; ++i)	/* gamma_table[0,1,2,3] */
    {
      for (j = 0; j < scanner->gamma_length; ++j)
	{
	  scanner->gamma_table[i][j] = j;
	}
    }

  init_options (scanner);

  scanner->next = first_handle;	/* insert newly opened handle into list of open handles: */
  first_handle = scanner;

  *handle = scanner;

  return SANE_STATUS_GOOD;
}


/* ------------------------------------ SANE CLOSE --------------------------------- */


void
sane_close (SANE_Handle handle)
{
  Pie_Scanner *prev, *scanner;

  DBG (DBG_sane_init, "sane_close\n");

  /* remove handle from list of open handles: */
  prev = 0;

  for (scanner = first_handle; scanner; scanner = scanner->next)
    {
      if (scanner == handle)
	{
	  break;
	}

      prev = scanner;
    }

  if (!scanner)
    {
      DBG (DBG_error, "close: invalid handle %p\n", handle);
      return;			/* oops, not a handle we know about */
    }

  if (scanner->scanning)	/* stop scan if still scanning */
    {
      do_cancel (handle);
    }

  if (prev)
    {
      prev->next = scanner->next;
    }
  else
    {
      first_handle = scanner->next;
    }

  free (scanner->gamma_table[0]);	/* free custom gamma tables */
  free (scanner->gamma_table[1]);
  free (scanner->gamma_table[2]);
  free (scanner->gamma_table[3]);
  free (scanner->val[OPT_MODE].s);
  free (scanner->val[OPT_SPEED].s);
  free (scanner->val[OPT_HALFTONE_PATTERN].s);

  scanner->bufsize = 0;

  free (scanner);		/* free scanner */
}


/* ---------------------------------- SANE GET OPTION DESCRIPTOR ----------------- */

const SANE_Option_Descriptor *
sane_get_option_descriptor (SANE_Handle handle, SANE_Int option)
{
  Pie_Scanner *scanner = handle;

  DBG (DBG_sane_option, "sane_get_option_descriptor %d\n", option);

  if ((unsigned) option >= NUM_OPTIONS)
    {
      return 0;
    }

  return scanner->opt + option;
}


/* ---------------------------------- SANE CONTROL OPTION ------------------------ */


SANE_Status
sane_control_option (SANE_Handle handle, SANE_Int option, SANE_Action action,
		     void *val, SANE_Int * info)
{
  Pie_Scanner *scanner = handle;
  SANE_Status status;
  SANE_Word cap;
  SANE_String_Const name;

  if (info)
    {
      *info = 0;
    }

  if (scanner->scanning)
    {
      return SANE_STATUS_DEVICE_BUSY;
    }

  if ((unsigned) option >= NUM_OPTIONS)
    {
      return SANE_STATUS_INVAL;
    }

  cap = scanner->opt[option].cap;
  if (!SANE_OPTION_IS_ACTIVE (cap))
    {
      return SANE_STATUS_INVAL;
    }

  name = scanner->opt[option].name;
  if (!name)
    {
      name = "(no name)";
    }

  if (action == SANE_ACTION_GET_VALUE)
    {

      DBG (DBG_sane_option, "get %s [#%d]\n", name, option);

      switch (option)
	{
	  /* word options: */
	case OPT_NUM_OPTS:
	case OPT_RESOLUTION:
	case OPT_TL_X:
	case OPT_TL_Y:
	case OPT_BR_X:
	case OPT_BR_Y:
	case OPT_PREVIEW:
	case OPT_THRESHOLD:
	  *(SANE_Word *) val = scanner->val[option].w;
	  return SANE_STATUS_GOOD;

	  /* word-array options: */
	case OPT_GAMMA_VECTOR:
	case OPT_GAMMA_VECTOR_R:
	case OPT_GAMMA_VECTOR_G:
	case OPT_GAMMA_VECTOR_B:
	  memcpy (val, scanner->val[option].wa, scanner->opt[option].size);
	  return SANE_STATUS_GOOD;

#if 0
	  /* string options: */
	case OPT_SOURCE:
#endif
	case OPT_MODE:
	case OPT_HALFTONE_PATTERN:
	case OPT_SPEED:
	  strcpy (val, scanner->val[option].s);
	  return SANE_STATUS_GOOD;
	}
    }
  else if (action == SANE_ACTION_SET_VALUE)
    {
      switch (scanner->opt[option].type)
	{
	case SANE_TYPE_INT:
	  DBG (DBG_sane_option, "set %s [#%d] to %d\n", name, option,
	       *(SANE_Word *) val);
	  break;

	case SANE_TYPE_FIXED:
	  DBG (DBG_sane_option, "set %s [#%d] to %f\n", name, option,
	       SANE_UNFIX (*(SANE_Word *) val));
	  break;

	case SANE_TYPE_STRING:
	  DBG (DBG_sane_option, "set %s [#%d] to %s\n", name, option,
	       (char *) val);
	  break;

	case SANE_TYPE_BOOL:
	  DBG (DBG_sane_option, "set %s [#%d] to %d\n", name, option,
	       *(SANE_Word *) val);
	  break;

	default:
	  DBG (DBG_sane_option, "set %s [#%d]\n", name, option);
	}

      if (!SANE_OPTION_IS_SETTABLE (cap))
	{
	  return SANE_STATUS_INVAL;
	}

      status = sanei_constrain_value (scanner->opt + option, val, info);
      if (status != SANE_STATUS_GOOD)
	{
	  return status;
	}

      switch (option)
	{
	  /* (mostly) side-effect-free word options: */
	case OPT_RESOLUTION:
	case OPT_TL_X:
	case OPT_TL_Y:
	case OPT_BR_X:
	case OPT_BR_Y:
	  if (info)
	    {
	      *info |= SANE_INFO_RELOAD_PARAMS;
	    }
	  /* fall through */
	case OPT_NUM_OPTS:
	case OPT_PREVIEW:
	case OPT_THRESHOLD:
	  scanner->val[option].w = *(SANE_Word *) val;
	  return SANE_STATUS_GOOD;

	  /* side-effect-free word-array options: */
	case OPT_GAMMA_VECTOR:
	case OPT_GAMMA_VECTOR_R:
	case OPT_GAMMA_VECTOR_G:
	case OPT_GAMMA_VECTOR_B:
	  memcpy (scanner->val[option].wa, val, scanner->opt[option].size);
	  return SANE_STATUS_GOOD;

	  /* options with side-effects: */

	case OPT_MODE:
	  {
	    int halftoning;

	    if (scanner->val[option].s)
	      {
		free (scanner->val[option].s);
	      }

	    scanner->val[option].s = (SANE_Char *) strdup (val);

	    if (info)
	      {
		*info |= SANE_INFO_RELOAD_OPTIONS | SANE_INFO_RELOAD_PARAMS;
	      }

	    scanner->opt[OPT_HALFTONE_PATTERN].cap |= SANE_CAP_INACTIVE;


	    scanner->opt[OPT_GAMMA_VECTOR].cap |= SANE_CAP_INACTIVE;
	    scanner->opt[OPT_GAMMA_VECTOR_R].cap |= SANE_CAP_INACTIVE;
	    scanner->opt[OPT_GAMMA_VECTOR_G].cap |= SANE_CAP_INACTIVE;
	    scanner->opt[OPT_GAMMA_VECTOR_B].cap |= SANE_CAP_INACTIVE;
	    scanner->opt[OPT_THRESHOLD].cap |= SANE_CAP_INACTIVE;

	    halftoning = (strcmp (val, HALFTONE_STR) == 0);

	    if (halftoning || strcmp (val, LINEART_STR) == 0)
	      {			/* one bit modes */
		if (halftoning)
		  {		/* halftoning modes */
		    scanner->opt[OPT_HALFTONE_PATTERN].cap &=
		      ~SANE_CAP_INACTIVE;
		  }
		else
		  {		/* lineart modes */
		  }
		scanner->opt[OPT_THRESHOLD].cap &= ~SANE_CAP_INACTIVE;
	      }
	    else
	      {			/* multi-bit modes(gray or color) */
	      }

	    if ((strcmp (val, LINEART_STR) == 0)
		|| (strcmp (val, HALFTONE_STR) == 0)
		|| (strcmp (val, GRAY_STR) == 0))
	      {
		scanner->opt[OPT_GAMMA_VECTOR].cap &= ~SANE_CAP_INACTIVE;
	      }
	    else if (strcmp (val, COLOR_STR) == 0)
	      {
		/* scanner->opt[OPT_GAMMA_VECTOR].cap &= ~SANE_CAP_INACTIVE; */
		scanner->opt[OPT_GAMMA_VECTOR_R].cap &= ~SANE_CAP_INACTIVE;
		scanner->opt[OPT_GAMMA_VECTOR_G].cap &= ~SANE_CAP_INACTIVE;
		scanner->opt[OPT_GAMMA_VECTOR_B].cap &= ~SANE_CAP_INACTIVE;
	      }
	    return SANE_STATUS_GOOD;
	  }

	case OPT_SPEED:
	case OPT_HALFTONE_PATTERN:
	  {
	    if (scanner->val[option].s)
	      {
		free (scanner->val[option].s);
	      }

	    scanner->val[option].s = (SANE_Char *) strdup (val);

	    return SANE_STATUS_GOOD;
	  }
	}
    }				/* else */
  return SANE_STATUS_INVAL;
}


/* ------------------------------------ SANE GET PARAMETERS ------------------------ */


SANE_Status
sane_get_parameters (SANE_Handle handle, SANE_Parameters * params)
{
  Pie_Scanner *scanner = handle;
  const char *mode;

  DBG (DBG_sane_info, "sane_get_parameters\n");

  if (!scanner->scanning)
    {				/* not scanning, so lets use recent values */
      double width, length, x_dpi, y_dpi;

      memset (&scanner->params, 0, sizeof (scanner->params));

      width =
	SANE_UNFIX (scanner->val[OPT_BR_X].w - scanner->val[OPT_TL_X].w);
      length =
	SANE_UNFIX (scanner->val[OPT_BR_Y].w - scanner->val[OPT_TL_Y].w);
      x_dpi = SANE_UNFIX (scanner->val[OPT_RESOLUTION].w);
      y_dpi = x_dpi;

#if 0
      if ((scanner->val[OPT_RESOLUTION_BIND].w == SANE_TRUE)
	  || (scanner->val[OPT_PREVIEW].w == SANE_TRUE))
	{
	  y_dpi = x_dpi;
	}
#endif
      if (x_dpi > 0.0 && y_dpi > 0.0 && width > 0.0 && length > 0.0)
	{
	  double x_dots_per_mm = x_dpi / MM_PER_INCH;
	  double y_dots_per_mm = y_dpi / MM_PER_INCH;

	  scanner->params.pixels_per_line = width * x_dots_per_mm;
	  scanner->params.lines = length * y_dots_per_mm;
	}
    }

  mode = scanner->val[OPT_MODE].s;

  if (strcmp (mode, LINEART_STR) == 0 || strcmp (mode, HALFTONE_STR) == 0)
    {
      scanner->params.format = SANE_FRAME_GRAY;
      scanner->params.bytes_per_line =
	(scanner->params.pixels_per_line + 7) / 8;
      scanner->params.depth = 1;
    }
  else if (strcmp (mode, GRAY_STR) == 0)
    {
      scanner->params.format = SANE_FRAME_GRAY;
      scanner->params.bytes_per_line = scanner->params.pixels_per_line;
      scanner->params.depth = 8;
    }
  else				/* RGB */
    {
      scanner->params.format = SANE_FRAME_RGB;
      scanner->params.bytes_per_line = 3 * scanner->params.pixels_per_line;
      scanner->params.depth = 8;
    }

  scanner->params.last_frame = (scanner->params.format != SANE_FRAME_RED
				&& scanner->params.format !=
				SANE_FRAME_GREEN);

  if (params)
    {
      *params = scanner->params;
    }

  return SANE_STATUS_GOOD;
}


/* ----------------------------------------- SANE START --------------------------------- */


SANE_Status
sane_start (SANE_Handle handle)
{
  Pie_Scanner *scanner = handle;
  int fds[2];
  const char *mode;
  int status;

  DBG (DBG_sane_init, "sane_start\n");

  /* Check for inconsistencies */

  if (scanner->val[OPT_TL_X].w > scanner->val[OPT_BR_X].w)
    {
      DBG (0, "sane_start: %s (%.1f mm) is bigger than %s (%.1f mm) "
              "-- aborting\n",
              scanner->opt[OPT_TL_X].title, SANE_UNFIX (scanner->val[OPT_TL_X].w),
              scanner->opt[OPT_BR_X].title, SANE_UNFIX (scanner->val[OPT_BR_X].w));
      return SANE_STATUS_INVAL;
    }
  if (scanner->val[OPT_TL_Y].w > scanner->val[OPT_BR_Y].w)
    {
      DBG (0, "sane_start: %s (%.1f mm) is bigger than %s (%.1f mm) "
	      "-- aborting\n",
	      scanner->opt[OPT_TL_Y].title, SANE_UNFIX (scanner->val[OPT_TL_Y].w),
	      scanner->opt[OPT_BR_Y].title, SANE_UNFIX (scanner->val[OPT_BR_Y].w));
      return SANE_STATUS_INVAL;
    }

  mode = scanner->val[OPT_MODE].s;

  if (scanner->sfd < 0)		/* first call, don`t run this routine again on multi frame or multi image scan */
    {
#ifdef HAVE_SANEI_SCSI_OPEN_EXTENDED
      int scsi_bufsize = 131072;	/* 128KB */

      if (sanei_scsi_open_extended
	  (scanner->device->sane.name, &(scanner->sfd), sense_handler,
	   scanner->device, &scsi_bufsize) != 0)

	{
	  DBG (DBG_error, "sane_start: open failed\n");
	  return SANE_STATUS_INVAL;
	}

      if (scsi_bufsize < 32768)	/* < 32KB */
	{
	  DBG (DBG_error,
	       "sane_start: sanei_scsi_open_extended returned too small scsi buffer (%d)\n",
	       scsi_bufsize);
	  sanei_scsi_close ((scanner->sfd));
	  return SANE_STATUS_NO_MEM;
	}
      DBG (DBG_info,
	   "sane_start: sanei_scsi_open_extended returned scsi buffer size = %d\n",
	   scsi_bufsize);


      scanner->bufsize = scsi_bufsize;
#else
      if (sanei_scsi_open
	  (scanner->device->sane.name, &(scanner->sfd), sense_handler,
	   scanner->device) != SANE_STATUS_GOOD)
	{
	  DBG (DBG_error, "sane_start: open of %s failed:\n",
	       scanner->device->sane.name);
	  return SANE_STATUS_INVAL;
	}

      /* there is no need to reallocate the buffer because the size is fixed */
#endif

#if 0
      if (pie_check_values (scanner->device) != 0)
	{
	  DBG (DBG_error, "ERROR: invalid scan-values\n");
	  scanner->scanning = SANE_FALSE;
	  pie_give_scanner (scanner);	/* reposition and release scanner */
	  sanei_scsi_close (scanner->sfd);
	  scanner->sfd = -1;
	  return SANE_STATUS_INVAL;
	}
#endif
#if 0
      scanner->params.bytes_per_line = scanner->device->row_len;
      scanner->params.pixels_per_line = scanner->device->width_in_pixels;
      scanner->params.lines = scanner->device->length_in_pixels;

      sane_get_parameters (scanner, 0);

      DBG (DBG_sane_info, "x_resolution (dpi)      = %u\n",
	   scanner->device->x_resolution);
      DBG (DBG_sane_info, "y_resolution (dpi)      = %u\n",
	   scanner->device->y_resolution);
      DBG (DBG_sane_info, "x_coordinate_base (dpi) = %u\n",
	   scanner->device->x_coordinate_base);
      DBG (DBG_sane_info, "y_coordinate_base (dpi) = %u\n",
	   scanner->device->y_coordinate_base);
      DBG (DBG_sane_info, "upper_left_x (xbase)    = %d\n",
	   scanner->device->upper_left_x);
      DBG (DBG_sane_info, "upper_left_y (ybase)    = %d\n",
	   scanner->device->upper_left_y);
      DBG (DBG_sane_info, "scanwidth    (xbase)    = %u\n",
	   scanner->device->scanwidth);
      DBG (DBG_sane_info, "scanlength   (ybase)    = %u\n",
	   scanner->device->scanlength);
      DBG (DBG_sane_info, "width in pixels         = %u\n",
	   scanner->device->width_in_pixels);
      DBG (DBG_sane_info, "length in pixels        = %u\n",
	   scanner->device->length_in_pixels);
      DBG (DBG_sane_info, "bits per pixel/color    = %u\n",
	   scanner->device->bits_per_pixel);
      DBG (DBG_sane_info, "bytes per line          = %d\n",
	   scanner->params.bytes_per_line);
      DBG (DBG_sane_info, "pixels_per_line         = %d\n",
	   scanner->params.pixels_per_line);
      DBG (DBG_sane_info, "lines                   = %d\n",
	   scanner->params.lines);
#endif

      /* grab scanner */
      if (pie_grab_scanner (scanner))
	{
	  sanei_scsi_close (scanner->sfd);
	  scanner->sfd = -1;
	  DBG (DBG_warning,
	       "WARNING: unable to reserve scanner: device busy\n");
	  return SANE_STATUS_DEVICE_BUSY;
	}

      scanner->scanning = SANE_TRUE;

      pie_power_save (scanner, 0);
    }				/* ------------ end of first call -------------- */


  if (strcmp (mode, LINEART_STR) == 0)
    {
      scanner->colormode = LINEART;
    }
  else if (strcmp (mode, HALFTONE_STR) == 0)
    {
      scanner->colormode = HALFTONE;
    }
  else if (strcmp (mode, GRAY_STR) == 0)
    {
      scanner->colormode = GRAYSCALE;
    }
  else if (strcmp (mode, COLOR_STR) == 0)
    {
      scanner->colormode = RGB;
    }

  /* get and set geometric values for scanning */
  scanner->resolution = SANE_UNFIX (scanner->val[OPT_RESOLUTION].w);

  pie_set_window (scanner);
  pie_send_exposure (scanner);
  pie_mode_select (scanner);
  pie_send_highlight_shadow (scanner);

  pie_scan (scanner, 1);

  status = pie_do_cal (scanner);
  if (status)
    return status;

  /* send gammacurves */

  pie_dwnld_gamma (scanner);

  pie_get_params (scanner);

  if (pipe (fds) < 0)		/* create a pipe, fds[0]=read-fd, fds[1]=write-fd */
    {
      DBG (DBG_error, "ERROR: could not create pipe\n");
      scanner->scanning = SANE_FALSE;
      pie_scan (scanner, 0);
      pie_give_scanner (scanner);	/* reposition and release scanner */
      sanei_scsi_close (scanner->sfd);
      scanner->sfd = -1;
      return SANE_STATUS_IO_ERROR;
    }

  scanner->pipe       = fds[0];
  scanner->reader_fds = fds[1];
  scanner->reader_pid = sanei_thread_begin( reader_process, (void*)scanner );

  if (!sanei_thread_is_valid (scanner->reader_pid))
    {
      DBG (1, "sane_start: sanei_thread_begin failed (%s)\n",
             strerror (errno));
      return SANE_STATUS_NO_MEM;
    }

  if (sanei_thread_is_forked ())
    {
      close (scanner->reader_fds);
      scanner->reader_fds = -1;
    }

  return SANE_STATUS_GOOD;
}


/* -------------------------------------- SANE READ ---------------------------------- */


SANE_Status
sane_read (SANE_Handle handle, SANE_Byte * buf, SANE_Int max_len,
	   SANE_Int * len)
{
  Pie_Scanner *scanner = handle;
  ssize_t nread;

  *len = 0;

  nread = read (scanner->pipe, buf, max_len);
  DBG (DBG_sane_info, "sane_read: read %ld bytes\n", (long) nread);

  if (!(scanner->scanning))	/* OOPS, not scanning */
    {
      return do_cancel (scanner);
    }

  if (nread < 0)
    {
      if (errno == EAGAIN)
	{
	  DBG (DBG_sane_info, "sane_read: EAGAIN\n");
	  return SANE_STATUS_GOOD;
	}
      else
	{
	  do_cancel (scanner);	/* we had an error, stop scanner */
	  return SANE_STATUS_IO_ERROR;
	}
    }

  *len = nread;

  if (nread == 0)		/* EOF */
    {
      do_cancel (scanner);

      return close_pipe (scanner);	/* close pipe */
    }

  return SANE_STATUS_GOOD;
}


/* ------------------------------------- SANE CANCEL -------------------------------- */


void
sane_cancel (SANE_Handle handle)
{
  Pie_Scanner *scanner = handle;

  DBG (DBG_sane_init, "sane_cancel\n");

  if (scanner->scanning)
    {
      do_cancel (scanner);
    }
}


/* -------------------------------------- SANE SET IO MODE --------------------------- */


SANE_Status
sane_set_io_mode (SANE_Handle handle, SANE_Bool non_blocking)
{
  Pie_Scanner *scanner = handle;

  DBG (DBG_sane_init, "sane_set_io_mode: non_blocking=%d\n", non_blocking);

  if (!scanner->scanning)
    {
      return SANE_STATUS_INVAL;
    }

  if (fcntl (scanner->pipe, F_SETFL, non_blocking ? O_NONBLOCK : 0) < 0)
    {
      return SANE_STATUS_IO_ERROR;
    }

  return SANE_STATUS_GOOD;
}


/* --------------------------------------- SANE GET SELECT FD ------------------------- */


SANE_Status
sane_get_select_fd (SANE_Handle handle, SANE_Int * fd)
{
  Pie_Scanner *scanner = handle;

  DBG (DBG_sane_init, "sane_get_select_fd\n");

  if (!scanner->scanning)
    {
      return SANE_STATUS_INVAL;
    }
  *fd = scanner->pipe;

  return SANE_STATUS_GOOD;
}