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

   This file is part of the SANE package, and implements a SANE backend
   for various Canon DR-series scanners.

   Copyright (C) 2008-2010 m. allan noah

   Yabarana Corp. www.yabarana.com provided significant funding
   EvriChart, Inc. www.evrichart.com provided funding and loaned equipment
   Canon, USA. www.usa.canon.com loaned equipment
   HPrint hprint.com.br provided funding and testing for DR-2510 support
   Stone-IT www.stone-it.com provided funding for DR-2010 and DR-2050 support

   --------------------------------------------------------------------------

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

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

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston,
   MA 02111-1307, USA.

   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.

   --------------------------------------------------------------------------

   The source code is divided in sections which you can easily find by
   searching for the tag "@@".

   Section 1 - Init & static stuff
   Section 2 - sane_init, _get_devices, _open & friends
   Section 3 - sane_*_option functions
   Section 4 - sane_start, _get_param, _read & friends
   Section 5 - calibration functions
   Section 6 - sane_close functions
   Section 7 - misc functions
   Section 8 - image processing functions

   Changes:
      v1 2008-10-29, MAN
         - initial version
      v2 2008-11-04, MAN
         - round scanlines to even bytes
	 - spin RS and usb_clear_halt code into new function
	 - update various scsi payloads
	 - calloc out block so it gets set to 0 initially
      v3 2008-11-07, MAN
         - back window uses id 1
         - add option and functions to read/send page counter
         - add rif option
      v4 2008-11-11, MAN
         - eject document when sane_read() returns EOF
      v5 2008-11-25, MAN
         - remove EOF ejection code
         - add SSM and GSM commands
         - add dropout, doublefeed, and jpeg compression options
         - disable adf backside
         - fix adf duplex
         - read two extra lines (ignore errors) at end of image
         - only send scan command at beginning of batch
	 - fix bug in hexdump with 0 length string
         - DR-7580 support
      v6 2008-11-29, MAN
         - fix adf simplex
         - rename ssm_duplex to ssm_buffer
         - add --buffer option
         - reduce inter-page commands when buffering is enabled
         - improve sense_handler output
         - enable counter option
         - drop unused code
      v7 2008-11-29, MAN
         - jpeg support (size rounding and header overwrite)
         - call object_position(load) between pages even if buffering is on
         - use request sense info bytes on short scsi reads
         - byte swap color BGR to RGB
         - round image width down, not up
         - round image height down to even # of lines
         - always transfer even # of lines per block
         - scsi and jpeg don't require reading extra lines to reach EOF
         - rename buffer option to buffermode to avoid conflict with scanimage
         - send ssm_do and ssm_df during sane_start
         - improve sense_handler output
      v8 2008-12-07, MAN
         - rename read/send_counter to read/send_panel
         - enable control panel during init
         - add options for all buttons
         - call TUR twice in wait_scanner(), even if first succeeds
         - disable rif
         - enable brightness/contrast/threshold options
      v9 2008-12-07, MAN
         - add rollerdeskew and stapledetect options
         - add rollerdeskew and stapledetect bits to ssm_df()
      v10 2008-12-10, MAN
         - add all documented request sense codes to sense_handler()
         - fix color jpeg (remove unneeded BGR to RGB swapping code)
         - add macros for LUT data
      v11 2009-01-10, MAN
         - send_panel() can disable too
         - add cancel() to send d8 command
         - call cancel() only after final read from scanner
         - stop button reqests cancel
      v12 2009-01-21, MAN
         - dont export private symbols
      v13 2009-03-06, MAN
         - new vendor ID for recent machines
         - add usb ids for several new machines
      v14 2009-03-07, MAN
         - remove HARD_SELECT from counter (Legitimate, but API violation)
         - attach to CR-series scanners as well
      v15 2009-03-15, MAN
         - add byte-oriented duplex interlace code
         - add RRGGBB color interlace code
         - add basic support for DR-2580C
      v16 2009-03-20, MAN
         - add more unknown setwindow bits
         - add support for 16 byte status packets
         - clean do_usb_cmd error handling (call reset more often)
         - add basic support for DR-2050C, DR-2080C, DR-2510C
      v17 2009-03-20, MAN
         - set status packet size from config file
      v18 2009-03-21, MAN
         - rewrite config file parsing to reset options after each scanner
         - add config options for vendor, model, version
         - dont call inquiry if those 3 options are set
         - remove default config file from code
         - add initial gray deinterlacing code for DR-2510C
         - rename do_usb_reset to do_usb_clear
      v19 2009-03-22, MAN
         - pad gray deinterlacing area for DR-2510C
         - override tl_x and br_x for fixed width scanners
      v20 2009-03-23, MAN
         - improved macros for inquiry and set window
         - shorten inquiry vpd length to match windows driver
         - remove status-length config option
         - add padded-read config option
         - rewrite do_usb_cmd to pad reads and calloc/copy buffers
      v21 2009-03-24, MAN
         - correct rgb padding macro
         - skip send_panel and ssm_df commands for DR-20xx scanners
      v22 2009-03-25, MAN
         - add deinterlacing code for DR-2510C in duplex and color 
      v23 2009-03-27, MAN
         - rewrite all image data processing code
         - handle more image interlacing formats
         - re-enable binary mode on some scanners
         - limit some machines to full-width scanning
      v24 2009-04-02, MAN
         - fix DR-2510C duplex deinterlacing code
         - rewrite sane_read helpers to read until EOF
         - update sane_start for scanners that dont use object_position
         - dont call sanei_usb_clear_halt() if device is not open
         - increase default buffer size to 4 megs
         - set buffermode on by default
         - hide modes and resolutions that DR-2510C lies about
         - read_panel() logs front-end access to sensors instead of timing
         - rewrite do_usb_cmd() to use remainder from RS info
      v25 2009-04-12, MAN
         - disable SANE_FRAME_JPEG
      v26 2009-04-14, MAN (SANE 1.0.20)
         - return cmd status for reads on sensors
         - allow rs to adjust read length for all bad status responses
      v27 2009-05-08, MAN
         - bug fix in read_panel()
         - initialize vars in do_usb_cmd()
         - set buffermode off by default
         - clear page counter during init and sane_start()
         - eject previous page during init and sane_start()
         - improved SSM_BUFF macros
         - moved set_window() to after ssm-*()
         - add coarse calibration (AFE offset/gain & per-channel exposure)
         - add fine calibration (per-cell offset/gain)
         - free image and fine cal buffers in sane_close()
         - compare page counter of small scanners only in non-buffered mode
         - add back-side gray mirroring code for DR-2580C
      v28 2009-05-20, MAN
         - use average instead of min/max for fine offset and gain
         - rewrite supported resolution list as x and y arrays
         - merge x and y resolution options into single option
         - move scan params into two new structs, s->u and s->s
         - sane_get_parameters() just returns values from s->u
         - dont call wait_scanner() in object_position()
         - dont call ssm_*() from option handler
         - refactor sane_start()
         - read_from_buffer() can workaround missing res, modes and cropping
         - set most DR-2xxx machines to use the read_from_buffer workarounds
         - set default threshold to 90
         - add option for button #3 of some machines
         - don't eject paper during init
         - add DR-2010 quirks
         - switch counter to HARD_SELECT, not SOFT
      v29 2009-06-01, MAN
         - split coarse and fine cal to run independently
         - add side option
         - reset scan params to user request if calibration fails
         - better handling of sane_cancel
         - better handling of errors during sane_start and sane_read
      v30 2009-06-17, MAN
         - add fine cal support for machines with internal buffer (2050/2080)
         - support fixed-width machines that require even bytes per scanline
         - pad end of scan with gray if scanner stops prematurely
         - better handling of errors during calibration
         - cleanup canceling debug messages
         - remove old cancel() prototype
         - small sleep before clearing usb halt condition
      v31 2009-06-29, MAN
         - reduce default buffer size to 2 megs
      v32 2009-07-21, MAN
         - crop/resample image data before buffering, not after
         - shink image buffers to size of output image, not input
         - correct some debug message
         - better handling of EOF
         - add intermediate param struct to existing user and scan versions
      v33 2009-07-23, MAN
         - add software brightness/contrast for dumb scanners
         - add blocking mode to allow full-page manipulation options to run
         - add swdespeck option and support code
         - add swdeskew and swcrop options (disabled)
      v34 2009-07-28, MAN
         - add simplified Hough transform based deskewing code
         - add extremity detecting cropping code
         - use per-model background color to fill corners after deskew
         - request and chop extra scanlines instead of rounding down
         - remove padding dumb scanners add to top of front side
         - sane_get_params uses intermediate struct instead of user struct
         - if scanner stops, clone the last line until the end of buffer
         - reset some intermediate params between duplex sides
      v35 2010-02-09, MAN (SANE 1.0.21)
         - cleanup #includes and copyright
         - add SANE_I18N to static strings
         - don't fail if scsi buffer is too small
      v36 2011-01-03, MAN
         - initial support for DR-3080 and DR-5060
         - add code to clamp scan width to an arbitrary byte width boundary
         - add code to prevent setting of brightness/threshold/contrast
         - don't send dropout color command on non-color scanners
         - initial support for DR-7090C
         - update credits
      v37 2011-01-26, MAN (SANE 1.0.22)
         - don't center window when using flatbed
         - improve request sense error messages
         - enable flatbed for all known models
      v38 2011-07-06, MAN
	 - initial support for DR-5020
	 - use ppl_mod instead of Bpl_mod, apply to all modes
	 - invert logic of read_panel tracking
	 - add ability to disable read_panel()
	 - automatically disable read/send_panel if unsupported
      v39 2011-11-01, MAN
         - DR-2580C pads the backside of duplex scans
      v40 2012-11-01, MAN
         - initial DR-9050C, DR-7550C, DR-6050C and DR-3010C support
      v41 2013-07-31, MAN (SANE 1.0.24)
         - initial P-208 and P-215 support
         - bug fix for calibration of scanners with duplex_offset
         - allow duplex_offset to be controlled from config file
      v42 2013-12-09, MAN
         - initial DR-G1100 support
         - add support for paper sensors (P-215 & P-208)
         - add initial support for card reader (P-215)
         - removed unused var from do_scsi_cmd()
      v43 2014-03-13, MAN
         - initial DR-M140 support
         - add extra_status config and code
         - split status code into do_usb_status
         - fix copy_line margin offset
         - add new color interlacing modes and code
         - comment out ssm2
         - add timestamp to do_usb_cmd
      v44 2014-03-26, MAN
         - buffermode support for machines with ssm2 command
         - DR-M140 needs always_op=0
      v45 2014-03-29, MAN
         - dropout support for machines with ssm2 command
         - doublefeed support for machines with ssm2 command
      v46 2014-04-09, MAN
         - split debug level 30 into two levels
         - simplify jpeg ifdefs
         - add support for DR-M160
      v47 2014-07-07, MAN
         - initial DR-G1130 support
      v48 2014-08-06, MAN
         - set another unknown byte in buffermode for ssm2
         - add another gettimeofday call at end of do_usb_cmd
         - don't print 0 length line in hexdump

   SANE FLOW DIAGRAM

   - sane_init() : initialize backend
   . - sane_get_devices() : query list of scanner devices
   . - sane_open() : open a particular scanner device
   . . - sane_set_io_mode : set blocking mode
   . . - sane_get_select_fd : get scanner fd
   . .
   . . - sane_get_option_descriptor() : get option information
   . . - sane_control_option() : change option values
   . . - sane_get_parameters() : returns estimated scan parameters
   . . - (repeat previous 3 functions)
   . .
   . . - sane_start() : start image acquisition
   . .   - sane_get_parameters() : returns actual scan parameters
   . .   - sane_read() : read image data (from pipe)
   . . (sane_read called multiple times; after sane_read returns EOF, 
   . . loop may continue with sane_start which may return a 2nd page
   . . when doing duplex scans, or load the next page from the ADF)
   . .
   . . - sane_cancel() : cancel operation
   . - sane_close() : close opened scanner device
   - sane_exit() : terminate use of backend

*/

/*
 * @@ Section 1 - Init
 */

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

#include <string.h> /*memcpy...*/
#include <ctype.h> /*isspace*/
#include <math.h> /*tan*/
#include <unistd.h> /*usleep*/
#include <sys/time.h> /*gettimeofday*/

#include "../include/sane/sanei_backend.h"
#include "../include/sane/sanei_scsi.h"
#include "../include/sane/sanei_usb.h"
#include "../include/sane/saneopts.h"
#include "../include/sane/sanei_config.h"

#include "canon_dr-cmd.h"
#include "canon_dr.h"

#define DEBUG 1
#define BUILD 48

/* values for SANE_DEBUG_CANON_DR env var:
 - errors           5
 - function trace  10
 - function detail 15
 - get/setopt cmds 20
 - scsi/usb trace  25 
 - scsi/usb writes 30
 - scsi/usb reads  31
 - useless noise   35
*/

/* ------------------------------------------------------------------------- */
/* if JPEG support is not enabled in sane.h, we setup our own defines */
#ifndef SANE_FRAME_JPEG
#define SANE_FRAME_JPEG 0x0B
#define SANE_JPEG_DISABLED 1
#endif
/* ------------------------------------------------------------------------- */
#define STRING_FLATBED SANE_I18N("Flatbed")
#define STRING_ADFFRONT SANE_I18N("ADF Front")
#define STRING_ADFBACK SANE_I18N("ADF Back")
#define STRING_ADFDUPLEX SANE_I18N("ADF Duplex")
#define STRING_CARDFRONT SANE_I18N("Card Front")
#define STRING_CARDBACK SANE_I18N("Card Back")
#define STRING_CARDDUPLEX SANE_I18N("Card Duplex")

#define STRING_LINEART SANE_VALUE_SCAN_MODE_LINEART
#define STRING_HALFTONE SANE_VALUE_SCAN_MODE_HALFTONE
#define STRING_GRAYSCALE SANE_VALUE_SCAN_MODE_GRAY
#define STRING_COLOR SANE_VALUE_SCAN_MODE_COLOR

#define STRING_RED SANE_I18N("Red")
#define STRING_GREEN SANE_I18N("Green")
#define STRING_BLUE SANE_I18N("Blue")
#define STRING_EN_RED SANE_I18N("Enhance Red")
#define STRING_EN_GREEN SANE_I18N("Enhance Green")
#define STRING_EN_BLUE SANE_I18N("Enhance Blue")

#define STRING_NONE SANE_I18N("None")
#define STRING_JPEG SANE_I18N("JPEG")

/* Also set via config file. */
static int global_buffer_size;
static int global_buffer_size_default = 2 * 1024 * 1024;
static int global_padded_read;
static int global_padded_read_default = 0;
static int global_extra_status;
static int global_extra_status_default = 0;
static int global_duplex_offset;
static int global_duplex_offset_default = 0;
static char global_vendor_name[9];
static char global_model_name[17];
static char global_version_name[5];

/*
 * used by attach* and sane_get_devices
 * a ptr to a null term array of ptrs to SANE_Device structs
 * a ptr to a single-linked list of scanner structs
 */
static const SANE_Device **sane_devArray = NULL;
static struct scanner *scanner_devList = NULL;

/*
 * @@ Section 2 - SANE & scanner init code
 */

/*
 * Called by SANE initially.
 * 
 * From the SANE spec:
 * This function must be called before any other SANE function can be
 * called. The behavior of a SANE backend is undefined if this
 * function is not called first. The version code of the backend is
 * returned in the value pointed to by version_code. If that pointer
 * is NULL, no version code is returned. Argument authorize is either
 * a pointer to a function that is invoked when the backend requires
 * authentication for a specific resource or NULL if the frontend does
 * not support authentication.
 */
SANE_Status
sane_init (SANE_Int * version_code, SANE_Auth_Callback authorize)
{
  authorize = authorize;        /* get rid of compiler warning */

  DBG_INIT ();
  DBG (10, "sane_init: start\n");

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

  DBG (5, "sane_init: canon_dr backend %d.%d.%d, from %s\n",
    SANE_CURRENT_MAJOR, V_MINOR, BUILD, PACKAGE_STRING);

  DBG (10, "sane_init: finish\n");

  return SANE_STATUS_GOOD;
}

/*
 * Called by SANE to find out about supported devices.
 * 
 * From the SANE spec:
 * This function can be used to query the list of devices that are
 * available. If the function executes successfully, it stores a
 * pointer to a NULL terminated array of pointers to SANE_Device
 * structures in *device_list. The returned list is guaranteed to
 * remain unchanged and valid until (a) another call to this function
 * is performed or (b) a call to sane_exit() is performed. This
 * function can be called repeatedly to detect when new devices become
 * available. If argument local_only is true, only local devices are
 * returned (devices directly attached to the machine that SANE is
 * running on). If it is false, the device list includes all remote
 * devices that are accessible to the SANE library.
 * 
 * SANE does not require that this function is called before a
 * sane_open() call is performed. A device name may be specified
 * explicitly by a user which would make it unnecessary and
 * undesirable to call this function first.
 */
/*
 * Read the config file, find scanners with help from sanei_*
 * and store in global device structs
 */
SANE_Status
sane_get_devices (const SANE_Device *** device_list, SANE_Bool local_only)
{
  SANE_Status ret = SANE_STATUS_GOOD;
  struct scanner * s;
  struct scanner * prev = NULL;
  char line[PATH_MAX];
  const char *lp;
  FILE *fp;
  int num_devices=0;
  int i=0;

  local_only = local_only;        /* get rid of compiler warning */

  DBG (10, "sane_get_devices: start\n");

  /* mark all existing scanners as missing, attach_one will remove mark */
  for (s = scanner_devList; s; s = s->next) {
    s->missing = 1;
  }

  sanei_usb_init();

  /* reset globals before reading the file */
  default_globals();

  fp = sanei_config_open (CANON_DR_CONFIG_FILE);

  if (fp) {

      DBG (15, "sane_get_devices: reading config file %s\n",
        CANON_DR_CONFIG_FILE);

      while (sanei_config_read (line, PATH_MAX, fp)) {
    
          lp = line;
    
          /* ignore comments */
          if (*lp == '#')
            continue;
    
          /* skip empty lines */
          if (*lp == 0)
            continue;
    
          if (!strncmp ("option", lp, 6) && isspace (lp[6])) {
    
              lp += 6;
              lp = sanei_config_skip_whitespace (lp);
    
              /* BUFFERSIZE: > 4K */
              if (!strncmp (lp, "buffer-size", 11) && isspace (lp[11])) {
    
                  int buf;
                  lp += 11;
                  lp = sanei_config_skip_whitespace (lp);
                  buf = atoi (lp);
    
                  if (buf < 4096) {
                    DBG (5, "sane_get_devices: config option \"buffer-size\" "
                      "(%d) is < 4096, ignoring!\n", buf);
                    continue;
                  }
    
                  if (buf > global_buffer_size_default) {
                    DBG (5, "sane_get_devices: config option \"buffer-size\" "
                      "(%d) is > %d, scanning problems may result\n", buf,
                      global_buffer_size_default);
                  }
    
                  DBG (15, "sane_get_devices: setting \"buffer-size\" to %d\n",
                    buf);

                  global_buffer_size = buf;
              }

              /* PADDED READ: we clamp to 0 or 1 */
              else if (!strncmp (lp, "padded-read", 11) && isspace (lp[11])) {
    
                  int buf;
                  lp += 11;
                  lp = sanei_config_skip_whitespace (lp);
                  buf = atoi (lp);
    
                  if (buf < 0) {
                    DBG (5, "sane_get_devices: config option \"padded-read\" "
                      "(%d) is < 0, ignoring!\n", buf);
                    continue;
                  }
    
                  if (buf > 1) {
                    DBG (5, "sane_get_devices: config option \"padded-read\" "
                      "(%d) is > 1, ignoring!\n", buf);
                    continue;
                  }
    
                  DBG (15, "sane_get_devices: setting \"padded-read\" to %d\n",
                    buf);

                  global_padded_read = buf;
              }

              /* EXTRA STATUS: we clamp to 0 or 1 */
              else if (!strncmp (lp, "extra-status", 12) && isspace (lp[12])) {
    
                  int buf;
                  lp += 12;
                  lp = sanei_config_skip_whitespace (lp);
                  buf = atoi (lp);
    
                  if (buf < 0) {
                    DBG (5, "sane_get_devices: config option \"extra-status\" "
                      "(%d) is < 0, ignoring!\n", buf);
                    continue;
                  }
    
                  if (buf > 1) {
                    DBG (5, "sane_get_devices: config option \"extra-status\" "
                      "(%d) is > 1, ignoring!\n", buf);
                    continue;
                  }
    
                  DBG (15, "sane_get_devices: setting \"extra-status\" to %d\n",
                    buf);

                  global_extra_status = buf;
              }

              /* DUPLEXOFFSET: < 1200 */
              else if (!strncmp (lp, "duplex-offset", 13) && isspace (lp[13])) {
    
                  int buf;
                  lp += 13;
                  lp = sanei_config_skip_whitespace (lp);
                  buf = atoi (lp);
    
                  if (buf > 1200) {
                    DBG (5, "sane_get_devices: config option \"duplex-offset\" "
                      "(%d) is > 1200, ignoring!\n", buf);
                    continue;
                  }
    
                  if (buf < 0) {
                    DBG (5, "sane_get_devices: config option \"duplex-offset\" "
                      "(%d) is < 0, ignoring!\n", buf);
                    continue;
                  }

                  DBG (15, "sane_get_devices: setting \"duplex-offset\" to %d\n",
                    buf);

                  global_duplex_offset = buf;
              }

              /* VENDOR: we ingest up to 8 bytes */
              else if (!strncmp (lp, "vendor-name", 11) && isspace (lp[11])) {

                  lp += 11;
                  lp = sanei_config_skip_whitespace (lp);
                  strncpy(global_vendor_name, lp, 8);
                  global_vendor_name[8] = 0;
    
                  DBG (15, "sane_get_devices: setting \"vendor-name\" to %s\n",
                    global_vendor_name);
              }

              /* MODEL: we ingest up to 16 bytes */
              else if (!strncmp (lp, "model-name", 10) && isspace (lp[10])) {

                  lp += 10;
                  lp = sanei_config_skip_whitespace (lp);
                  strncpy(global_model_name, lp, 16);
                  global_model_name[16] = 0;
    
                  DBG (15, "sane_get_devices: setting \"model-name\" to %s\n",
                    global_model_name);
              }

              /* VERSION: we ingest up to 4 bytes */
              else if (!strncmp (lp, "version-name", 12) && isspace (lp[12])) {

                  lp += 12;
                  lp = sanei_config_skip_whitespace (lp);
                  strncpy(global_version_name, lp, 4);
                  global_version_name[4] = 0;
    
                  DBG (15, "sane_get_devices: setting \"version-name\" to %s\n",
                    global_version_name);
              }

              else {
                  DBG (5, "sane_get_devices: config option \"%s\" unrecognized "
                  "- ignored.\n", lp);
              }
          }
          else if ((strncmp ("usb", lp, 3) == 0) && isspace (lp[3])) {
              DBG (15, "sane_get_devices: looking for '%s'\n", lp);
              sanei_usb_attach_matching_devices(lp, attach_one_usb);

              /* re-default these after reading the usb line */
              default_globals();
          }
          else if ((strncmp ("scsi", lp, 4) == 0) && isspace (lp[4])) {
              DBG (15, "sane_get_devices: looking for '%s'\n", lp);
              sanei_config_attach_matching_devices (lp, attach_one_scsi);

              /* re-default these after reading the scsi line */
              default_globals();
          }
          else{
              DBG (5, "sane_get_devices: config line \"%s\" unrecognized - "
              "ignored.\n", lp);
          }
      }
      fclose (fp);
  }

  else {
      DBG (5, "sane_get_devices: missing required config file '%s'!\n",
        CANON_DR_CONFIG_FILE);
  }

  /*delete missing scanners from list*/
  for (s = scanner_devList; s;) {
    if(s->missing){
      DBG (5, "sane_get_devices: missing scanner %s\n",s->device_name);

      /*splice s out of list by changing pointer in prev to next*/
      if(prev){
        prev->next = s->next;
        free(s);
        s=prev->next;
      }
      /*remove s from head of list, using prev to cache it*/
      else{
        prev = s;
        s = s->next;
        free(prev);
	prev=NULL;

	/*reset head to next s*/
	scanner_devList = s;
      }
    }
    else{
      prev = s;
      s=prev->next;
    }
  }

  for (s = scanner_devList; s; s=s->next) {
    DBG (15, "sane_get_devices: found scanner %s\n",s->device_name);
    num_devices++;
  }

  DBG (15, "sane_get_devices: found %d scanner(s)\n",num_devices);

  if (sane_devArray)
    free (sane_devArray);

  sane_devArray = calloc (num_devices + 1, sizeof (SANE_Device*));
  if (!sane_devArray)
    return SANE_STATUS_NO_MEM;

  for (s = scanner_devList; s; s=s->next) {
    sane_devArray[i++] = (SANE_Device *)&s->sane;
  }
  sane_devArray[i] = 0;

  if(device_list){
      *device_list = sane_devArray;
  }

  DBG (10, "sane_get_devices: finish\n");

  return ret;
}

/* callbacks used by sane_get_devices */
static SANE_Status
attach_one_scsi (const char *device_name)
{
  return attach_one(device_name,CONNECTION_SCSI);
}

static SANE_Status
attach_one_usb (const char *device_name)
{
  return attach_one(device_name,CONNECTION_USB);
}

/* build the scanner struct and link to global list 
 * unless struct is already loaded, then pretend 
 */
static SANE_Status
attach_one (const char *device_name, int connType)
{
  struct scanner *s;
  int ret;

  DBG (10, "attach_one: start\n");
  DBG (15, "attach_one: looking for '%s'\n", device_name);

  for (s = scanner_devList; s; s = s->next) {
    if (strcmp (s->device_name, device_name) == 0){
      DBG (10, "attach_one: already attached!\n");
      s->missing = 0;
      return SANE_STATUS_GOOD;
    }
  }

  /* build a scanner struct to hold it */
  if ((s = calloc (sizeof (*s), 1)) == NULL)
    return SANE_STATUS_NO_MEM;

  /* config file settings */
  s->buffer_size = global_buffer_size;
  s->padded_read = global_padded_read;
  s->extra_status = global_extra_status;
  s->duplex_offset = global_duplex_offset;

  /* copy the device name */
  strcpy (s->device_name, device_name);

  /* connect the fd */
  s->connection = connType;
  s->fd = -1;
  ret = connect_fd(s);
  if(ret != SANE_STATUS_GOOD){
    free (s);
    return ret;
  }

  /* query the device to load its vendor/model/version, */
  /* if config file doesn't give all three */
  if ( !strlen(global_vendor_name)
    || !strlen(global_model_name)
    || !strlen(global_version_name)
  ){
    ret = init_inquire (s);
    if (ret != SANE_STATUS_GOOD) {
      disconnect_fd(s);
      free (s);
      DBG (5, "attach_one: inquiry failed\n");
      return ret;
    }
  }

  /* override any inquiry settings with those from config file */
  if(strlen(global_vendor_name))
    strcpy(s->vendor_name, global_vendor_name);
  if(strlen(global_model_name))
    strcpy(s->model_name, global_model_name);
  if(strlen(global_version_name))
    strcpy(s->version_name, global_version_name);

  /* load detailed specs/capabilities from the device */
  /* if a model cannot support inquiry vpd, this function will die */
  ret = init_vpd (s);
  if (ret != SANE_STATUS_GOOD) {
    disconnect_fd(s);
    free (s);
    DBG (5, "attach_one: vpd failed\n");
    return ret;
  }

  /* clean up the scanner struct based on model */
  /* this is the big piece of model specific code */
  ret = init_model (s);
  if (ret != SANE_STATUS_GOOD) {
    disconnect_fd(s);
    free (s);
    DBG (5, "attach_one: model failed\n");
    return ret;
  }

  /* enable/read the buttons */
  ret = init_panel (s);
  if (ret != SANE_STATUS_GOOD) {
    disconnect_fd(s);
    free (s);
    DBG (5, "attach_one: model failed\n");
    return ret;
  }

  /* sets SANE option 'values' to good defaults */
  ret = init_user (s);
  if (ret != SANE_STATUS_GOOD) {
    disconnect_fd(s);
    free (s);
    DBG (5, "attach_one: user failed\n");
    return ret;
  }

  ret = init_options (s);
  if (ret != SANE_STATUS_GOOD) {
    disconnect_fd(s);
    free (s);
    DBG (5, "attach_one: options failed\n");
    return ret;
  }

  /* load strings into sane_device struct */
  s->sane.name = s->device_name;
  s->sane.vendor = s->vendor_name;
  s->sane.model = s->model_name;
  s->sane.type = "scanner";

  /* change name in sane_device struct if scanner has serial number
  ret = init_serial (s);
  if (ret == SANE_STATUS_GOOD) {
    s->sane.name = s->serial_name;
  }
  else{
    DBG (5, "attach_one: serial number unsupported?\n");
  }
  */

  /* we close the connection, so that another backend can talk to scanner */
  disconnect_fd(s);

  /* store this scanner in global vars */
  s->next = scanner_devList;
  scanner_devList = s;

  DBG (10, "attach_one: finish\n");

  return SANE_STATUS_GOOD;
}

/*
 * connect the fd in the scanner struct
 */
static SANE_Status
connect_fd (struct scanner *s)
{
  SANE_Status ret;
  int buffer_size = s->buffer_size;

  DBG (10, "connect_fd: start\n");

  if(s->fd > -1){
    DBG (5, "connect_fd: already open\n");
    ret = SANE_STATUS_GOOD;
  }
  else if (s->connection == CONNECTION_USB) {
    DBG (15, "connect_fd: opening USB device (%s)\n", s->device_name);
    ret = sanei_usb_open (s->device_name, &(s->fd));
    if(!ret){
      ret = sanei_usb_clear_halt(s->fd);
    }
  }
  else {
    DBG (15, "connect_fd: opening SCSI device (%s)\n", s->device_name);
    ret = sanei_scsi_open_extended (s->device_name, &(s->fd), sense_handler, s,
      &s->buffer_size);
    if(!ret && buffer_size != s->buffer_size){
      DBG (5, "connect_fd: cannot get requested buffer size (%d/%d)\n",
        buffer_size, s->buffer_size);
    }
  }

  if(ret == SANE_STATUS_GOOD){

    /* first generation usb scanners can get flaky if not closed 
     * properly after last use. very first commands sent to device 
     * must be prepared to correct this- see wait_scanner() */
    ret = wait_scanner(s);
    if (ret != SANE_STATUS_GOOD) {
      DBG (5, "connect_fd: could not wait_scanner\n");
      disconnect_fd(s);
    }

  }
  else{
    DBG (5, "connect_fd: could not open device: %d\n", ret);
  }

  DBG (10, "connect_fd: finish\n");

  return ret;
}

/*
 * This routine will check if a certain device is a Canon scanner
 * It also copies interesting data from INQUIRY into the handle structure
 */
static SANE_Status
init_inquire (struct scanner *s)
{
  int i;
  SANE_Status ret;

  unsigned char cmd[INQUIRY_len];
  size_t cmdLen = INQUIRY_len;

  unsigned char in[INQUIRY_std_len];
  size_t inLen = INQUIRY_std_len;

  DBG (10, "init_inquire: start\n");

  memset(cmd,0,cmdLen);
  set_SCSI_opcode(cmd, INQUIRY_code);
  set_IN_return_size (cmd, inLen);
  set_IN_evpd (cmd, 0);
  set_IN_page_code (cmd, 0);
 
  ret = do_cmd (
    s, 1, 0, 
    cmd, cmdLen,
    NULL, 0,
    in, &inLen
  );

  if (ret != SANE_STATUS_GOOD){
    DBG (10, "init_inquire: failed: %d\n", ret);
    return ret;
  }

  if (get_IN_periph_devtype (in) != IN_periph_devtype_scanner){
    DBG (5, "The device at '%s' is not a scanner.\n", s->device_name);
    return SANE_STATUS_INVAL;
  }

  get_IN_vendor (in, s->vendor_name);
  get_IN_product (in, s->model_name);
  get_IN_version (in, s->version_name);

  s->vendor_name[8] = 0;
  s->model_name[16] = 0;
  s->version_name[4] = 0;

  /* gobble trailing spaces */
  for (i = 7; s->vendor_name[i] == ' ' && i >= 0; i--)
    s->vendor_name[i] = 0;
  for (i = 15; s->model_name[i] == ' ' && i >= 0; i--)
    s->model_name[i] = 0;
  for (i = 3; s->version_name[i] == ' ' && i >= 0; i--)
    s->version_name[i] = 0;

  /*check for vendor name*/
  if (strcmp ("CANON", s->vendor_name)) {
    DBG (5, "The device at '%s' is reported to be made by '%s'\n",
      s->device_name, s->vendor_name);
    DBG (5, "This backend only supports Canon products.\n");
    return SANE_STATUS_INVAL;
  }

  /*check for model name*/
  if (strncmp ("DR", s->model_name, 2)
   && strncmp ("CR", s->model_name, 2)
   && strncmp ("P-", s->model_name, 2)
  ) {
    DBG (5, "The device at '%s' is reported to be a '%s'\n",
      s->device_name, s->model_name);
    DBG (5, "This backend only supports Canon P-, CR & DR-series products.\n");
    return SANE_STATUS_INVAL;
  }

  DBG (15, "init_inquire: Found %s scanner %s version %s at %s\n",
    s->vendor_name, s->model_name, s->version_name, s->device_name);

  DBG (10, "init_inquire: finish\n");

  return SANE_STATUS_GOOD;
}

/*
 * Use INQUIRY VPD to setup more detail about the scanner
 */
static SANE_Status
init_vpd (struct scanner *s)
{
  SANE_Status ret;

  unsigned char cmd[INQUIRY_len];
  size_t cmdLen = INQUIRY_len;

  unsigned char in[INQUIRY_vpd_len];
  size_t inLen = INQUIRY_vpd_len;

  DBG (10, "init_vpd: start\n");

  /* get EVPD */
  memset(cmd,0,cmdLen);
  set_SCSI_opcode(cmd, INQUIRY_code);
  set_IN_return_size (cmd, inLen);
  set_IN_evpd (cmd, 1);
  set_IN_page_code (cmd, 0xf0);

  ret = do_cmd (
    s, 1, 0,
    cmd, cmdLen,
    NULL, 0,
    in, &inLen
  );

  DBG (15, "init_vpd: length=%0x\n",get_IN_page_length (in));

  /* This scanner supports vital product data.
   * Use this data to set dpi-lists etc. */
  if (ret == SANE_STATUS_GOOD || ret == SANE_STATUS_EOF) {

      DBG (15, "standard options\n");

      s->basic_x_res = get_IN_basic_x_res (in);
      DBG (15, "  basic x res: %d dpi\n",s->basic_x_res);

      s->basic_y_res = get_IN_basic_y_res (in);
      DBG (15, "  basic y res: %d dpi\n",s->basic_y_res);

      s->step_x_res = get_IN_step_x_res (in);
      DBG (15, "  step x res: %d dpi\n", s->step_x_res);

      s->step_y_res = get_IN_step_y_res (in);
      DBG (15, "  step y res: %d dpi\n", s->step_y_res);

      s->max_x_res = get_IN_max_x_res (in);
      DBG (15, "  max x res: %d dpi\n", s->max_x_res);

      s->max_y_res = get_IN_max_y_res (in);
      DBG (15, "  max y res: %d dpi\n", s->max_y_res);

      s->min_x_res = get_IN_min_x_res (in);
      DBG (15, "  min x res: %d dpi\n", s->min_x_res);

      s->min_y_res = get_IN_min_y_res (in);
      DBG (15, "  min y res: %d dpi\n", s->min_y_res);

      /* some scanners list B&W resolutions. */
      s->std_res_x[DPI_60] = get_IN_std_res_60 (in);
      s->std_res_y[DPI_60] = s->std_res_x[DPI_60];
      DBG (15, "  60 dpi: %d\n", s->std_res_x[DPI_60]);

      s->std_res_x[DPI_75] = get_IN_std_res_75 (in);
      s->std_res_y[DPI_75] = s->std_res_x[DPI_75];
      DBG (15, "  75 dpi: %d\n", s->std_res_x[DPI_75]);

      s->std_res_x[DPI_100] = get_IN_std_res_100 (in);
      s->std_res_y[DPI_100] = s->std_res_x[DPI_100];
      DBG (15, "  100 dpi: %d\n", s->std_res_x[DPI_100]);

      s->std_res_x[DPI_120] = get_IN_std_res_120 (in);
      s->std_res_y[DPI_120] = s->std_res_x[DPI_120];
      DBG (15, "  120 dpi: %d\n", s->std_res_x[DPI_120]);

      s->std_res_x[DPI_150] = get_IN_std_res_150 (in);
      s->std_res_y[DPI_150] = s->std_res_x[DPI_150];
      DBG (15, "  150 dpi: %d\n", s->std_res_x[DPI_150]);

      s->std_res_x[DPI_160] = get_IN_std_res_160 (in);
      s->std_res_y[DPI_160] = s->std_res_x[DPI_160];
      DBG (15, "  160 dpi: %d\n", s->std_res_x[DPI_160]);

      s->std_res_x[DPI_180] = get_IN_std_res_180 (in);
      s->std_res_y[DPI_180] = s->std_res_x[DPI_180];
      DBG (15, "  180 dpi: %d\n", s->std_res_x[DPI_180]);

      s->std_res_x[DPI_200] = get_IN_std_res_200 (in);
      s->std_res_y[DPI_200] = s->std_res_x[DPI_200];
      DBG (15, "  200 dpi: %d\n", s->std_res_x[DPI_200]);

      s->std_res_x[DPI_240] = get_IN_std_res_240 (in);
      s->std_res_y[DPI_240] = s->std_res_x[DPI_240];
      DBG (15, "  240 dpi: %d\n", s->std_res_x[DPI_240]);

      s->std_res_x[DPI_300] = get_IN_std_res_300 (in);
      s->std_res_y[DPI_300] = s->std_res_x[DPI_300];
      DBG (15, "  300 dpi: %d\n", s->std_res_x[DPI_300]);

      s->std_res_x[DPI_320] = get_IN_std_res_320 (in);
      s->std_res_y[DPI_320] = s->std_res_x[DPI_320];
      DBG (15, "  320 dpi: %d\n", s->std_res_x[DPI_320]);

      s->std_res_x[DPI_400] = get_IN_std_res_400 (in);
      s->std_res_y[DPI_400] = s->std_res_x[DPI_400];
      DBG (15, "  400 dpi: %d\n", s->std_res_x[DPI_400]);

      s->std_res_x[DPI_480] = get_IN_std_res_480 (in);
      s->std_res_y[DPI_480] = s->std_res_x[DPI_480];
      DBG (15, "  480 dpi: %d\n", s->std_res_x[DPI_480]);

      s->std_res_x[DPI_600] = get_IN_std_res_600 (in);
      s->std_res_y[DPI_600] = s->std_res_x[DPI_600];
      DBG (15, "  600 dpi: %d\n", s->std_res_x[DPI_600]);

      s->std_res_x[DPI_800] = get_IN_std_res_800 (in);
      s->std_res_y[DPI_800] = s->std_res_x[DPI_800];
      DBG (15, "  800 dpi: %d\n", s->std_res_x[DPI_800]);

      s->std_res_x[DPI_1200] = get_IN_std_res_1200 (in);
      s->std_res_y[DPI_1200] = s->std_res_x[DPI_1200];
      DBG (15, "  1200 dpi: %d\n", s->std_res_x[DPI_1200]);

      /* maximum window width and length are reported in basic units.*/
      s->max_x = get_IN_window_width(in) * 1200 / s->basic_x_res;
      DBG(15, "  max width: %d (%2.2f in)\n",s->max_x,(float)s->max_x/1200);

      s->max_y = get_IN_window_length(in) * 1200 / s->basic_y_res;
      DBG(15, "  max length: %d (%2.2f in)\n",s->max_y,(float)s->max_y/1200);

      DBG (15, "  AWD: %d\n", get_IN_awd(in));
      DBG (15, "  CE Emphasis: %d\n", get_IN_ce_emphasis(in));
      DBG (15, "  C Emphasis: %d\n", get_IN_c_emphasis(in));
      DBG (15, "  High quality: %d\n", get_IN_high_quality(in));

      /* known modes FIXME more here? */
      s->can_grayscale = get_IN_multilevel (in);
      DBG (15, "  grayscale: %d\n", s->can_grayscale);

      s->can_halftone = get_IN_half_tone (in);
      DBG (15, "  halftone: %d\n", s->can_halftone);

      s->can_monochrome = get_IN_monochrome (in);
      DBG (15, "  monochrome: %d\n", s->can_monochrome);

      s->can_overflow = get_IN_overflow(in);
      DBG (15, "  overflow: %d\n", s->can_overflow);
  }
  /*FIXME no vpd, set some defaults? */
  else{
    DBG (5, "init_vpd: Your scanner does not support VPD?\n");
    DBG (5, "init_vpd: Please contact kitno455 at gmail dot com\n");
    DBG (5, "init_vpd: with details of your scanner model.\n");
  }

  DBG (10, "init_vpd: finish\n");

  return ret;
}

/*
 * get model specific info that is not in vpd, and correct
 * errors in vpd data. struct is already initialized to 0.
 */
static SANE_Status
init_model (struct scanner *s)
{

  DBG (10, "init_model: start\n");

  s->reverse_by_mode[MODE_LINEART] = 1;
  s->reverse_by_mode[MODE_HALFTONE] = 1;
  s->reverse_by_mode[MODE_GRAYSCALE] = 0;
  s->reverse_by_mode[MODE_COLOR] = 0;

  s->color_interlace[SIDE_FRONT] = COLOR_INTERLACE_RGB;
  s->color_interlace[SIDE_BACK] = COLOR_INTERLACE_RGB;

  s->always_op = 1;
  s->has_df = 1;
  s->has_btc = 1;
  s->has_counter = 1;
  s->has_adf = 1;
  s->has_duplex = 1;
  s->has_buffer = 1;
  s->can_read_panel = 1;
  s->can_write_panel = 1;
  s->has_ssm = 1;

  s->brightness_steps = 255;
  s->contrast_steps = 255;
  s->threshold_steps = 255;

  s->ppl_mod = 1;
  s->bg_color = 0xee;

  /* assume these are same as adf, override below */
  s->valid_x = s->max_x;
  s->max_x_fb = s->max_x;
  s->max_y_fb = s->max_y;

  /* generic settings missing from vpd */
  if (strstr (s->model_name,"C")){
    s->can_color = 1;
  }

  /* specific settings missing from vpd */
  if (strstr (s->model_name,"DR-9080")
    || strstr (s->model_name,"DR-7580")){
    s->has_comp_JPEG = 1;
    s->rgb_format = 2;
  }

  else if (strstr (s->model_name,"DR-7090")){
    s->has_flatbed = 1;
  }

  else if (strstr (s->model_name,"DR-9050")
    || strstr (s->model_name,"DR-7550")
    || strstr (s->model_name,"DR-6050")
    || strstr (s->model_name,"DR-G1100")
    || strstr (s->model_name,"DR-G1130")
  ){

    /*missing*/
    s->std_res_x[DPI_100]=1;
    s->std_res_y[DPI_100]=1;
    s->std_res_x[DPI_150]=1;
    s->std_res_y[DPI_150]=1;
    s->std_res_x[DPI_200]=1;
    s->std_res_y[DPI_200]=1;
    s->std_res_x[DPI_240]=1;
    s->std_res_y[DPI_240]=1;
    s->std_res_x[DPI_300]=1;
    s->std_res_y[DPI_300]=1;
    s->std_res_x[DPI_400]=1;
    s->std_res_y[DPI_400]=1;
    s->std_res_x[DPI_600]=1;
    s->std_res_y[DPI_600]=1;
    
    /*weirdness*/
    s->has_ssm = 0;
    s->has_ssm2 = 1;
  }

  else if (strstr (s->model_name,"DR-4080")
    || strstr (s->model_name,"DR-4580")
    || strstr (s->model_name,"DR-7080")){
    s->has_flatbed = 1;
  }

  else if (strstr (s->model_name,"DR-2580")){
    s->invert_tly = 1;
    s->rgb_format = 1;
    s->color_interlace[SIDE_FRONT] = COLOR_INTERLACE_RRGGBB;
    s->color_interlace[SIDE_BACK] = COLOR_INTERLACE_rRgGbB;
    s->gray_interlace[SIDE_BACK] = GRAY_INTERLACE_gG;
    s->duplex_interlace = DUPLEX_INTERLACE_FBFB;
    s->need_ccal = 1;
    s->need_fcal = 1;
    /*s->duplex_offset = 432; now set in config file*/
    s->duplex_offset_side = SIDE_BACK;

    /*lies*/
    s->can_halftone=0;
    s->can_monochrome=0;
  }

  else if (strstr (s->model_name,"DR-2510")
   || strstr (s->model_name,"DR-2010")
  ){
    s->rgb_format = 1;
    s->always_op = 0;
    s->unknown_byte2 = 0x80;
    s->fixed_width = 1;
    s->valid_x = 8.5 * 1200;
    s->gray_interlace[SIDE_FRONT] = GRAY_INTERLACE_2510;
    s->gray_interlace[SIDE_BACK] = GRAY_INTERLACE_2510;
    s->color_interlace[SIDE_FRONT] = COLOR_INTERLACE_2510;
    s->color_interlace[SIDE_BACK] = COLOR_INTERLACE_2510;
    s->duplex_interlace = DUPLEX_INTERLACE_2510;
    /*s->duplex_offset = 400; now set in config file*/
    s->need_ccal = 1;
    s->need_fcal = 1;
    s->sw_lut = 1;
    /*s->invert_tly = 1;*/

    /*only in Y direction, so we trash them in X*/
    s->std_res_x[DPI_100]=0;
    s->std_res_x[DPI_150]=0;
    s->std_res_x[DPI_200]=0;
    s->std_res_x[DPI_240]=0;
    s->std_res_x[DPI_400]=0;

    /*lies*/
    s->can_halftone=0;
    s->can_monochrome=0;
  }

  /* copied from 2510, possibly incorrect */
  else if (strstr (s->model_name,"DR-3010")){
    s->rgb_format = 1;
    s->always_op = 0;
    s->unknown_byte2 = 0x80;
    s->fixed_width = 1;
    s->valid_x = 8.5 * 1200;
    s->gray_interlace[SIDE_FRONT] = GRAY_INTERLACE_2510;
    s->gray_interlace[SIDE_BACK] = GRAY_INTERLACE_2510;
    s->color_interlace[SIDE_FRONT] = COLOR_INTERLACE_2510;
    s->color_interlace[SIDE_BACK] = COLOR_INTERLACE_2510;
    s->duplex_interlace = DUPLEX_INTERLACE_2510;
    /*s->duplex_offset = 400; now set in config file*/
    s->need_ccal = 1;
    s->need_fcal = 1;
    s->sw_lut = 1;
    s->invert_tly = 1;

    /*only in Y direction, so we trash them in X*/
    s->std_res_x[DPI_100]=0;
    s->std_res_x[DPI_150]=0;
    s->std_res_x[DPI_200]=0;
    s->std_res_x[DPI_240]=0;
    s->std_res_x[DPI_400]=0;

    /*lies*/
    s->can_halftone=0;
    s->can_monochrome=0;
  }

  else if (strstr (s->model_name,"DR-2050")
   || strstr (s->model_name,"DR-2080")){
    s->can_write_panel = 0;
    s->has_df = 0;
    s->fixed_width = 1;
    s->even_Bpl = 1;
    s->color_interlace[SIDE_FRONT] = COLOR_INTERLACE_RRGGBB;
    s->color_interlace[SIDE_BACK] = COLOR_INTERLACE_RRGGBB;
    s->duplex_interlace = DUPLEX_INTERLACE_FBFB;
    s->need_fcal_buffer = 1;
    s->bg_color = 0x08;
    /*s->duplex_offset = 840; now set in config file*/
    s->sw_lut = 1;

    /*lies*/
    s->can_halftone=0;
    s->can_monochrome=0;
  }

  else if (strstr (s->model_name,"DR-3080")){
    s->can_write_panel = 0;
    s->has_df = 0;
    s->has_btc = 0;
  }

  else if (strstr (s->model_name,"DR-5060F")){
    s->can_write_panel = 0;
    s->has_df = 0;
    s->has_btc = 0;
    s->ppl_mod = 32;
    s->reverse_by_mode[MODE_LINEART] = 0;
    s->reverse_by_mode[MODE_HALFTONE] = 0;
  }

  else if (strstr (s->model_name,"DR-5020")){
    s->can_read_panel = 0;
    s->can_write_panel = 0;
    s->has_df = 0;
    s->has_btc = 0;
    s->ppl_mod = 32;
    s->reverse_by_mode[MODE_LINEART] = 0;
    s->reverse_by_mode[MODE_HALFTONE] = 0;
  }

  else if (strstr (s->model_name, "P-208")) {
    s->color_interlace[SIDE_FRONT] = COLOR_INTERLACE_RRGGBB;
    s->color_interlace[SIDE_BACK] = COLOR_INTERLACE_rRgGbB;
    s->gray_interlace[SIDE_BACK] = GRAY_INTERLACE_gG;
    s->duplex_interlace = DUPLEX_INTERLACE_FBFB;
    s->need_ccal = 1;
    s->invert_tly = 1;
    s->can_color = 1;
    s->unknown_byte2 = 0x88;
    s->rgb_format = 1;
    s->has_ssm_pay_head_len = 1;
    s->ppl_mod = 8;
    s->ccal_version = 3;
    s->can_read_sensors = 1;
  }

  else if (strstr (s->model_name, "P-215")) {
    s->color_interlace[SIDE_FRONT] = COLOR_INTERLACE_rRgGbB;
    s->color_interlace[SIDE_BACK] = COLOR_INTERLACE_RRGGBB;
    s->gray_interlace[SIDE_FRONT] = GRAY_INTERLACE_gG;
    s->duplex_interlace = DUPLEX_INTERLACE_FBFB;
    s->need_ccal = 1;
    s->invert_tly = 1;
    s->can_color = 1;
    s->unknown_byte2 = 0x88;
    s->rgb_format = 1;
    s->has_ssm_pay_head_len = 1;
    s->ppl_mod = 8;
    s->ccal_version = 3;
    s->can_read_sensors = 1;
    s->has_card = 1;
  }

  else if (strstr (s->model_name,"DR-M160")){

    /*missing*/
    s->std_res_x[DPI_100]=1;
    s->std_res_y[DPI_100]=1;
    s->std_res_x[DPI_150]=1;
    s->std_res_y[DPI_150]=1;
    s->std_res_x[DPI_200]=1;
    s->std_res_y[DPI_200]=1;
    s->std_res_x[DPI_300]=1;
    s->std_res_y[DPI_300]=1;
    s->std_res_x[DPI_400]=1;
    s->std_res_y[DPI_400]=1;
    s->std_res_x[DPI_600]=1;
    s->std_res_y[DPI_600]=1;
    
    s->has_comp_JPEG = 1;
    s->rgb_format = 1;
    s->can_color = 1;
    s->has_df_ultra = 1;

    s->color_inter_by_res[DPI_100] = COLOR_INTERLACE_GBR;
    s->color_inter_by_res[DPI_150] = COLOR_INTERLACE_GBR;
    s->color_inter_by_res[DPI_200] = COLOR_INTERLACE_BRG;
    s->color_inter_by_res[DPI_400] = COLOR_INTERLACE_GBR;

    /*weirdness*/
    s->always_op = 0;
    s->fixed_width = 1;
    s->invert_tly = 1;
    s->can_write_panel = 0;
    s->has_ssm = 0;
    s->has_ssm2 = 1;
    s->duplex_interlace = DUPLEX_INTERLACE_FFBB;
    s->duplex_offset_side = SIDE_FRONT;

    /*lies*/
    s->can_halftone=0;
    s->can_monochrome=0;
  }

  else if (strstr (s->model_name,"DR-M140")){

    /*missing*/
    s->std_res_x[DPI_100]=1;
    s->std_res_y[DPI_100]=1;
    s->std_res_x[DPI_150]=1;
    s->std_res_y[DPI_150]=1;
    s->std_res_x[DPI_200]=1;
    s->std_res_y[DPI_200]=1;
    s->std_res_x[DPI_300]=1;
    s->std_res_y[DPI_300]=1;
    s->std_res_x[DPI_400]=1;
    s->std_res_y[DPI_400]=1;
    s->std_res_x[DPI_600]=1;
    s->std_res_y[DPI_600]=1;
    
    s->has_comp_JPEG = 1;
    s->rgb_format = 1;
    s->can_color = 1;
    s->has_df_ultra = 1;

    s->color_inter_by_res[DPI_100] = COLOR_INTERLACE_GBR;
    s->color_inter_by_res[DPI_150] = COLOR_INTERLACE_GBR;
    s->color_inter_by_res[DPI_200] = COLOR_INTERLACE_BRG;
    s->color_inter_by_res[DPI_400] = COLOR_INTERLACE_GBR;

    /*weirdness*/
    s->always_op = 0;
    s->fixed_width = 1;
    s->invert_tly = 1;
    s->can_write_panel = 0;
    s->has_ssm = 0;
    s->has_ssm2 = 1;
    s->duplex_interlace = DUPLEX_INTERLACE_FFBB;
    s->duplex_offset_side = SIDE_BACK;

    /*lies*/
    s->can_halftone=0;
    s->can_monochrome=0;
  }

  DBG (10, "init_model: finish\n");

  return SANE_STATUS_GOOD;
}

/*
 * This function enables the buttons and preloads the current panel values
 */
static SANE_Status
init_panel (struct scanner *s)
{
  SANE_Status ret = SANE_STATUS_GOOD;

  DBG (10, "init_panel: start\n");

  ret = read_panel(s,0);
  if(ret){
    DBG (5, "init_panel: disabling read_panel\n");
    s->can_read_panel = 0;
    ret = SANE_STATUS_GOOD;
  }

  s->panel_enable_led = 1;
  s->panel_counter = 0;
  ret = send_panel(s);
  if(ret){
    DBG (5, "init_panel: disabling send_panel\n");
    s->can_write_panel = 0;
    ret = SANE_STATUS_GOOD;
  }

  DBG (10, "init_panel: finish\n");

  return ret;
}

/*
 * set good default user values.
 * struct is already initialized to 0.
 */
static SANE_Status
init_user (struct scanner *s)
{

  DBG (10, "init_user: start\n");

  /* source */
  if(s->has_flatbed)
    s->u.source = SOURCE_FLATBED;
  else if(s->has_adf)
    s->u.source = SOURCE_ADF_FRONT;
  else if(s->has_card)
    s->u.source = SOURCE_CARD_FRONT;

  /* scan mode */
  if(s->can_monochrome)
    s->u.mode=MODE_LINEART;
  else if(s->can_halftone)
    s->u.mode=MODE_HALFTONE;
  else if(s->can_grayscale)
    s->u.mode=MODE_GRAYSCALE;
  else if(s->can_color)
    s->u.mode=MODE_COLOR;

  /*x and y res*/
  s->u.dpi_x = s->basic_x_res;
  s->u.dpi_y = s->basic_x_res;

  /* page width US-Letter */
  s->u.page_x = 8.5 * 1200;
  if(s->u.page_x > s->valid_x){
    s->u.page_x = s->valid_x;
  }

  /* page height US-Letter */
  s->u.page_y = 11 * 1200;
  if(s->u.page_y > s->max_y){
    s->u.page_y = s->max_y;
  }

  /* bottom-right x */
  s->u.br_x = s->u.page_x;

  /* bottom-right y */
  s->u.br_y = s->u.page_y;

  s->threshold = 90;
  s->compress_arg = 50;

  DBG (10, "init_user: finish\n");

  return SANE_STATUS_GOOD;
}

/*
 * This function presets the "option" array to blank
 */
static SANE_Status
init_options (struct scanner *s)
{
  int i;

  DBG (10, "init_options: start\n");

  memset (s->opt, 0, sizeof (s->opt));
  for (i = 0; i < NUM_OPTIONS; ++i) {
      s->opt[i].name = "filler";
      s->opt[i].size = sizeof (SANE_Word);
      s->opt[i].cap = SANE_CAP_INACTIVE;
  }

  /* go ahead and setup the first opt, because 
   * frontend may call control_option on it 
   * before calling get_option_descriptor 
   */
  s->opt[OPT_NUM_OPTS].name = SANE_NAME_NUM_OPTIONS;
  s->opt[OPT_NUM_OPTS].title = SANE_TITLE_NUM_OPTIONS;
  s->opt[OPT_NUM_OPTS].desc = SANE_DESC_NUM_OPTIONS;
  s->opt[OPT_NUM_OPTS].type = SANE_TYPE_INT;
  s->opt[OPT_NUM_OPTS].cap = SANE_CAP_SOFT_DETECT;

  DBG (10, "init_options: finish\n");

  return SANE_STATUS_GOOD;
}

/*
 * From the SANE spec:
 * This function is used to establish a connection to a particular
 * device. The name of the device to be opened is passed in argument
 * name. If the call completes successfully, a handle for the device
 * is returned in *h. As a special case, specifying a zero-length
 * string as the device requests opening the first available device
 * (if there is such a device).
 */
SANE_Status
sane_open (SANE_String_Const name, SANE_Handle * handle)
{
  struct scanner *dev = NULL;
  struct scanner *s = NULL;
  SANE_Status ret;
 
  DBG (10, "sane_open: start\n");

  if(scanner_devList){
    DBG (15, "sane_open: searching currently attached scanners\n");
  }
  else{
    DBG (15, "sane_open: no scanners currently attached, attaching\n");

    ret = sane_get_devices(NULL,0);
    if(ret != SANE_STATUS_GOOD){
      return ret;
    }
  }

  if(name[0] == 0){
    DBG (15, "sane_open: no device requested, using default\n");
    s = scanner_devList;
  }
  else{
    DBG (15, "sane_open: device %s requested\n", name);
                                                                                
    for (dev = scanner_devList; dev; dev = dev->next) {
      if (strcmp (dev->sane.name, name) == 0
       || strcmp (dev->device_name, name) == 0) { /*always allow sanei devname*/
        s = dev;
        break;
      }
    }
  }

  if (!s) {
    DBG (5, "sane_open: no device found\n");
    return SANE_STATUS_INVAL;
  }

  DBG (15, "sane_open: device %s found\n", s->sane.name);

  *handle = s;

  /* connect the fd so we can talk to scanner */
  ret = connect_fd(s);
  if(ret != SANE_STATUS_GOOD){
    return ret;
  }

  DBG (10, "sane_open: finish\n");

  return SANE_STATUS_GOOD;
}

/*
 * @@ Section 3 - SANE Options functions
 */

/*
 * Returns the options we know.
 *
 * From the SANE spec:
 * This function is used to access option descriptors. The function
 * returns the option descriptor for option number n of the device
 * represented by handle h. Option number 0 is guaranteed to be a
 * valid option. Its value is an integer that specifies the number of
 * options that are available for device handle h (the count includes
 * option 0). If n is not a valid option index, the function returns
 * NULL. The returned option descriptor is guaranteed to remain valid
 * (and at the returned address) until the device is closed.
 */
const SANE_Option_Descriptor *
sane_get_option_descriptor (SANE_Handle handle, SANE_Int option)
{
  struct scanner *s = handle;
  int i;
  SANE_Option_Descriptor *opt = &s->opt[option];

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

  if ((unsigned) option >= NUM_OPTIONS)
    return NULL;

  /* "Mode" group -------------------------------------------------------- */
  if(option==OPT_STANDARD_GROUP){
    opt->name = SANE_NAME_STANDARD;
    opt->title = SANE_TITLE_STANDARD;
    opt->desc = SANE_DESC_STANDARD;
    opt->type = SANE_TYPE_GROUP;
    opt->constraint_type = SANE_CONSTRAINT_NONE;
  }

  /* source */
  if(option==OPT_SOURCE){
    i=0;
    if(s->has_flatbed){
      s->source_list[i++]=STRING_FLATBED;
    }
    if(s->has_adf){
      s->source_list[i++]=STRING_ADFFRONT;
  
      if(s->has_back){
        s->source_list[i++]=STRING_ADFBACK;
      }
      if(s->has_duplex){
        s->source_list[i++]=STRING_ADFDUPLEX;
      }
    }
    if(s->has_card){
      s->source_list[i++]=STRING_CARDFRONT;
  
      if(s->has_back){
        s->source_list[i++]=STRING_CARDBACK;
      }
      if(s->has_duplex){
        s->source_list[i++]=STRING_CARDDUPLEX;
      }
    }
    s->source_list[i]=NULL;

    opt->name = SANE_NAME_SCAN_SOURCE;
    opt->title = SANE_TITLE_SCAN_SOURCE;
    opt->desc = SANE_DESC_SCAN_SOURCE;
    opt->type = SANE_TYPE_STRING;
    opt->constraint_type = SANE_CONSTRAINT_STRING_LIST;
    opt->constraint.string_list = s->source_list;
    opt->size = maxStringSize (opt->constraint.string_list);
    opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
  }

  /* scan mode */
  if(option==OPT_MODE){
    i=0;
    if(s->can_monochrome || s->can_grayscale || s->can_color){
      s->mode_list[i++]=STRING_LINEART;
    }
    if(s->can_halftone){
      s->mode_list[i++]=STRING_HALFTONE;
    }
    if(s->can_grayscale || s->can_color){
      s->mode_list[i++]=STRING_GRAYSCALE;
    }
    if(s->can_color){
      s->mode_list[i++]=STRING_COLOR;
    }
    s->mode_list[i]=NULL;
  
    opt->name = SANE_NAME_SCAN_MODE;
    opt->title = SANE_TITLE_SCAN_MODE;
    opt->desc = SANE_DESC_SCAN_MODE;
    opt->type = SANE_TYPE_STRING;
    opt->constraint_type = SANE_CONSTRAINT_STRING_LIST;
    opt->constraint.string_list = s->mode_list;
    opt->size = maxStringSize (opt->constraint.string_list);
    opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
  }

  /* resolution */
  /* some scanners only support fixed res
   * build a list of possible choices */
  /* we actually only look at the y resolution choices,
   * and interpolate the image data as required for limited x resolutions */
  if(option==OPT_RES){
    i=0;
    if(s->std_res_y[DPI_60] && s->max_y_res >= 60 && s->min_y_res <= 60){
      s->res_list[++i] = 60;
    }
    if(s->std_res_y[DPI_75] && s->max_y_res >= 75 && s->min_y_res <= 75){
      s->res_list[++i] = 75;
    }
    if(s->std_res_y[DPI_100] && s->max_y_res >= 100 && s->min_y_res <= 100){
      s->res_list[++i] = 100;
    }
    if(s->std_res_y[DPI_120] && s->max_y_res >= 120 && s->min_y_res <= 120){
      s->res_list[++i] = 120;
    }
    if(s->std_res_y[DPI_150] && s->max_y_res >= 150 && s->min_y_res <= 150){
      s->res_list[++i] = 150;
    }
    if(s->std_res_y[DPI_160] && s->max_y_res >= 160 && s->min_y_res <= 160){
      s->res_list[++i] = 160;
    }
    if(s->std_res_y[DPI_180] && s->max_y_res >= 180 && s->min_y_res <= 180){
      s->res_list[++i] = 180;
    }
    if(s->std_res_y[DPI_200] && s->max_y_res >= 200 && s->min_y_res <= 200){
      s->res_list[++i] = 200;
    }
    if(s->std_res_y[DPI_240] && s->max_y_res >= 240 && s->min_y_res <= 240){
      s->res_list[++i] = 240;
    }
    if(s->std_res_y[DPI_300] && s->max_y_res >= 300 && s->min_y_res <= 300){
      s->res_list[++i] = 300;
    }
    if(s->std_res_y[DPI_320] && s->max_y_res >= 320 && s->min_y_res <= 320){
      s->res_list[++i] = 320;
    }
    if(s->std_res_y[DPI_400] && s->max_y_res >= 400 && s->min_y_res <= 400){
      s->res_list[++i] = 400;
    }
    if(s->std_res_y[DPI_480] && s->max_y_res >= 480 && s->min_y_res <= 480){
      s->res_list[++i] = 480;
    }
    if(s->std_res_y[DPI_600] && s->max_y_res >= 600 && s->min_y_res <= 600){
      s->res_list[++i] = 600;
    }
    if(s->std_res_y[DPI_800] && s->max_y_res >= 800 && s->min_y_res <= 800){
      s->res_list[++i] = 800;
    }
    if(s->std_res_y[DPI_1200] && s->max_y_res >= 1200 && s->min_y_res <= 1200){
      s->res_list[++i] = 1200;
    }
    s->res_list[0] = i;
  
    opt->name = SANE_NAME_SCAN_RESOLUTION;
    opt->title = SANE_TITLE_SCAN_RESOLUTION;
    opt->desc = SANE_DESC_SCAN_RESOLUTION;
    opt->type = SANE_TYPE_INT;
    opt->unit = SANE_UNIT_DPI;
    opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
  
    if(s->step_y_res){
      s->res_range.min = s->min_y_res;
      s->res_range.max = s->max_y_res;
      s->res_range.quant = s->step_y_res;
      opt->constraint_type = SANE_CONSTRAINT_RANGE;
      opt->constraint.range = &s->res_range;
    }
    else{
      opt->constraint_type = SANE_CONSTRAINT_WORD_LIST;
      opt->constraint.word_list = s->res_list;
    }
  }

  /* "Geometry" group ---------------------------------------------------- */
  if(option==OPT_GEOMETRY_GROUP){
    opt->name = SANE_NAME_GEOMETRY;
    opt->title = SANE_TITLE_GEOMETRY;
    opt->desc = SANE_DESC_GEOMETRY;
    opt->type = SANE_TYPE_GROUP;
    opt->constraint_type = SANE_CONSTRAINT_NONE;
  }

  /* top-left x */
  if(option==OPT_TL_X){
    /* values stored in 1200 dpi units */
    /* must be converted to MM for sane */
    s->tl_x_range.min = SCANNER_UNIT_TO_FIXED_MM(s->min_x);
    s->tl_x_range.max = SCANNER_UNIT_TO_FIXED_MM(get_page_width(s));
    s->tl_x_range.quant = MM_PER_UNIT_FIX;
  
    opt->name = SANE_NAME_SCAN_TL_X;
    opt->title = SANE_TITLE_SCAN_TL_X;
    opt->desc = SANE_DESC_SCAN_TL_X;
    opt->type = SANE_TYPE_FIXED;
    opt->unit = SANE_UNIT_MM;
    opt->constraint_type = SANE_CONSTRAINT_RANGE;
    opt->constraint.range = &(s->tl_x_range);
    opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
  }

  /* top-left y */
  if(option==OPT_TL_Y){
    /* values stored in 1200 dpi units */
    /* must be converted to MM for sane */
    s->tl_y_range.min = SCANNER_UNIT_TO_FIXED_MM(s->min_y);
    s->tl_y_range.max = SCANNER_UNIT_TO_FIXED_MM(get_page_height(s));
    s->tl_y_range.quant = MM_PER_UNIT_FIX;
  
    opt->name = SANE_NAME_SCAN_TL_Y;
    opt->title = SANE_TITLE_SCAN_TL_Y;
    opt->desc = SANE_DESC_SCAN_TL_Y;
    opt->type = SANE_TYPE_FIXED;
    opt->unit = SANE_UNIT_MM;
    opt->constraint_type = SANE_CONSTRAINT_RANGE;
    opt->constraint.range = &(s->tl_y_range);
    opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
  }

  /* bottom-right x */
  if(option==OPT_BR_X){
    /* values stored in 1200 dpi units */
    /* must be converted to MM for sane */
    s->br_x_range.min = SCANNER_UNIT_TO_FIXED_MM(s->min_x);
    s->br_x_range.max = SCANNER_UNIT_TO_FIXED_MM(get_page_width(s));
    s->br_x_range.quant = MM_PER_UNIT_FIX;
  
    opt->name = SANE_NAME_SCAN_BR_X;
    opt->title = SANE_TITLE_SCAN_BR_X;
    opt->desc = SANE_DESC_SCAN_BR_X;
    opt->type = SANE_TYPE_FIXED;
    opt->unit = SANE_UNIT_MM;
    opt->constraint_type = SANE_CONSTRAINT_RANGE;
    opt->constraint.range = &(s->br_x_range);
    opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
  }

  /* bottom-right y */
  if(option==OPT_BR_Y){
    /* values stored in 1200 dpi units */
    /* must be converted to MM for sane */
    s->br_y_range.min = SCANNER_UNIT_TO_FIXED_MM(s->min_y);
    s->br_y_range.max = SCANNER_UNIT_TO_FIXED_MM(get_page_height(s));
    s->br_y_range.quant = MM_PER_UNIT_FIX;
  
    opt->name = SANE_NAME_SCAN_BR_Y;
    opt->title = SANE_TITLE_SCAN_BR_Y;
    opt->desc = SANE_DESC_SCAN_BR_Y;
    opt->type = SANE_TYPE_FIXED;
    opt->unit = SANE_UNIT_MM;
    opt->constraint_type = SANE_CONSTRAINT_RANGE;
    opt->constraint.range = &(s->br_y_range);
    opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
  }

  /* page width */
  if(option==OPT_PAGE_WIDTH){
    /* values stored in 1200 dpi units */
    /* must be converted to MM for sane */
    s->paper_x_range.min = SCANNER_UNIT_TO_FIXED_MM(s->min_x);
    s->paper_x_range.max = SCANNER_UNIT_TO_FIXED_MM(s->valid_x);
    s->paper_x_range.quant = MM_PER_UNIT_FIX;

    opt->name = SANE_NAME_PAGE_WIDTH;
    opt->title = SANE_TITLE_PAGE_WIDTH;
    opt->desc = SANE_DESC_PAGE_WIDTH;
    opt->type = SANE_TYPE_FIXED;
    opt->unit = SANE_UNIT_MM;
    opt->constraint_type = SANE_CONSTRAINT_RANGE;
    opt->constraint.range = &s->paper_x_range;

    if(s->has_adf || s->has_card){
      opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
      if(s->u.source == SOURCE_FLATBED){
        opt->cap |= SANE_CAP_INACTIVE;
      }
    }
    else{
      opt->cap = SANE_CAP_INACTIVE;
    }
  }

  /* page height */
  if(option==OPT_PAGE_HEIGHT){
    /* values stored in 1200 dpi units */
    /* must be converted to MM for sane */
    s->paper_y_range.min = SCANNER_UNIT_TO_FIXED_MM(s->min_y);
    s->paper_y_range.max = SCANNER_UNIT_TO_FIXED_MM(s->max_y);
    s->paper_y_range.quant = MM_PER_UNIT_FIX;

    opt->name = SANE_NAME_PAGE_HEIGHT;
    opt->title = SANE_TITLE_PAGE_HEIGHT;
    opt->desc = SANE_DESC_PAGE_HEIGHT;
    opt->type = SANE_TYPE_FIXED;
    opt->unit = SANE_UNIT_MM;
    opt->constraint_type = SANE_CONSTRAINT_RANGE;
    opt->constraint.range = &s->paper_y_range;

    if(s->has_adf || s->has_card){
      opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
      if(s->u.source == SOURCE_FLATBED){
        opt->cap |= SANE_CAP_INACTIVE;
      }
    }
    else{
      opt->cap = SANE_CAP_INACTIVE;
    }
  }

  /* "Enhancement" group ------------------------------------------------- */
  if(option==OPT_ENHANCEMENT_GROUP){
    opt->name = SANE_NAME_ENHANCEMENT;
    opt->title = SANE_TITLE_ENHANCEMENT;
    opt->desc = SANE_DESC_ENHANCEMENT;
    opt->type = SANE_TYPE_GROUP;
    opt->constraint_type = SANE_CONSTRAINT_NONE;
  }

  /* brightness */
  if(option==OPT_BRIGHTNESS){
    opt->name = SANE_NAME_BRIGHTNESS;
    opt->title = SANE_TITLE_BRIGHTNESS;
    opt->desc = SANE_DESC_BRIGHTNESS;
    opt->type = SANE_TYPE_INT;
    opt->unit = SANE_UNIT_NONE;
    opt->constraint_type = SANE_CONSTRAINT_RANGE;
    opt->constraint.range = &s->brightness_range;
    s->brightness_range.quant=1;

    /* some have hardware brightness (always 0 to 255?) */
    /* some use LUT or GT (-127 to +127)*/
    if (s->brightness_steps){
      s->brightness_range.min=-127;
      s->brightness_range.max=127;
      opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
    }
    else{
      opt->cap = SANE_CAP_INACTIVE;
    }
  }

  /* contrast */
  if(option==OPT_CONTRAST){
    opt->name = SANE_NAME_CONTRAST;
    opt->title = SANE_TITLE_CONTRAST;
    opt->desc = SANE_DESC_CONTRAST;
    opt->type = SANE_TYPE_INT;
    opt->unit = SANE_UNIT_NONE;
    opt->constraint_type = SANE_CONSTRAINT_RANGE;
    opt->constraint.range = &s->contrast_range;
    s->contrast_range.quant=1;

    /* some have hardware contrast (always 0 to 255?) */
    /* some use LUT or GT (-127 to +127)*/
    if (s->contrast_steps){
      s->contrast_range.min=-127;
      s->contrast_range.max=127;
      opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
    }
    else {
      opt->cap = SANE_CAP_INACTIVE;
    }
  }

  /*threshold*/
  if(option==OPT_THRESHOLD){
    opt->name = SANE_NAME_THRESHOLD;
    opt->title = SANE_TITLE_THRESHOLD;
    opt->desc = SANE_DESC_THRESHOLD;
    opt->type = SANE_TYPE_INT;
    opt->unit = SANE_UNIT_NONE;
    opt->constraint_type = SANE_CONSTRAINT_RANGE;
    opt->constraint.range = &s->threshold_range;
    s->threshold_range.min=0;
    s->threshold_range.max=s->threshold_steps;
    s->threshold_range.quant=1;

    if (s->threshold_steps){
      opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
      if(s->u.mode != MODE_LINEART){
        opt->cap |= SANE_CAP_INACTIVE;
      }
    }
    else {
      opt->cap = SANE_CAP_INACTIVE;
    }
  }

  if(option==OPT_RIF){
    opt->name = "rif";
    opt->title = "RIF";
    opt->desc = "Reverse image format";
    opt->type = SANE_TYPE_BOOL;
    opt->unit = SANE_UNIT_NONE;
    if (s->has_rif)
      opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
    else
      opt->cap = SANE_CAP_INACTIVE;
  }

  /* "Advanced" group ------------------------------------------------------ */
  if(option==OPT_ADVANCED_GROUP){
    opt->name = SANE_NAME_ADVANCED;
    opt->title = SANE_TITLE_ADVANCED;
    opt->desc = SANE_DESC_ADVANCED;
    opt->type = SANE_TYPE_GROUP;
    opt->constraint_type = SANE_CONSTRAINT_NONE;
  }

  /*image compression*/
  if(option==OPT_COMPRESS){
    i=0;
    s->compress_list[i++]=STRING_NONE;

    if(s->has_comp_JPEG){
#ifndef SANE_JPEG_DISABLED
      s->compress_list[i++]=STRING_JPEG;
#endif
    }

    s->compress_list[i]=NULL;

    opt->name = "compression";
    opt->title = "Compression";
    opt->desc = "Enable compressed data. May crash your front-end program";
    opt->type = SANE_TYPE_STRING;
    opt->constraint_type = SANE_CONSTRAINT_STRING_LIST;
    opt->constraint.string_list = s->compress_list;
    opt->size = maxStringSize (opt->constraint.string_list);

    if (i > 1){
      opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
      if (s->u.mode != MODE_COLOR && s->u.mode != MODE_GRAYSCALE){
        opt->cap |= SANE_CAP_INACTIVE;
      }
    }
    else
      opt->cap = SANE_CAP_INACTIVE;
  }

  /*image compression arg*/
  if(option==OPT_COMPRESS_ARG){

    opt->name = "compression-arg";
    opt->title = "Compression argument";
    opt->desc = "Level of JPEG compression. 1 is small file, 100 is large file.";
    opt->type = SANE_TYPE_INT;
    opt->unit = SANE_UNIT_NONE;
    opt->constraint_type = SANE_CONSTRAINT_RANGE;
    opt->constraint.range = &s->compress_arg_range;
    s->compress_arg_range.quant=1;

    if(s->has_comp_JPEG){
      s->compress_arg_range.min=0;
      s->compress_arg_range.max=100;
      opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;

      if(s->compress != COMP_JPEG){
        opt->cap |= SANE_CAP_INACTIVE;
      }
    }
    else
      opt->cap = SANE_CAP_INACTIVE;
  }

  /*double feed by length*/
  if(option==OPT_DF_LENGTH){
    opt->name = "df-length";
    opt->title = "DF by length";
    opt->desc = "Detect double feeds by comparing document lengths";
    opt->type = SANE_TYPE_BOOL;
    opt->unit = SANE_UNIT_NONE;
    opt->constraint_type = SANE_CONSTRAINT_NONE;

    if (1)
     opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT | SANE_CAP_ADVANCED;
    else
     opt->cap = SANE_CAP_INACTIVE;
  }

  /*double feed by thickness */
  if(option==OPT_DF_THICKNESS){
  
    opt->name = "df-thickness";
    opt->title = "DF by thickness";
    opt->desc = "Detect double feeds using thickness sensor";
    opt->type = SANE_TYPE_BOOL;
    opt->unit = SANE_UNIT_NONE;
    opt->constraint_type = SANE_CONSTRAINT_NONE;

    if (1){
     opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT | SANE_CAP_ADVANCED;
    }
    else
     opt->cap = SANE_CAP_INACTIVE;
  }

  /*deskew by roller*/
  if(option==OPT_ROLLERDESKEW){
    opt->name = "rollerdeskew";
    opt->title = "Roller deskew";
    opt->desc = "Request scanner to correct skewed pages mechanically";
    opt->type = SANE_TYPE_BOOL;
    if (1)
     opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT | SANE_CAP_ADVANCED;
    else
     opt->cap = SANE_CAP_INACTIVE;
  }

  /*deskew by software*/
  if(option==OPT_SWDESKEW){
    opt->name = "swdeskew";
    opt->title = "Software deskew";
    opt->desc = "Request driver to rotate skewed pages digitally";
    opt->type = SANE_TYPE_BOOL;
    if (1)
     opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT | SANE_CAP_ADVANCED;
    else
     opt->cap = SANE_CAP_INACTIVE;
  }

  /*software despeckle radius*/
  if(option==OPT_SWDESPECK){

    opt->name = "swdespeck";
    opt->title = "Software despeckle diameter";
    opt->desc = "Maximum diameter of lone dots to remove from scan";
    opt->type = SANE_TYPE_INT;
    opt->unit = SANE_UNIT_NONE;
    opt->constraint_type = SANE_CONSTRAINT_RANGE;
    opt->constraint.range = &s->swdespeck_range;
    s->swdespeck_range.quant=1;

    if(1){
      s->swdespeck_range.min=0;
      s->swdespeck_range.max=9;
      opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT;
    }
    else
      opt->cap = SANE_CAP_INACTIVE;
  }

  /*crop by software*/
  if(option==OPT_SWCROP){
    opt->name = "swcrop";
    opt->title = "Software crop";
    opt->desc = "Request driver to remove border from pages digitally";
    opt->type = SANE_TYPE_BOOL;
    if (1)
     opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT | SANE_CAP_ADVANCED;
    else
     opt->cap = SANE_CAP_INACTIVE;
  }

  /*staple detection*/
  if(option==OPT_STAPLEDETECT){
    opt->name = "stapledetect";
    opt->title = "Staple detect";
    opt->desc = "Request scanner to halt if stapled pages are detected";
    opt->type = SANE_TYPE_BOOL;
    if (1)
     opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT | SANE_CAP_ADVANCED;
    else
     opt->cap = SANE_CAP_INACTIVE;
  }

  /*dropout color front*/
  if(option==OPT_DROPOUT_COLOR_F){
    s->do_color_list[0] = STRING_NONE;
    s->do_color_list[1] = STRING_RED;
    s->do_color_list[2] = STRING_GREEN;
    s->do_color_list[3] = STRING_BLUE;
    s->do_color_list[4] = STRING_EN_RED;
    s->do_color_list[5] = STRING_EN_GREEN;
    s->do_color_list[6] = STRING_EN_BLUE;
    s->do_color_list[7] = NULL;
  
    opt->name = "dropout-front";
    opt->title = "Dropout color front";
    opt->desc = "One-pass scanners use only one color during gray or binary scanning, useful for colored paper or ink";
    opt->type = SANE_TYPE_STRING;
    opt->constraint_type = SANE_CONSTRAINT_STRING_LIST;
    opt->constraint.string_list = s->do_color_list;
    opt->size = maxStringSize (opt->constraint.string_list);

    if (1){
      opt->cap = SANE_CAP_SOFT_SELECT|SANE_CAP_SOFT_DETECT|SANE_CAP_ADVANCED;
      if(s->u.mode == MODE_COLOR)
        opt->cap |= SANE_CAP_INACTIVE;
    }
    else
      opt->cap = SANE_CAP_INACTIVE;
  }

  /*dropout color back*/
  if(option==OPT_DROPOUT_COLOR_B){
    s->do_color_list[0] = STRING_NONE;
    s->do_color_list[1] = STRING_RED;
    s->do_color_list[2] = STRING_GREEN;
    s->do_color_list[3] = STRING_BLUE;
    s->do_color_list[4] = STRING_EN_RED;
    s->do_color_list[5] = STRING_EN_GREEN;
    s->do_color_list[6] = STRING_EN_BLUE;
    s->do_color_list[7] = NULL;
  
    opt->name = "dropout-back";
    opt->title = "Dropout color back";
    opt->desc = "One-pass scanners use only one color during gray or binary scanning, useful for colored paper or ink";
    opt->type = SANE_TYPE_STRING;
    opt->constraint_type = SANE_CONSTRAINT_STRING_LIST;
    opt->constraint.string_list = s->do_color_list;
    opt->size = maxStringSize (opt->constraint.string_list);

    if (1){
      opt->cap = SANE_CAP_SOFT_SELECT|SANE_CAP_SOFT_DETECT|SANE_CAP_ADVANCED;
      if(s->u.mode == MODE_COLOR)
        opt->cap |= SANE_CAP_INACTIVE;
    }
    else
      opt->cap = SANE_CAP_INACTIVE;
  }

  /*buffer mode*/
  if(option==OPT_BUFFERMODE){
    opt->name = "buffermode";
    opt->title = "Buffer mode";
    opt->desc = "Request scanner to read pages async into internal memory";
    opt->type = SANE_TYPE_BOOL;
    if (s->has_buffer)
     opt->cap = SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT | SANE_CAP_ADVANCED;
    else
     opt->cap = SANE_CAP_INACTIVE;
  }

  if(option==OPT_SIDE){
    opt->name = "side";
    opt->title = "Duplex side";
    opt->desc = "Tells which side (0=front, 1=back) of a duplex scan the next call to sane_read will return.";
    opt->type = SANE_TYPE_BOOL;
    opt->unit = SANE_UNIT_NONE;
    opt->size = sizeof(SANE_Word);
    opt->cap = SANE_CAP_SOFT_DETECT | SANE_CAP_ADVANCED;
    opt->constraint_type = SANE_CONSTRAINT_NONE;
  }

  /* "Sensor" group ------------------------------------------------------ */
  if(option==OPT_SENSOR_GROUP){
    opt->name = SANE_NAME_SENSORS;
    opt->title = SANE_TITLE_SENSORS;
    opt->desc = SANE_DESC_SENSORS;
    opt->type = SANE_TYPE_GROUP;
    opt->constraint_type = SANE_CONSTRAINT_NONE;
  }

  if(option==OPT_START){
    opt->name = "start";
    opt->title = "Start/1 button";
    opt->desc = "Big green or small 1 button";
    opt->type = SANE_TYPE_BOOL;
    opt->unit = SANE_UNIT_NONE;
    opt->cap = SANE_CAP_SOFT_DETECT | SANE_CAP_HARD_SELECT | SANE_CAP_ADVANCED;
    if(!s->can_read_panel)
      opt->cap = SANE_CAP_INACTIVE;
  }

  if(option==OPT_STOP){
    opt->name = "stop";
    opt->title = "Stop/2 button";
    opt->desc = "Small orange or small 2 button";
    opt->type = SANE_TYPE_BOOL;
    opt->unit = SANE_UNIT_NONE;
    opt->cap = SANE_CAP_SOFT_DETECT | SANE_CAP_HARD_SELECT | SANE_CAP_ADVANCED;
    if(!s->can_read_panel)
      opt->cap = SANE_CAP_INACTIVE;
  }

  if(option==OPT_BUTT3){
    opt->name = "button-3";
    opt->title = "3 button";
    opt->desc = "Small 3 button";
    opt->type = SANE_TYPE_BOOL;
    opt->unit = SANE_UNIT_NONE;
    opt->cap = SANE_CAP_SOFT_DETECT | SANE_CAP_HARD_SELECT | SANE_CAP_ADVANCED;
    if(!s->can_read_panel)
      opt->cap = SANE_CAP_INACTIVE;
  }

  if(option==OPT_NEWFILE){
    opt->name = "newfile";
    opt->title = "New File button";
    opt->desc = "New File button";
    opt->type = SANE_TYPE_BOOL;
    opt->unit = SANE_UNIT_NONE;
    opt->cap = SANE_CAP_SOFT_DETECT | SANE_CAP_HARD_SELECT | SANE_CAP_ADVANCED;
    if(!s->can_read_panel)
      opt->cap = SANE_CAP_INACTIVE;
  }

  if(option==OPT_COUNTONLY){
    opt->name = "countonly";
    opt->title = "Count Only button";
    opt->desc = "Count Only button";
    opt->type = SANE_TYPE_BOOL;
    opt->unit = SANE_UNIT_NONE;
    opt->cap = SANE_CAP_SOFT_DETECT | SANE_CAP_HARD_SELECT | SANE_CAP_ADVANCED;
    if(!s->can_read_panel)
      opt->cap = SANE_CAP_INACTIVE;
  }

  if(option==OPT_BYPASSMODE){
    opt->name = "bypassmode";
    opt->title = "Bypass Mode button";
    opt->desc = "Bypass Mode button";
    opt->type = SANE_TYPE_BOOL;
    opt->unit = SANE_UNIT_NONE;
    opt->cap = SANE_CAP_SOFT_DETECT | SANE_CAP_HARD_SELECT | SANE_CAP_ADVANCED;
    if(!s->can_read_panel)
      opt->cap = SANE_CAP_INACTIVE;
  }

  if(option==OPT_COUNTER){
    opt->name = "counter";
    opt->title = "Counter";
    opt->desc = "Scan counter";
    opt->type = SANE_TYPE_INT;
    opt->unit = SANE_UNIT_NONE;
    opt->constraint_type = SANE_CONSTRAINT_RANGE;
    opt->constraint.range = &s->counter_range;
    s->counter_range.min=0;
    s->counter_range.max=500;
    s->counter_range.quant=1;

    if (s->can_read_panel && s->has_counter)
     opt->cap = SANE_CAP_SOFT_DETECT | SANE_CAP_HARD_SELECT | SANE_CAP_ADVANCED;
    else
      opt->cap = SANE_CAP_INACTIVE;
  }

  if(option==OPT_ADF_LOADED){
    opt->name = "adf-loaded";
    opt->title = "ADF Loaded";
    opt->desc = "Paper available in ADF input hopper";
    opt->type = SANE_TYPE_BOOL;
    opt->unit = SANE_UNIT_NONE;
    opt->cap = SANE_CAP_SOFT_DETECT | SANE_CAP_HARD_SELECT | SANE_CAP_ADVANCED;
    if(!s->can_read_sensors)
      opt->cap = SANE_CAP_INACTIVE;
  }

  if(option==OPT_CARD_LOADED){
    opt->name = "card-loaded";
    opt->title = "Card Loaded";
    opt->desc = "Paper available in card reader";
    opt->type = SANE_TYPE_BOOL;
    opt->unit = SANE_UNIT_NONE;
    opt->cap = SANE_CAP_SOFT_DETECT | SANE_CAP_HARD_SELECT | SANE_CAP_ADVANCED;
    if(!s->can_read_sensors || !s->has_card)
      opt->cap = SANE_CAP_INACTIVE;
  }

  return opt;
}

/**
 * Gets or sets an option value.
 * 
 * From the SANE spec:
 * This function is used to set or inquire the current value of option
 * number n of the device represented by handle h. The manner in which
 * the option is controlled is specified by parameter action. The
 * possible values of this parameter are described in more detail
 * below.  The value of the option is passed through argument val. It
 * is a pointer to the memory that holds the option value. The memory
 * area pointed to by v must be big enough to hold the entire option
 * value (determined by member size in the corresponding option
 * descriptor).
 * 
 * The only exception to this rule is that when setting the value of a
 * string option, the string pointed to by argument v may be shorter
 * since the backend will stop reading the option value upon
 * encountering the first NUL terminator in the string. If argument i
 * is not NULL, the value of *i will be set to provide details on how
 * well the request has been met.
 */
SANE_Status
sane_control_option (SANE_Handle handle, SANE_Int option,
                     SANE_Action action, void *val, SANE_Int * info)
{
  struct scanner *s = (struct scanner *) handle;
  SANE_Int dummy = 0;
  SANE_Status ret = SANE_STATUS_GOOD;

  /* Make sure that all those statements involving *info cannot break (better
   * than having to do "if (info) ..." everywhere!)
   */
  if (info == 0)
    info = &dummy;

  if (option >= NUM_OPTIONS) {
    DBG (5, "sane_control_option: %d too big\n", option);
    return SANE_STATUS_INVAL;
  }

  if (!SANE_OPTION_IS_ACTIVE (s->opt[option].cap)) {
    DBG (5, "sane_control_option: %d inactive\n", option);
    return SANE_STATUS_INVAL;
  }

  /*
   * SANE_ACTION_GET_VALUE: We have to find out the current setting and
   * return it in a human-readable form (often, text).
   */
  if (action == SANE_ACTION_GET_VALUE) {
      SANE_Word * val_p = (SANE_Word *) val;

      DBG (20, "sane_control_option: get value for '%s' (%d)\n", s->opt[option].name,option);

      switch (option) {

        case OPT_NUM_OPTS:
          *val_p = NUM_OPTIONS;
          return SANE_STATUS_GOOD;

        case OPT_SOURCE:
          if(s->u.source == SOURCE_FLATBED){
            strcpy (val, STRING_FLATBED);
          }
          else if(s->u.source == SOURCE_ADF_FRONT){
            strcpy (val, STRING_ADFFRONT);
          }
          else if(s->u.source == SOURCE_ADF_BACK){
            strcpy (val, STRING_ADFBACK);
          }
          else if(s->u.source == SOURCE_ADF_DUPLEX){
            strcpy (val, STRING_ADFDUPLEX);
          }
          else if(s->u.source == SOURCE_CARD_FRONT){
            strcpy (val, STRING_CARDFRONT);
          }
          else if(s->u.source == SOURCE_CARD_BACK){
            strcpy (val, STRING_CARDBACK);
          }
          else if(s->u.source == SOURCE_CARD_DUPLEX){
            strcpy (val, STRING_CARDDUPLEX);
          }
          return SANE_STATUS_GOOD;

        case OPT_MODE:
          if(s->u.mode == MODE_LINEART){
            strcpy (val, STRING_LINEART);
          }
          else if(s->u.mode == MODE_HALFTONE){
            strcpy (val, STRING_HALFTONE);
          }
          else if(s->u.mode == MODE_GRAYSCALE){
            strcpy (val, STRING_GRAYSCALE);
          }
          else if(s->u.mode == MODE_COLOR){
            strcpy (val, STRING_COLOR);
          }
          return SANE_STATUS_GOOD;

        case OPT_RES:
          *val_p = s->u.dpi_x;
          return SANE_STATUS_GOOD;

        case OPT_TL_X:
          *val_p = SCANNER_UNIT_TO_FIXED_MM(s->u.tl_x);
          return SANE_STATUS_GOOD;

        case OPT_TL_Y:
          *val_p = SCANNER_UNIT_TO_FIXED_MM(s->u.tl_y);
          return SANE_STATUS_GOOD;

        case OPT_BR_X:
          *val_p = SCANNER_UNIT_TO_FIXED_MM(s->u.br_x);
          return SANE_STATUS_GOOD;

        case OPT_BR_Y:
          *val_p = SCANNER_UNIT_TO_FIXED_MM(s->u.br_y);
          return SANE_STATUS_GOOD;

        case OPT_PAGE_WIDTH:
          *val_p = SCANNER_UNIT_TO_FIXED_MM(s->u.page_x);
          return SANE_STATUS_GOOD;

        case OPT_PAGE_HEIGHT:
          *val_p = SCANNER_UNIT_TO_FIXED_MM(s->u.page_y);
          return SANE_STATUS_GOOD;

        case OPT_BRIGHTNESS:
          *val_p = s->brightness;
          return SANE_STATUS_GOOD;

        case OPT_CONTRAST:
          *val_p = s->contrast;
          return SANE_STATUS_GOOD;

        case OPT_THRESHOLD:
          *val_p = s->threshold;
          return SANE_STATUS_GOOD;

        case OPT_RIF:
          *val_p = s->rif;
          return SANE_STATUS_GOOD;

        /* Advanced Group */
        case OPT_COMPRESS:
          if(s->compress == COMP_JPEG){
            strcpy (val, STRING_JPEG);
          }
          else{
            strcpy (val, STRING_NONE);
          }
          return SANE_STATUS_GOOD;

        case OPT_COMPRESS_ARG:
          *val_p = s->compress_arg;
          return SANE_STATUS_GOOD;

        case OPT_DF_LENGTH:
          *val_p = s->df_length;
          return SANE_STATUS_GOOD;

        case OPT_DF_THICKNESS:
          *val_p = s->df_thickness;
          return SANE_STATUS_GOOD;

        case OPT_ROLLERDESKEW:
          *val_p = s->rollerdeskew;
          return SANE_STATUS_GOOD;

        case OPT_SWDESKEW:
          *val_p = s->swdeskew;
          return SANE_STATUS_GOOD;

        case OPT_SWDESPECK:
          *val_p = s->swdespeck;
          return SANE_STATUS_GOOD;

        case OPT_SWCROP:
          *val_p = s->swcrop;
          return SANE_STATUS_GOOD;

        case OPT_STAPLEDETECT:
          *val_p = s->stapledetect;
          return SANE_STATUS_GOOD;

        case OPT_DROPOUT_COLOR_F:
          switch (s->dropout_color_f) {
            case COLOR_NONE:
              strcpy (val, STRING_NONE);
              break;
            case COLOR_RED:
              strcpy (val, STRING_RED);
              break;
            case COLOR_GREEN:
              strcpy (val, STRING_GREEN);
              break;
            case COLOR_BLUE:
              strcpy (val, STRING_BLUE);
              break;
            case COLOR_EN_RED:
              strcpy (val, STRING_EN_RED);
              break;
            case COLOR_EN_GREEN:
              strcpy (val, STRING_EN_GREEN);
              break;
            case COLOR_EN_BLUE:
              strcpy (val, STRING_EN_BLUE);
              break;
          }
          return SANE_STATUS_GOOD;

        case OPT_DROPOUT_COLOR_B:
          switch (s->dropout_color_b) {
            case COLOR_NONE:
              strcpy (val, STRING_NONE);
              break;
            case COLOR_RED:
              strcpy (val, STRING_RED);
              break;
            case COLOR_GREEN:
              strcpy (val, STRING_GREEN);
              break;
            case COLOR_BLUE:
              strcpy (val, STRING_BLUE);
              break;
            case COLOR_EN_RED:
              strcpy (val, STRING_EN_RED);
              break;
            case COLOR_EN_GREEN:
              strcpy (val, STRING_EN_GREEN);
              break;
            case COLOR_EN_BLUE:
              strcpy (val, STRING_EN_BLUE);
              break;
          }
          return SANE_STATUS_GOOD;

        case OPT_BUFFERMODE:
          *val_p = s->buffermode;
          return SANE_STATUS_GOOD;

        case OPT_SIDE:
          *val_p = s->side;
          return SANE_STATUS_GOOD;

        /* Sensor Group */
        case OPT_START:
          ret = read_panel(s,OPT_START);
          *val_p = s->panel_start;
          return ret;

        case OPT_STOP:
          ret = read_panel(s,OPT_STOP);
          *val_p = s->panel_stop;
          return ret;

        case OPT_BUTT3:
          ret = read_panel(s,OPT_BUTT3);
          *val_p = s->panel_butt3;
          return ret;

        case OPT_NEWFILE:
          ret = read_panel(s,OPT_NEWFILE);
          *val_p = s->panel_new_file;
          return ret;

        case OPT_COUNTONLY:
          ret = read_panel(s,OPT_COUNTONLY);
          *val_p = s->panel_count_only;
          return ret;

        case OPT_BYPASSMODE:
          ret = read_panel(s,OPT_BYPASSMODE);
          *val_p = s->panel_bypass_mode;
          return ret;

        case OPT_COUNTER:
          ret = read_panel(s,OPT_COUNTER);
          *val_p = s->panel_counter;
          return ret;

        case OPT_ADF_LOADED:
          ret = read_sensors(s,OPT_ADF_LOADED);
          *val_p = s->sensor_adf_loaded;
          return ret;

        case OPT_CARD_LOADED:
          ret = read_sensors(s,OPT_CARD_LOADED);
          *val_p = s->sensor_card_loaded;
          return ret;
      }
  }
  else if (action == SANE_ACTION_SET_VALUE) {
      int tmp;
      SANE_Word val_c;
      SANE_Status status;

      DBG (20, "sane_control_option: set value for '%s' (%d)\n", s->opt[option].name,option);

      if ( s->started ) {
        DBG (5, "sane_control_option: cant set, device busy\n");
        return SANE_STATUS_DEVICE_BUSY;
      }

      if (!SANE_OPTION_IS_SETTABLE (s->opt[option].cap)) {
        DBG (5, "sane_control_option: not settable\n");
        return SANE_STATUS_INVAL;
      }

      status = sanei_constrain_value (s->opt + option, val, info);
      if (status != SANE_STATUS_GOOD) {
        DBG (5, "sane_control_option: bad value\n");
        return status;
      }

      /* may have been changed by constrain, so dont copy until now */
      val_c = *(SANE_Word *)val;

      /*
       * Note - for those options which can assume one of a list of
       * valid values, we can safely assume that they will have
       * exactly one of those values because that's what
       * sanei_constrain_value does. Hence no "else: invalid" branches
       * below.
       */
      switch (option) {
 
        /* Mode Group */
        case OPT_SOURCE:
          if (!strcmp (val, STRING_ADFFRONT)) {
            tmp = SOURCE_ADF_FRONT;
          }
          else if (!strcmp (val, STRING_ADFBACK)) {
            tmp = SOURCE_ADF_BACK;
          }
          else if (!strcmp (val, STRING_ADFDUPLEX)) {
            tmp = SOURCE_ADF_DUPLEX;
          }
          else if (!strcmp (val, STRING_CARDFRONT)) {
            tmp = SOURCE_CARD_FRONT;
          }
          else if (!strcmp (val, STRING_CARDBACK)) {
            tmp = SOURCE_CARD_BACK;
          }
          else if (!strcmp (val, STRING_CARDDUPLEX)) {
            tmp = SOURCE_CARD_DUPLEX;
          }
          else{
            tmp = SOURCE_FLATBED;
          }

          if (s->u.source == tmp) 
              return SANE_STATUS_GOOD;

          s->u.source = tmp;

          *info |= SANE_INFO_RELOAD_PARAMS | SANE_INFO_RELOAD_OPTIONS;
          return SANE_STATUS_GOOD;

        case OPT_MODE:
          if (!strcmp (val, STRING_LINEART)) {
            tmp = MODE_LINEART;
          }
          else if (!strcmp (val, STRING_HALFTONE)) {
            tmp = MODE_HALFTONE;
          }
          else if (!strcmp (val, STRING_GRAYSCALE)) {
            tmp = MODE_GRAYSCALE;
          }
          else{
            tmp = MODE_COLOR;
          }

          if (tmp == s->u.mode)
              return SANE_STATUS_GOOD;

          s->u.mode = tmp;

          *info |= SANE_INFO_RELOAD_PARAMS | SANE_INFO_RELOAD_OPTIONS;
          return SANE_STATUS_GOOD;

        case OPT_RES:

          if (s->u.dpi_x == val_c && s->u.dpi_y == val_c) 
              return SANE_STATUS_GOOD;

          s->u.dpi_x = val_c;
          s->u.dpi_y = val_c;

          *info |= SANE_INFO_RELOAD_PARAMS | SANE_INFO_RELOAD_OPTIONS;
          return SANE_STATUS_GOOD;

        /* Geometry Group */
        case OPT_TL_X:
          if (s->u.tl_x == FIXED_MM_TO_SCANNER_UNIT(val_c))
              return SANE_STATUS_GOOD;

          s->u.tl_x = FIXED_MM_TO_SCANNER_UNIT(val_c);

          *info |= SANE_INFO_RELOAD_PARAMS | SANE_INFO_RELOAD_OPTIONS;
          return SANE_STATUS_GOOD;

        case OPT_TL_Y:
          if (s->u.tl_y == FIXED_MM_TO_SCANNER_UNIT(val_c))
              return SANE_STATUS_GOOD;

          s->u.tl_y = FIXED_MM_TO_SCANNER_UNIT(val_c);

          *info |= SANE_INFO_RELOAD_PARAMS | SANE_INFO_RELOAD_OPTIONS;
          return SANE_STATUS_GOOD;

        case OPT_BR_X:
          if (s->u.br_x == FIXED_MM_TO_SCANNER_UNIT(val_c))
              return SANE_STATUS_GOOD;

          s->u.br_x = FIXED_MM_TO_SCANNER_UNIT(val_c);

          *info |= SANE_INFO_RELOAD_PARAMS | SANE_INFO_RELOAD_OPTIONS;
          return SANE_STATUS_GOOD;

        case OPT_BR_Y:
          if (s->u.br_y == FIXED_MM_TO_SCANNER_UNIT(val_c))
              return SANE_STATUS_GOOD;

          s->u.br_y = FIXED_MM_TO_SCANNER_UNIT(val_c);

          *info |= SANE_INFO_RELOAD_PARAMS | SANE_INFO_RELOAD_OPTIONS;
          return SANE_STATUS_GOOD;

        case OPT_PAGE_WIDTH:
          if (s->u.page_x == FIXED_MM_TO_SCANNER_UNIT(val_c))
              return SANE_STATUS_GOOD;

          s->u.page_x = FIXED_MM_TO_SCANNER_UNIT(val_c);

          *info |= SANE_INFO_RELOAD_OPTIONS;
          return SANE_STATUS_GOOD;

        case OPT_PAGE_HEIGHT:
          if (s->u.page_y == FIXED_MM_TO_SCANNER_UNIT(val_c))
              return SANE_STATUS_GOOD;

          s->u.page_y = FIXED_MM_TO_SCANNER_UNIT(val_c);

          *info |= SANE_INFO_RELOAD_OPTIONS;
          return SANE_STATUS_GOOD;

        /* Enhancement Group */
        case OPT_BRIGHTNESS:
          s->brightness = val_c;
          return SANE_STATUS_GOOD;

        case OPT_CONTRAST:
          s->contrast = val_c;
          return SANE_STATUS_GOOD;

        case OPT_THRESHOLD:
          s->threshold = val_c;
          return SANE_STATUS_GOOD;

        case OPT_RIF:
          s->rif = val_c;
          return SANE_STATUS_GOOD;

        /* Advanced Group */
        case OPT_COMPRESS:
          if (!strcmp (val, STRING_JPEG)) {
            s->compress = COMP_JPEG;
          }
          else{
            s->compress = COMP_NONE;
          }
          return SANE_STATUS_GOOD;

        case OPT_COMPRESS_ARG:
          s->compress_arg = val_c;
          return SANE_STATUS_GOOD;

        case OPT_DF_LENGTH:
          s->df_length = val_c;
          return SANE_STATUS_GOOD;

        case OPT_DF_THICKNESS:
          s->df_thickness = val_c;
          return SANE_STATUS_GOOD;

        case OPT_ROLLERDESKEW:
          s->rollerdeskew = val_c;
          return SANE_STATUS_GOOD;

        case OPT_SWDESKEW:
          s->swdeskew = val_c;
          return SANE_STATUS_GOOD;

        case OPT_SWDESPECK:
          s->swdespeck = val_c;
          return SANE_STATUS_GOOD;

        case OPT_SWCROP:
          s->swcrop = val_c;
          return SANE_STATUS_GOOD;

        case OPT_STAPLEDETECT:
          s->stapledetect = val_c;
          return SANE_STATUS_GOOD;

        case OPT_DROPOUT_COLOR_F:
          if (!strcmp(val, STRING_NONE))
            s->dropout_color_f = COLOR_NONE;
          else if (!strcmp(val, STRING_RED))
            s->dropout_color_f = COLOR_RED;
          else if (!strcmp(val, STRING_GREEN))
            s->dropout_color_f = COLOR_GREEN;
          else if (!strcmp(val, STRING_BLUE))
            s->dropout_color_f = COLOR_BLUE;
          else if (!strcmp(val, STRING_EN_RED))
            s->dropout_color_f = COLOR_EN_RED;
          else if (!strcmp(val, STRING_EN_GREEN))
            s->dropout_color_f = COLOR_EN_GREEN;
          else if (!strcmp(val, STRING_EN_BLUE))
            s->dropout_color_f = COLOR_EN_BLUE;
          return SANE_STATUS_GOOD;

        case OPT_DROPOUT_COLOR_B:
          if (!strcmp(val, STRING_NONE))
            s->dropout_color_b = COLOR_NONE;
          else if (!strcmp(val, STRING_RED))
            s->dropout_color_b = COLOR_RED;
          else if (!strcmp(val, STRING_GREEN))
            s->dropout_color_b = COLOR_GREEN;
          else if (!strcmp(val, STRING_BLUE))
            s->dropout_color_b = COLOR_BLUE;
          else if (!strcmp(val, STRING_EN_RED))
            s->dropout_color_b = COLOR_EN_RED;
          else if (!strcmp(val, STRING_EN_GREEN))
            s->dropout_color_b = COLOR_EN_GREEN;
          else if (!strcmp(val, STRING_EN_BLUE))
            s->dropout_color_b = COLOR_EN_BLUE;
          return SANE_STATUS_GOOD;

        case OPT_BUFFERMODE:
          s->buffermode = val_c;
          return SANE_STATUS_GOOD;

      }
  }                           /* else */

  return SANE_STATUS_INVAL;
}

static SANE_Status
ssm_buffer (struct scanner *s)
{
  SANE_Status ret = SANE_STATUS_GOOD;

  DBG (10, "ssm_buffer: start\n");

  if(s->has_ssm){
  
    unsigned char cmd[SET_SCAN_MODE_len];
    size_t cmdLen = SET_SCAN_MODE_len;
  
    unsigned char out[SSM_PAY_len];
    size_t outLen = SSM_PAY_len;
  
    memset(cmd,0,cmdLen);
    set_SCSI_opcode(cmd, SET_SCAN_MODE_code);
    set_SSM_pf(cmd, 1);
    set_SSM_pay_len(cmd, outLen);
  
    memset(out,0,outLen);
    if(s->has_ssm_pay_head_len){
      set_SSM_pay_head_len(out, SSM_PAY_HEAD_len);
    }
    set_SSM_page_code(out, SM_pc_buffer);
    set_SSM_page_len(out, SSM_PAGE_len);
  
    if(s->s.source == SOURCE_ADF_DUPLEX || s->s.source == SOURCE_CARD_DUPLEX){
      set_SSM_BUFF_duplex(out, 1);
    }
    if(s->s.source == SOURCE_FLATBED){
      set_SSM_BUFF_fb(out, 1);
    }
    else if(s->s.source >= SOURCE_CARD_FRONT){
      set_SSM_BUFF_card(out, 1);
    }
    if(s->buffermode){
      set_SSM_BUFF_async(out, 1);
    }
    if(0){
      set_SSM_BUFF_ald(out, 1);
    }
    if(0){
      set_SSM_BUFF_unk(out,1);
    }
  
    ret = do_cmd (
        s, 1, 0,
        cmd, cmdLen,
        out, outLen,
        NULL, NULL
    );
  }

  else if(s->has_ssm2){

    unsigned char cmd[SET_SCAN_MODE2_len];
    size_t cmdLen = SET_SCAN_MODE2_len;
  
    unsigned char out[SSM2_PAY_len];
    size_t outLen = SSM2_PAY_len;
  
    memset(cmd,0,cmdLen);
    set_SCSI_opcode(cmd, SET_SCAN_MODE2_code);
    set_SSM2_page_code(cmd, SM2_pc_buffer);
    set_SSM2_pay_len(cmd, outLen);
  
    memset(out,0,outLen);
    set_SSM2_BUFF_unk(out, !s->buffermode);
    set_SSM2_BUFF_unk2(out, 0x40);
    set_SSM2_BUFF_sync(out, !s->buffermode);
  
    ret = do_cmd (
        s, 1, 0,
        cmd, cmdLen,
        out, outLen,
        NULL, NULL
    );
  }

  else{
    DBG (10, "ssm_buffer: unsupported\n");
  }

  DBG (10, "ssm_buffer: finish\n");

  return ret;
}

static SANE_Status
ssm_df (struct scanner *s)
{
  SANE_Status ret = SANE_STATUS_GOOD;

  DBG (10, "ssm_df: start\n");
  
  if(!s->has_df){
    DBG (10, "ssm_df: unsupported, finishing\n");
    return ret;
  }
  
  if(s->has_ssm){

    unsigned char cmd[SET_SCAN_MODE_len];
    size_t cmdLen = SET_SCAN_MODE_len;
  
    unsigned char out[SSM_PAY_len];
    size_t outLen = SSM_PAY_len;
  
    memset(cmd,0,cmdLen);
    set_SCSI_opcode(cmd, SET_SCAN_MODE_code);
    set_SSM_pf(cmd, 1);
    set_SSM_pay_len(cmd, outLen);
  
    memset(out,0,outLen);
    if(s->has_ssm_pay_head_len){
      set_SSM_pay_head_len(out, SSM_PAY_HEAD_len);
    }
    set_SSM_page_code(out, SM_pc_df);
    set_SSM_page_len(out, SSM_PAGE_len);
  
    /* deskew by roller */
    if(s->rollerdeskew){
      set_SSM_DF_deskew_roll(out, 1);
    }
    
    /* staple detection */
    if(s->stapledetect){
      set_SSM_DF_staple(out, 1);
    }
  
    /* thickness */
    if(s->df_thickness){
      set_SSM_DF_thick(out, 1);
    }
    
    /* length */
    if(s->df_length){
      set_SSM_DF_len(out, 1);
    }
  
    ret = do_cmd (
        s, 1, 0,
        cmd, cmdLen,
        out, outLen,
        NULL, NULL
    );

  }

  else if(s->has_ssm2){

    unsigned char cmd[SET_SCAN_MODE2_len];
    size_t cmdLen = SET_SCAN_MODE2_len;
  
    unsigned char out[SSM2_PAY_len];
    size_t outLen = SSM2_PAY_len;

    /* send ultrasonic offsets first */
    if(s->df_thickness && s->has_df_ultra){
      memset(cmd,0,cmdLen);
      set_SCSI_opcode(cmd, SET_SCAN_MODE2_code);
      set_SSM2_page_code(cmd, SM2_pc_ultra);
      set_SSM2_pay_len(cmd, outLen);
    
      memset(out,0,outLen);
      set_SSM2_ULTRA_top(out, 0);
      set_SSM2_ULTRA_bot(out, 0);
  
      ret = do_cmd (
          s, 1, 0,
          cmd, cmdLen,
          out, outLen,
          NULL, NULL
      );
    }

    memset(cmd,0,cmdLen);
    set_SCSI_opcode(cmd, SET_SCAN_MODE2_code);
    set_SSM2_page_code(cmd, SM2_pc_df);
    set_SSM2_pay_len(cmd, outLen);
  
    memset(out,0,outLen);
  
    /* thickness */
    if(s->df_thickness){
      set_SSM2_DF_thick(out, 1);
    }
    
    /* length */
    if(s->df_length){
      set_SSM2_DF_len(out, 1);
    }
  
    ret = do_cmd (
        s, 1, 0,
        cmd, cmdLen,
        out, outLen,
        NULL, NULL
    );

  }

  else{
    DBG (10, "ssm_df: unsupported\n");
  }

  DBG (10, "ssm_df: finish\n");

  return ret;
}

static SANE_Status
ssm_do (struct scanner *s)
{
  SANE_Status ret = SANE_STATUS_GOOD;

 DBG (10, "ssm_do: start\n");

 if(!s->can_color){
   DBG (10, "ssm_do: unsupported, finishing\n");
   return ret;
 }
  
 if(s->has_ssm){

    unsigned char cmd[SET_SCAN_MODE_len];
    size_t cmdLen = SET_SCAN_MODE_len;
  
    unsigned char out[SSM_PAY_len];
    size_t outLen = SSM_PAY_len;
  
    memset(cmd,0,cmdLen);
    set_SCSI_opcode(cmd, SET_SCAN_MODE_code);
    set_SSM_pf(cmd, 1);
    set_SSM_pay_len(cmd, outLen);
  
    memset(out,0,outLen);
    if(s->has_ssm_pay_head_len){
      set_SSM_pay_head_len(out, SSM_PAY_HEAD_len);
    }
    set_SSM_page_code(out, SM_pc_dropout);
    set_SSM_page_len(out, SSM_PAGE_len);
  
    set_SSM_DO_unk1(out, 0x03);
  
    switch(s->dropout_color_f){
      case COLOR_RED:
        set_SSM_DO_unk2(out, 0x05);
        set_SSM_DO_f_do(out,SSM_DO_red);
        break;
      case COLOR_GREEN:
        set_SSM_DO_unk2(out, 0x05);
        set_SSM_DO_f_do(out,SSM_DO_green);
        break;
      case COLOR_BLUE:
        set_SSM_DO_unk2(out, 0x05);
        set_SSM_DO_f_do(out,SSM_DO_blue);
        break;
      case COLOR_EN_RED:
        set_SSM_DO_unk2(out, 0x05);
        set_SSM_DO_f_en(out,SSM_DO_red);
        break;
      case COLOR_EN_GREEN:
        set_SSM_DO_unk2(out, 0x05);
        set_SSM_DO_f_en(out,SSM_DO_green);
        break;
      case COLOR_EN_BLUE:
        set_SSM_DO_unk2(out, 0x05);
        set_SSM_DO_f_en(out,SSM_DO_blue);
        break;
    }
  
    switch(s->dropout_color_b){
      case COLOR_RED:
        set_SSM_DO_unk2(out, 0x05);
        set_SSM_DO_b_do(out,SSM_DO_red);
        break;
      case COLOR_GREEN:
        set_SSM_DO_unk2(out, 0x05);
        set_SSM_DO_b_do(out,SSM_DO_green);
        break;
      case COLOR_BLUE:
        set_SSM_DO_unk2(out, 0x05);
        set_SSM_DO_b_do(out,SSM_DO_blue);
        break;
      case COLOR_EN_RED:
        set_SSM_DO_unk2(out, 0x05);
        set_SSM_DO_b_en(out,SSM_DO_red);
        break;
      case COLOR_EN_GREEN:
        set_SSM_DO_unk2(out, 0x05);
        set_SSM_DO_b_en(out,SSM_DO_green);
        break;
      case COLOR_EN_BLUE:
        set_SSM_DO_unk2(out, 0x05);
        set_SSM_DO_b_en(out,SSM_DO_blue);
        break;
    }
  
    ret = do_cmd (
        s, 1, 0,
        cmd, cmdLen,
        out, outLen,
        NULL, NULL
    );

  }

  else if(s->has_ssm2){

    unsigned char cmd[SET_SCAN_MODE2_len];
    size_t cmdLen = SET_SCAN_MODE2_len;
  
    unsigned char out[SSM2_PAY_len];
    size_t outLen = SSM2_PAY_len;
  
    memset(cmd,0,cmdLen);
    set_SCSI_opcode(cmd, SET_SCAN_MODE2_code);
    set_SSM2_page_code(cmd, SM2_pc_dropout);
    set_SSM2_pay_len(cmd, outLen);
  
    memset(out,0,outLen);
  
    switch(s->dropout_color_f){
      case COLOR_RED:
        set_SSM2_DO_do(out,SSM_DO_red);
        break;
      case COLOR_GREEN:
        set_SSM2_DO_do(out,SSM_DO_green);
        break;
      case COLOR_BLUE:
        set_SSM2_DO_do(out,SSM_DO_blue);
        break;
      case COLOR_EN_RED:
        set_SSM2_DO_en(out,SSM_DO_red);
        break;
      case COLOR_EN_GREEN:
        set_SSM2_DO_en(out,SSM_DO_green);
        break;
      case COLOR_EN_BLUE:
        set_SSM2_DO_en(out,SSM_DO_blue);
        break;
    }

    ret = do_cmd (
        s, 1, 0,
        cmd, cmdLen,
        out, outLen,
        NULL, NULL
    );
  }

  else{
    DBG (10, "ssm_do: unsupported\n");
  }

  DBG (10, "ssm_do: finish\n");

  return ret;
}

static SANE_Status
read_sensors(struct scanner *s,SANE_Int option)
{
  SANE_Status ret=SANE_STATUS_GOOD;

  unsigned char cmd[READ_len];
  size_t cmdLen = READ_len;

  unsigned char in[R_SENSORS_len];
  size_t inLen = R_SENSORS_len;

  DBG (10, "read_sensors: start %d\n", option);
 
  if(!s->can_read_sensors){
    DBG (10, "read_sensors: unsupported, finishing\n");
    return ret;
  }

  /* only run this if frontend has already read the last time we got it */
  /* or if we don't care for such bookkeeping (private use) */
  if (!option || !s->sensors_read[option-OPT_ADF_LOADED]) {

    DBG (15, "read_sensors: running\n");

    memset(cmd,0,cmdLen);
    set_SCSI_opcode(cmd, READ_code);
    set_R_datatype_code (cmd, SR_datatype_sensors);
    set_R_xfer_length (cmd, inLen);
    
    ret = do_cmd (
      s, 1, 0,
      cmd, cmdLen,
      NULL, 0,
      in, &inLen
    );
    
    if (ret == SANE_STATUS_GOOD || ret == SANE_STATUS_EOF) {
      /*set flags indicating there is data to read*/
      memset(s->sensors_read,1,sizeof(s->sensors_read));

      s->sensor_adf_loaded = get_R_SENSORS_adf(in);
      s->sensor_card_loaded = get_R_SENSORS_card(in);

      ret = SANE_STATUS_GOOD;
    }
  }
  
  if(option)
    s->sensors_read[option-OPT_ADF_LOADED] = 0;

  DBG (10, "read_sensors: finish\n");
  
  return ret;
}

static SANE_Status
read_panel(struct scanner *s,SANE_Int option)
{
  SANE_Status ret=SANE_STATUS_GOOD;

  unsigned char cmd[READ_len];
  size_t cmdLen = READ_len;

  unsigned char in[R_PANEL_len];
  size_t inLen = R_PANEL_len;

  DBG (10, "read_panel: start %d\n", option);
 
  if(!s->can_read_panel){
    DBG (10, "read_panel: unsupported, finishing\n");
    return ret;
  }

  /* only run this if frontend has already read the last time we got it */
  /* or if we don't care for such bookkeeping (private use) */
  if (!option || !s->panel_read[option-OPT_START]) {

    DBG (15, "read_panel: running\n");

    memset(cmd,0,cmdLen);
    set_SCSI_opcode(cmd, READ_code);
    set_R_datatype_code (cmd, SR_datatype_panel);
    set_R_xfer_length (cmd, inLen);
    
    ret = do_cmd (
      s, 1, 0,
      cmd, cmdLen,
      NULL, 0,
      in, &inLen
    );
    
    if (ret == SANE_STATUS_GOOD || ret == SANE_STATUS_EOF) {
      /*set flags indicating there is data to read*/
      memset(s->panel_read,1,sizeof(s->panel_read));

      s->panel_start = get_R_PANEL_start(in);
      s->panel_stop = get_R_PANEL_stop(in);
      s->panel_butt3 = get_R_PANEL_butt3(in);
      s->panel_new_file = get_R_PANEL_new_file(in);
      s->panel_count_only = get_R_PANEL_count_only(in);
      s->panel_bypass_mode = get_R_PANEL_bypass_mode(in);
      s->panel_enable_led = get_R_PANEL_enable_led(in);
      s->panel_counter = get_R_PANEL_counter(in);

      ret = SANE_STATUS_GOOD;
    }
  }
  
  if(option)
    s->panel_read[option-OPT_START] = 0;

  DBG (10, "read_panel: finish %d\n",s->panel_counter);
  
  return ret;
}

static SANE_Status
send_panel(struct scanner *s)
{
    SANE_Status ret=SANE_STATUS_GOOD;

    unsigned char cmd[SEND_len];
    size_t cmdLen = SEND_len;

    unsigned char out[S_PANEL_len];
    size_t outLen = S_PANEL_len;

    DBG (10, "send_panel: start\n");

    if(!s->can_write_panel){
      DBG (10, "send_panel: unsupported, finishing\n");
      return ret;
    }

    memset(cmd,0,cmdLen);
    set_SCSI_opcode(cmd, SEND_code);
    set_S_xfer_datatype (cmd, SR_datatype_panel);
    set_S_xfer_length (cmd, outLen);

    memset(out,0,outLen);
    set_S_PANEL_enable_led(out,s->panel_enable_led);
    set_S_PANEL_counter(out,s->panel_counter);
  
    ret = do_cmd (
      s, 1, 0,
      cmd, cmdLen,
      out, outLen,
      NULL, NULL
    );
  
    if (ret == SANE_STATUS_EOF) {
        ret = SANE_STATUS_GOOD;
    }
  
    DBG (10, "send_panel: finish %d\n", ret);
  
    return ret;
}

/*
 * @@ Section 4 - SANE scanning functions
 */
/*
 * Called by SANE to retrieve information about the type of data
 * that the current scan will return.
 *
 * From the SANE spec:
 * This function is used to obtain the current scan parameters. The
 * returned parameters are guaranteed to be accurate between the time
 * a scan has been started (sane_start() has been called) and the
 * completion of that request. Outside of that window, the returned
 * values are best-effort estimates of what the parameters will be
 * when sane_start() gets invoked.
 * 
 * Calling this function before a scan has actually started allows,
 * for example, to get an estimate of how big the scanned image will
 * be. The parameters passed to this function are the handle h of the
 * device for which the parameters should be obtained and a pointer p
 * to a parameter structure.
 */
SANE_Status
sane_get_parameters (SANE_Handle handle, SANE_Parameters * params)
{
    SANE_Status ret = SANE_STATUS_GOOD;
    struct scanner *s = (struct scanner *) handle;
  
    DBG (10, "sane_get_parameters: start\n");

    if(!s->started){
      ret = update_params(s,0);
      if(ret){
        DBG (5, "sane_get_parameters: up error, returning %d\n", ret);
        return ret;
      }
    }

    /* this backend only sends single frame images */
    params->last_frame = 1;

    params->format = s->i.format;
    params->lines = s->i.height;
    params->depth = s->i.bpp;
    if(params->depth == 24) params->depth = 8;
    params->pixels_per_line = s->i.width;
    params->bytes_per_line = s->i.Bpl;

    DBG(15,"sane_get_parameters: x: max=%d, page=%d, gpw=%d, res=%d\n",
      s->valid_x, s->i.page_x, get_page_width(s), s->i.dpi_x);

    DBG(15,"sane_get_parameters: y: max=%d, page=%d, gph=%d, res=%d\n",
      s->max_y, s->i.page_y, get_page_height(s), s->i.dpi_y);

    DBG(15,"sane_get_parameters: area: tlx=%d, brx=%d, tly=%d, bry=%d\n",
      s->i.tl_x, s->i.br_x, s->i.tl_y, s->i.br_y);

    DBG (15, "sane_get_parameters: params: ppl=%d, Bpl=%d, lines=%d\n", 
      params->pixels_per_line, params->bytes_per_line, params->lines);

    DBG (15, "sane_get_parameters: params: format=%d, depth=%d, last=%d\n", 
      params->format, params->depth, params->last_frame);

    DBG (10, "sane_get_parameters: finish\n");
  
    return ret;
}

SANE_Status
update_params(struct scanner *s, int calib)
{
    SANE_Status ret = SANE_STATUS_GOOD;
  
    DBG (10, "update_params: start\n");
  
    s->u.width = (s->u.br_x - s->u.tl_x) * s->u.dpi_x / 1200;
    s->u.height = (s->u.br_y - s->u.tl_y) * s->u.dpi_y / 1200;

    if (s->u.mode == MODE_COLOR) {
      s->u.format = SANE_FRAME_RGB;
      s->u.bpp = 24;
    }
    else if (s->u.mode == MODE_GRAYSCALE) {
      s->u.format = SANE_FRAME_GRAY;
      s->u.bpp = 8;
    }
    else {
      s->u.format = SANE_FRAME_GRAY;
      s->u.bpp = 1;

      /* round down to byte boundary */
      s->u.width -= s->u.width % 8;
    }

    /* round down to pixel boundary for some scanners */
    s->u.width -= s->u.width % s->ppl_mod;

    /* jpeg requires 8x8 squares */
    if(s->compress == COMP_JPEG && s->u.mode >= MODE_GRAYSCALE){
      s->u.format = SANE_FRAME_JPEG;
      s->u.width -= s->u.width % 8;
      s->u.height -= s->u.height % 8;
    }

    s->u.Bpl = s->u.width * s->u.bpp / 8;
    s->u.valid_Bpl = s->u.Bpl;
    s->u.valid_width = s->u.width;

    DBG (15, "update_params: user params: w:%d h:%d m:%d f:%d b:%d\n",
      s->u.width, s->u.height, s->u.mode, s->u.format, s->u.bpp);
    DBG (15, "update_params: user params: B:%d vB:%d vw:%d\n",
      s->u.Bpl, s->u.valid_Bpl, s->u.valid_width);
    DBG (15, "update_params: user params: x b:%d t:%d d:%d y b:%d t:%d d:%d\n",
      s->u.br_x, s->u.tl_x, s->u.dpi_x, s->u.br_y, s->u.tl_y, s->u.dpi_y);

    /* some scanners are limited in their valid scan params
     * make a second version of the params struct, but 
     * override the user's values with what the scanner can actually do */

    memcpy(&s->s,&s->u,sizeof(struct img_params));

    /*********** missing modes (move up to valid one) **************/
    if(s->s.mode == MODE_LINEART && !s->can_monochrome){
      s->s.mode = MODE_GRAYSCALE;
      s->s.format = SANE_FRAME_GRAY;
      s->s.bpp = 8;
    }
    if(s->s.mode == MODE_GRAYSCALE && !s->can_grayscale){
      s->s.mode = MODE_COLOR;
      s->s.format = SANE_FRAME_RGB;
      s->s.bpp = 24;
    }
    if(s->s.mode == MODE_COLOR && !s->can_color){
      DBG (5, "update_params: no valid mode\n");
      return SANE_STATUS_INVAL;
    }

    /********** missing resolutions (move up to valid one) *********/
    if(!s->step_x_res){
      int i;
      for(i=0;i<DPI_1200;i++){

        /* this res is smaller or invalid, skip it */
        if(s->s.dpi_x > dpi_list[i] || !s->std_res_x[i])
          continue;

        /* same & valid res, done */
        if(s->s.dpi_x == dpi_list[i])
          break;

        /* different & valid res, switch */
        s->s.dpi_x = dpi_list[i];
        break;
      }

      if(i > DPI_1200){
        DBG (5, "update_params: no dpi\n");
        return SANE_STATUS_INVAL;
      }
    }

    /*********** weird scan area (increase to valid one) *********/
    if(s->fixed_width){
      s->s.tl_x = 0;
      s->s.br_x = s->max_x;
      s->s.page_x = s->max_x;
    }

    /*recalculate new params*/
    s->s.width = (s->s.br_x - s->s.tl_x) * s->s.dpi_x / 1200;

    /* round down to byte boundary */
    if(s->s.mode < MODE_GRAYSCALE){
      s->s.width -= s->s.width % 8;
    }

    /* round down to pixel boundary for some scanners */
    s->s.width -= s->s.width % s->ppl_mod;

    s->s.valid_width = s->s.width;
    s->s.valid_Bpl = s->s.valid_width * s->s.bpp / 8;

    /* some machines (DR-2050) require even bytes per scanline */
    /* increase width and Bpl, but not valid_width and valid_Bpl */
    if(s->even_Bpl && (s->s.width % 2)){
      s->s.width++;
    }

    s->s.Bpl = s->s.width * s->s.bpp / 8;

    /* figure out how many valid bytes per line (2510 is padded) */
    if(s->color_interlace[SIDE_FRONT] == COLOR_INTERLACE_2510){
      s->s.valid_Bpl = s->s.Bpl*11/12;
      s->s.valid_width = s->s.width*11/12;
    }

    /* some scanners need longer scans because front/back is offset */
    if((s->u.source == SOURCE_ADF_DUPLEX || s->u.source == SOURCE_CARD_DUPLEX)
      && s->duplex_offset && !calib)
      s->s.height = (s->u.br_y-s->u.tl_y+s->duplex_offset) * s->u.dpi_y / 1200;

    /* round lines up to even number */
    s->s.height += s->s.height % 2;
  
    DBG (15, "update_params: scan params: w:%d h:%d m:%d f:%d b:%d\n",
      s->s.width, s->s.height, s->s.mode, s->s.format, s->s.bpp);
    DBG (15, "update_params: scan params: B:%d vB:%d vw:%d\n",
      s->s.Bpl, s->s.valid_Bpl, s->s.valid_width);
    DBG (15, "update_params: scan params: x b:%d t:%d d:%d y b:%d t:%d d:%d\n",
      s->s.br_x, s->s.tl_x, s->s.dpi_x, s->s.br_y, s->s.tl_y, s->s.dpi_y);

    /* make a third (intermediate) version of the params struct,
     * currently identical to the user's params. this is what
     * we actually will send back to the user (though buffer_xxx
     * functions might change these values after this runs) */

    /* calibration code needs the data just as it comes from the scanner */
    if(calib)
      memcpy(&s->i,&s->s,sizeof(struct img_params));
    /* normal scans need the data cleaned for presentation to the user */
    else{
      memcpy(&s->i,&s->u,sizeof(struct img_params));
      /*dumb scanners pad the top of front page in duplex*/
      if(s->i.source == SOURCE_ADF_DUPLEX || s->i.source == SOURCE_CARD_DUPLEX)
        s->i.skip_lines[s->duplex_offset_side] = s->duplex_offset * s->i.dpi_y / 1200;
    }

    DBG (15, "update_params: i params: w:%d h:%d m:%d f:%d b:%d\n",
      s->i.width, s->i.height, s->i.mode, s->i.format, s->i.bpp);
    DBG (15, "update_params: i params: B:%d vB:%d vw:%d\n",
      s->i.Bpl, s->i.valid_Bpl, s->i.valid_width);
    DBG (15, "update_params: i params: x b:%d t:%d d:%d y b:%d t:%d d:%d\n",
      s->i.br_x, s->i.tl_x, s->i.dpi_x, s->i.br_y, s->i.tl_y, s->i.dpi_y);

    DBG (10, "update_params: finish\n");
    return ret;
}

/* reset image size parameters after buffer_xxx functions changed them */
SANE_Status
update_i_params(struct scanner *s)
{
    SANE_Status ret = SANE_STATUS_GOOD;
  
    DBG (10, "update_i_params: start\n");

    s->i.width = s->u.width;
    s->i.Bpl = s->u.Bpl;
 
    DBG (10, "update_i_params: finish\n");
    return ret;
}

/*
 * Called by SANE when a page acquisition operation is to be started.
 * commands: set window, object pos, and scan
 *
 * this will be called between sides of a duplex scan,
 * and at the start of each page of an adf batch.
 * hence, we spend alot of time playing with s->started, etc.
 */
SANE_Status
sane_start (SANE_Handle handle)
{
  struct scanner *s = handle;
  SANE_Status ret = SANE_STATUS_GOOD;

  DBG (10, "sane_start: start\n");
  DBG (15, "started=%d, side=%d, source=%d\n",
    s->started, s->side, s->u.source);

  /* undo any prior sane_cancel calls */
  s->cancelled=0;

  /* protect this block from sane_cancel */
  s->reading=1;

  /* not finished with current side, error */
  if (s->started && !s->u.eof[s->side]) {
    DBG(5,"sane_start: previous transfer not finished?");
    return SANE_STATUS_INVAL;
  }

  /* batch start? inititalize struct and scanner */
  if(!s->started){

    /* load side marker */
    if(s->u.source == SOURCE_ADF_BACK || s->u.source == SOURCE_CARD_BACK){
      s->side = SIDE_BACK;
    }
    else{
      s->side = SIDE_FRONT;
    }

    /* eject paper leftover*/
    if(object_position (s, SANE_FALSE)){
      DBG (5, "sane_start: ERROR: cannot eject page\n");
    }

    /* wait for scanner to finish eject */
    ret = wait_scanner (s);
    if (ret != SANE_STATUS_GOOD) {
      DBG (5, "sane_start: ERROR: cannot wait scanner\n");
      goto errors;
    }

    /* load the brightness/contrast lut with linear slope for calibration */
    ret = load_lut (s->lut, 8, 8, 0, 255, 0, 0);
    if (ret != SANE_STATUS_GOOD) {
      DBG (5, "sane_start: ERROR: cannot load lut\n");
      goto errors;
    }

    /* AFE cal */
    if((ret = calibrate_AFE(s))){
      DBG (5, "sane_start: ERROR: cannot cal afe\n");
      goto errors;
    }

    /* fine cal */
    if((ret = calibrate_fine(s))){
      DBG (5, "sane_start: ERROR: cannot cal fine\n");
      goto errors;
    }

    if((ret = calibrate_fine_buffer(s))){
      DBG (5, "sane_start: ERROR: cannot cal fine from buffer\n");
      goto errors;
    }

    /* reset the page counter after calibration */
    s->panel_counter = 0;
    s->prev_page = 0;
    if(send_panel(s)){
      DBG (5, "sane_start: ERROR: cannot send panel\n");
    }

    /* load our own private copy of scan params */
    ret = update_params(s,0);
    if (ret != SANE_STATUS_GOOD) {
      DBG (5, "sane_start: ERROR: cannot update_params\n");
      goto errors;
    }

    /* set window command */
    ret = set_window(s);
    if (ret != SANE_STATUS_GOOD) {
      DBG (5, "sane_start: ERROR: cannot set window\n");
      goto errors;
    }

    /* buffer/duplex/ald/fb/card command */
    ret = ssm_buffer(s);
    if (ret != SANE_STATUS_GOOD) {
      DBG (5, "sane_start: ERROR: cannot ssm buffer\n");
      goto errors;
    }

    /* dropout color command */
    ret = ssm_do(s);
    if (ret != SANE_STATUS_GOOD) {
      DBG (5, "sane_start: ERROR: cannot ssm do\n");
      goto errors;
    }

    /* double feed detection command */
    ret = ssm_df(s);
    if (ret != SANE_STATUS_GOOD) {
      DBG (5, "sane_start: ERROR: cannot ssm df\n");
      goto errors;
    }

    /* clean scan params for new scan */
    ret = clean_params(s);
    if (ret != SANE_STATUS_GOOD) {
      DBG (5, "sane_start: ERROR: cannot clean_params\n");
      goto errors;
    }

    /* make large buffers to hold the images */
    ret = image_buffers(s,1);
    if (ret != SANE_STATUS_GOOD) {
      DBG (5, "sane_start: ERROR: cannot load buffers\n");
      goto errors;
    }

    /* load the brightness/contrast lut with user choices */
    ret = load_lut (s->lut, 8, 8, 0, 255, s->contrast, s->brightness);
    if (ret != SANE_STATUS_GOOD) {
      DBG (5, "sane_start: ERROR: cannot load lut\n");
      goto errors;
    }

    /* card reader dislikes op? */
    if(s->s.source < SOURCE_CARD_FRONT){
      /* grab next page */
      ret = object_position (s, SANE_TRUE);
      if (ret != SANE_STATUS_GOOD) {
        DBG (5, "sane_start: ERROR: cannot load page\n");
        goto errors;
      }
  
      /* wait for scanner to finish load */
      ret = wait_scanner (s);
      if (ret != SANE_STATUS_GOOD) {
        DBG (5, "sane_start: ERROR: cannot wait scanner\n");
        goto errors;
      }
    }

    /* start scanning */
    ret = start_scan (s,0);
    if (ret != SANE_STATUS_GOOD) {
      DBG (5, "sane_start: ERROR: cannot start_scan\n");
      goto errors;
    }

    s->started = 1;
  }

  /* stuff done for subsequent images */
  else{

    /* duplex needs to switch sides */
    if(s->s.source == SOURCE_ADF_DUPLEX || s->s.source == SOURCE_CARD_DUPLEX){
      s->side = !s->side;
    }

    /* reset the intermediate params */
    ret = update_i_params(s);
    if (ret != SANE_STATUS_GOOD) {
      DBG (5, "sane_start: ERROR: cannot update_i_params\n");
      goto errors;
    }

    /* set clean defaults with new sheet of paper */
    /* dont reset the transfer vars on backside of duplex page */
    /* otherwise buffered back page will be lost */
    /* ingest paper with adf (no-op for fb) */
    /* dont call object pos or scan on back side of duplex scan */
    if(s->side == SIDE_FRONT || s->s.source == SOURCE_ADF_BACK || s->s.source == SOURCE_CARD_BACK){

      /* clean scan params for new scan */
      ret = clean_params(s);
      if (ret != SANE_STATUS_GOOD) {
        DBG (5, "sane_start: ERROR: cannot clean_params\n");
        goto errors;
      }

      /* big scanners and small ones in non-buff mode: OP to detect paper */
      if(s->always_op || !s->buffermode){
        ret = object_position (s, SANE_TRUE);
        if (ret != SANE_STATUS_GOOD) {
          DBG (5, "sane_start: ERROR: cannot load page\n");
          goto errors;
        }

        /* user wants unbuffered scans */
        /* send scan command */
        if(!s->buffermode){
          ret = start_scan (s,0);
          if (ret != SANE_STATUS_GOOD) {
            DBG (5, "sane_start: ERROR: cannot start_scan\n");
            goto errors;
          }
        }
      }
  
      /* small, buffering scanners check for more pages by reading counter */
      else{
        ret = read_panel (s, OPT_COUNTER);
        if (ret != SANE_STATUS_GOOD) {
          DBG (5, "sane_start: ERROR: cannot load page\n");
          goto errors;
        }
        if(s->prev_page == s->panel_counter){
          DBG (5, "sane_start: same counter (%d) no paper?\n",s->prev_page);
          ret = SANE_STATUS_NO_DOCS;
          goto errors;
        }
        DBG (5, "sane_start: diff counter (%d/%d)\n",
          s->prev_page,s->panel_counter);
      }
    }
  }

  /* reset jpeg params on each page */
  s->jpeg_stage=JPEG_STAGE_NONE;
  s->jpeg_ff_offset=0;

  DBG (15, "started=%d, side=%d, source=%d\n",
    s->started, s->side, s->u.source);

  /* certain options require the entire image to 
   * be collected from the scanner before we can
   * tell the user the size of the image. the sane 
   * API has no way to inform the frontend of this,
   * so we block and buffer. yuck */
  if( (s->swdeskew || s->swdespeck || s->swcrop)
    && s->s.format != SANE_FRAME_JPEG
  ){

    /* get image */
    while(!s->s.eof[s->side] && !ret){
      SANE_Int len = 0;
      ret = sane_read((SANE_Handle)s, NULL, 0, &len);
    }

    /* check for errors */
    if (ret != SANE_STATUS_GOOD) {
      DBG (5, "sane_start: ERROR: cannot buffer image\n");
      goto errors;
    }

    DBG (5, "sane_start: OK: done buffering\n");

    /* finished buffering, adjust image as required */
    if(s->swdeskew){
      buffer_deskew(s,s->side);
    }
    if(s->swcrop){
      buffer_crop(s,s->side);
    }
    if(s->swdespeck){
      buffer_despeck(s,s->side);
    }

  }

  ret = check_for_cancel(s);
  s->reading = 0;

  DBG (10, "sane_start: finish %d\n", ret);
  return ret;

  errors:
    DBG (10, "sane_start: error %d\n", ret);
    s->started = 0;
    s->cancelled = 0;
    s->reading = 0;
    return ret;
}

/*
 * cleans params for new scan
 */
static SANE_Status
clean_params (struct scanner *s)
{
  SANE_Status ret = SANE_STATUS_GOOD;

  DBG (10, "clean_params: start\n");

  s->u.eof[0]=0;
  s->u.eof[1]=0;
  s->u.bytes_sent[0]=0;
  s->u.bytes_sent[1]=0;
  s->u.bytes_tot[0]=0;
  s->u.bytes_tot[1]=0;

  s->i.eof[0]=0;
  s->i.eof[1]=0;
  s->i.bytes_sent[0]=0;
  s->i.bytes_sent[1]=0;
  s->i.bytes_tot[0]=0;
  s->i.bytes_tot[1]=0;

  s->s.eof[0]=0;
  s->s.eof[1]=0;
  s->s.bytes_sent[0]=0;
  s->s.bytes_sent[1]=0;
  s->s.bytes_tot[0]=0;
  s->s.bytes_tot[1]=0;

  /* store the number of front bytes */ 
  if ( s->u.source != SOURCE_ADF_BACK && s->u.source != SOURCE_CARD_BACK )
    s->u.bytes_tot[SIDE_FRONT] = s->u.Bpl * s->u.height;

  if ( s->i.source != SOURCE_ADF_BACK && s->i.source != SOURCE_CARD_BACK )
    s->i.bytes_tot[SIDE_FRONT] = s->i.Bpl * s->i.height;

  if ( s->s.source != SOURCE_ADF_BACK && s->s.source != SOURCE_CARD_BACK )
    s->s.bytes_tot[SIDE_FRONT] = s->s.Bpl * s->s.height;

  /* store the number of back bytes */ 
  if ( s->u.source == SOURCE_ADF_DUPLEX || s->u.source == SOURCE_ADF_BACK 
    || s->u.source == SOURCE_CARD_DUPLEX || s->u.source == SOURCE_CARD_BACK )
    s->u.bytes_tot[SIDE_BACK] = s->u.Bpl * s->u.height;

  if ( s->i.source == SOURCE_ADF_DUPLEX || s->i.source == SOURCE_ADF_BACK
    || s->i.source == SOURCE_CARD_DUPLEX || s->i.source == SOURCE_CARD_BACK )
    s->i.bytes_tot[SIDE_BACK] = s->i.Bpl * s->i.height;

  if ( s->s.source == SOURCE_ADF_DUPLEX || s->s.source == SOURCE_ADF_BACK
    || s->s.source == SOURCE_CARD_DUPLEX || s->s.source == SOURCE_CARD_BACK )
    s->s.bytes_tot[SIDE_BACK] = s->s.Bpl * s->s.height;

  DBG (10, "clean_params: finish\n");

  return ret;
}

/*
 * frees/callocs buffers to hold the scan data
 */
static SANE_Status
image_buffers (struct scanner *s, int setup)
{
  SANE_Status ret = SANE_STATUS_GOOD;
  int side;

  DBG (10, "image_buffers: start\n");

  for(side=0;side<2;side++){

    /* free current buffer */
    if (s->buffers[side]) {
      DBG (15, "image_buffers: free buffer %d.\n",side);
      free(s->buffers[side]);
      s->buffers[side] = NULL;
    }

    /* build new buffer if asked */
    if(s->i.bytes_tot[side] && setup){
      s->buffers[side] = calloc (1,s->i.bytes_tot[side]);
      if (!s->buffers[side]) {
        DBG (5, "image_buffers: Error, no buffer %d.\n",side);
        return SANE_STATUS_NO_MEM;
      }
    }
  }

  DBG (10, "image_buffers: finish\n");

  return ret;
}

/*
 * This routine issues a SCSI SET WINDOW command to the scanner, using the
 * values currently in the s->s param structure.
 */
static SANE_Status
set_window (struct scanner *s)
{
  SANE_Status ret = SANE_STATUS_GOOD;

  /* The command specifies the number of bytes in the data phase 
   * the data phase has a header, followed by 1 window desc block 
   * the header specifies the number of bytes in 1 window desc block
   */

  unsigned char cmd[SET_WINDOW_len];
  size_t cmdLen = SET_WINDOW_len;
 
  unsigned char out[SW_header_len + SW_desc_len];
  size_t outLen = SW_header_len + SW_desc_len;

  unsigned char * header = out;                       /*header*/
  unsigned char * desc1 = out + SW_header_len;        /*descriptor*/

  DBG (10, "set_window: start\n");

  /*build the payload*/
  memset(out,0,outLen);

  /* set window desc size in header */
  set_WPDB_wdblen(header, SW_desc_len);

  /* init the window block */
  if (s->s.source == SOURCE_ADF_BACK || s->s.source == SOURCE_CARD_BACK) {
    set_WD_wid (desc1, WD_wid_back);
  }
  else{
    set_WD_wid (desc1, WD_wid_front);
  }

  set_WD_Xres (desc1, s->s.dpi_x);
  set_WD_Yres (desc1, s->s.dpi_y);

  /* some machines need max width */
  if(s->fixed_width){
    set_WD_ULX (desc1, 0);
    set_WD_width (desc1, s->max_x);
  }

  /* or they align left */
  else if(s->u.source == SOURCE_FLATBED){
    set_WD_ULX (desc1, s->s.tl_x);
    set_WD_width (desc1, s->s.width * 1200/s->s.dpi_x);
  }

  /* or we have to center the window ourselves */
  else{
    set_WD_ULX (desc1, (s->max_x - s->s.page_x) / 2 + s->s.tl_x);
    set_WD_width (desc1, s->s.width * 1200/s->s.dpi_x);
  }

  /* some models require that the tly value be inverted? */
  if(s->invert_tly)
    set_WD_ULY (desc1, ~s->s.tl_y);
  else
    set_WD_ULY (desc1, s->s.tl_y);

  set_WD_length (desc1, s->s.height * 1200/s->s.dpi_y);

  if(s->has_btc){
    /*convert our common -127 to +127 range into HW's range
     *FIXME: this code assumes hardware range of 0-255 */
    set_WD_brightness (desc1, s->brightness+128);
  
    set_WD_threshold (desc1, s->threshold);
  
    /*convert our common -127 to +127 range into HW's range
     *FIXME: this code assumes hardware range of 0-255 */
    set_WD_contrast (desc1, s->contrast+128);
  }

  set_WD_composition (desc1, s->s.mode);

  if(s->s.bpp == 24)
    set_WD_bitsperpixel (desc1, 8);
  else
    set_WD_bitsperpixel (desc1, s->s.bpp);

  if(s->s.mode == MODE_HALFTONE){
    /*set_WD_ht_type(desc1, s->ht_type);
    set_WD_ht_pattern(desc1, s->ht_pattern);*/
  }

  set_WD_rif (desc1, s->rif);
  set_WD_rgb(desc1, s->rgb_format);
  set_WD_padding(desc1, s->padding);

  /*FIXME: what is this? */
  set_WD_reserved2(desc1, s->unknown_byte2);

  set_WD_compress_type(desc1, COMP_NONE);
  set_WD_compress_arg(desc1, 0);

  /* some scanners support jpeg image compression, for color/gs only */
  if(s->s.format == SANE_FRAME_JPEG){
    set_WD_compress_type(desc1, COMP_JPEG);
    set_WD_compress_arg(desc1, s->compress_arg);
  }

  /*build the command*/
  memset(cmd,0,cmdLen);
  set_SCSI_opcode(cmd, SET_WINDOW_code);
  set_SW_xferlen(cmd, outLen);

  ret = do_cmd (
    s, 1, 0,
    cmd, cmdLen,
    out, outLen,
    NULL, NULL
  );

  if (!ret && (s->s.source == SOURCE_ADF_DUPLEX || s->s.source == SOURCE_CARD_DUPLEX)) {
      set_WD_wid (desc1, WD_wid_back);
      ret = do_cmd (
        s, 1, 0,
        cmd, cmdLen,
        out, outLen,
        NULL, NULL
      );
  }

  DBG (10, "set_window: finish\n");

  return ret;
}

/*
 * Issues the SCSI OBJECT POSITION command if an ADF is in use.
 */
static SANE_Status
object_position (struct scanner *s, int i_load)
{
  SANE_Status ret = SANE_STATUS_GOOD;

  unsigned char cmd[OBJECT_POSITION_len];
  size_t cmdLen = OBJECT_POSITION_len;

  DBG (10, "object_position: start\n");

  if (s->u.source == SOURCE_FLATBED) {
    DBG (10, "object_position: flatbed no-op\n");
    return SANE_STATUS_GOOD;
  }

  memset(cmd,0,cmdLen);
  set_SCSI_opcode(cmd, OBJECT_POSITION_code);

  if (i_load) {
    DBG (15, "object_position: load\n");
    set_OP_autofeed (cmd, OP_Feed);
  }
  else {
    DBG (15, "object_position: eject\n");
    set_OP_autofeed (cmd, OP_Discharge);
  }

  ret = do_cmd (
    s, 1, 0,
    cmd, cmdLen,
    NULL, 0,
    NULL, NULL
  );
  if (ret != SANE_STATUS_GOOD)
    return ret;

  DBG (10, "object_position: finish\n");

  return ret;
}

/*
 * Issues SCAN command.
 * 
 * (This doesn't actually read anything, it just tells the scanner
 * to start scanning.)
 */
static SANE_Status
start_scan (struct scanner *s, int type)
{
  SANE_Status ret = SANE_STATUS_GOOD;

  unsigned char cmd[SCAN_len];
  size_t cmdLen = SCAN_len;

  unsigned char out[] = {WD_wid_front, WD_wid_back};
  size_t outLen = 2;

  DBG (10, "start_scan: start\n");

  /* calibration scans use 0xff or 0xfe */
  if(type){
    out[0] = type;
    out[1] = type;
  }

  if (s->s.source != SOURCE_ADF_DUPLEX && s->s.source != SOURCE_CARD_DUPLEX) {
    outLen--;
    if(s->s.source == SOURCE_ADF_BACK || s->s.source == SOURCE_CARD_BACK) {
      out[0] = WD_wid_back;
    }
  }

  memset(cmd,0,cmdLen);
  set_SCSI_opcode(cmd, SCAN_code);
  set_SC_xfer_length (cmd, outLen);

  ret = do_cmd (
    s, 1, 0,
    cmd, cmdLen,
    out, outLen,
    NULL, NULL
  );

  DBG (10, "start_scan: finish\n");

  return ret;
}

/*
 * Called by SANE to read data.
 * 
 * From the SANE spec:
 * This function is used to read image data from the device
 * represented by handle h.  Argument buf is a pointer to a memory
 * area that is at least maxlen bytes long.  The number of bytes
 * returned is stored in *len. A backend must set this to zero when
 * the call fails (i.e., when a status other than SANE_STATUS_GOOD is
 * returned).
 * 
 * When the call succeeds, the number of bytes returned can be
 * anywhere in the range from 0 to maxlen bytes.
 */
SANE_Status
sane_read (SANE_Handle handle, SANE_Byte * buf, SANE_Int max_len, SANE_Int * len)
{
  struct scanner *s = (struct scanner *) handle;
  SANE_Status ret=SANE_STATUS_GOOD;

  DBG (10, "sane_read: start\n");

  *len=0;

  /* maybe cancelled? */
  if(!s->started){
    DBG (5, "sane_read: not started, call sane_start\n");
    return SANE_STATUS_CANCELLED;
  }

  /* sane_start required between sides */
  if(s->u.bytes_sent[s->side] == s->i.bytes_tot[s->side]){
    s->u.eof[s->side] = 1;
    DBG (15, "sane_read: returning eof\n");
    return SANE_STATUS_EOF;
  }

  s->reading = 1;

  /* double width pnm interlacing */
  if((s->s.source == SOURCE_ADF_DUPLEX || s->s.source == SOURCE_CARD_DUPLEX)
    && s->s.format <= SANE_FRAME_RGB
    && s->duplex_interlace != DUPLEX_INTERLACE_NONE
  ){

    /* buffer both sides */
    if(!s->s.eof[SIDE_FRONT] || !s->s.eof[SIDE_BACK]){
      ret = read_from_scanner_duplex(s, 0);
      if(ret){
        DBG(5,"sane_read: front returning %d\n",ret);
        goto errors;
      }
      /*read last block, update counter*/
      if(s->s.eof[SIDE_FRONT] && s->s.eof[SIDE_BACK]){
        s->prev_page++;
        DBG(15,"sane_read: duplex counter %d\n",s->prev_page);
      }
    }
  }
    
  /* simplex or non-alternating duplex */
  else{
    if(!s->s.eof[s->side]){
      ret = read_from_scanner(s, s->side, 0);
      if(ret){
        DBG(5,"sane_read: side %d returning %d\n",s->side,ret);
        goto errors;
      }
      /*read last block, update counter*/
      if(s->s.eof[s->side]){
        s->prev_page++;
        DBG(15,"sane_read: side %d counter %d\n",s->side,s->prev_page);
      }
    }
  }

  /* copy a block from buffer to frontend */
  ret = read_from_buffer(s,buf,max_len,len,s->side);
  if(ret)
    goto errors;
  
  ret = check_for_cancel(s);
  s->reading = 0;

  DBG (10, "sane_read: finish %d\n", ret);
  return ret;

  errors:
    DBG (10, "sane_read: error %d\n", ret);
    s->reading = 0;
    s->cancelled = 0;
    s->started = 0;
    return ret;
}

static SANE_Status
read_from_scanner(struct scanner *s, int side, int exact)
{
  SANE_Status ret=SANE_STATUS_GOOD;

  unsigned char cmd[READ_len];
  size_t cmdLen = READ_len;

  unsigned char * in;
  size_t inLen = 0;

  size_t bytes = s->buffer_size;
  size_t remain = s->s.bytes_tot[side] - s->s.bytes_sent[side];

  DBG (10, "read_from_scanner: start\n");

  /* all requests must end on line boundary */
  bytes -= (bytes % s->s.Bpl);

  /* some larger scanners require even bytes per block */
  if(bytes % 2){
    bytes -= s->s.Bpl;
  }

  /* usually (image) we want to read too much data, and get RS */
  /* sometimes (calib) we want to do an exact read */
  if(exact && bytes > remain){
    bytes = remain;
  }

  DBG(15, "read_from_scanner: si:%d to:%d rx:%d re:%lu bu:%d pa:%lu ex:%d\n",
      side, s->s.bytes_tot[side], s->s.bytes_sent[side],
      (unsigned long)remain, s->buffer_size, (unsigned long)bytes, exact);

  inLen = bytes;
  in = malloc(inLen);
  if(!in){
    DBG(5, "read_from_scanner: not enough mem for buffer: %d\n",(int)inLen);
    return SANE_STATUS_NO_MEM;
  }

  memset(cmd,0,cmdLen);
  set_SCSI_opcode(cmd, READ_code);
  set_R_datatype_code (cmd, SR_datatype_image);

  set_R_xfer_length (cmd, inLen);

  ret = do_cmd (
    s, 1, 0,
    cmd, cmdLen,
    NULL, 0,
    in, &inLen
  );

  if (ret == SANE_STATUS_GOOD) {
    DBG(15, "read_from_scanner: got GOOD, returning GOOD %lu\n", (unsigned long)inLen);
  }
  else if (ret == SANE_STATUS_EOF) {
    DBG(15, "read_from_scanner: got EOF, finishing %lu\n", (unsigned long)inLen);
  }
  else if (ret == SANE_STATUS_DEVICE_BUSY) {
    DBG(5, "read_from_scanner: got BUSY, returning GOOD\n");
    inLen = 0;
    ret = SANE_STATUS_GOOD;
  }
  else {
    DBG(5, "read_from_scanner: error reading data block status = %d\n",ret);
    inLen = 0;
  }

  /* this is jpeg data, we need to fix the missing image size */
  if(s->s.format == SANE_FRAME_JPEG){

    /* look for the SOF header near the beginning */
    if(s->jpeg_stage == JPEG_STAGE_NONE || s->jpeg_ff_offset < 0x0d){

      size_t i;

      for(i=0;i<inLen;i++){
  
        /* about to change stage */
        if(s->jpeg_stage == JPEG_STAGE_NONE && in[i] == 0xff){
          s->jpeg_ff_offset=0;
          continue;
        }
  
        s->jpeg_ff_offset++;

        /* last byte was an ff, this byte is SOF */
        if(s->jpeg_ff_offset == 1 && in[i] == 0xc0){
          s->jpeg_stage = JPEG_STAGE_SOF;
          continue;
        }
  
        if(s->jpeg_stage == JPEG_STAGE_SOF){

          /* lines in start of frame, overwrite it */
          if(s->jpeg_ff_offset == 5){
            in[i] = (s->s.height >> 8) & 0xff;
            continue;
          }
          if(s->jpeg_ff_offset == 6){
            in[i] = s->s.height & 0xff;
            continue;
          }
      
          /* width in start of frame, overwrite it */
          if(s->jpeg_ff_offset == 7){
            in[i] = (s->s.width >> 8) & 0xff;
            continue;
          }
          if(s->jpeg_ff_offset == 8){
            in[i] = s->s.width & 0xff;
            continue;
          }
        }
      }
    }
  }

  /*scanner may have sent more data than we asked for, chop it*/
  if(inLen > remain){
    inLen = remain;
  }

  /* we've got some data, descramble and store it */
  if(inLen){
    copy_simplex(s,in,inLen,side);
  }

  free(in);

  /* we've read all data, but not eof. clear and pretend */
  if(exact && inLen == remain){
    DBG (10, "read_from_scanner: exact read, clearing\n");
    ret = object_position (s,SANE_FALSE);
    if(ret){
      return ret;
    }
    ret = SANE_STATUS_EOF;
  }

  if(ret == SANE_STATUS_EOF){

    /* this is jpeg data, we need to change the total size */
    if(s->s.format == SANE_FRAME_JPEG){
      s->s.bytes_tot[side] = s->s.bytes_sent[side];
      s->i.bytes_tot[side] = s->i.bytes_sent[side];
      s->u.bytes_tot[side] = s->i.bytes_sent[side];
    } 

    /* this is non-jpeg data, fill remainder, change rx'd size */
    else{

      DBG (15, "read_from_scanner: eof: %d %d\n", s->i.bytes_tot[side], s->i.bytes_sent[side]);

      /* clone the last line repeatedly until the end */
      while(s->i.bytes_tot[side] > s->i.bytes_sent[side]){
        memcpy(
          s->buffers[side]+s->i.bytes_sent[side]-s->i.Bpl,
          s->buffers[side]+s->i.bytes_sent[side],
          s->i.Bpl
        );
        s->i.bytes_sent[side] += s->i.Bpl;
      }

      DBG (15, "read_from_scanner: eof2: %d %d\n", s->i.bytes_tot[side], s->i.bytes_sent[side]);

      /* pretend we got all the data from scanner */
      s->s.bytes_sent[side] = s->s.bytes_tot[side];
    }

    s->i.eof[side] = 1;
    s->s.eof[side] = 1;
    ret = SANE_STATUS_GOOD;
  }

  DBG(15, "read_from_scanner: sto:%d srx:%d sef:%d uto:%d urx:%d uef:%d\n",
    s->s.bytes_tot[side], s->s.bytes_sent[side], s->s.eof[side],
    s->u.bytes_tot[side], s->u.bytes_sent[side], s->u.eof[side]);

  DBG (10, "read_from_scanner: finish\n");

  return ret;
}

/* cheaper scanners interlace duplex scans on a byte basis
 * this code requests double width lines from scanner */
static SANE_Status
read_from_scanner_duplex(struct scanner *s,int exact)
{
  SANE_Status ret=SANE_STATUS_GOOD;

  unsigned char cmd[READ_len];
  size_t cmdLen = READ_len;

  unsigned char * in;
  size_t inLen = 0;

  size_t bytes = s->buffer_size;
  size_t remain = s->s.bytes_tot[SIDE_FRONT] + s->s.bytes_tot[SIDE_BACK]
    - s->s.bytes_sent[SIDE_FRONT] - s->s.bytes_sent[SIDE_BACK];

  DBG (10, "read_from_scanner_duplex: start\n");

  /* all requests must end on WIDE line boundary */
  bytes -= (bytes % (s->s.Bpl*2));

  /* usually (image) we want to read too much data, and get RS */
  /* sometimes (calib) we want to do an exact read */
  if(exact && bytes > remain){
    bytes = remain;
  }

  DBG(15, "read_from_scanner_duplex: re:%lu bu:%d pa:%lu ex:%d\n",
      (unsigned long)remain, s->buffer_size, (unsigned long)bytes, exact);

  inLen = bytes;
  in = malloc(inLen);
  if(!in){
    DBG(5, "read_from_scanner_duplex: not enough mem for buffer: %d\n",
      (int)inLen);
    return SANE_STATUS_NO_MEM;
  }

  memset(cmd,0,cmdLen);
  set_SCSI_opcode(cmd, READ_code);
  set_R_datatype_code (cmd, SR_datatype_image);

  set_R_xfer_length (cmd, inLen);

  ret = do_cmd (
    s, 1, 0,
    cmd, cmdLen,
    NULL, 0,
    in, &inLen
  );

  if (ret == SANE_STATUS_GOOD) {
    DBG(15, "read_from_scanner_duplex: got GOOD, returning GOOD %lu\n", (unsigned long)inLen);
  }
  else if (ret == SANE_STATUS_EOF) {
    DBG(15, "read_from_scanner_duplex: got EOF, finishing %lu\n", (unsigned long)inLen);
  }
  else if (ret == SANE_STATUS_DEVICE_BUSY) {
    DBG(5, "read_from_scanner_duplex: got BUSY, returning GOOD\n");
    inLen = 0;
    ret = SANE_STATUS_GOOD;
  }
  else {
    DBG(5, "read_from_scanner_duplex: error reading data block status = %d\n",
      ret);
    inLen = 0;
  }

  /*scanner may have sent more data than we asked for, chop it*/
  if(inLen > remain){
    inLen = remain;
  }

  /* we've got some data, descramble and store it */
  if(inLen){
    copy_duplex(s,in,inLen);
  }

  free(in);

  /* we've read all data, but not eof. clear and pretend */
  if(exact && inLen == remain){
    DBG (10, "read_from_scanner_duplex: exact read, clearing\n");
    ret = object_position (s,SANE_FALSE);
    if(ret){
      return ret;
    }
    ret = SANE_STATUS_EOF;
  }

  if(ret == SANE_STATUS_EOF){

    /* this is jpeg data, we need to change the total size */
    if(s->s.format == SANE_FRAME_JPEG){
      s->s.bytes_tot[SIDE_FRONT] = s->s.bytes_sent[SIDE_FRONT];
      s->s.bytes_tot[SIDE_BACK] = s->s.bytes_sent[SIDE_BACK];
      s->i.bytes_tot[SIDE_FRONT] = s->i.bytes_sent[SIDE_FRONT];
      s->i.bytes_tot[SIDE_BACK] = s->i.bytes_sent[SIDE_BACK];
      s->u.bytes_tot[SIDE_FRONT] = s->i.bytes_sent[SIDE_FRONT];
      s->u.bytes_tot[SIDE_BACK] = s->i.bytes_sent[SIDE_BACK];
    }

    /* this is non-jpeg data, fill remainder, change rx'd size */
    else{

      DBG (15, "read_from_scanner_duplex: eof: %d %d %d %d\n",
        s->i.bytes_tot[SIDE_FRONT], s->i.bytes_sent[SIDE_FRONT],
        s->i.bytes_tot[SIDE_BACK], s->i.bytes_sent[SIDE_BACK]
      );

      /* clone the last line repeatedly until the end */
      while(s->i.bytes_tot[SIDE_FRONT] > s->i.bytes_sent[SIDE_FRONT]){
        memcpy(
          s->buffers[SIDE_FRONT]+s->i.bytes_sent[SIDE_FRONT]-s->i.Bpl,
          s->buffers[SIDE_FRONT]+s->i.bytes_sent[SIDE_FRONT],
          s->i.Bpl
        );
        s->i.bytes_sent[SIDE_FRONT] += s->i.Bpl;
      }

      /* clone the last line repeatedly until the end */
      while(s->i.bytes_tot[SIDE_BACK] > s->i.bytes_sent[SIDE_BACK]){
        memcpy(
          s->buffers[SIDE_BACK]+s->i.bytes_sent[SIDE_BACK]-s->i.Bpl,
          s->buffers[SIDE_BACK]+s->i.bytes_sent[SIDE_BACK],
          s->i.Bpl
        );
        s->i.bytes_sent[SIDE_BACK] += s->i.Bpl;
      }

      DBG (15, "read_from_scanner_duplex: eof2: %d %d %d %d\n",
        s->i.bytes_tot[SIDE_FRONT], s->i.bytes_sent[SIDE_FRONT],
        s->i.bytes_tot[SIDE_BACK], s->i.bytes_sent[SIDE_BACK]
      );

      /* pretend we got all the data from scanner */
      s->s.bytes_sent[SIDE_FRONT] = s->s.bytes_tot[SIDE_FRONT];
      s->s.bytes_sent[SIDE_BACK] = s->s.bytes_tot[SIDE_BACK];
    }

    s->i.eof[SIDE_FRONT] = 1;
    s->i.eof[SIDE_BACK] = 1;
    s->s.eof[SIDE_FRONT] = 1;
    s->s.eof[SIDE_BACK] = 1;
    ret = SANE_STATUS_GOOD;
  }

  DBG (10, "read_from_scanner_duplex: finish\n");

  return ret;
}

/* these functions copy image data from input buffer to scanner struct 
 * descrambling it, and putting it in the right side buffer */
/* NOTE: they assume buffer is scanline aligned */
static SANE_Status
copy_simplex(struct scanner *s, unsigned char * buf, int len, int side)
{
  SANE_Status ret=SANE_STATUS_GOOD;
  int i, j;
  int bwidth = s->s.Bpl;
  int pwidth = s->s.width;
  int t = bwidth/3;
  int f = bwidth/4;
  int tw = bwidth/12;

  unsigned char * line = NULL;
  int line_next = 0;
  int inter = get_color_inter(s,side,s->s.dpi_x);

  /* jpeg data should not pass thru this function, so copy and bail out */
  if(s->s.format > SANE_FRAME_RGB){
    DBG (15, "copy_simplex: jpeg bulk copy\n");
    memcpy(s->buffers[side]+s->i.bytes_sent[side], buf, len);
    s->i.bytes_sent[side] += len;
    s->s.bytes_sent[side] += len;
    return ret;
  }
  
  DBG (15, "copy_simplex: per-line copy\n");

  line = malloc(bwidth);
  if(!line) return SANE_STATUS_NO_MEM;

  /* ingest each line */
  for(i=0; i<len; i+=bwidth){

    int lineNum = s->s.bytes_sent[side] / bwidth;
  
    /*increment number of bytes rx'd from scanner*/
    s->s.bytes_sent[side] += bwidth;

    /*have some padding from scanner to drop*/
    if ( lineNum < s->i.skip_lines[side]
      || lineNum - s->i.skip_lines[side] >= s->i.height
    ){
      continue;
    }

    line_next = 0;

    if(s->s.format == SANE_FRAME_GRAY){
  
      switch (s->gray_interlace[side]) {
  
        /* one line has the following format: ggg...GGG
         * where the 'capital' letters are the beginning of the line */
        case GRAY_INTERLACE_gG:
          DBG (17, "copy_simplex: gray, gG\n");
          for (j=bwidth-1; j>=0; j--){
            line[line_next++] = buf[i+j];
          }
          break;
    
        case GRAY_INTERLACE_2510:
          DBG (17, "copy_simplex: gray, 2510\n");
       
          /* first read head (third byte of every three) */
          for(j=bwidth-1;j>=0;j-=3){
            line[line_next++] = buf[i+j];
          }
          /* second read head (first byte of every three) */
          for(j=bwidth*3/4-3;j>=0;j-=3){
            line[line_next++] = buf[i+j];
          }
          /* third read head (second byte of every three) */
          for(j=bwidth-2;j>=0;j-=3){
            line[line_next++] = buf[i+j];
          }
          /* padding */
          for(j=0;j<tw;j++){
            line[line_next++] = 0;
          }
          break;
      }
    }
  
    else if (s->s.format == SANE_FRAME_RGB){
  
      switch (inter) {
    
        /* scanner returns color data as bgrbgr... */
        case COLOR_INTERLACE_BGR:
          DBG (17, "copy_simplex: color, BGR\n");
          for (j=0; j<pwidth; j++){
            line[line_next++] = buf[i+j*3+2];
            line[line_next++] = buf[i+j*3+1];
            line[line_next++] = buf[i+j*3];
          }
          break;
    
        /* scanner returns color data as gbrgbr... */
        case COLOR_INTERLACE_GBR:
          DBG (17, "copy_simplex: color, GBR\n");
          for (j=0; j<pwidth; j++){
            line[line_next++] = buf[i+j*3+2];
            line[line_next++] = buf[i+j*3];
            line[line_next++] = buf[i+j*3+1];
          }
          break;
    
        /* scanner returns color data as brgbrg... */
        case COLOR_INTERLACE_BRG:
          DBG (17, "copy_simplex: color, BRG\n");
          for (j=0; j<pwidth; j++){
            line[line_next++] = buf[i+j*3+1];
            line[line_next++] = buf[i+j*3+2];
            line[line_next++] = buf[i+j*3];
          }
          break;
    
        /* one line has the following format: RRR...rrrGGG...gggBBB...bbb */
        case COLOR_INTERLACE_RRGGBB:
          DBG (17, "copy_simplex: color, RRGGBB\n");
          for (j=0; j<pwidth; j++){
            line[line_next++] = buf[i+j];
            line[line_next++] = buf[i+pwidth+j];
            line[line_next++] = buf[i+2*pwidth+j];
          }
          break;
    
        /* one line has the following format: rrr...RRRggg...GGGbbb...BBB
         * where the 'capital' letters are the beginning of the line */
        case COLOR_INTERLACE_rRgGbB:
          DBG (17, "copy_simplex: color, rRgGbB\n");
          for (j=pwidth-1; j>=0; j--){
            line[line_next++] = buf[i+j];
            line[line_next++] = buf[i+pwidth+j];
            line[line_next++] = buf[i+2*pwidth+j];
          }
          break;
    
        case COLOR_INTERLACE_2510:
          DBG (17, "copy_simplex: color, 2510\n");
        
          /* first read head (third byte of every three) */
          for(j=t-1;j>=0;j-=3){
            line[line_next++] = buf[i+j];
            line[line_next++] = buf[i+t+j];
            line[line_next++] = buf[i+2*t+j];
          }
          /* second read head (first byte of every three) */
          for(j=f-3;j>=0;j-=3){
            line[line_next++] = buf[i+j];
            line[line_next++] = buf[i+t+j];
            line[line_next++] = buf[i+2*t+j];
          }
          /* third read head (second byte of every three) */
          for(j=t-2;j>=0;j-=3){
            line[line_next++] = buf[i+j];
            line[line_next++] = buf[i+t+j];
            line[line_next++] = buf[i+2*t+j];
          }
          /* padding */
          for(j=0;j<tw;j++){
            line[line_next++] = 0;
          }
          break;
      }
    }
  
    /* nothing sent above? just copy one line of the block */
    /* used by uninterlaced gray/color */
    if(!line_next){
      DBG (17, "copy_simplex: default\n");
      memcpy(line+line_next,buf+i,bwidth);
      line_next = bwidth;
    }
  
    /* invert image if scanner needs it for this mode */
    if(s->reverse_by_mode[s->s.mode]){
      for(j=0; j<line_next; j++){
        line[j] ^= 0xff;
      }
    }
  
    /* apply calibration if we have it */
    if(s->f_offset[side]){
      DBG (17, "copy_simplex: apply offset\n");
      for(j=0; j<s->s.valid_Bpl; j++){
        int curr = line[j] - s->f_offset[side][j];
        if(curr < 0) curr = 0;
        line[j] = curr;
      }
    }

    if(s->f_gain[side]){
      DBG (17, "copy_simplex: apply gain\n");
      for(j=0; j<s->s.valid_Bpl; j++){
        int curr = line[j] * 240/s->f_gain[side][j];
        if(curr > 255) curr = 255;
        line[j] = curr;
      }
    }
  
    /* apply brightness and contrast if hardware cannot do it */
    if(s->sw_lut && (s->s.mode == MODE_COLOR || s->s.mode == MODE_GRAYSCALE)){
      DBG (17, "copy_simplex: apply brightness/contrast\n");
      for(j=0; j<s->s.valid_Bpl; j++){
        line[j] = s->lut[line[j]];
      }
    }

    /*copy the line into the buffer*/
    ret = copy_line(s,line,side);
    if(ret){
      break;
    }
  }

  free(line);

  DBG (10, "copy_simplex: finished\n");

  return ret;
}

/* split the data between two buffers, hand them to copy_simplex()
 * assumes that the buffer aligns to a double-wide line boundary */
static SANE_Status
copy_duplex(struct scanner *s, unsigned char * buf, int len)
{
  SANE_Status ret=SANE_STATUS_GOOD;
  int i,j;
  int bwidth = s->s.Bpl;
  int dbwidth = 2*bwidth;
  unsigned char * front;
  unsigned char * back;
  int flen=0, blen=0;

  DBG (10, "copy_duplex: start\n");

  /*split the input into two simplex output buffers*/
  front = calloc(1,len/2);
  if(!front){
    DBG (5, "copy_duplex: no front mem\n");
    return SANE_STATUS_NO_MEM;
  }
  back = calloc(1,len/2);
  if(!back){
    DBG (5, "copy_duplex: no back mem\n");
    free(front);
    return SANE_STATUS_NO_MEM;
  }

  if(s->duplex_interlace == DUPLEX_INTERLACE_2510){

    DBG (10, "copy_duplex: 2510\n");

    for(i=0; i<len; i+=dbwidth){
  
      for(j=0;j<dbwidth;j+=6){

        /* we are actually only partially descrambling,
         * copy_simplex() does the rest */

        /* front */
        /* 2nd head: 2nd byte -> 1st byte */
        /* 3rd head: 4th byte -> 2nd byte */
        /* 1st head: 5th byte -> 3rd byte */
        front[flen++] = buf[i+j+2];
        front[flen++] = buf[i+j+4];
        front[flen++] = buf[i+j+5];

        /* back */
        /* 2nd head: 3rd byte -> 1st byte */
        /* 3rd head: 0th byte -> 2nd byte */
        /* 1st head: 1st byte -> 3rd byte */
        back[blen++] = buf[i+j+3];
        back[blen++] = buf[i+j];
        back[blen++] = buf[i+j+1];
      }
    }
  }

  /* full line of front, then full line of back */
  else if(s->duplex_interlace == DUPLEX_INTERLACE_FFBB){
    for(i=0; i<len; i+=dbwidth){
      memcpy(front+flen,buf+i,bwidth);
      flen+=bwidth;
      memcpy(back+blen,buf+i+bwidth,bwidth);
      blen+=bwidth;
    }
  }

  /*just alternating bytes, FBFBFB*/
  else {
    for(i=0; i<len; i+=2){
      front[flen++] = buf[i];
      back[blen++] = buf[i+1];
    }
  }

  copy_simplex(s,front,flen,SIDE_FRONT);
  copy_simplex(s,back,blen,SIDE_BACK);

  free(front);
  free(back);

  DBG (10, "copy_duplex: finished\n");

  return ret;
}

/* downsample a single line from scanner's size to user's size */
/* and copy into final buffer */
static SANE_Status
copy_line(struct scanner *s, unsigned char * buff, int side)
{
  SANE_Status ret=SANE_STATUS_GOOD;
  int spwidth = s->s.width;
  int sbwidth = s->s.Bpl;
  int ibwidth = s->i.Bpl;
  unsigned char * line;
  int offset = 0;
  int i, j;

  DBG (20, "copy_line: start\n");

  /* the 'standard' case: non-stupid scan */
  if(s->s.width == s->i.width
    && s->s.dpi_x == s->i.dpi_x
    && s->s.mode == s->i.mode
  ){

    memcpy(s->buffers[side]+s->i.bytes_sent[side], buff, sbwidth);
    s->i.bytes_sent[side] += sbwidth;

    DBG (20, "copy_line: finished smart\n");
    return ret;
  }

  /* the 'corner' case: stupid scan */

  /*setup 24 bit color single line buffer*/
  line = malloc(spwidth*3);
  if(!line) return SANE_STATUS_NO_MEM;

  /*load single line color buffer*/
  switch (s->s.mode) {

    case MODE_COLOR:
      memcpy(line, buff, sbwidth);
      break;

    case MODE_GRAYSCALE:
      for(i=0;i<spwidth;i++){
        line[i*3] = line[i*3+1] = line[i*3+2] = buff[i];
      }
      break;

    default:
      for(i=0;i<sbwidth;i++){
        unsigned char curr = buff[i];

        line[i*24+0] = line[i*24+1] = line[i*24+2] = ((curr >> 7) & 1) ?0:255;
        line[i*24+3] = line[i*24+4] = line[i*24+5] = ((curr >> 6) & 1) ?0:255;
        line[i*24+6] = line[i*24+7] = line[i*24+8] = ((curr >> 5) & 1) ?0:255;
        line[i*24+9] = line[i*24+10] = line[i*24+11] = ((curr >> 4) & 1) ?0:255;
        line[i*24+12] = line[i*24+13] = line[i*24+14] =((curr >> 3) & 1) ?0:255;
        line[i*24+15] = line[i*24+16] = line[i*24+17] =((curr >> 2) & 1) ?0:255;
        line[i*24+18] = line[i*24+19] = line[i*24+20] =((curr >> 1) & 1) ?0:255;
        line[i*24+21] = line[i*24+22] = line[i*24+23] =((curr >> 0) & 1) ?0:255;
      }
      break;
  }

  /* scan is higher res than user wanted, scale it */
  /*FIXME: interpolate instead */
  if(s->i.dpi_x != s->s.dpi_x){
    for(i=0;i<spwidth;i++){
      int source = i * s->s.dpi_x/s->i.dpi_x * 3;

      if(source+2 >= spwidth*3)
        break;

      line[i*3] = line[source];
      line[i*3+1] = line[source+1];
      line[i*3+2] = line[source+2];
    }
  }
  
  /* scan is wider than user wanted, skip some pixels on left side */
  if(s->i.width != s->s.width){
    offset = ((s->valid_x-s->i.page_x) / 2 + s->i.tl_x) * s->i.dpi_x/1200;
  }

  /* change mode, store line in buffer */
  switch (s->i.mode) {
  
    case MODE_COLOR:
      memcpy(s->buffers[side]+s->i.bytes_sent[side], line+offset, ibwidth);
      s->i.bytes_sent[side] += ibwidth;
      break;
  
    case MODE_GRAYSCALE:
      for(i=0;i<ibwidth;i++){
        int source = (offset+i)*3;
        s->buffers[side][s->i.bytes_sent[side]++]
          = ((int)line[source] + line[source+1] + line[source+2])/3;
      }
      break;
  
    default:
      /*loop over output bytes*/
      for(i=0;i<ibwidth;i++){

        unsigned char curr = 0;
        int thresh = s->threshold*3;

        /*loop over output bits*/
        for(j=0;j<8;j++){
          int source = offset*3 + i*24 + j*3;
          if( (line[source] + line[source+1] + line[source+2]) < thresh ){
            curr |= 1 << (7-j); 
          }
        }

        s->buffers[side][s->i.bytes_sent[side]++] = curr;
      }
      break;
  }

  free(line);

  DBG (20, "copy_line: finish stupid\n");

  return ret;
}

static SANE_Status
read_from_buffer(struct scanner *s, SANE_Byte * buf, SANE_Int max_len,
  SANE_Int * len, int side)
{
  SANE_Status ret=SANE_STATUS_GOOD;
  int bytes = max_len;
  int remain = s->i.bytes_sent[side] - s->u.bytes_sent[side];

  DBG (10, "read_from_buffer: start\n");

  /* figure out the max amount to transfer */
  if(bytes > remain)
    bytes = remain;
  
  *len = bytes;
  
  /*FIXME this needs to timeout eventually */
  if(!bytes){
    DBG(5,"read_from_buffer: nothing to do\n");
    return SANE_STATUS_GOOD;
  }
  
  DBG(15, "read_from_buffer: si:%d to:%d tx:%d bu:%d pa:%d\n", side,
    s->i.bytes_tot[side], s->u.bytes_sent[side], max_len, bytes);

  /* copy to caller */
  memcpy(buf,s->buffers[side]+s->u.bytes_sent[side],bytes);
  s->u.bytes_sent[side] += bytes;

  DBG (10, "read_from_buffer: finished\n");

  return ret;
}

/*
 * @@ Section 5 - calibration functions
 */

#if 0
static SANE_Status
foo_AFE(struct scanner *s)
{
  SANE_Status ret = SANE_STATUS_GOOD;

  unsigned char cmd[] = {
    0x3b, 0x00, 0x10, 0x08, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00
  };
  size_t cmdLen = 12;

  unsigned char in[4];
  size_t inLen = 4;

  DBG (10, "foo_AFE: start\n");

  ret = do_cmd (
    s, 1, 0,
    cmd, cmdLen,
    NULL, 0,
    in, &inLen
  );
  if (ret != SANE_STATUS_GOOD)
    return ret;

  DBG (10, "foo_AFE: finish\n");

  return ret;
}
#endif

/*
 * makes several scans, adjusts coarse calibration
 */
static SANE_Status
calibrate_AFE (struct scanner *s)
{
  SANE_Status ret = SANE_STATUS_GOOD;
  int i, j, k;
  int min, max;
  int lines = 8;

  /*buffer these for later*/
  int old_tl_y = s->u.tl_y;
  int old_br_y = s->u.br_y;
  int old_mode = s->u.mode;
  int old_source = s->u.source;

  DBG (10, "calibrate_AFE: start\n");

  if(!s->need_ccal){
    DBG (10, "calibrate_AFE: not required\n");
    return ret;
  }

  /* always cal with a short scan in duplex color */
  s->u.tl_y = 0;
  s->u.br_y = lines * 1200 / s->u.dpi_y;
  s->u.mode = MODE_COLOR;
  s->u.source = SOURCE_ADF_DUPLEX;

  /* load our own private copy of scan params */
  ret = update_params(s,1);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_AFE: ERROR: cannot update_params\n");
    goto cleanup;
  }

  if(s->c_res == s->s.dpi_x && s->c_mode == s->s.mode){
    DBG (10, "calibrate_AFE: already done\n");
    goto cleanup;
  }

  /* clean scan params for new scan */
  ret = clean_params(s);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_AFE: ERROR: cannot clean_params\n");
    goto cleanup;
  }

  /* make buffers to hold the images */
  ret = image_buffers(s,1);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_AFE: ERROR: cannot load buffers\n");
    goto cleanup;
  }

  /*blast the existing fine cal data so reading code wont apply it*/
  ret = offset_buffers(s,0);
  ret = gain_buffers(s,0);

  /* need to tell it we want duplex */
  ret = ssm_buffer(s);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_AFE: ERROR: cannot ssm buffer\n");
    goto cleanup;
  }

  /* set window command */
  ret = set_window(s);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_AFE: ERROR: cannot set window\n");
    goto cleanup;
  }
  
  /* first pass (black offset), lamp off, no offset/gain/exposure */
  DBG (15, "calibrate_AFE: offset\n");

  /* blast all the existing coarse cal data */
  for(i=0;i<2;i++){
    s->c_gain[i]   = 1;
    s->c_offset[i] = 1;
    for(j=0;j<3;j++){
      s->c_exposure[i][j] = 0;
    }
  }

  ret = write_AFE(s);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_AFE: ERROR: cannot write afe\n");
    goto cleanup;
  }

  ret = calibration_scan(s,0xff);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_AFE: ERROR: cannot make offset cal scan\n");
    goto cleanup;
  }

  for(i=0;i<2;i++){
    min = 255;
    for(j=0; j<s->s.valid_Bpl; j++){
      if(s->buffers[i][j] < min)
        min = s->buffers[i][j];
    }
    s->c_offset[i] = min*3-2;
    DBG (15, "calibrate_AFE: offset %d %d %02x\n", i, min, s->c_offset[i]);
  }

  /*handle second pass (per channel exposure), lamp on, overexposed*/
  DBG (15, "calibrate_AFE: exposure\n");
  for(i=0;i<2;i++){
    for(j=0; j<3; j++){
      s->c_exposure[i][j] = 0x320;
    }
  }

  ret = write_AFE(s);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_AFE: ERROR: cannot write afe\n");
    goto cleanup;
  }

  ret = calibration_scan(s,0xfe);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_AFE: ERROR: cannot make exposure cal scan\n");
    goto cleanup;
  }

  for(i=0;i<2;i++){ /*sides*/
    for(j=0;j<3;j++){ /*channels*/
      max = 0;
      for(k=j; k<s->s.valid_Bpl; k+=3){ /*bytes*/
        if(s->buffers[i][k] > max)
          max = s->buffers[i][k];
      }

      /*generally we reduce the exposure (smaller number) */
      if(old_mode == MODE_COLOR)
        s->c_exposure[i][j] = s->c_exposure[i][j] * 102/max;
      else
        s->c_exposure[i][j] = s->c_exposure[i][j] * 64/max;

      DBG (15, "calibrate_AFE: exp %d %d %d %02x\n", i, j, max,
        s->c_exposure[i][j]);
    }
  }

  /*handle third pass (gain), lamp on with current offset/exposure */
  DBG (15, "calibrate_AFE: gain\n");

  ret = write_AFE(s);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_AFE: ERROR: cannot write afe\n");
    goto cleanup;
  }

  ret = calibration_scan(s,0xfe);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_AFE: ERROR: cannot make gain cal scan\n");
    goto cleanup;
  }

  for(i=0;i<2;i++){
    max = 0;
    for(j=0; j<s->s.valid_Bpl; j++){
      if(s->buffers[i][j] > max)
        max = s->buffers[i][j];
    }

    if(old_mode == MODE_COLOR)
      s->c_gain[i] = (250-max)*4/5;
    else
      s->c_gain[i] = (125-max)*4/5;

    if(s->c_gain[i] < 1)
      s->c_gain[i] = 1;

    DBG (15, "calibrate_AFE: gain %d %d %02x\n", i, max, s->c_gain[i]);
  }

  /*handle fourth pass (offset again), lamp off*/
#if 0
  DBG (15, "calibrate_AFE: offset2\n");

  ret = write_AFE(s);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_AFE: ERROR: cannot write afe\n");
    goto cleanup;
  }

  ret = calibration_scan(s,0xff);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_AFE: ERROR: cannot make offset2 cal scan\n");
    goto cleanup;
  }

  for(i=0;i<2;i++){
    min = 255;
    for(j=0; j<s->s.valid_Bpl; j++){
      if(s->buffers[i][j] < min)
        min = s->buffers[i][j];
    }
    /*s->c_offset[i] += min*3-2;*/
    DBG (15, "calibrate_AFE: offset2 %d %d %02x\n", i, min, s->c_offset[i]);
  }
#endif

  /*send final afe params to scanner*/
  ret = write_AFE(s);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_AFE: ERROR: cannot write afe\n");
    goto cleanup;
  }

  /* log current cal type */
  s->c_res = s->s.dpi_x;
  s->c_mode = s->s.mode;

  cleanup:

  /* recover user settings */
  s->u.tl_y = old_tl_y;
  s->u.br_y = old_br_y;
  s->u.mode = old_mode;
  s->u.source = old_source;

  DBG (10, "calibrate_AFE: finish %d\n",ret);

  return ret;
}


/* alternative version- extracts data from scanner memory */
static SANE_Status
calibrate_fine_buffer (struct scanner *s)
{
  SANE_Status ret = SANE_STATUS_GOOD;
  int i, j, k;

  unsigned char cmd[READ_len];
  size_t cmdLen = READ_len;

  unsigned char * in = NULL;
  size_t inLen = 0, reqLen = 0;

  /*buffer these for later*/
  int old_tl_y = s->u.tl_y;
  int old_br_y = s->u.br_y;
  int old_source = s->u.source;

  DBG (10, "calibrate_fine_buffer: start\n");

  if(!s->need_fcal_buffer){
    DBG (10, "calibrate_fine_buffer: not required\n");
    return ret;
  }

  /* pretend we are doing a 1 line scan in duplex */
  s->u.tl_y = 0;
  s->u.br_y = 1200 / s->u.dpi_y;
  s->u.source = SOURCE_ADF_DUPLEX;

  /* load our own private copy of scan params */
  ret = update_params(s,1);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_fine_buffer: ERROR: cannot update_params\n");
    goto cleanup;
  }

  if(s->f_res == s->s.dpi_x && s->f_mode == s->s.mode){
    DBG (10, "calibrate_fine_buffer: already done\n");
    goto cleanup;
  }

  /* clean scan params for new scan */
  ret = clean_params(s);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_fine_buffer: ERROR: cannot clean_params\n");
    goto cleanup;
  }

  /*calibration buffers in scanner are single color channel, but duplex*/
  reqLen = s->s.width*2;

  in = malloc(reqLen);
  if (!in) {
    DBG (5, "calibrate_fine_buffer: ERROR: cannot malloc in\n");
    ret = SANE_STATUS_NO_MEM;
    goto cleanup;
  }

  /*fine offset*/
  ret = offset_buffers(s,1);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_fine_buffer: ERROR: cannot load offset buffers\n");
    goto cleanup;
  }
 
  DBG (5, "calibrate_fine_buffer: %d %x\n", s->s.dpi_x/10, s->s.dpi_x/10);

  memset(cmd,0,cmdLen);
  set_SCSI_opcode(cmd, READ_code);
  set_R_datatype_code (cmd, SR_datatype_fineoffset);
  set_R_xfer_lid (cmd, s->s.dpi_x/10);
  set_R_xfer_length (cmd, reqLen);

  inLen = reqLen;

  hexdump(15, "cmd:", cmd, cmdLen);

  ret = do_cmd (
    s, 1, 0,
    cmd, cmdLen,
    NULL, 0,
    in, &inLen
  );
  if (ret != SANE_STATUS_GOOD)
    goto cleanup;

  for(i=0;i<2;i++){

    /*color mode, expand offset across all three channels? */
    if(s->s.format == SANE_FRAME_RGB){
      for(j=0; j<s->s.valid_width; j++){
        
        /*red*/  
        s->f_offset[i][j*3] = in[j*2+i];
        if(s->f_offset[i][j*3] < 1)
          s->f_offset[i][j*3] = 1;

        /*green and blue, same as red*/  
        s->f_offset[i][j*3+1] = s->f_offset[i][j*3+2] = s->f_offset[i][j*3];
      }
    }

    /*gray mode, copy*/
    else{
      for(j=0; j<s->s.valid_width; j++){

        s->f_offset[i][j] = in[j*2+i];
        if(s->f_offset[i][j] < 1)
          s->f_offset[i][j] = 1;
      }
    }

    hexdump(15, "off:", s->f_offset[i], s->s.valid_Bpl);
  }

  /*fine gain*/
  ret = gain_buffers(s,1);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_fine_buffer: ERROR: cannot load gain buffers\n");
    goto cleanup;
  }

  memset(cmd,0,cmdLen);
  set_SCSI_opcode(cmd, READ_code);
  set_R_datatype_code (cmd, SR_datatype_finegain);
  set_R_xfer_lid (cmd, s->s.dpi_x/10);
  set_R_xfer_length (cmd, reqLen);

  /*color gain split into three buffers, grab them and merge*/
  if(s->s.format == SANE_FRAME_RGB){

    int codes[] = {R_FINE_uid_red,R_FINE_uid_green,R_FINE_uid_blue};

    for(k=0;k<3;k++){
  
      set_R_xfer_uid (cmd, codes[k]);
      inLen = reqLen;
    
      hexdump(15, "cmd:", cmd, cmdLen);

      ret = do_cmd (
        s, 1, 0,
        cmd, cmdLen,
        NULL, 0,
        in, &inLen
      );
      if (ret != SANE_STATUS_GOOD)
        goto cleanup;
  
      for(i=0;i<2;i++){
        for(j=0; j<s->s.valid_width; j++){
          
          s->f_gain[i][j*3+k] = in[j*2+i]*3/4;
    
          if(s->f_gain[i][j*3+k] < 1)
            s->f_gain[i][j*3+k] = 1;
        }
      }
    }
  }

  /*gray gain, copy*/
  else{

    set_R_xfer_uid (cmd, R_FINE_uid_gray);
    inLen = reqLen;
    
    hexdump(15, "cmd:", cmd, cmdLen);

    ret = do_cmd (
      s, 1, 0,
      cmd, cmdLen,
      NULL, 0,
      in, &inLen
    );
    if (ret != SANE_STATUS_GOOD)
      goto cleanup;
  
    for(i=0;i<2;i++){
      for(j=0; j<s->s.valid_width; j++){
        
        s->f_gain[i][j] = in[j*2+i]*3/4;
    
        if(s->f_gain[i][j] < 1)
          s->f_gain[i][j] = 1;
      }
    }
  }

  for(i=0;i<2;i++){
    hexdump(15, "gain:", s->f_gain[i], s->s.valid_Bpl);
  }

  /* log current cal type */
  s->f_res = s->s.dpi_x;
  s->f_mode = s->s.mode;

  cleanup:

  if(in){
    free(in);
  }

  /* recover user settings */
  s->u.tl_y = old_tl_y;
  s->u.br_y = old_br_y;
  s->u.source = old_source;

  DBG (10, "calibrate_fine_buffer: finish %d\n",ret);

  return ret;
}

/*
 * makes several scans, adjusts fine calibration
 */
static SANE_Status
calibrate_fine (struct scanner *s)
{
  SANE_Status ret = SANE_STATUS_GOOD;
  int i, j, k;
  int min, max;
  int lines = 8;

  /*buffer these for later*/
  int old_tl_y = s->u.tl_y;
  int old_br_y = s->u.br_y;
  int old_source = s->u.source;

  DBG (10, "calibrate_fine: start\n");

  if(!s->need_fcal){
    DBG (10, "calibrate_fine: not required\n");
    return ret;
  }

  /* always cal with a short scan in duplex */
  s->u.tl_y = 0;
  s->u.br_y = lines * 1200 / s->u.dpi_y;
  s->u.source = SOURCE_ADF_DUPLEX;

  /* load our own private copy of scan params */
  ret = update_params(s,1);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_fine: ERROR: cannot update_params\n");
    goto cleanup;
  }

  if(s->f_res == s->s.dpi_x && s->f_mode == s->s.mode){
    DBG (10, "calibrate_fine: already done\n");
    goto cleanup;
  }

  /* clean scan params for new scan */
  ret = clean_params(s);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibration_fine: ERROR: cannot clean_params\n");
    goto cleanup;
  }

  /* make buffers to hold the images */
  ret = image_buffers(s,1);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_fine: ERROR: cannot load buffers\n");
    goto cleanup;
  }
  
  /*blast the existing fine cal data so reading code wont apply it*/
  ret = offset_buffers(s,0);
  ret = gain_buffers(s,0);

  /* need to tell it we want duplex */
  ret = ssm_buffer(s);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_fine: ERROR: cannot ssm buffer\n");
    goto cleanup;
  }
  
  /* set window command */
  ret = set_window(s);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_fine: ERROR: cannot set window\n");
    goto cleanup;
  }
  
  /*handle fifth pass (fine offset), lamp off*/
  DBG (15, "calibrate_fine: offset\n");
  ret = calibration_scan(s,0xff);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_fine: ERROR: cannot make offset cal scan\n");
    goto cleanup;
  }

  ret = offset_buffers(s,1);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_fine: ERROR: cannot load offset buffers\n");
    goto cleanup;
  }
  
  for(i=0;i<2;i++){
    for(j=0; j<s->s.valid_Bpl; j++){
      min = 0;
      for(k=j;k<lines*s->s.Bpl;k+=s->s.Bpl){
        min += s->buffers[i][k];
      }
      s->f_offset[i][j] = min/lines;
    }
    hexdump(15, "off:", s->f_offset[i], s->s.valid_Bpl);
  }

  /*handle sixth pass (fine gain), lamp on*/
  DBG (15, "calibrate_fine: gain\n");
  ret = calibration_scan(s,0xfe);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_fine: ERROR: cannot make gain cal scan\n");
    goto cleanup;
  }

  ret = gain_buffers(s,1);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibrate_fine: ERROR: cannot load gain buffers\n");
    goto cleanup;
  }
  
  for(i=0;i<2;i++){
    for(j=0; j<s->s.valid_Bpl; j++){
      max = 0;
      for(k=j;k<lines*s->s.Bpl;k+=s->s.Bpl){
        max += s->buffers[i][k];
      }
      s->f_gain[i][j] = max/lines;

      if(s->f_gain[i][j] < 1)
        s->f_gain[i][j] = 1;
    }
    hexdump(15, "gain:", s->f_gain[i], s->s.valid_Bpl);
  }

  /* log current cal type */
  s->f_res = s->s.dpi_x;
  s->f_mode = s->s.mode;

  cleanup:

  /* recover user settings */
  s->u.tl_y = old_tl_y;
  s->u.br_y = old_br_y;
  s->u.source = old_source;

  DBG (10, "calibrate_fine: finish %d\n",ret);

  return ret;
}

/*
 * sends AFE params, and ingests entire duplex image into buffers
 */
static SANE_Status
calibration_scan (struct scanner *s, int scan)
{
  SANE_Status ret = SANE_STATUS_GOOD;

  DBG (10, "calibration_scan: start\n");

  /* clean scan params for new scan */
  ret = clean_params(s);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibration_scan: ERROR: cannot clean_params\n");
    return ret;
  }
  
  /* start scanning */
  ret = start_scan (s,scan);
  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "calibration_scan: ERROR: cannot start_scan\n");
    return ret;
  }
  
  while(!s->s.eof[SIDE_FRONT] && !s->s.eof[SIDE_BACK]){
    ret = read_from_scanner_duplex(s,1);
  }

  DBG (10, "calibration_scan: finished\n");

  return ret;
}

/*
 * sends AFE and exposure params
 */
static SANE_Status
write_AFE(struct scanner *s)
{
  SANE_Status ret = SANE_STATUS_GOOD;

  unsigned char cmd[COR_CAL_len];
  size_t cmdLen = COR_CAL_len;

  /*use the longest payload for buffer*/
  unsigned char pay[CC3_pay_len]; 
  size_t payLen = CC3_pay_len;

  DBG (10, "write_AFE: start\n");

  /* newer scanners use a longer cc payload */
  if(s->ccal_version == 3){

    memset(cmd,0,cmdLen);
    set_SCSI_opcode(cmd, COR_CAL_code);
    set_CC_version(cmd,CC3_pay_ver);
    set_CC_xferlen(cmd,payLen);
  
    memset(pay,0,payLen);

    set_CC3_gain_f_r(pay,s->c_gain[SIDE_FRONT]);
    set_CC3_gain_f_g(pay,s->c_gain[SIDE_FRONT]);
    set_CC3_gain_f_b(pay,s->c_gain[SIDE_FRONT]);

    set_CC3_off_f_r(pay,s->c_offset[SIDE_FRONT]);
    set_CC3_off_f_g(pay,s->c_offset[SIDE_FRONT]);
    set_CC3_off_f_b(pay,s->c_offset[SIDE_FRONT]);
  
    set_CC3_exp_f_r(pay,s->c_exposure[SIDE_FRONT][CHAN_RED]);
    set_CC3_exp_f_g(pay,s->c_exposure[SIDE_FRONT][CHAN_GREEN]);
    set_CC3_exp_f_b(pay,s->c_exposure[SIDE_FRONT][CHAN_BLUE]);

    set_CC3_gain_b_r(pay,s->c_gain[SIDE_BACK]);
    set_CC3_gain_b_g(pay,s->c_gain[SIDE_BACK]);
    set_CC3_gain_b_b(pay,s->c_gain[SIDE_BACK]);

    set_CC3_off_b_r(pay,s->c_offset[SIDE_BACK]);
    set_CC3_off_b_g(pay,s->c_offset[SIDE_BACK]);
    set_CC3_off_b_b(pay,s->c_offset[SIDE_BACK]);

    set_CC3_exp_b_r(pay,s->c_exposure[SIDE_BACK][CHAN_RED]);
    set_CC3_exp_b_g(pay,s->c_exposure[SIDE_BACK][CHAN_GREEN]);
    set_CC3_exp_b_b(pay,s->c_exposure[SIDE_BACK][CHAN_BLUE]);
  }

  else{
    payLen = CC_pay_len;

    memset(cmd,0,cmdLen);
    set_SCSI_opcode(cmd, COR_CAL_code);
    set_CC_version(cmd,CC_pay_ver);
    set_CC_xferlen(cmd,payLen);
  
    memset(pay,0,payLen);
    set_CC_f_gain(pay,s->c_gain[SIDE_FRONT]);
    set_CC_unk1(pay,1);
    set_CC_f_offset(pay,s->c_offset[SIDE_FRONT]);
    set_CC_unk2(pay,1);
    set_CC_exp_f_r1(pay,s->c_exposure[SIDE_FRONT][CHAN_RED]);
    set_CC_exp_f_g1(pay,s->c_exposure[SIDE_FRONT][CHAN_GREEN]);
    set_CC_exp_f_b1(pay,s->c_exposure[SIDE_FRONT][CHAN_BLUE]);
    set_CC_exp_f_r2(pay,s->c_exposure[SIDE_FRONT][CHAN_RED]);
    set_CC_exp_f_g2(pay,s->c_exposure[SIDE_FRONT][CHAN_GREEN]);
    set_CC_exp_f_b2(pay,s->c_exposure[SIDE_FRONT][CHAN_BLUE]);
  
    set_CC_b_gain(pay,s->c_gain[SIDE_BACK]);
    set_CC_b_offset(pay,s->c_offset[SIDE_BACK]);
    set_CC_exp_b_r1(pay,s->c_exposure[SIDE_BACK][CHAN_RED]);
    set_CC_exp_b_g1(pay,s->c_exposure[SIDE_BACK][CHAN_GREEN]);
    set_CC_exp_b_b1(pay,s->c_exposure[SIDE_BACK][CHAN_BLUE]);
    set_CC_exp_b_r2(pay,s->c_exposure[SIDE_BACK][CHAN_RED]);
    set_CC_exp_b_g2(pay,s->c_exposure[SIDE_BACK][CHAN_GREEN]);
    set_CC_exp_b_b2(pay,s->c_exposure[SIDE_BACK][CHAN_BLUE]);
  }

  ret = do_cmd (
    s, 1, 0,
    cmd, cmdLen,
    pay, payLen,
    NULL, NULL
  );
  if (ret != SANE_STATUS_GOOD)
    return ret;

  DBG (10, "write_AFE: finish\n");

  return ret;
}

/*
 * frees/callocs buffers to hold the fine cal offset data
 */
static SANE_Status
offset_buffers (struct scanner *s, int setup)
{
  SANE_Status ret = SANE_STATUS_GOOD;
  int side;

  DBG (10, "offset_buffers: start\n");

  for(side=0;side<2;side++){

    if (s->f_offset[side]) {
      DBG (15, "offset_buffers: free f_offset %d.\n",side);
      free(s->f_offset[side]);
      s->f_offset[side] = NULL;
    }

    if(setup){
      s->f_offset[side] = calloc (1,s->s.Bpl);
      if (!s->f_offset[side]) {
        DBG (5, "offset_buffers: error, no f_offset %d.\n",side);
        return SANE_STATUS_NO_MEM;
      }
    }
  }

  DBG (10, "offset_buffers: finish\n");

  return ret;
}

/*
 * frees/callocs buffers to hold the fine cal gain data
 */
static SANE_Status
gain_buffers (struct scanner *s, int setup)
{
  SANE_Status ret = SANE_STATUS_GOOD;
  int side;

  DBG (10, "gain_buffers: start\n");

  for(side=0;side<2;side++){

    if (s->f_gain[side]) {
      DBG (15, "gain_buffers: free f_gain %d.\n",side);
      free(s->f_gain[side]);
      s->f_gain[side] = NULL;
    }

    if(setup){
      s->f_gain[side] = calloc (1,s->s.Bpl);
      if (!s->f_gain[side]) {
        DBG (5, "gain_buffers: error, no f_gain %d.\n",side);
        return SANE_STATUS_NO_MEM;
      }
    }
  }

  DBG (10, "gain_buffers: finish\n");

  return ret;
}

/*
 * @@ Section 6 - SANE cleanup functions
 */
/*
 * Cancels a scan. 
 *
 * It has been said on the mailing list that sane_cancel is a bit of a
 * misnomer because it is routinely called to signal the end of a
 * batch - quoting David Mosberger-Tang:
 * 
 * > In other words, the idea is to have sane_start() be called, and
 * > collect as many images as the frontend wants (which could in turn
 * > consist of multiple frames each as indicated by frame-type) and
 * > when the frontend is done, it should call sane_cancel(). 
 * > Sometimes it's better to think of sane_cancel() as "sane_stop()"
 * > but that name would have had some misleading connotations as
 * > well, that's why we stuck with "cancel".
 * 
 * The current consensus regarding duplex and ADF scans seems to be
 * the following call sequence: sane_start; sane_read (repeat until
 * EOF); sane_start; sane_read...  and then call sane_cancel if the
 * batch is at an end. I.e. do not call sane_cancel during the run but
 * as soon as you get a SANE_STATUS_NO_DOCS.
 * 
 * From the SANE spec:
 * This function is used to immediately or as quickly as possible
 * cancel the currently pending operation of the device represented by
 * handle h.  This function can be called at any time (as long as
 * handle h is a valid handle) but usually affects long-running
 * operations only (such as image acquisition). It is safe to call
 * this function asynchronously (e.g., from within a signal handler).
 * It is important to note that completion of this operaton does not
 * imply that the currently pending operation has been cancelled. It
 * only guarantees that cancellation has been initiated. Cancellation
 * completes only when the cancelled call returns (typically with a
 * status value of SANE_STATUS_CANCELLED).  Since the SANE API does
 * not require any other operations to be re-entrant, this implies
 * that a frontend must not call any other operation until the
 * cancelled operation has returned.
 */
void
sane_cancel (SANE_Handle handle)
{
  struct scanner * s = (struct scanner *) handle;

  DBG (10, "sane_cancel: start\n");
  s->cancelled = 1;

  /* if there is no other running function to check, we do it */
  if(!s->reading)
    check_for_cancel(s);

  DBG (10, "sane_cancel: finish\n");
}

/* checks started and cancelled flags in scanner struct,
 * sends cancel command to scanner if required. don't call
 * this function asyncronously, wait for pending operation */
static SANE_Status
check_for_cancel(struct scanner *s)
{
  SANE_Status ret=SANE_STATUS_GOOD;

  DBG (10, "check_for_cancel: start\n");

  if(s->started && s->cancelled){
    unsigned char cmd[CANCEL_len];
    size_t cmdLen = CANCEL_len;
  
    DBG (15, "check_for_cancel: cancelling\n");
  
    /* cancel scan */
    memset(cmd,0,cmdLen);
    set_SCSI_opcode(cmd, CANCEL_code);
  
    ret = do_cmd (
        s, 1, 0,
        cmd, cmdLen,
        NULL, 0,
        NULL, NULL
    );
    if(ret){
      DBG (5, "check_for_cancel: ignoring bad cancel: %d\n",ret);
    }
  
    ret = object_position(s,SANE_FALSE);
    if(ret){
      DBG (5, "check_for_cancel: ignoring bad eject: %d\n",ret);
    }

    s->started = 0;
    s->cancelled = 0;
    ret = SANE_STATUS_CANCELLED;
  }
  else if(s->cancelled){
    DBG (15, "check_for_cancel: already cancelled\n");
    s->cancelled = 0;
    ret = SANE_STATUS_CANCELLED;
  }

  DBG (10, "check_for_cancel: finish %d\n",ret);
  return ret;
}

/*
 * Ends use of the scanner.
 * 
 * From the SANE spec:
 * This function terminates the association between the device handle
 * passed in argument h and the device it represents. If the device is
 * presently active, a call to sane_cancel() is performed first. After
 * this function returns, handle h must not be used anymore.
 */
void
sane_close (SANE_Handle handle)
{
  struct scanner * s = (struct scanner *) handle;

  DBG (10, "sane_close: start\n");
  disconnect_fd(s);
  image_buffers(s,0);
  offset_buffers(s,0);
  gain_buffers(s,0);
  DBG (10, "sane_close: finish\n");
}

static SANE_Status
disconnect_fd (struct scanner *s)
{
  DBG (10, "disconnect_fd: start\n");

  if(s->fd > -1){
    if (s->connection == CONNECTION_USB) {
      DBG (15, "disconnecting usb device\n");
      sanei_usb_close (s->fd);
    }
    else if (s->connection == CONNECTION_SCSI) {
      DBG (15, "disconnecting scsi device\n");
      sanei_scsi_close (s->fd);
    }
    s->fd = -1;
  }

  DBG (10, "disconnect_fd: finish\n");

  return SANE_STATUS_GOOD;
}

/*
 * Terminates the backend.
 * 
 * From the SANE spec:
 * This function must be called to terminate use of a backend. The
 * function will first close all device handles that still might be
 * open (it is recommended to close device handles explicitly through
 * a call to sane_close(), but backends are required to release all
 * resources upon a call to this function). After this function
 * returns, no function other than sane_init() may be called
 * (regardless of the status value returned by sane_exit(). Neglecting
 * to call this function may result in some resources not being
 * released properly.
 */
void
sane_exit (void)
{
  struct scanner *dev, *next;

  DBG (10, "sane_exit: start\n");

  for (dev = scanner_devList; dev; dev = next) {
      disconnect_fd(dev);
      next = dev->next;
      free (dev);
  }

  if (sane_devArray)
    free (sane_devArray);

  scanner_devList = NULL;
  sane_devArray = NULL;

  DBG (10, "sane_exit: finish\n");
}


/*
 * @@ Section 7 - misc helper functions
 */
static void
default_globals(void)
{
  global_buffer_size = global_buffer_size_default;
  global_padded_read = global_padded_read_default;
  global_extra_status = global_extra_status_default;
  global_duplex_offset = global_duplex_offset_default;
  global_vendor_name[0] = 0;
  global_model_name[0] = 0;
  global_version_name[0] = 0;
}

/*
 * Called by the SANE SCSI core and our usb code on device errors
 * parses the request sense return data buffer,
 * decides the best SANE_Status for the problem, produces debug msgs,
 * and copies the sense buffer into the scanner struct
 */
static SANE_Status
sense_handler (int fd, unsigned char * sensed_data, void *arg)
{
  struct scanner *s = arg;
  unsigned int sense = get_RS_sense_key (sensed_data);
  unsigned int asc = get_RS_ASC (sensed_data);
  unsigned int ascq = get_RS_ASCQ (sensed_data);
  unsigned int eom = get_RS_EOM (sensed_data);
  unsigned int ili = get_RS_ILI (sensed_data);
  unsigned int info = get_RS_information (sensed_data);

  DBG (5, "sense_handler: start\n");

  /* kill compiler warning */
  fd = fd;

  /* copy the rs return data into the scanner struct
     so that the caller can use it if he wants
  memcpy(&s->rs_buffer,sensed_data,RS_return_size);
  */

  DBG (5, "Sense=%#02x, ASC=%#02x, ASCQ=%#02x, EOM=%d, ILI=%d, info=%#08x\n", sense, asc, ascq, eom, ili, info);

  switch (sense) {
    case 0:
      if (ili == 1) {
        s->rs_info = info;
        DBG  (5, "No sense: EOM remainder:%d\n",info);
        return SANE_STATUS_EOF;
      }
      DBG  (5, "No sense: unknown asc/ascq\n");
      return SANE_STATUS_GOOD;

    case 1:
      if (asc == 0x37 && ascq == 0x00) {
        DBG  (5, "Recovered error: parameter rounded\n");
        return SANE_STATUS_GOOD;
      }
      DBG  (5, "Recovered error: unknown asc/ascq\n");
      return SANE_STATUS_GOOD;

    case 2:
      if (asc == 0x04 && ascq == 0x01) {
        DBG  (5, "Not ready: previous command unfinished\n");
        return SANE_STATUS_DEVICE_BUSY;
      }
      DBG  (5, "Not ready: unknown asc/ascq\n");
      return SANE_STATUS_DEVICE_BUSY;

    case 3:
      if (asc == 0x36 && ascq == 0x00) {
        DBG  (5, "Medium error: no cartridge\n");
        return SANE_STATUS_IO_ERROR;
      }
      if (asc == 0x3a && ascq == 0x00) {
        DBG  (5, "Medium error: hopper empty\n");
        return SANE_STATUS_NO_DOCS;
      }
      if (asc == 0x80 && ascq == 0x00) {
        DBG  (5, "Medium error: paper jam\n");
        return SANE_STATUS_JAMMED;
      }
      if (asc == 0x80 && ascq == 0x01) {
        DBG  (5, "Medium error: cover open\n");
        return SANE_STATUS_COVER_OPEN;
      }
      if (asc == 0x81 && ascq == 0x01) {
        DBG  (5, "Medium error: double feed\n");
        return SANE_STATUS_JAMMED;
      }
      if (asc == 0x81 && ascq == 0x02) {
        DBG  (5, "Medium error: skew detected\n");
        return SANE_STATUS_JAMMED;
      }
      if (asc == 0x81 && ascq == 0x04) {
        DBG  (5, "Medium error: staple detected\n");
        return SANE_STATUS_JAMMED;
      }
      DBG  (5, "Medium error: unknown asc/ascq\n");
      return SANE_STATUS_IO_ERROR;

    case 4:
      if (asc == 0x60 && ascq == 0x00) {
        DBG  (5, "Hardware error: lamp error\n");
        return SANE_STATUS_IO_ERROR;
      }
      if (asc == 0x80 && ascq == 0x01) {
        DBG  (5, "Hardware error: CPU check error\n");
        return SANE_STATUS_IO_ERROR;
      }
      if (asc == 0x80 && ascq == 0x02) {
        DBG  (5, "Hardware error: RAM check error\n");
        return SANE_STATUS_IO_ERROR;
      }
      if (asc == 0x80 && ascq == 0x03) {
        DBG  (5, "Hardware error: ROM check error\n");
        return SANE_STATUS_IO_ERROR;
      }
      if (asc == 0x80 && ascq == 0x04) {
        DBG  (5, "Hardware error: hardware check error\n");
        return SANE_STATUS_IO_ERROR;
      }
      DBG  (5, "Hardware error: unknown asc/ascq\n");
      return SANE_STATUS_IO_ERROR;

    case 5:
      if (asc == 0x1a && ascq == 0x00) {
        DBG  (5, "Illegal request: Parameter list error\n");
        return SANE_STATUS_INVAL;
      }
      if (asc == 0x20 && ascq == 0x00) {
        DBG  (5, "Illegal request: invalid command\n");
        return SANE_STATUS_INVAL;
      }
      if (asc == 0x24 && ascq == 0x00) {
        DBG  (5, "Illegal request: invalid CDB field\n");
        return SANE_STATUS_INVAL;
      }
      if (asc == 0x25 && ascq == 0x00) {
        DBG  (5, "Illegal request: unsupported logical unit\n");
        return SANE_STATUS_UNSUPPORTED;
      }
      if (asc == 0x26 && ascq == 0x00) {
        DBG  (5, "Illegal request: invalid field in parm list\n");
        return SANE_STATUS_INVAL;
      }
      if (asc == 0x2c && ascq == 0x00) {
        DBG  (5, "Illegal request: command sequence error\n");
        return SANE_STATUS_INVAL;
      }
      if (asc == 0x2c && ascq == 0x01) {
        DBG  (5, "Illegal request: too many windows\n");
        return SANE_STATUS_INVAL;
      }
      if (asc == 0x3a && ascq == 0x00) {
        DBG  (5, "Illegal request: no paper\n");
        return SANE_STATUS_NO_DOCS;
      }
      if (asc == 0x3d && ascq == 0x00) {
        DBG  (5, "Illegal request: invalid IDENTIFY\n");
        return SANE_STATUS_INVAL;
      }
      if (asc == 0x55 && ascq == 0x00) {
        DBG  (5, "Illegal request: scanner out of memory\n");
        return SANE_STATUS_NO_MEM;
      }
      DBG  (5, "Illegal request: unknown asc/ascq\n");
      return SANE_STATUS_IO_ERROR;
      break;

    case 6:
      if (asc == 0x29 && ascq == 0x00) {
        DBG  (5, "Unit attention: device reset\n");
        return SANE_STATUS_GOOD;
      }
      if (asc == 0x2a && ascq == 0x00) {
        DBG  (5, "Unit attention: param changed by 2nd initiator\n");
        return SANE_STATUS_GOOD;
      }
      DBG  (5, "Unit attention: unknown asc/ascq\n");
      return SANE_STATUS_IO_ERROR;
      break;

    case 7:
      DBG  (5, "Data protect: unknown asc/ascq\n");
      return SANE_STATUS_IO_ERROR;

    case 8:
      DBG  (5, "Blank check: unknown asc/ascq\n");
      return SANE_STATUS_IO_ERROR;

    case 9:
      DBG  (5, "Vendor defined: unknown asc/ascq\n");
      return SANE_STATUS_IO_ERROR;

    case 0xa:
      DBG  (5, "Copy aborted: unknown asc/ascq\n");
      return SANE_STATUS_IO_ERROR;

    case 0xb:
      if (asc == 0x00 && ascq == 0x00) {
        DBG  (5, "Aborted command: no sense/cancelled\n");
        return SANE_STATUS_CANCELLED;
      }
      if (asc == 0x45 && ascq == 0x00) {
        DBG  (5, "Aborted command: reselect failure\n");
        return SANE_STATUS_IO_ERROR;
      }
      if (asc == 0x47 && ascq == 0x00) {
        DBG  (5, "Aborted command: SCSI parity error\n");
        return SANE_STATUS_IO_ERROR;
      }
      if (asc == 0x48 && ascq == 0x00) {
        DBG  (5, "Aborted command: initiator error message\n");
        return SANE_STATUS_IO_ERROR;
      }
      if (asc == 0x49 && ascq == 0x00) {
        DBG  (5, "Aborted command: invalid message\n");
        return SANE_STATUS_IO_ERROR;
      }
      if (asc == 0x80 && ascq == 0x00) {
        DBG  (5, "Aborted command: timeout\n");
        return SANE_STATUS_IO_ERROR;
      }
      DBG  (5, "Aborted command: unknown asc/ascq\n");
      return SANE_STATUS_IO_ERROR;
      break;

    case 0xc:
      DBG  (5, "Equal: unknown asc/ascq\n");
      return SANE_STATUS_IO_ERROR;

    case 0xd:
      DBG  (5, "Volume overflow: unknown asc/ascq\n");
      return SANE_STATUS_IO_ERROR;

    case 0xe:
      if (asc == 0x3b && ascq == 0x0d) {
        DBG  (5, "Miscompare: too many docs\n");
        return SANE_STATUS_IO_ERROR;
      }
      if (asc == 0x3b && ascq == 0x0e) {
        DBG  (5, "Miscompare: too few docs\n");
        return SANE_STATUS_IO_ERROR;
      }
      DBG  (5, "Miscompare: unknown asc/ascq\n");
      return SANE_STATUS_IO_ERROR;

    default:
      DBG (5, "Unknown Sense Code\n");
      return SANE_STATUS_IO_ERROR;
  }

  DBG (5, "sense_handler: should never happen!\n");

  return SANE_STATUS_IO_ERROR;
}

/*
 * take a bunch of pointers, send commands to scanner
 */
static SANE_Status
do_cmd(struct scanner *s, int runRS, int shortTime,
 unsigned char * cmdBuff, size_t cmdLen,
 unsigned char * outBuff, size_t outLen,
 unsigned char * inBuff, size_t * inLen
)
{
    if (s->connection == CONNECTION_SCSI) {
        return do_scsi_cmd(s, runRS, shortTime,
                 cmdBuff, cmdLen,
                 outBuff, outLen,
                 inBuff, inLen
        );
    }
    if (s->connection == CONNECTION_USB) {
        return do_usb_cmd(s, runRS, shortTime,
                 cmdBuff, cmdLen,
                 outBuff, outLen,
                 inBuff, inLen
        );
    }
    return SANE_STATUS_INVAL;
}

static SANE_Status
do_scsi_cmd(struct scanner *s, int runRS, int shortTime,
 unsigned char * cmdBuff, size_t cmdLen,
 unsigned char * outBuff, size_t outLen,
 unsigned char * inBuff, size_t * inLen
)
{
  int ret;

  /*shut up compiler*/
  runRS=runRS;
  shortTime=shortTime;

  DBG(10, "do_scsi_cmd: start\n");

  DBG(25, "cmd: writing %d bytes\n", (int)cmdLen);
  hexdump(30, "cmd: >>", cmdBuff, cmdLen);

  if(outBuff && outLen){
    DBG(25, "out: writing %d bytes\n", (int)outLen);
    hexdump(30, "out: >>", outBuff, outLen);
  }
  if (inBuff && inLen){
    DBG(25, "in: reading %d bytes\n", (int)*inLen);
    memset(inBuff,0,*inLen);
  }

  ret = sanei_scsi_cmd2(s->fd, cmdBuff, cmdLen, outBuff, outLen, inBuff, inLen);

  if(ret != SANE_STATUS_GOOD && ret != SANE_STATUS_EOF){
    DBG(5,"do_scsi_cmd: return '%s'\n",sane_strstatus(ret));
    return ret;
  }

  if (inBuff && inLen){
    if(ret == SANE_STATUS_EOF){
      DBG(25, "in: short read, remainder %lu bytes\n", (u_long)s->rs_info);
      *inLen -= s->rs_info;
    }
    hexdump(31, "in: <<", inBuff, *inLen);
    DBG(25, "in: read %d bytes\n", (int)*inLen);
  }

  DBG(10, "do_scsi_cmd: finish\n");

  return ret;
}

static SANE_Status
do_usb_cmd(struct scanner *s, int runRS, int shortTime,
 unsigned char * cmdBuff, size_t cmdLen,
 unsigned char * outBuff, size_t outLen,
 unsigned char * inBuff, size_t * inLen
)
{
    size_t cmdOffset = 0;
    size_t cmdLength = 0;
    size_t cmdActual = 0;
    unsigned char * cmdBuffer = NULL;
    int cmdTimeout = 0;

    size_t outOffset = 0;
    size_t outLength = 0;
    size_t outActual = 0;
    unsigned char * outBuffer = NULL;
    int outTimeout = 0;

    size_t inOffset = 0;
    size_t inLength = 0;
    size_t inActual = 0;
    unsigned char * inBuffer = NULL;
    int inTimeout = 0;

    size_t extraLength = 0;

    int ret = 0;
    int ret2 = 0;

    struct timeval timer;
    gettimeofday(&timer,NULL);

    DBG (10, "do_usb_cmd: start %lu %lu\n", (long unsigned int)timer.tv_sec, (long unsigned int)timer.tv_usec);

    /****************************************************************/
    /* the command stage */
    {
      cmdOffset = USB_HEADER_LEN;
      cmdLength = cmdOffset+USB_COMMAND_LEN;
      cmdActual = cmdLength;
      cmdTimeout = USB_COMMAND_TIME;

      /* change timeout */
      if(shortTime)
        cmdTimeout/=60;
      sanei_usb_set_timeout(cmdTimeout);

      /* build buffer */
      cmdBuffer = calloc(cmdLength,1);
      if(!cmdBuffer){
        DBG(5,"cmd: no mem\n");
        return SANE_STATUS_NO_MEM;
      }
  
      /* build a USB packet around the SCSI command */
      cmdBuffer[3] = cmdLength-4;
      cmdBuffer[5] = 1;
      cmdBuffer[6] = 0x90;
      memcpy(cmdBuffer+cmdOffset,cmdBuff,cmdLen);
  
      /* write the command out */
      DBG(25, "cmd: writing %d bytes, timeout %d\n", (int)cmdLength, cmdTimeout);
      hexdump(30, "cmd: >>", cmdBuffer, cmdLength);
      ret = sanei_usb_write_bulk(s->fd, cmdBuffer, &cmdActual);
      DBG(25, "cmd: wrote %d bytes, retVal %d\n", (int)cmdActual, ret);
  
      if(cmdLength != cmdActual){
        DBG(5,"cmd: wrong size %d/%d\n", (int)cmdLength, (int)cmdActual);
        free(cmdBuffer);
        return SANE_STATUS_IO_ERROR;
      }
      if(ret != SANE_STATUS_GOOD){
        DBG(5,"cmd: write error '%s'\n",sane_strstatus(ret));
        free(cmdBuffer);
        return ret;
      }
      free(cmdBuffer);
    }

    /****************************************************************/
    /* the extra status stage, used by few scanners                 */
    /* this is like the regular status block, with an additional    */
    /* length component at the end */
    if(s->extra_status){
      ret2 = do_usb_status(s,runRS,shortTime,&extraLength);

      /* bail out on bad RS status */
      if(ret2){
        DBG(5,"extra: bad RS status, %d\n", ret2);
        return ret2;
      }
    }

    /****************************************************************/
    /* the output stage */
    if(outBuff && outLen){

      outOffset = USB_HEADER_LEN;
      outLength = outOffset+outLen;
      outActual = outLength;
      outTimeout = USB_DATA_TIME;

      /* change timeout */
      if(shortTime)
        outTimeout/=60;
      sanei_usb_set_timeout(outTimeout);

      /* build outBuffer */
      outBuffer = calloc(outLength,1);
      if(!outBuffer){
        DBG(5,"out: no mem\n");
        return SANE_STATUS_NO_MEM;
      }
  
      /* build a USB packet around the SCSI command */
      outBuffer[3] = outLength-4;
      outBuffer[5] = 2;
      outBuffer[6] = 0xb0;
      memcpy(outBuffer+outOffset,outBuff,outLen);
  
      /* write the command out */
      DBG(25, "out: writing %d bytes, timeout %d\n", (int)outLength, outTimeout);
      hexdump(30, "out: >>", outBuffer, outLength);
      ret = sanei_usb_write_bulk(s->fd, outBuffer, &outActual);
      DBG(25, "out: wrote %d bytes, retVal %d\n", (int)outActual, ret);
  
      if(outLength != outActual){
        DBG(5,"out: wrong size %d/%d\n", (int)outLength, (int)outActual);
        free(outBuffer);
        return SANE_STATUS_IO_ERROR;
      }
      if(ret != SANE_STATUS_GOOD){
        DBG(5,"out: write error '%s'\n",sane_strstatus(ret));
        free(outBuffer);
        return ret;
      }
      free(outBuffer);
    }

    /****************************************************************/
    /* the input stage */
    if(inBuff && inLen){

      inOffset = 0;
      if(s->padded_read)
        inOffset = USB_HEADER_LEN;

      inLength = inOffset+*inLen;
      inActual = inLength;

      /* use the extra length to alter the amount of in we request */
      if(s->extra_status && extraLength && *inLen > extraLength){
        DBG(5,"in: adjust extra, %d %d\n", (int)*inLen, (int)extraLength);
        inActual = inOffset+extraLength;
      }

      /*blast caller's copy in case we error out*/
      *inLen = 0;

      inTimeout = USB_DATA_TIME;

      /* change timeout */
      if(shortTime)
        inTimeout/=60;
      sanei_usb_set_timeout(inTimeout);

      /* build inBuffer */
      inBuffer = calloc(inActual,1);
      if(!inBuffer){
        DBG(5,"in: no mem\n");
        return SANE_STATUS_NO_MEM;
      }
  
      DBG(25, "in: reading %d bytes, timeout %d\n", (int)inActual, inTimeout);
      ret = sanei_usb_read_bulk(s->fd, inBuffer, &inActual);
      DBG(25, "in: read %d bytes, retval %d\n", (int)inActual, ret);
      hexdump(31, "in: <<", inBuffer, inActual);

      if(!inActual){
        DBG(5,"in: got no data, clearing\n");
        free(inBuffer);
	return do_usb_clear(s,1,runRS);
      }
      if(inActual < inOffset){
        DBG(5,"in: read shorter than inOffset\n");
        free(inBuffer);
        return SANE_STATUS_IO_ERROR;
      }
      if(ret != SANE_STATUS_GOOD){
        DBG(5,"in: return error '%s'\n",sane_strstatus(ret));
        free(inBuffer);
        return ret;
      }

      /* note that inBuffer is not copied and freed here...*/
    }

    /****************************************************************/
    /* the normal status stage */
    ret2 = do_usb_status(s,runRS,shortTime,&extraLength);

    /* if status said EOF, adjust input with remainder count */
    if(ret2 == SANE_STATUS_EOF && inBuffer){

      /* EOF is ok */
      ret2 = SANE_STATUS_GOOD;

      if(inActual < inLength - s->rs_info){
        DBG(5,"in: we read < RS, ignoring RS: %d < %d (%d-%d)\n",
          (int)inActual,(int)(inLength-s->rs_info),(int)inLength,(int)s->rs_info);
      }
      else if(inActual > inLength - s->rs_info){
        DBG(5,"in: we read > RS, using RS: %d to %d (%d-%d)\n",
          (int)inActual,(int)(inLength-s->rs_info),(int)inLength,(int)s->rs_info);
        inActual = inLength - s->rs_info;
      }
    }

    /* bail out on bad RS status */
    if(ret2){
      if(inBuffer) free(inBuffer);
      DBG(5,"stat: bad RS status, %d\n", ret2);
      return ret2;
    }

    /* now that we have read status, deal with input buffer */
    if(inBuffer){
      if(inLength != inActual){
        ret = SANE_STATUS_EOF;
        DBG(5,"in: short read, %d/%d\n", (int)inLength,(int)inActual);
      }
  
      /* ignore the USB packet around the SCSI command */
      *inLen = inActual - inOffset;
      memcpy(inBuff,inBuffer+inOffset,*inLen);
  
      free(inBuffer);
    }

    gettimeofday(&timer,NULL);

    DBG (10, "do_usb_cmd: finish %lu %lu\n", (long unsigned int)timer.tv_sec, (long unsigned int)timer.tv_usec);

    return ret;
}

static SANE_Status
do_usb_status(struct scanner *s, int runRS, int shortTime, size_t * extraLength)
{

#define EXTRA_READ_len 4

    size_t statPadding = 0;
    size_t statOffset = 0;
    size_t statLength = 0;
    size_t statActual = 0;
    unsigned char * statBuffer = NULL;
    int statTimeout = 0;

    int ret = 0;

    if(s->padded_read)
      statPadding = USB_HEADER_LEN;

    statLength = statPadding+USB_STATUS_LEN;
    statOffset = statLength-1;

    if(s->extra_status)
      statLength += EXTRA_READ_len;

    statActual = statLength;
    statTimeout = USB_STATUS_TIME;

    /* change timeout */
    if(shortTime)
      statTimeout/=60;
    sanei_usb_set_timeout(statTimeout);

    /* build statBuffer */
    statBuffer = calloc(statLength,1);
    if(!statBuffer){
      DBG(5,"stat: no mem\n");
      return SANE_STATUS_NO_MEM;
    }
  
    DBG(25, "stat: reading %d bytes, timeout %d\n", (int)statLength, statTimeout);
    ret = sanei_usb_read_bulk(s->fd, statBuffer, &statActual);
    DBG(25, "stat: read %d bytes, retval %d\n", (int)statActual, ret);
    hexdump(30, "stat: <<", statBuffer, statActual);
  
    /*weird status*/
    if(ret != SANE_STATUS_GOOD){
      DBG(5,"stat: clearing error '%s'\n",sane_strstatus(ret));
      ret = do_usb_clear(s,1,runRS);
    }
    /*short read*/
    else if(statLength != statActual){
      DBG(5,"stat: clearing short %d/%d\n",(int)statLength,(int)statActual);
      ret = do_usb_clear(s,1,runRS);
    }
    /*inspect the status byte of the response*/
    else if(statBuffer[statOffset]){
      DBG(5,"stat: status %d\n",statBuffer[statLength-1-4]);
      ret = do_usb_clear(s,0,runRS);
    }

    /*extract the extra length byte of the response*/
    if(s->extra_status){
      *extraLength = get_ES_length(statBuffer);
      DBG(15,"stat: extra %d\n",(int)*extraLength);
    }

    free(statBuffer);

    return ret;
}

static SANE_Status
do_usb_clear(struct scanner *s, int clear, int runRS)
{
    SANE_Status ret, ret2;

    DBG (10, "do_usb_clear: start\n");

    usleep(100000);

    if(clear){
      DBG (15, "do_usb_clear: clear halt\n");
      ret = sanei_usb_clear_halt(s->fd);
      if(ret != SANE_STATUS_GOOD){
        DBG(5,"do_usb_clear: cant clear halt, returning %d\n", ret);
        return ret;
      }
    }

    /* caller is interested in having RS run on errors */
    if(runRS){

        unsigned char rs_cmd[REQUEST_SENSE_len];
        size_t rs_cmdLen = REQUEST_SENSE_len;

        unsigned char rs_in[RS_return_size];
        size_t rs_inLen = RS_return_size;

        memset(rs_cmd,0,rs_cmdLen);
        set_SCSI_opcode(rs_cmd, REQUEST_SENSE_code);
	set_RS_return_size(rs_cmd, rs_inLen);

        DBG(25,"rs sub call >>\n");
        ret2 = do_cmd(
          s,0,0,
          rs_cmd, rs_cmdLen,
          NULL,0,
          rs_in, &rs_inLen
        );
        DBG(25,"rs sub call <<\n");
  
        if(ret2 == SANE_STATUS_EOF){
          DBG(5,"rs: got EOF, returning IO_ERROR\n");
          return SANE_STATUS_IO_ERROR;
        }
        if(ret2 != SANE_STATUS_GOOD){
          DBG(5,"rs: return error '%s'\n",sane_strstatus(ret2));
          return ret2;
        }

        /* parse the rs data */
        ret2 = sense_handler( 0, rs_in, (void *)s );

        DBG (10, "do_usb_clear: finish after RS\n");
        return ret2;
    }

    DBG (10, "do_usb_clear: finish with io error\n");

    return SANE_STATUS_IO_ERROR;
}

static SANE_Status
wait_scanner(struct scanner *s) 
{
  SANE_Status ret = SANE_STATUS_GOOD;

  unsigned char cmd[TEST_UNIT_READY_len];
  size_t cmdLen = TEST_UNIT_READY_len;

  DBG (10, "wait_scanner: start\n");

  memset(cmd,0,cmdLen);
  set_SCSI_opcode(cmd,TEST_UNIT_READY_code);

  ret = do_cmd (
    s, 0, 1,
    cmd, cmdLen,
    NULL, 0,
    NULL, NULL
  );
  
  if (ret != SANE_STATUS_GOOD) {
    DBG(5,"WARNING: Brain-dead scanner. Hitting with stick\n");
    ret = do_cmd (
      s, 0, 1,
      cmd, cmdLen,
      NULL, 0,
      NULL, NULL
    );
  }
  if (ret != SANE_STATUS_GOOD) {
    DBG(5,"WARNING: Brain-dead scanner. Hitting with stick again\n");
    ret = do_cmd (
      s, 0, 1,
      cmd, cmdLen,
      NULL, 0,
      NULL, NULL
    );
  }

  if (ret != SANE_STATUS_GOOD) {
    DBG (5, "wait_scanner: error '%s'\n", sane_strstatus (ret));
  }

  DBG (10, "wait_scanner: finish\n");

  return ret;
}

/* Some scanners have per-resolution
 * color interlacing values, but most
 * don't. This helper can tell the 
 * difference.
 */
static int
get_color_inter(struct scanner *s, int side, int res) 
{
  int i;
  for(i=0;i<DPI_1200;i++){
    if(res == dpi_list[i])
      break;
  }

  if(s->color_inter_by_res[i])
    return s->color_inter_by_res[i];

  return s->color_interlace[side];
}

/* s->u.page_x stores the user setting
 * for the paper width in adf. sometimes,
 * we need a value that differs from this
 * due to using FB or overscan.
 */
static int
get_page_width(struct scanner *s) 
{
  int width = s->u.page_x;

  /* scanner max for fb */
  if(s->u.source == SOURCE_FLATBED){
      return s->max_x_fb;
  }

  /* cant overscan larger than scanner max */
  if(width > s->valid_x){
      return s->valid_x;
  }

  /* overscan adds a margin to both sides */
  return width;
}

/* s->u.page_y stores the user setting
 * for the paper height in adf. sometimes,
 * we need a value that differs from this
 * due to using FB or overscan.
 */
static int
get_page_height(struct scanner *s) 
{
  int height = s->u.page_y;

  /* scanner max for fb */
  if(s->u.source == SOURCE_FLATBED){
      return s->max_y_fb;
  }

  /* cant overscan larger than scanner max */
  if(height > s->max_y){
      return s->max_y;
  }

  /* overscan adds a margin to both sides */
  return height;
}


/**
 * Convenience method to determine longest string size in a list.
 */
static size_t
maxStringSize (const 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;
}

/*
 * Prints a hex dump of the given buffer onto the debug output stream.
 */
static void
hexdump (int level, char *comment, unsigned char *p, int l)
{
  int i;
  char line[70]; /* 'xxx: xx xx ... xx xx abc */
  char *hex = line+4;
  char *bin = line+53;

  if(DBG_LEVEL < level)
    return;

  line[0] = 0;

  DBG (level, "%s\n", comment);

  for (i = 0; i < l; i++, p++) {

    /* at start of line */
    if ((i % 16) == 0) {

      /* not at start of first line, print current, reset */
      if (i) {
        DBG (level, "%s\n", line);
      }

      memset(line,0x20,69);
      line[69] = 0;
      hex = line + 4;
      bin = line + 53;

      sprintf (line, "%3.3x:", i);
    }

    /* the hex section */
    sprintf (hex, " %2.2x", *p);
    hex += 3;
    *hex = ' ';

    /* the char section */
    if(*p >= 0x20 && *p <= 0x7e){
      *bin=*p;
    }
    else{
      *bin='.';
    }
    bin++;
  }

  /* print last (partial) line */
  if (i)
    DBG (level, "%s\n", line);
}

/**
 * An advanced method we don't support but have to define.
 */
SANE_Status
sane_set_io_mode (SANE_Handle h, SANE_Bool non_blocking)
{
  DBG (10, "sane_set_io_mode\n");
  DBG (15, "%d %p\n", non_blocking, h);
  return SANE_STATUS_UNSUPPORTED;
}

/**
 * An advanced method we don't support but have to define.
 */
SANE_Status
sane_get_select_fd (SANE_Handle h, SANE_Int *fdp)
{
  DBG (10, "sane_get_select_fd\n");
  DBG (15, "%p %d\n", h, *fdp);
  return SANE_STATUS_UNSUPPORTED;
}

/*
 * @@ Section 8 - Image processing functions
 */

/* Look in image for likely upper and left paper edges, then rotate
 * image so that upper left corner of paper is upper left of image.
 * FIXME: should we do this before we binarize instead of after? */
static SANE_Status
buffer_deskew(struct scanner *s, int side)
{
  SANE_Status ret = SANE_STATUS_GOOD;

  int pwidth = s->i.width;
  int width = s->i.Bpl;
  int height = s->i.height;

  double TSlope = 0;
  int TXInter = 0;
  int TYInter = 0;
  double TSlopeHalf = 0;
  int TOffsetHalf = 0;

  double LSlope = 0;
  int LXInter = 0;
  int LYInter = 0;
  double LSlopeHalf = 0;
  int LOffsetHalf = 0;

  int rotateX = 0;
  int rotateY = 0;

  int * topBuf = NULL, * botBuf = NULL;

  DBG (10, "buffer_deskew: start\n");

  /* get buffers for edge detection */
  topBuf = getTransitionsY(s,side,1);
  if(!topBuf){
    DBG (5, "buffer_deskew: cant gTY\n");
    ret = SANE_STATUS_NO_MEM;
    goto cleanup;
  }

  if(0){
    int i;
    for(i=0;i<width;i++){
      if(topBuf[i] >=0 && topBuf[i] < height)
        s->buffers[side][topBuf[i]*width+i] = 0;
    }
  }

  botBuf = getTransitionsY(s,side,0);
  if(!botBuf){
    DBG (5, "buffer_deskew: cant gTY\n");
    ret = SANE_STATUS_NO_MEM;
    goto cleanup;
  }

  /* find best top line */
  ret = getEdgeIterate (pwidth, height, s->i.dpi_y, topBuf,
    &TSlope, &TXInter, &TYInter);
  if(ret){
    DBG(5,"buffer_deskew: gEI error: %d",ret);
    goto cleanup;
  }
  DBG(15,"top: %04.04f %d %d\n",TSlope,TXInter,TYInter);

  /* slope is too shallow, don't want to divide by 0 */
  if(fabs(TSlope) < 0.0001){
    DBG(15,"buffer_deskew: slope too shallow: %0.08f\n",TSlope);
    goto cleanup;
  }

  /* find best left line, perpendicular to top line */
  LSlope = (double)-1/TSlope;
  ret = getEdgeSlope (pwidth, height, topBuf, botBuf, LSlope,
    &LXInter, &LYInter);
  if(ret){
    DBG(5,"buffer_deskew: gES error: %d",ret);
    goto cleanup;
  }
  DBG(15,"buffer_deskew: left: %04.04f %d %d\n",LSlope,LXInter,LYInter);

  /* find point about which to rotate */
  TSlopeHalf = tan(atan(TSlope)/2);
  TOffsetHalf = LYInter;
  DBG(15,"buffer_deskew: top half: %04.04f %d\n",TSlopeHalf,TOffsetHalf);

  LSlopeHalf = tan((atan(LSlope) + ((LSlope < 0)?-M_PI_2:M_PI_2))/2);
  LOffsetHalf = - LSlopeHalf * TXInter;
  DBG(15,"buffer_deskew: left half: %04.04f %d\n",LSlopeHalf,LOffsetHalf);

  rotateX = (LOffsetHalf-TOffsetHalf) / (TSlopeHalf-LSlopeHalf);
  rotateY = TSlopeHalf * rotateX + TOffsetHalf;
  DBG(15,"buffer_deskew: rotate: %d %d\n",rotateX,rotateY);

  ret = rotateOnCenter (s, side, rotateX, rotateY, TSlope);
  if(ret){
    DBG(5,"buffer_deskew: gES error: %d",ret);
    goto cleanup;
  }

  cleanup:
  if(topBuf)
    free(topBuf);
  if(botBuf)
    free(botBuf);

  DBG (10, "buffer_deskew: finish\n");
  return ret;
}

/* Look in image for likely left/right/bottom paper edges, then crop
 * image to match. Does not attempt to rotate the image.
 * FIXME: should we do this before we binarize instead of after? */
static SANE_Status
buffer_crop(struct scanner *s, int side)
{
  SANE_Status ret = SANE_STATUS_GOOD;

  int bwidth = s->i.Bpl;
  int width = s->i.width;
  int height = s->i.height;

  int top = 0;
  int bot = 0;
  int left = width;
  int right = 0;

  int * topBuf = NULL, * botBuf = NULL;
  int * leftBuf = NULL, * rightBuf = NULL;
  int leftCount = 0, rightCount = 0, botCount = 0;
  int i;

  DBG (10, "buffer_crop: start\n");

  /* get buffers to find sides and bottom */
  topBuf = getTransitionsY(s,side,1);
  if(!topBuf){
    DBG (5, "buffer_crop: no topBuf\n");
    ret = SANE_STATUS_NO_MEM;
    goto cleanup;
  }

  botBuf = getTransitionsY(s,side,0);
  if(!botBuf){
    DBG (5, "buffer_crop: no botBuf\n");
    ret = SANE_STATUS_NO_MEM;
    goto cleanup;
  }

  leftBuf = getTransitionsX(s,side,1);
  if(!leftBuf){
    DBG (5, "buffer_crop: no leftBuf\n");
    ret = SANE_STATUS_NO_MEM;
    goto cleanup;
  }

  rightBuf = getTransitionsX(s,side,0);
  if(!rightBuf){
    DBG (5, "buffer_crop: no rightBuf\n");
    ret = SANE_STATUS_NO_MEM;
    goto cleanup;
  }

  /* loop thru top and bottom lists, look for l and r extremes */
  for(i=0; i<width; i++){
    if(botBuf[i] > topBuf[i]){
      if(left > i){
        left = i;
      }

      leftCount++;
      if(leftCount > 3){
        break;
      }
    }
    else{
      leftCount = 0;
      left = width;
    }
  }

  for(i=width-1; i>=0; i--){
    if(botBuf[i] > topBuf[i]){
      if(right < i){
        right = i;
      }

      rightCount++;
      if(rightCount > 3){
        break;
      }
    }
    else{
      rightCount = 0;
      right = -1;
    }
  }

  /* loop thru left and right lists, look for bottom extreme */
  for(i=height-1; i>=0; i--){
    if(rightBuf[i] > leftBuf[i]){
      if(bot < i){
        bot = i;
      }

      botCount++;
      if(botCount > 3){
        break;
      }
    }
    else{
      botCount = 0;
      bot = -1;
    }
  }

  DBG (15, "buffer_crop: t:%d b:%d l:%d r:%d\n",top,bot,left,right);

  /* now crop the image */
  /*FIXME: crop duplex backside at same time?*/
  if(left < right && top < bot){

    int pixels = 0;
    int bytes = 0;
    unsigned char * line = NULL;

    /*convert left and right to bytes, figure new byte and pixel width */
    switch (s->i.mode) {

      case MODE_COLOR:
        pixels = right-left;
        bytes = pixels * 3;
        left *= 3;
        right *= 3;
        break;

      case MODE_GRAYSCALE:
        pixels = right-left;
        bytes = right-left;
        break;

      case MODE_LINEART:
      case MODE_HALFTONE:
        left /= 8;
        right = (right+7)/8;
        bytes = right-left;
        pixels = bytes * 8;
        break;
    }

    DBG (15, "buffer_crop: l:%d r:%d p:%d b:%d\n",left,right,pixels,bytes);

    line = malloc(bytes);
    if(!line){
      DBG (5, "buffer_crop: no line\n");
      ret = SANE_STATUS_NO_MEM;
      goto cleanup;
    }

    s->i.bytes_sent[side] = 0;

    for(i=top; i<bot; i++){
      memcpy(line, s->buffers[side] + i*bwidth + left, bytes);
      memcpy(s->buffers[side] + s->i.bytes_sent[side], line, bytes);
      s->i.bytes_sent[side] += bytes;
    }

    s->i.bytes_tot[side] = s->i.bytes_sent[side];
    s->i.width = pixels;
    s->i.height = bot-top;
    s->i.Bpl = bytes;

    free(line);
  }

  cleanup:
  if(topBuf)
    free(topBuf);
  if(botBuf)
    free(botBuf);
  if(leftBuf)
    free(leftBuf);
  if(rightBuf)
    free(rightBuf);

  DBG (10, "buffer_crop: finish\n");
  return ret;
}

/* Look in image for disconnected 'spots' of the requested size.
 * Replace the spots with the average color of the surrounding pixels.
 * FIXME: should we do this before we binarize instead of after? */
static SANE_Status
buffer_despeck(struct scanner *s, int side)
{
  SANE_Status ret = SANE_STATUS_GOOD;
  int i,j,k,l,n;
  int w = s->i.Bpl;
  int pw = s->i.width;
  int h = s->i.height;
  int t = w*h;
  int d = s->swdespeck;

  DBG (10, "buffer_despeck: start\n");

  switch (s->i.mode){

    case MODE_COLOR:
      for(i=w; i<t-w-(w*d); i+=w){
        for(j=1; j<pw-1-d; j++){

          int thresh = 255*3;
          int outer[] = {0,0,0};
          int hits = 0;

          /*loop over rows and columns in window */
          for(k=0; k<d; k++){
            for(l=0; l<d; l++){
              int tmp = 0;

              for(n=0; n<3; n++){
                tmp += s->buffers[side][i + j*3 + k*w + l*3 + n];
              }

              if(tmp < thresh)
                thresh = tmp;
            }
          }

          thresh = (thresh + 255*3 + 255*3)/3;
    
          /*loop over rows and columns around window */
          for(k=-1; k<d+1; k++){
            for(l=-1; l<d+1; l++){

              int tmp[3];
  
              /* dont count pixels in the window */
              if(k != -1 && k != d && l != -1 && l != d)
                continue;
  
              for(n=0; n<3; n++){
                tmp[n] = s->buffers[side][i + j*3 + k*w + l*3 + n];
                outer[n] += tmp[n];
              }
              if(tmp[0]+tmp[1]+tmp[2] < thresh){
                hits++;
                break;
              }
            }
          }

          for(n=0; n<3; n++){
            outer[n] /= (4*d + 4);
          }

          /*no hits, overwrite with avg surrounding color*/
          if(!hits){
            for(k=0; k<d; k++){
              for(l=0; l<d; l++){
                for(n=0; n<3; n++){
                  s->buffers[side][i + j*3 + k*w + l*3 + n] = outer[n];
                }
              }
            }
          }

        }
      }
      break;

    case MODE_GRAYSCALE:
      for(i=w; i<t-w-(w*d); i+=w){
        for(j=1; j<w-1-d; j++){

          int thresh = 255;
          int outer = 0;
          int hits = 0;

          for(k=0; k<d; k++){
            for(l=0; l<d; l++){
              if(s->buffers[side][i + j + k*w + l] < thresh)
                thresh = s->buffers[side][i + j + k*w + l];
            }
          }

          thresh = (thresh + 255 + 255)/3;
    
          /*loop over rows and columns around window */
          for(k=-1; k<d+1; k++){
            for(l=-1; l<d+1; l++){

              int tmp = 0;

              /* dont count pixels in the window */
              if(k != -1 && k != d && l != -1 && l != d)
                continue;
  
              tmp = s->buffers[side][i + j + k*w + l];

              if(tmp < thresh){
                hits++;
                break;
              }

              outer += tmp;
            }
          }

          outer /= (4*d + 4);

          /*no hits, overwrite with avg surrounding color*/
          if(!hits){
            for(k=0; k<d; k++){
              for(l=0; l<d; l++){
                s->buffers[side][i + j + k*w + l] = outer;
              }
            }
          }

        }
      }
      break;

    case MODE_LINEART:
    case MODE_HALFTONE:
      for(i=w; i<t-w-(w*d); i+=w){
        for(j=1; j<pw-1-d; j++){
          
          int curr = 0;
          int hits = 0;

          for(k=0; k<d; k++){
            for(l=0; l<d; l++){
              curr += s->buffers[side][i + k*w + (j+l)/8] >> (7-(j+l)%8) & 1;
            }
          }

          if(!curr)
            continue;

          /*loop over rows and columns around window */
          for(k=-1; k<d+1; k++){
            for(l=-1; l<d+1; l++){

              /* dont count pixels in the window */
              if(k != -1 && k != d && l != -1 && l != d)
                continue;
  
              hits += s->buffers[side][i + k*w + (j+l)/8] >> (7-(j+l)%8) & 1;

              if(hits)
                break;
            }
          }

          /*no hits, overwrite with white*/
          if(!hits){
            for(k=0; k<d; k++){
              for(l=0; l<d; l++){
                s->buffers[side][i + k*w + (j+l)/8] &= ~(1 << (7-(j+l)%8));
              }
            }
          }

        }
      }
      break;

    default:
      break;
  }

  DBG (10, "buffer_despeck: finish\n");
  return ret;
}

/* Loop thru the image width and look for first color change in each column.
 * Return a malloc'd array. Caller is responsible for freeing. */
int * 
getTransitionsY (struct scanner *s, int side, int top)
{
  int * buff;

  int i, j, k;
  int near, far;
  int winLen = 9;

  int width = s->i.width;
  int height = s->i.height;
  int depth = 1;

  /* defaults for bottom-up */
  int firstLine = height-1;
  int lastLine = -1;
  int direction = -1;

  DBG (10, "getTransitionsY: start\n");

  buff = calloc(width,sizeof(int));
  if(!buff){
    DBG (5, "getTransitionsY: no buff\n");
    return NULL;
  }

  /* override for top-down */
  if(top){
    firstLine = 0;
    lastLine = height;
    direction = 1;
  }

  /* load the buff array with y value for first color change from edge
   * gray/color uses a different algo from binary/halftone */
  switch (s->i.mode) {

    case MODE_COLOR:
      depth = 3;

    case MODE_GRAYSCALE:

      for(i=0; i<width; i++){
        buff[i] = lastLine;
  
        /* load the near and far windows with repeated copy of first pixel */
        near = 0;
        for(k=0; k<depth; k++){
          near += s->buffers[side][(firstLine*width+i) * depth + k];
        }
        near *= winLen;
        far = near;
  
        /* move windows, check delta */
        for(j=firstLine+direction; j!=lastLine; j+=direction){
  
          int farLine = j-winLen*2*direction;
          int nearLine = j-winLen*direction;

          if(farLine < 0 || farLine >= height){
            farLine = firstLine;
          }
          if(nearLine < 0 || nearLine >= height){
            nearLine = firstLine;
          }

          for(k=0; k<depth; k++){
            far -= s->buffers[side][(farLine*width+i)*depth+k];
            far += s->buffers[side][(nearLine*width+i)*depth+k];

            near -= s->buffers[side][(nearLine*width+i)*depth+k];
            near += s->buffers[side][(j*width+i)*depth+k];
          }
  
          if(abs(near - far) > winLen*depth*9){
            buff[i] = j;
            break;
          }
        }
      }
      break;

    case MODE_LINEART:
    case MODE_HALFTONE:
      for(i=0; i<width; i++){
        buff[i] = lastLine;
  
        /* load the near window with first pixel */
        near = s->buffers[side][(firstLine*width+i)/8] >> (7-(i%8)) & 1;
  
        /* move */
        for(j=firstLine+direction; j!=lastLine; j+=direction){
          if((s->buffers[side][(j*width+i)/8] >> (7-(i%8)) & 1) != near){
            buff[i] = j;
            break;
          }
        }
      }
      break;

  }

  /* blast any stragglers with no neighbors within .5 inch */
  for(i=0;i<width-7;i++){
    int sum = 0;
    for(j=1;j<=7;j++){
      if(abs(buff[i+j] - buff[i]) < s->i.dpi_y/2)
        sum++;
    }
    if(sum < 2)
      buff[i] = lastLine;
  }

  DBG (10, "getTransitionsY: finish\n");

  return buff;
}

/* Loop thru the image height and look for first color change in each row.
 * Return a malloc'd array. Caller is responsible for freeing. */
int * 
getTransitionsX (struct scanner *s, int side, int left)
{
  int * buff;

  int i, j, k;
  int near, far;
  int winLen = 9;

  int bwidth = s->i.Bpl;
  int width = s->i.width;
  int height = s->i.height;
  int depth = 1;

  /* defaults for right-first */
  int firstCol = width-1;
  int lastCol = -1;
  int direction = -1;

  DBG (10, "getTransitionsX: start\n");

  buff = calloc(height,sizeof(int));
  if(!buff){
    DBG (5, "getTransitionsY: no buff\n");
    return NULL;
  }

  /* override for left-first*/
  if(left){
    firstCol = 0;
    lastCol = width;
    direction = 1;
  }

  /* load the buff array with x value for first color change from edge
   * gray/color uses a different algo from binary/halftone */
  switch (s->i.mode) {

    case MODE_COLOR:
      depth = 3;

    case MODE_GRAYSCALE:

      for(i=0; i<height; i++){
        buff[i] = lastCol;
  
        /* load the near and far windows with repeated copy of first pixel */
        near = 0;
        for(k=0; k<depth; k++){
          near += s->buffers[side][i*bwidth + k];
        }
        near *= winLen;
        far = near;
  
        /* move windows, check delta */
        for(j=firstCol+direction; j!=lastCol; j+=direction){
  
          int farCol = j-winLen*2*direction;
          int nearCol = j-winLen*direction;

          if(farCol < 0 || farCol >= width){
            farCol = firstCol;
          }
          if(nearCol < 0 || nearCol >= width){
            nearCol = firstCol;
          }

          for(k=0; k<depth; k++){
            far -= s->buffers[side][i*bwidth + farCol*depth + k];
            far += s->buffers[side][i*bwidth + nearCol*depth + k];

            near -= s->buffers[side][i*bwidth + nearCol*depth + k];
            near += s->buffers[side][i*bwidth + j*depth + k];
          }
  
          if(abs(near - far) > winLen*depth*9){
            buff[i] = j;
            break;
          }
        }
      }
      break;

    case MODE_LINEART:
    case MODE_HALFTONE:
      for(i=0; i<height; i++){
        buff[i] = lastCol;
  
        /* load the near window with first pixel */
        near = s->buffers[side][i*bwidth + firstCol/8] >> (7-(firstCol%8)) & 1;
  
        /* move */
        for(j=firstCol+direction; j!=lastCol; j+=direction){
          if((s->buffers[side][i*bwidth + j/8] >> (7-(j%8)) & 1) != near){
            buff[i] = j;
            break;
          }
        }
      }
      break;

  }

  /* blast any stragglers with no neighbors within .5 inch */
  for(i=0;i<height-7;i++){
    int sum = 0;
    for(j=1;j<=7;j++){
      if(abs(buff[i+j] - buff[i]) < s->i.dpi_x/2)
        sum++;
    }
    if(sum < 2)
      buff[i] = lastCol;
  }

  DBG (10, "getTransitionsX: finish\n");

  return buff;
}

/* Loop thru a getTransitions array, and use a simplified Hough transform
 * to divide likely edges into a 2-d array of bins. Then weight each
 * bin based on its angle and offset. Return the 'best' bin. */
static SANE_Status
getLine (int height, int width, int * buff,
 int slopes, double minSlope, double maxSlope,
 int offsets, int minOffset, int maxOffset,
 double * finSlope, int * finOffset, int * finDensity)
{
  SANE_Status ret = 0;

  int ** lines = NULL;
  int i, j;
  int rise, run;
  double slope;
  int offset;
  int sIndex, oIndex;
  int hWidth = width/2;

  double * slopeCenter = NULL;
  int * slopeScale = NULL;
  double * offsetCenter = NULL;
  int * offsetScale = NULL;

  int maxDensity = 1;
  double absMaxSlope = fabs(maxSlope);
  double absMinSlope = fabs(minSlope);
  int absMaxOffset = abs(maxOffset);
  int absMinOffset = abs(minOffset);

  DBG(10,"getLine: start %+0.4f %+0.4f %d %d\n",
    minSlope,maxSlope,minOffset,maxOffset);

  /*silence compiler*/
  height = height;

  if(absMaxSlope < absMinSlope)
    absMaxSlope = absMinSlope;

  if(absMaxOffset < absMinOffset)
    absMaxOffset = absMinOffset;

  /* build an array of pretty-print values for slope */
  slopeCenter = calloc(slopes,sizeof(double));
  if(!slopeCenter){
    DBG(5,"getLine: cant load slopeCenter\n");
    ret = SANE_STATUS_NO_MEM;
    goto cleanup;
  }

  /* build an array of scaling factors for slope */
  slopeScale = calloc(slopes,sizeof(int));
  if(!slopeScale){
    DBG(5,"getLine: cant load slopeScale\n");
    ret = SANE_STATUS_NO_MEM;
    goto cleanup;
  }

  for(j=0;j<slopes;j++){

    /* find central value of this 'bucket' */
    slopeCenter[j] = (
      (double)j*(maxSlope-minSlope)/slopes+minSlope 
      + (double)(j+1)*(maxSlope-minSlope)/slopes+minSlope
    )/2;

    /* scale value from the requested range into an inverted 100-1 range
     * input close to 0 makes output close to 100 */
    slopeScale[j] = 101 - fabs(slopeCenter[j])*100/absMaxSlope;
  }

  /* build an array of pretty-print values for offset */
  offsetCenter = calloc(offsets,sizeof(double));
  if(!offsetCenter){
    DBG(5,"getLine: cant load offsetCenter\n");
    ret = SANE_STATUS_NO_MEM;
    goto cleanup;
  }

  /* build an array of scaling factors for offset */
  offsetScale = calloc(offsets,sizeof(int));
  if(!offsetScale){
    DBG(5,"getLine: cant load offsetScale\n");
    ret = SANE_STATUS_NO_MEM;
    goto cleanup;
  }

  for(j=0;j<offsets;j++){

    /* find central value of this 'bucket'*/
    offsetCenter[j] = (
      (double)j/offsets*(maxOffset-minOffset)+minOffset
      + (double)(j+1)/offsets*(maxOffset-minOffset)+minOffset
    )/2;

    /* scale value from the requested range into an inverted 100-1 range
     * input close to 0 makes output close to 100 */
    offsetScale[j] = 101 - fabs(offsetCenter[j])*100/absMaxOffset;
  }

  /* build 2-d array of 'density', divided into slope and offset ranges */
  lines = calloc(slopes, sizeof(int *));
  if(!lines){
    DBG(5,"getLine: cant load lines\n");
    ret = SANE_STATUS_NO_MEM;
    goto cleanup;
  }

  for(i=0;i<slopes;i++){
    if(!(lines[i] = calloc(offsets, sizeof(int)))){
      DBG(5,"getLine: cant load lines %d\n",i);
      ret = SANE_STATUS_NO_MEM;
      goto cleanup;
    }
  }

  for(i=0;i<width;i++){
    for(j=i+1;j<width && j<i+width/3;j++){

      /*FIXME: check for invalid (min/max) values?*/
      rise = buff[j] - buff[i];
      run = j-i;

      slope = (double)rise/run;
      if(slope >= maxSlope || slope < minSlope)
        continue;

      /* offset in center of width, not y intercept! */
      offset = slope * hWidth + buff[i] - slope * i;
      if(offset >= maxOffset || offset < minOffset)
        continue;

      sIndex = (slope - minSlope) * slopes/(maxSlope-minSlope);
      if(sIndex >= slopes)
        continue;

      oIndex = (offset - minOffset) * offsets/(maxOffset-minOffset);
      if(oIndex >= offsets)
        continue;

      lines[sIndex][oIndex]++;
    }
  }

  /* go thru array, and find most dense line (highest number) */
  for(i=0;i<slopes;i++){
    for(j=0;j<offsets;j++){
      if(lines[i][j] > maxDensity)
        maxDensity = lines[i][j];
    }
  }
  
  DBG(15,"getLine: maxDensity %d\n",maxDensity);

  *finSlope = 0;
  *finOffset = 0;
  *finDensity = 0;

  /* go thru array, and scale densities to % of maximum, plus adjust for
   * prefered (smaller absolute value) slope and offset */
  for(i=0;i<slopes;i++){
    for(j=0;j<offsets;j++){
      lines[i][j] = lines[i][j] * slopeScale[i] * offsetScale[j] / maxDensity;
      if(lines[i][j] > *finDensity){
        *finDensity = lines[i][j];
        *finSlope = slopeCenter[i];
        *finOffset = offsetCenter[j];
      }
    }
  }
  
  if(0){
    DBG(15,"offsetCenter:       ");
    for(j=0;j<offsets;j++){
      DBG(15," %+04.0f",offsetCenter[j]);
    }
    DBG(15,"\n");
  
    DBG(15,"offsetScale:        ");
    for(j=0;j<offsets;j++){
      DBG(15," %04d",offsetScale[j]);
    }
    DBG(15,"\n");
  
    for(i=0;i<slopes;i++){
      DBG(15,"slope: %02d %+02.2f %03d:",i,slopeCenter[i],slopeScale[i]);
      for(j=0;j<offsets;j++){
        DBG(15,"% 5d",lines[i][j]/100);
      }
      DBG(15,"\n");
    }
  }

  /* dont forget to cleanup */
  cleanup:
  for(i=0;i<10;i++){
    if(lines[i])
      free(lines[i]);
  }
  if(lines)
    free(lines);
  if(slopeCenter)
    free(slopeCenter);
  if(slopeScale)
    free(slopeScale);
  if(offsetCenter)
    free(offsetCenter);
  if(offsetScale)
    free(offsetScale);

  DBG(10,"getLine: finish\n");

  return ret;
}

/* Repeatedly find the best range of slope and offset via Hough transform.
 * Shift the ranges thru 4 different positions to avoid splitting data
 * across multiple bins (false positive). Home-in on the most likely upper
 * line of the paper inside the image. Return the 'best' line. */
SANE_Status
getEdgeIterate (int width, int height, int resolution,
int * buff, double * finSlope, int * finXInter, int * finYInter)
{
  SANE_Status ret = SANE_STATUS_GOOD;

  int slopes = 11;
  int offsets = 11;
  double maxSlope = 1;
  double minSlope = -1;
  int maxOffset = resolution/6;
  int minOffset = -resolution/6;

  double topSlope = 0;
  int topOffset = 0;
  int topDensity = 0;
  
  int i,j;
  int pass = 0;

  DBG(10,"getEdgeIterate: start\n");

  while(pass++ < 7){
    double sStep = (maxSlope-minSlope)/slopes;
    int oStep = (maxOffset-minOffset)/offsets;

    double slope = 0;
    int offset = 0;
    int density = 0;
    int go = 0;

    topSlope = 0;
    topOffset = 0;
    topDensity = 0;

    /* find lines 4 times with slightly moved params,
     * to bypass binning errors, highest density wins */
    for(i=0;i<2;i++){
      double sStep2 = sStep*i/2;
      for(j=0;j<2;j++){
        int oStep2 = oStep*j/2;
        ret = getLine(height,width,buff,slopes,minSlope+sStep2,maxSlope+sStep2,offsets,minOffset+oStep2,maxOffset+oStep2,&slope,&offset,&density);
        if(ret){
          DBG(5,"getEdgeIterate: getLine error %d\n",ret);
          return ret;
        }
        DBG(15,"getEdgeIterate: %d %d %+0.4f %d %d\n",i,j,slope,offset,density);

        if(density > topDensity){
          topSlope = slope;
          topOffset = offset;
          topDensity = density;
        }
      }
    }

    DBG(15,"getEdgeIterate: ok %+0.4f %d %d\n",topSlope,topOffset,topDensity);

    /* did not find anything promising on first pass,
     * give up instead of fixating on some small, pointless feature */
    if(pass == 1 && topDensity < width/5){
      DBG(5,"getEdgeIterate: density too small %d %d\n",topDensity,width);
      topOffset = 0;
      topSlope = 0;
      break;
    }

    /* if slope can zoom in some more, do so. */
    if(sStep >= 0.0001){
      minSlope = topSlope - sStep;
      maxSlope = topSlope + sStep;
      go = 1;
    }

    /* if offset can zoom in some more, do so. */
    if(oStep){
      minOffset = topOffset - oStep;
      maxOffset = topOffset + oStep;
      go = 1;
    }

    /* cannot zoom in more, bail out */
    if(!go){
      break;
    }

    DBG(15,"getEdgeIterate: zoom: %+0.4f %+0.4f %d %d\n",
      minSlope,maxSlope,minOffset,maxOffset);
  }

  /* topOffset is in the center of the image,
   * convert to x and y intercept */
  if(topSlope != 0){
    *finYInter = topOffset - topSlope * width/2;
    *finXInter = *finYInter / -topSlope;
    *finSlope = topSlope;
  }
  else{
    *finYInter = 0;
    *finXInter = 0;
    *finSlope = 0;
  }

  DBG(10,"getEdgeIterate: finish\n");

  return 0;
}

/* find the left side of paper by moving a line 
 * perpendicular to top slope across the image
 * the 'left-most' point on the paper is the
 * one with the smallest X intercept
 * return x and y intercepts */
SANE_Status 
getEdgeSlope (int width, int height, int * top, int * bot,
 double slope, int * finXInter, int * finYInter)
{

  int i;
  int topXInter, topYInter;
  int botXInter, botYInter;
  int leftCount;

  DBG(10,"getEdgeSlope: start\n");

  topXInter = width;
  topYInter = 0;
  leftCount = 0;

  for(i=0;i<width;i++){
    
    if(top[i] < height){
      int tyi = top[i] - (slope * i);
      int txi = tyi/-slope;

      if(topXInter > txi){
        topXInter = txi;
        topYInter = tyi;
      }

      leftCount++;
      if(leftCount > 5){
        break;
      }
    }
    else{
      topXInter = width;
      topYInter = 0;
      leftCount = 0;
    }
  }

  botXInter = width;
  botYInter = 0;
  leftCount = 0;

  for(i=0;i<width;i++){
    
    if(bot[i] > -1){

      int byi = bot[i] - (slope * i);
      int bxi = byi/-slope;

      if(botXInter > bxi){
        botXInter = bxi;
        botYInter = byi;
      }

      leftCount++;
      if(leftCount > 5){
        break;
      }
    }
    else{
      botXInter = width;
      botYInter = 0;
      leftCount = 0;
    }
  }

  if(botXInter < topXInter){
    *finXInter = botXInter;
    *finYInter = botYInter;
  }
  else{
    *finXInter = topXInter;
    *finYInter = topYInter;
  }

  DBG(10,"getEdgeSlope: finish\n");

  return 0;
}

/* function to do a simple rotation by a given slope, around
 * a given point. The point can be outside of image to get
 * proper edge alignment. Unused areas filled with bg color
 * FIXME: Do in-place rotation to save memory */
SANE_Status
rotateOnCenter (struct scanner *s, int side,
  int centerX, int centerY, double slope)
{
  double slopeRad = -atan(slope);
  double slopeSin = sin(slopeRad);
  double slopeCos = cos(slopeRad);

  int bwidth = s->i.Bpl;
  int pwidth = s->i.width;
  int height = s->i.height;
  int depth = 1;
  int bg_color = s->lut[s->bg_color];

  unsigned char * outbuf;
  int i, j, k;

  DBG(10,"rotateOnCenter: start: %d %d\n",centerX,centerY);

  outbuf = malloc(s->i.bytes_tot[side]);
  if(!outbuf){
    DBG(15,"rotateOnCenter: no outbuf\n");
    return SANE_STATUS_NO_MEM;
  }

  switch (s->i.mode){

    case MODE_COLOR:
      depth = 3;

    case MODE_GRAYSCALE:
      memset(outbuf,bg_color,s->i.bytes_tot[side]);

      for (i=0; i<height; i++) {
        int shiftY = centerY - i;
    
        for (j=0; j<pwidth; j++) {
          int shiftX = centerX - j;
          int sourceX, sourceY;
    
          sourceX = centerX - (int)(shiftX * slopeCos + shiftY * slopeSin);
          if (sourceX < 0 || sourceX >= pwidth)
            continue;
    
          sourceY = centerY + (int)(-shiftY * slopeCos + shiftX * slopeSin);
          if (sourceY < 0 || sourceY >= height)
            continue;
    
          for (k=0; k<depth; k++) {
            outbuf[i*bwidth+j*depth+k]
              = s->buffers[side][sourceY*bwidth+sourceX*depth+k];
          }
        }
      }
      break;

    case MODE_LINEART:
    case MODE_HALFTONE:
      memset(outbuf,(bg_color<s->threshold)?0xff:0x00,s->i.bytes_tot[side]);

      for (i=0; i<height; i++) {
        int shiftY = centerY - i;
    
        for (j=0; j<pwidth; j++) {
          int shiftX = centerX - j;
          int sourceX, sourceY;
    
          sourceX = centerX - (int)(shiftX * slopeCos + shiftY * slopeSin);
          if (sourceX < 0 || sourceX >= pwidth)
            continue;
    
          sourceY = centerY + (int)(-shiftY * slopeCos + shiftX * slopeSin);
          if (sourceY < 0 || sourceY >= height)
            continue;

          /* wipe out old bit */
          outbuf[i*bwidth + j/8] &= ~(1 << (7-(j%8)));

          /* fill in new bit */
          outbuf[i*bwidth + j/8] |= 
            ((s->buffers[side][sourceY*bwidth + sourceX/8]
            >> (7-(sourceX%8))) & 1) << (7-(j%8));
        }
      }
      break;
  }

  memcpy(s->buffers[side],outbuf,s->i.bytes_tot[side]);

  free(outbuf);

  DBG(10,"rotateOnCenter: finish\n");

  return 0;
}

/* Function to build a lookup table (LUT), often
   used by scanners to implement brightness/contrast/gamma
   or by backends to speed binarization/thresholding

   offset and slope inputs are -127 to +127 

   slope rotates line around central input/output val,
   0 makes horizontal line

       pos           zero          neg
       .       x     .             .  x
       .      x      .             .   x
   out .     x       .xxxxxxxxxxx  .    x
       .    x        .             .     x
       ....x.......  ............  .......x....
            in            in            in

   offset moves line vertically, and clamps to output range
   0 keeps the line crossing the center of the table

       pos            zero          neg 
       .   xxxxxxxx   .        xx   .
       . x            .      x      . 
   out x              .    x        .          x
       .              .  x          .        x
       ............   xx..........  xxxxxxxx....
            in             in

   out_min/max provide bounds on output values,
   useful when building thresholding lut.
   0 and 255 are good defaults otherwise.
  */
static SANE_Status
load_lut (unsigned char * lut,
  int in_bits, int out_bits,
  int out_min, int out_max,
  int slope, int offset)
{
  SANE_Status ret = SANE_STATUS_GOOD;
  int i, j;
  double shift, rise;
  int max_in_val = (1 << in_bits) - 1;
  int max_out_val = (1 << out_bits) - 1;
  unsigned char * lut_p = lut;

  DBG (10, "load_lut: start %d %d\n", slope, offset);

  /* slope is converted to rise per unit run:
   * first [-127,127] to [-.999,.999]
   * then to [-PI/4,PI/4] then [0,PI/2]
   * then take the tangent (T.O.A)
   * then multiply by the normal linear slope 
   * because the table may not be square, i.e. 1024x256*/
  rise = tan((double)slope/128 * M_PI_4 + M_PI_4) * max_out_val / max_in_val;

  /* line must stay vertically centered, so figure
   * out vertical offset at central input value */
  shift = (double)max_out_val/2 - (rise*max_in_val/2);

  /* convert the user offset setting to scale of output
   * first [-127,127] to [-1,1]
   * then to [-max_out_val/2,max_out_val/2]*/
  shift += (double)offset / 127 * max_out_val / 2;

  for(i=0;i<=max_in_val;i++){
    j = rise*i + shift;

    if(j<out_min){
      j=out_min;
    }
    else if(j>out_max){
      j=out_max;
    }

    *lut_p=j;
    lut_p++;
  }

  hexdump(5, "load_lut: ", lut, max_in_val+1);

  DBG (10, "load_lut: finish\n");
  return ret;
}