summaryrefslogtreecommitdiff
path: root/backend/dc25.c
blob: 3bb81f51c4f6fe1c674b0c7df8681d781c72ddc4 (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
/***************************************************************************
 * SANE - Scanner Access Now Easy.

   dc25.c

   $Id$

   This file (C) 1998 Peter Fales

   This file is part of the SANE package.

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

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

   You should have received a copy of the GNU General Public License
   along with this program; if not, 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.

 ***************************************************************************

   This file implements a SANE backend for the Kodak DC-25 (and
   probably the DC-20) digital cameras.  THIS IS EXTREMELY ALPHA CODE!
   USE AT YOUR OWN RISK!!

   (feedback to:  dc25-devel@fales-lorenz.net)

   This backend is based heavily on the dc20ctrl package by Ugo
   Paternostro <paterno@dsi.unifi.it>.  I've attached his header below:

 ***************************************************************************

 *	Copyright (C) 1998 Ugo Paternostro <paterno@dsi.unifi.it>
 *
 *	This file is part of the dc20ctrl package. The complete package can be
 *	downloaded from:
 *	    http://aguirre.dsi.unifi.it/~paterno/binaries/dc20ctrl.tar.gz
 *
 *	This package is derived from the dc20 package, built by Karl Hakimian
 *	<hakimian@aha.com> that you can find it at ftp.eecs.wsu.edu in the
 *	/pub/hakimian directory. The complete URL is:
 *	    ftp://ftp.eecs.wsu.edu/pub/hakimian/dc20.tar.gz
 *
 *	This package also includes a sligthly modified version of the Comet to ppm
 *	conversion routine written by YOSHIDA Hideki <hideki@yk.rim.or.jp>
 *
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published
 *	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., 675 Mass Ave, Cambridge, MA 02139, USA.
 *

 ***************************************************************************/

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

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>

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

#define BACKEND_NAME	dc25
#include "../include/sane/sanei_backend.h"

#include "dc25.h"

#ifndef PATH_MAX
# define PATH_MAX	1024
#endif

#define MAGIC			(void *)0xab730324
#define DC25_CONFIG_FILE 	"dc25.conf"
#define THUMBSIZE  ( (CameraInfo.model == 0x25 ) ? 14400 : 5120 )

static SANE_Bool is_open = 0;

static SANE_Byte dc25_opt_image_number = 1;	/* Image to load */
static SANE_Bool dc25_opt_thumbnails;	/* Load thumbnails */
static SANE_Bool dc25_opt_snap;	/* Take new picture */
static SANE_Bool dc25_opt_lowres;	/* Use low resoluiton */
#define DC25_OPT_CONTRAST_DEFAULT 1.6
						/* Contrast enhancement */
static SANE_Fixed dc25_opt_contrast = SANE_FIX (DC25_OPT_CONTRAST_DEFAULT);
#define DC25_OPT_GAMMA_DEFAULT 4.5
						/* Gamma correction (10x) */
static SANE_Fixed dc25_opt_gamma = SANE_FIX (DC25_OPT_GAMMA_DEFAULT);
static SANE_Bool dc25_opt_erase;	/* Erase all after download */
static SANE_Bool dc25_opt_erase_one;	/* Erase one after download */
static SANE_Bool dumpinquiry;

static SANE_Int info_flags;

static int tfd;			/* Camera File Descriptor */
static char tty_name[PATH_MAX];
#define DEF_TTY_NAME "/dev/ttyS0"

static speed_t tty_baud = DEFAULT_TTY_BAUD;
static char *tmpname;
static char tmpnamebuf[] = "/tmp/dc25XXXXXX";

static Dc20Info *dc20_info;
static Dc20Info CameraInfo;

static SANE_Byte contrast_table[256];

static struct pixmap *pp;

static const SANE_Range contrast_range = {
  0 << SANE_FIXED_SCALE_SHIFT,	/* minimum */
  3 << SANE_FIXED_SCALE_SHIFT,	/* maximum */
  16384				/* quantization ~ 0.025 */
};

static const SANE_Range gamma_range = {
  0 << SANE_FIXED_SCALE_SHIFT,	/* minimum */
  10 << SANE_FIXED_SCALE_SHIFT,	/* maximum */
  16384				/* quantization ~ 0.025 */
};

static SANE_Range image_range = {
  0,
  14,
  0
};

static SANE_Option_Descriptor sod[] = {
  {
   SANE_NAME_NUM_OPTIONS,
   SANE_TITLE_NUM_OPTIONS,
   SANE_DESC_NUM_OPTIONS,
   SANE_TYPE_INT,
   SANE_UNIT_NONE,
   sizeof (SANE_Word),
   SANE_CAP_SOFT_DETECT,
   SANE_CONSTRAINT_NONE,
   {NULL}
   }
  ,

#define D25_OPT_IMAGE_SELECTION 1
  {
   "",
   "Image Selection",
   "Selection of the image to load.",
   SANE_TYPE_GROUP,
   SANE_UNIT_NONE,
   0,
   0,
   SANE_CONSTRAINT_NONE,
   {NULL}
   }
  ,

#define DC25_OPT_IMAGE_NUMBER 2
  {
   "image",
   "Image Number",
   "Select Image Number to load from camera",
   SANE_TYPE_INT,
   SANE_UNIT_NONE,
   4,
   SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT,
   SANE_CONSTRAINT_RANGE,
   {(SANE_String_Const *) & image_range}	/* this is ANSI conformant! */
   }
  ,

#define DC25_OPT_THUMBS 3
  {
   "thumbs",
   "Load Thumbnail",
   "Load the image as thumbnail.",
   SANE_TYPE_BOOL,
   SANE_UNIT_NONE,
   sizeof (SANE_Word),
   SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT,
   SANE_CONSTRAINT_NONE,
   {NULL}
   }
  ,
#define DC25_OPT_SNAP 4
  {
   "snap",
   "Snap new picture",
   "Take new picture and download it",
   SANE_TYPE_BOOL,
   SANE_UNIT_NONE,
   sizeof (SANE_Word),
   SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT | SANE_CAP_ADVANCED,
   SANE_CONSTRAINT_NONE,
   {NULL}
   }
  ,
#define DC25_OPT_LOWRES 5
  {
   "lowres",
   "Low Resolution",
   "New pictures taken in low resolution",
   SANE_TYPE_BOOL,
   SANE_UNIT_NONE,
   sizeof (SANE_Word),
   SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT | SANE_CAP_INACTIVE |
   SANE_CAP_ADVANCED,
   SANE_CONSTRAINT_NONE,
   {NULL}
   }
  ,

#define DC25_OPT_ERASE 6
  {
   "erase",
   "Erase",
   "Erase all pictures after downloading",
   SANE_TYPE_BOOL,
   SANE_UNIT_NONE,
   sizeof (SANE_Word),
   SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT,
   SANE_CONSTRAINT_NONE,
   {NULL}
   }
  ,

#define DC25_OPT_ERASE_ONE 7
  {
   "erase-one",
   "Erase One",
   "Erase downloaded picture after downloading",
   SANE_TYPE_BOOL,
   SANE_UNIT_NONE,
   sizeof (SANE_Word),
   SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT,
   SANE_CONSTRAINT_NONE,
   {NULL}
   }
  ,

#define DC25_OPT_ENHANCE 8
  {
   "",
   "Image Parameters",
   "Modifications to image parameters",
   SANE_TYPE_GROUP,
   SANE_UNIT_NONE,
   0,
   0,
   SANE_CONSTRAINT_NONE,
   {NULL}
   }
  ,

#define DC25_OPT_CONTRAST 9
  {
   "contrast",
   "Contrast Adjustment",
   "Values > 1 enhance contrast",
   SANE_TYPE_FIXED,
   SANE_UNIT_NONE,
   sizeof (SANE_Word),
   SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT,
   SANE_CONSTRAINT_RANGE,
   {(const SANE_String_Const *) &contrast_range}	/* this is ANSI conformant! */
   },

#define DC25_OPT_GAMMA 10
  {
   "gamma",
   "Gamma Adjustment",
   "Larger values make image darker",
   SANE_TYPE_FIXED,
   SANE_UNIT_NONE,
   sizeof (SANE_Word),
   SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT,
   SANE_CONSTRAINT_RANGE,
   {(const SANE_String_Const *) &gamma_range}	/* this is ANSI conformant! */
   },

#define DC25_OPT_DEFAULT 11
  {
   "default-enhancements",
   "Defaults",
   "Set default values for enhancement controls (i.e. contrast).",
   SANE_TYPE_BUTTON,
   SANE_UNIT_NONE,
   0,
   SANE_CAP_SOFT_SELECT | SANE_CAP_SOFT_DETECT,
   SANE_CONSTRAINT_NONE,
   {NULL}
   }
};

static SANE_Parameters parms = {
  SANE_FRAME_RGB,
  1,
  500,				/* Number of bytes returned per scan line: */
  500,				/* Number of pixels per scan line.  */
  373,				/* Number of lines for the current scan.  */
  8,				/* Number of bits per sample. */
};




static unsigned char init_pck[] = INIT_PCK;

/*
 * List of speeds to try to establish connection with the camera.
 * Check 9600 first, as it's the speed the camera comes up in, then
 * 115200, as that is the one most likely to be configured from a
 * previous run
 */
static struct pkt_speed speeds[] = { {B9600, {0x96, 0x00}},
#ifdef B115200
{B115200, {0x11, 0x52}},
#endif
#ifdef B57600
{B57600, {0x57, 0x60}},
#endif
{B38400, {0x38, 0x40}},
{B19200, {0x19, 0x20}},
};
#define NUM_OF_SPEEDS	((int)(sizeof(speeds) / sizeof(struct pkt_speed)))

static struct termios tty_orig;

static int
send_pck (int fd, unsigned char *pck)
{
  int n;
  unsigned char r;

  /*
   * Not quite sure why we need this, but the program works a whole
   * lot better (at least on the DC25)  with this short delay.
   */
#ifdef HAVE_USLEEP
  usleep (10);
#else
  sleep (1);
#endif
  if (write (fd, (char *) pck, 8) != 8)
    {
      DBG (2, "send_pck: error: write returned -1\n");
      return -1;
    }

  if ((n = read (fd, (char *) &r, 1)) != 1)
    {
      DBG (2, "send_pck: error: read returned -1\n");
      return -1;
    }

  return (r == 0xd1) ? 0 : -1;
}

static int
init_dc20 (char *device, speed_t speed)
{
  struct termios tty_new;
  int speed_index;

  DBG (1, "DC-20/25 Backend 05/07/01\n");

  for (speed_index = 0; speed_index < NUM_OF_SPEEDS; speed_index++)
    {
      if (speeds[speed_index].baud == speed)
	{
	  init_pck[2] = speeds[speed_index].pkt_code[0];
	  init_pck[3] = speeds[speed_index].pkt_code[1];
	  break;
	}
    }

  if (init_pck[2] == 0)
    {
      DBG (2, "unsupported baud rate.\n");
      return -1;
    }

  /*
     Open device file.
   */
  if ((tfd = open (device, O_RDWR)) == -1)
    {
      DBG (2, "init_dc20: error: could not open %s for read/write\n", device);
      return -1;
    }
  /*
     Save old device information to restore when we are done.
   */
  if (tcgetattr (tfd, &tty_orig) == -1)
    {
      DBG (2, "init_dc20: error: could not get attributes\n");
      return -1;
    }

  memcpy ((char *) &tty_new, (char *) &tty_orig, sizeof (struct termios));
  /*
     We need the device to be raw. 8 bits even parity on 9600 baud to start.
   */
#ifdef HAVE_CFMAKERAW
  cfmakeraw (&tty_new);
#else
  tty_new.c_lflag &= ~(ICANON | ECHO | ISIG);
#endif
  tty_new.c_oflag &= ~CSTOPB;
  tty_new.c_cflag |= PARENB;
  tty_new.c_cflag &= ~PARODD;
  tty_new.c_cc[VMIN] = 0;
  tty_new.c_cc[VTIME] = 50;
  cfsetospeed (&tty_new, B9600);
  cfsetispeed (&tty_new, B9600);

  if (tcsetattr (tfd, TCSANOW, &tty_new) == -1)
    {
      DBG (2, "init_dc20: error: could not set attributes\n");
      return -1;
    }

  if (send_pck (tfd, init_pck) == -1)
    {
      /*
       *      The camera always powers up at 9600, so we try
       *      that first.  However, it may be already set to
       *      a different speed.  Try the entries in the table:
       */

      for (speed_index = NUM_OF_SPEEDS - 1; speed_index > 0; speed_index--)
	{
	  DBG (3, "init_dc20: changing speed to %d\n",
	       (int) speeds[speed_index].baud);

	  cfsetospeed (&tty_new, speeds[speed_index].baud);
	  cfsetispeed (&tty_new, speeds[speed_index].baud);

	  if (tcsetattr (tfd, TCSANOW, &tty_new) == -1)
	    {
	      DBG (2, "init_dc20: error: could not set attributes\n");
	      return -1;
	    }
	  if (send_pck (tfd, init_pck) != -1)
	    break;
	}

      if (speed_index == 0)
	{
	  tcsetattr (tfd, TCSANOW, &tty_orig);
	  DBG (2, "init_dc20: error: no suitable baud rate\n");
	  return -1;
	}
    }
  /*
     Set speed to requested speed. Also, make a long timeout (we need this for
     erase and shoot operations)
   */
  tty_new.c_cc[VTIME] = 150;
  cfsetospeed (&tty_new, speed);
  cfsetispeed (&tty_new, speed);

  if (tcsetattr (tfd, TCSANOW, &tty_new) == -1)
    {
      DBG (2, "init_dc20: error: could not set attributes\n");
      return -1;
    }

  return tfd;
}

static void
close_dc20 (int fd)
{
  DBG (127, "close_dc20() called\n");
  /*
   *      Put the camera back to 9600 baud
   */

  init_pck[2] = speeds[0].pkt_code[0];
  init_pck[3] = speeds[0].pkt_code[1];
  if (send_pck (fd, init_pck) == -1)
    {
      DBG (4, "close_dc20: error: could not set attributes\n");
    }

  /*
     Restore original device settings.
   */
  if (tcsetattr (fd, TCSANOW, &tty_orig) == -1)
    {
      DBG (4, "close_dc20: error: could not set attributes\n");
    }

  if (close (fd) == -1)
    {
      DBG (4, "close_dc20: error: could not close device\n");
    }
}

static unsigned char info_pck[] = INFO_PCK;

static Dc20Info *
get_info (int fd)
{
  unsigned char buf[256];

  if (send_pck (fd, info_pck) == -1)
    {
      DBG (2, "get_info: error: send_pck returned -1\n");
      return NULL;
    }

  DBG (9, "get_info: read info packet\n");

  if (read_data (fd, buf, 256) == -1)
    {
      DBG (2, "get_info: error: read_data returned -1\n");
      return NULL;
    }

  if (end_of_data (fd) == -1)
    {
      DBG (2, "get_info: error: end_of_data returned -1\n");
      return NULL;
    }

  CameraInfo.model = buf[1];
  CameraInfo.ver_major = buf[2];
  CameraInfo.ver_minor = buf[3];
  CameraInfo.pic_taken = buf[8] << 8 | buf[9];
  if (CameraInfo.model == 0x25)
    {

      /* Not sure where the previous line came from.  All the
       * information I have says that even on the DC20 the number of
       * standard res pics is in byte 17 and the number of high res pics
       * is in byte 19.  This is definitely true on my DC25.
       */
      CameraInfo.pic_taken = buf[17] + buf[19];
    }

  image_range.max = CameraInfo.pic_taken;
  image_range.min = CameraInfo.pic_taken ? 1 : 0;

  CameraInfo.pic_left = buf[10] << 8 | buf[11];

  if (CameraInfo.model == 0x25)
    {
      /* Not sure where the previous line came from.  All the
       * information I have says that even on the DC20 the number of
       * standard res pics left is in byte 23 and the number of high res
       * pics left is in byte 21.  It seems to me that the conservative
       * approach is to report the number of high res pics left.
       */
      CameraInfo.pic_left = buf[21];
    }
  CameraInfo.flags.low_res = buf[23];

  if (CameraInfo.model == 0x25)
    {
      /* Not sure where the previous line came from.  All the
       * information I have says that even on the DC20 the low_res
       * byte is 11.
       */
      CameraInfo.flags.low_res = buf[11];
    }
  CameraInfo.flags.low_batt = buf[29];

  return &CameraInfo;
}

static int
read_data (int fd, unsigned char *buf, int sz)
{
  unsigned char ccsum;
  unsigned char rcsum;
  unsigned char c;
  int retries = 0;
  int n;
  int r = 0;
  int i;

  while (retries++ < 5)
    {

      /*
       * If this is not the first time through, then it must be
       * a retry - signal the camera that we didn't like what
       * we got.  In either case, start filling the packet
       */
      if (retries != 1)
	{

	  DBG (2, "Attempt retry %d\n", retries);
	  c = 0xe3;
	  if (write (fd, (char *) &c, 1) != 1)
	    {
	      DBG (2, "read_data: error: write ack\n");
	      return -1;
	    }

	}

      for (n = 0; n < sz && (r = read (fd, (char *) &buf[n], sz - n)) > 0;
	   n += r)
	;

      if (r <= 0)
	{
	  DBG (2, "read_data: error: read returned -1\n");
	  continue;
	}

      if (n < sz || read (fd, &rcsum, 1) != 1)
	{
	  DBG (2, "read_data: error: buffer underrun or no checksum\n");
	  continue;
	}

      for (i = 0, ccsum = 0; i < n; i++)
	ccsum ^= buf[i];

      if (ccsum != rcsum)
	{
	  DBG (2, "read_data: error: bad checksum (%02x != %02x)\n", rcsum,
	       ccsum);
	  continue;
	}

      /* If we got this far, then the packet is OK */
      break;
    }

  c = 0xd2;

  if (write (fd, (char *) &c, 1) != 1)
    {
      DBG (2, "read_data: error: write ack\n");
      return -1;
    }

  return 0;
}

static int
end_of_data (int fd)
{
  char c;

  if (read (fd, &c, 1) != 1)
    {
      DBG (2, "end_of_data: error: read returned -1\n");
      return -1;
    }

  if (c != 0)
    {
      DBG (2, "end_of_data: error: bad EOD from camera (%02x)\n",
	   (unsigned) c);
      return -1;
    }

  return 0;
}

#include <math.h>

#define BIDIM_ARRAY(name, x, y, width)	(name[((x) + ((y) * (width)))])

/*
 *	These definitions depend on the resolution of the image
 */

#define MY_LOW_RIGHT_MARGIN 6

/*
 *	These definitions are constant with resolution
 */

#define MY_LEFT_MARGIN 2

#define NET_COLUMNS (columns - MY_LEFT_MARGIN - right_margin)
#define NET_LINES   (HEIGHT - TOP_MARGIN - BOTTOM_MARGIN)
#define NET_PIXELS  (NET_COLUMNS * NET_LINES)


#define SCALE 64
#define SMAX (256 * SCALE - 1)
#define HORIZONTAL_INTERPOLATIONS 3
#define HISTOGRAM_STEPS 4096

#define RFACTOR 0.64
#define GFACTOR 0.58
#define BFACTOR 1.00
#define RINTENSITY 0.476
#define GINTENSITY 0.299
#define BINTENSITY 0.175

#define SATURATION 1.0
#define NORM_PERCENTAGE 3

static int columns = HIGH_WIDTH,
  right_margin = HIGH_RIGHT_MARGIN, camera_header_size = HIGH_CAMERA_HEADER;
static int low_i = -1, high_i = -1, norm_percentage = NORM_PERCENTAGE;
static float saturation = SATURATION,
  rfactor = RFACTOR, gfactor = GFACTOR, bfactor = BFACTOR;

static void
set_initial_interpolation (const unsigned char ccd[],
			   short horizontal_interpolation[])
{
  int column, line;
  for (line = 0; line < HEIGHT; line++)
    {
      BIDIM_ARRAY (horizontal_interpolation, MY_LEFT_MARGIN, line, columns) =
	BIDIM_ARRAY (ccd, MY_LEFT_MARGIN + 1, line, columns) * SCALE;
      BIDIM_ARRAY (horizontal_interpolation, columns - right_margin - 1, line,
		   columns) =
	BIDIM_ARRAY (ccd, columns - right_margin - 2, line, columns) * SCALE;
      for (column = MY_LEFT_MARGIN + 1; column < columns - right_margin - 1;
	   column++)
	{
	  BIDIM_ARRAY (horizontal_interpolation, column, line, columns) =
	    (BIDIM_ARRAY (ccd, column - 1, line, columns) +
	     BIDIM_ARRAY (ccd, column + 1, line, columns)) * (SCALE / 2);
	}
    }
}

static void
interpolate_horizontally (const unsigned char ccd[],
			  short horizontal_interpolation[])
{
  int column, line, i, initial_column;
  for (line = TOP_MARGIN - 1; line < HEIGHT - BOTTOM_MARGIN + 1; line++)
    {
      for (i = 0; i < HORIZONTAL_INTERPOLATIONS; i++)
	{
	  for (initial_column = MY_LEFT_MARGIN + 1;
	       initial_column <= MY_LEFT_MARGIN + 2; initial_column++)
	    {
	      for (column = initial_column;
		   column < columns - right_margin - 1; column += 2)
		{
		  BIDIM_ARRAY (horizontal_interpolation, column, line,
			       columns) =
		    ((float) BIDIM_ARRAY (ccd, column - 1, line, columns) /
		     BIDIM_ARRAY (horizontal_interpolation, column - 1, line,
				  columns) + (float) BIDIM_ARRAY (ccd,
								  column + 1,
								  line,
								  columns) /
		     BIDIM_ARRAY (horizontal_interpolation, column + 1, line,
				  columns)) * BIDIM_ARRAY (ccd, column, line,
							   columns) * (SCALE *
								       SCALE /
								       2) +
		    0.5;
		}
	    }
	}
    }
}

static void
interpolate_vertically (const unsigned char ccd[],
			const short horizontal_interpolation[],
			short red[], short green[], short blue[])
{
  int column, line;
  for (line = TOP_MARGIN; line < HEIGHT - BOTTOM_MARGIN; line++)
    {
      for (column = MY_LEFT_MARGIN; column < columns - right_margin; column++)
	{
	  int r2gb, g2b, rg2, rgb2, r, g, b;
	  int this_ccd = BIDIM_ARRAY (ccd, column, line, columns) * SCALE;
	  int up_ccd = BIDIM_ARRAY (ccd, column, line - 1, columns) * SCALE;
	  int down_ccd = BIDIM_ARRAY (ccd, column, line + 1, columns) * SCALE;
	  int this_horizontal_interpolation =
	    BIDIM_ARRAY (horizontal_interpolation, column, line, columns);
	  int this_intensity = this_ccd + this_horizontal_interpolation;
	  int up_intensity =
	    BIDIM_ARRAY (horizontal_interpolation, column, line - 1,
			 columns) + up_ccd;
	  int down_intensity =
	    BIDIM_ARRAY (horizontal_interpolation, column, line + 1,
			 columns) + down_ccd;
	  int this_vertical_interpolation;

	  /*
	   * PSF: I don't understand all this code, but I've found pictures
	   * where up_intensity or down_intensity are zero, resulting in a
	   * divide by zero error.  It looks like this only happens when
	   * up_ccd or down_ccd are also zero, so we just set the intensity
	   * value to non-zero to prevent the error.
	   */
	  if (down_ccd == 0)
	    DBG (10, "down_ccd==0 at %d,%d\n", line, column);
	  if (up_ccd == 0)
	    DBG (10, "up_ccd==0 at %d,%d\n", line, column);
	  if (down_intensity == 0)
	    {
	      DBG (9, "Found down_intensity==0 at %d,%d down_ccd=%d\n", line,
		   column, down_ccd);
	      down_intensity = 1;
	    }
	  if (up_intensity == 0)
	    {
	      DBG (9, "Found up_intensity==0 at %d,%d up_ccd=%d\n", line,
		   column, up_ccd);
	      up_intensity = 1;
	    }

	  if (line == TOP_MARGIN)
	    {
	      this_vertical_interpolation =
		(float) down_ccd / down_intensity * this_intensity + 0.5;
	    }
	  else if (line == HEIGHT - BOTTOM_MARGIN - 1)
	    {
	      this_vertical_interpolation =
		(float) up_ccd / up_intensity * this_intensity + 0.5;
	    }
	  else
	    {
	      this_vertical_interpolation =
		((float) up_ccd / up_intensity +
		 (float) down_ccd / down_intensity) * this_intensity / 2.0 +
		0.5;
	    }
	  if (line & 1)
	    {
	      if (column & 1)
		{
		  r2gb = this_ccd;
		  g2b = this_horizontal_interpolation;
		  rg2 = this_vertical_interpolation;
		  r = (2 * (r2gb - g2b) + rg2) / 5;
		  g = (rg2 - r) / 2;
		  b = g2b - 2 * g;
		}
	      else
		{
		  g2b = this_ccd;
		  r2gb = this_horizontal_interpolation;
		  rgb2 = this_vertical_interpolation;
		  r = (3 * r2gb - g2b - rgb2) / 5;
		  g = 2 * r - r2gb + g2b;
		  b = g2b - 2 * g;
		}
	    }
	  else
	    {
	      if (column & 1)
		{
		  rg2 = this_ccd;
		  rgb2 = this_horizontal_interpolation;
		  r2gb = this_vertical_interpolation;
		  b = (3 * rgb2 - r2gb - rg2) / 5;
		  g = (rgb2 - r2gb + rg2 - b) / 2;
		  r = rg2 - 2 * g;
		}
	      else
		{
		  rgb2 = this_ccd;
		  rg2 = this_horizontal_interpolation;
		  g2b = this_vertical_interpolation;
		  b = (g2b - 2 * (rg2 - rgb2)) / 5;
		  g = (g2b - b) / 2;
		  r = rg2 - 2 * g;
		}
	    }
	  if (r < 0)
	    r = 0;
	  if (g < 0)
	    g = 0;
	  if (b < 0)
	    b = 0;
	  BIDIM_ARRAY (red, column, line, columns) = r;
	  BIDIM_ARRAY (green, column, line, columns) = g;
	  BIDIM_ARRAY (blue, column, line, columns) = b;
	}
    }
}

static void
adjust_color_and_saturation (short red[], short green[], short blue[])
{
  int line, column;
  int r_min = SMAX, g_min = SMAX, b_min = SMAX;
  int r_max = 0, g_max = 0, b_max = 0;
  int r_sum = 0, g_sum = 0, b_sum = 0;
  float sqr_saturation = sqrt (saturation);
  for (line = TOP_MARGIN; line < HEIGHT - BOTTOM_MARGIN; line++)
    {
      for (column = MY_LEFT_MARGIN; column < columns - right_margin; column++)
	{
	  float r = BIDIM_ARRAY (red, column, line, columns) * rfactor;
	  float g = BIDIM_ARRAY (green, column, line, columns) * gfactor;
	  float b = BIDIM_ARRAY (blue, column, line, columns) * bfactor;
	  if (saturation != 1.0)
	    {
	      float *min, *mid, *max, new_intensity;
	      float intensity =
		r * RINTENSITY + g * GINTENSITY + b * BINTENSITY;
	      if (r > g)
		{
		  if (r > b)
		    {
		      max = &r;
		      if (g > b)
			{
			  min = &b;
			  mid = &g;
			}
		      else
			{
			  min = &g;
			  mid = &b;
			}
		    }
		  else
		    {
		      min = &g;
		      mid = &r;
		      max = &b;
		    }
		}
	      else
		{
		  if (g > b)
		    {
		      max = &g;
		      if (r > b)
			{
			  min = &b;
			  mid = &r;
			}
		      else
			{
			  min = &r;
			  mid = &b;
			}
		    }
		  else
		    {
		      min = &r;
		      mid = &g;
		      max = &b;
		    }
		}
	      *mid = *min + sqr_saturation * (*mid - *min);
	      *max = *min + saturation * (*max - *min);
	      new_intensity =
		r * RINTENSITY + g * GINTENSITY + b * BINTENSITY;
	      r *= intensity / new_intensity;
	      g *= intensity / new_intensity;
	      b *= intensity / new_intensity;
	    }
	  r += 0.5;
	  g += 0.5;
	  b += 0.5;
	  if (r_min > r)
	    r_min = r;
	  if (g_min > g)
	    g_min = g;
	  if (b_min > b)
	    b_min = b;
	  if (r_max < r)
	    r_max = r;
	  if (g_max < g)
	    g_max = g;
	  if (b_max < b)
	    b_max = b;
	  r_sum += r;
	  g_sum += g;
	  b_sum += b;
	  BIDIM_ARRAY (red, column, line, columns) = r;
	  BIDIM_ARRAY (green, column, line, columns) = g;
	  BIDIM_ARRAY (blue, column, line, columns) = b;
	}
    }
}

static int
min3 (int x, int y, int z)
{
  return (x < y ? (x < z ? x : z) : (y < z ? y : z));
}

static int
max3 (int x, int y, int z)
{
  return (x > y ? (x > z ? x : z) : (y > z ? y : z));
}

static void
determine_limits (const short red[],
		  const short green[],
		  const short blue[], int *low_i_ptr, int *high_i_ptr)
{
  unsigned int histogram[HISTOGRAM_STEPS + 1];
  int column, line, i, s;
  int low_i = *low_i_ptr, high_i = *high_i_ptr;
  int max_i = 0;
  for (line = TOP_MARGIN; line < HEIGHT - BOTTOM_MARGIN; line++)
    {
      for (column = MY_LEFT_MARGIN; column < columns - right_margin; column++)
	{
	  i = max3 (BIDIM_ARRAY (red, column, line, columns),
		    BIDIM_ARRAY (green, column, line, columns),
		    BIDIM_ARRAY (blue, column, line, columns));
	  if (i > max_i)
	    max_i = i;
	}
    }
  if (low_i == -1)
    {
      for (i = 0; i <= HISTOGRAM_STEPS; i++)
	histogram[i] = 0;
      for (line = TOP_MARGIN; line < HEIGHT - BOTTOM_MARGIN; line++)
	{
	  for (column = MY_LEFT_MARGIN; column < columns - right_margin;
	       column++)
	    {
	      i = min3 (BIDIM_ARRAY (red, column, line, columns),
			BIDIM_ARRAY (green, column, line, columns),
			BIDIM_ARRAY (blue, column, line, columns));
	      histogram[i * HISTOGRAM_STEPS / max_i]++;
	    }
	}
      for (low_i = 0, s = 0;
	   low_i <= HISTOGRAM_STEPS && s < NET_PIXELS * norm_percentage / 100;
	   low_i++)
	{
	  s += histogram[low_i];
	}
      low_i = (low_i * max_i + HISTOGRAM_STEPS / 2) / HISTOGRAM_STEPS;
      *low_i_ptr = low_i;
    }
  if (high_i == -1)
    {
      for (i = 0; i <= HISTOGRAM_STEPS; i++)
	histogram[i] = 0;
      for (line = TOP_MARGIN; line < HEIGHT - BOTTOM_MARGIN; line++)
	{
	  for (column = MY_LEFT_MARGIN; column < columns - right_margin;
	       column++)
	    {
	      i = max3 (BIDIM_ARRAY (red, column, line, columns),
			BIDIM_ARRAY (green, column, line, columns),
			BIDIM_ARRAY (blue, column, line, columns));
	      histogram[i * HISTOGRAM_STEPS / max_i]++;
	    }
	}
      for (high_i = HISTOGRAM_STEPS, s = 0;
	   high_i >= 0 && s < NET_PIXELS * norm_percentage / 100; high_i--)
	{
	  s += histogram[high_i];
	}
      high_i = (high_i * max_i + HISTOGRAM_STEPS / 2) / HISTOGRAM_STEPS;
      *high_i_ptr = high_i;
    }
/*
if (verbose) printf ("%s: determine_limits: low_i = %d, high_i = %d\n", __progname, low_i, high_i);
*/
}

/*
 * The original dc20ctrl program used a default gamma of 0.35, but I thougt
 * 0.45 looks better.  In addition, since xscanimage seems to always force
 * a resolution of 0.1, I multiply everything by 10 and make the default
 * 4.5.
 */

static unsigned char *
make_gamma_table (int range)
{
  int i;
  double factor =
    pow (256.0, 1.0 / (SANE_UNFIX (dc25_opt_gamma) / 10.0)) / range;
  unsigned char *gamma_table;
  if ((gamma_table = malloc (range * sizeof (unsigned char))) == NULL)
    {
      DBG (1, "make_gamma_table: can't allocate memory for gamma table\n");
      return NULL;
    }
  for (i = 0; i < range; i++)
    {
      int g =
	pow ((double) i * factor, (SANE_UNFIX (dc25_opt_gamma) / 10.0)) + 0.5;
/*
		if (verbose) fprintf (stderr, "%s: make_gamma_table: gamma[%4d] = %3d\n", __progname, i, g);
*/
      if (g > 255)
	g = 255;
      gamma_table[i] = g;
    }
  return gamma_table;
}

static int
lookup_gamma_table (int i, int low_i, int high_i,
		    const unsigned char gamma_table[])
{
  if (i <= low_i)
    return 0;
  if (i >= high_i)
    return 255;
  return gamma_table[i - low_i];
}

static int
output_rgb (const short red[],
	    const short green[],
	    const short blue[], int low_i, int high_i, struct pixmap *pp)
{
  int r_min = 255, g_min = 255, b_min = 255;
  int r_max = 0, g_max = 0, b_max = 0;
  int r_sum = 0, g_sum = 0, b_sum = 0;
  int column, line;
  unsigned char *gamma_table = make_gamma_table (high_i - low_i);

  if (gamma_table == NULL)
    {
      DBG (10, "output_rgb: error: cannot make gamma table\n");
      return -1;
    }

  for (line = TOP_MARGIN; line < HEIGHT - BOTTOM_MARGIN; line++)
    {
      for (column = MY_LEFT_MARGIN; column < columns - right_margin; column++)
	{
	  int r =
	    lookup_gamma_table (BIDIM_ARRAY (red, column, line, columns),
				low_i, high_i, gamma_table);
	  int g =
	    lookup_gamma_table (BIDIM_ARRAY (green, column, line, columns),
				low_i, high_i, gamma_table);
	  int b =
	    lookup_gamma_table (BIDIM_ARRAY (blue, column, line, columns),
				low_i, high_i, gamma_table);
	  if (r > 255)
	    r = 255;
	  else if (r < 0)
	    r = 0;
	  if (g > 255)
	    g = 255;
	  else if (g < 0)
	    g = 0;
	  if (b > 255)
	    b = 255;
	  else if (b < 0)
	    b = 0;
	  set_pixel_rgb (pp, column - MY_LEFT_MARGIN, line - TOP_MARGIN, r, g,
			 b);
	  if (r_min > r)
	    r_min = r;
	  if (g_min > g)
	    g_min = g;
	  if (b_min > b)
	    b_min = b;
	  if (r_max < r)
	    r_max = r;
	  if (g_max < g)
	    g_max = g;
	  if (b_max < b)
	    b_max = b;
	  r_sum += r;
	  g_sum += g;
	  b_sum += b;
	}
    }
  free (gamma_table);
/*
	{
		fprintf (stderr, "%s: output_rgb: r: min = %d, max = %d, ave = %d\n", __progname, r_min, r_max, r_sum / NET_PIXELS);
		fprintf (stderr, "%s: output_rgb: g: min = %d, max = %d, ave = %d\n", __progname, g_min, g_max, g_sum / NET_PIXELS);
		fprintf (stderr, "%s: output_rgb: b: min = %d, max = %d, ave = %d\n", __progname, b_min, b_max, b_sum / NET_PIXELS);
	}
*/
  return 0;
}

static int
comet_to_pixmap (unsigned char *pic, struct pixmap *pp)
{
  unsigned char *ccd;
  short *horizontal_interpolation, *red, *green, *blue;
  int retval = 0;

  if (pic == NULL)
    {
      DBG (1, "cmttoppm: error: no input image\n");
      return -1;
    }

  if (pic[4] == 0x01)
    {
      /* Low resolution mode */
      columns = LOW_WIDTH;
      right_margin = MY_LOW_RIGHT_MARGIN;
      camera_header_size = LOW_CAMERA_HEADER;
    }
  else
    {
      /* High resolution mode */
      columns = HIGH_WIDTH;
      right_margin = HIGH_RIGHT_MARGIN;
      camera_header_size = HIGH_CAMERA_HEADER;
    }
  ccd = pic + camera_header_size;

  if ((horizontal_interpolation =
       malloc (sizeof (short) * HEIGHT * columns)) == NULL)
    {
      DBG (1,
	   "cmttoppm: error: not enough memory for horizontal_interpolation\n");
      return -1;
    }


  if ((red = malloc (sizeof (short) * HEIGHT * columns)) == NULL)
    {
      DBG (1, "error: not enough memory for red\n");
      return -1;
    }

  if ((green = malloc (sizeof (short) * HEIGHT * columns)) == NULL)
    {
      DBG (1, "error: not enough memory for green\n");
      return -1;
    }

  if ((blue = malloc (sizeof (short) * HEIGHT * columns)) == NULL)
    {
      DBG (1, "error: not enough memory for blue\n");
      return -1;
    }

  /* Decode raw CCD data to RGB */
  set_initial_interpolation (ccd, horizontal_interpolation);
  interpolate_horizontally (ccd, horizontal_interpolation);
  interpolate_vertically (ccd, horizontal_interpolation, red, green, blue);

  adjust_color_and_saturation (red, green, blue);

  /* Determine lower and upper limit using histogram */
  if (low_i == -1 || high_i == -1)
    {
      determine_limits (red, green, blue, &low_i, &high_i);
    }

  /* Output pixmap structure */
  retval = output_rgb (red, green, blue, low_i, high_i, pp);

  return retval;
}

static int
convert_pic (char *base_name, int format)
{
  FILE *ifp;
  unsigned char pic[MAX_IMAGE_SIZE];
  int res, image_width, net_width, components;
  struct pixmap *pp2;

  DBG (127, "convert_pic() called\n");

  /*
   *      Read the image in memory
   */

  if ((ifp = fopen (base_name, "rb")) == NULL)
    {
      DBG (10, "convert_pic: error: cannot open %s for reading\n", base_name);
      return -1;
    }

  if (fread (pic, COMET_HEADER_SIZE, 1, ifp) != 1)
    {
      DBG (10, "convert_pic: error: cannot read COMET header\n");
      fclose (ifp);
      return -1;
    }

  if (strncmp ((char *) pic, COMET_MAGIC, sizeof (COMET_MAGIC)) != 0)
    {
      DBG (10, "convert_pic: error: file %s is not in COMET format\n",
	   base_name);
      fclose (ifp);
      return -1;
    }

  if (fread (pic, LOW_CAMERA_HEADER, 1, ifp) != 1)
    {
      DBG (10, "convert_pic: error: cannot read camera header\n");
      fclose (ifp);
      return -1;
    }

  res = pic[4];
  if (res == 0)
    {
      /*
       *      We just read a LOW_CAMERA_HEADER block, so resync with the
       *      HIGH_CAMERA_HEADER length by reading once more one of this.
       */
      if (fread (pic + LOW_CAMERA_HEADER, LOW_CAMERA_HEADER, 1, ifp) != 1)
	{
	  DBG (10,
	       "convert_pic: error: cannot resync with high resolution header\n");
	  fclose (ifp);
	  return -1;
	}
    }

  if (fread (pic + CAMERA_HEADER (res), WIDTH (res), HEIGHT, ifp) != HEIGHT)
    {
      DBG (9, "convert_pic: error: cannot read picture\n");
      fclose (ifp);
      return -1;
    }

  fclose (ifp);

  /*
   *      Setup image size with resolution
   */

  image_width = WIDTH (res);
  net_width = image_width - LEFT_MARGIN - RIGHT_MARGIN (res);
  components = (format & SAVE_24BITS) ? 3 : 1;

  /*
   *      Convert the image to 24 bits
   */

  if ((pp =
       alloc_pixmap (net_width - 1, HEIGHT - BOTTOM_MARGIN - 1,
		     components)) == NULL)
    {
      DBG (1, "convert_pic: error: alloc_pixmap\n");
      return -1;
    }

  comet_to_pixmap (pic, pp);

  if (format & SAVE_ADJASPECT)
    {
      /*
       *      Strech image
       */

      if (res)
	pp2 = alloc_pixmap (320, HEIGHT - BOTTOM_MARGIN - 1, components);
      else
	pp2 = alloc_pixmap (net_width - 1, 373, components);

      if (pp2 == NULL)
	{
	  DBG (2, "convert_pic: error: alloc_pixmap\n");
	  free_pixmap (pp);
	  return -1;
	}

      if (res)
	zoom_x (pp, pp2);
      else
	zoom_y (pp, pp2);

      free_pixmap (pp);
      pp = pp2;
      pp2 = NULL;

    }

  return 0;
}

#define PGM_EXT		"pgm"
#define PPM_EXT		"ppm"

#define RED		0.30
#define GREEN		0.59
#define BLUE		0.11

#define RED_OFFSET	0
#define GREEN_OFFSET	1
#define BLUE_OFFSET	2

#define GET_COMP(pp, x, y, c)	(pp->planes[((x) + (y)*pp->width)*pp->components + (c)])

#define GET_R(pp, x, y)	(GET_COMP(pp, x, y, RED_OFFSET))
#define GET_G(pp, x, y)	(GET_COMP(pp, x, y, GREEN_OFFSET))
#define GET_B(pp, x, y)	(GET_COMP(pp, x, y, BLUE_OFFSET))

static struct pixmap *
alloc_pixmap (int x, int y, int d)
{
  struct pixmap *result = NULL;

  if (d == 1 || d == 3)
    {
      if (x > 0)
	{
	  if (y > 0)
	    {
	      if ((result = malloc (sizeof (struct pixmap))) != NULL)
		{
		  result->width = x;
		  result->height = y;
		  result->components = d;
		  if (!(result->planes = malloc (x * y * d)))
		    {
		      DBG (10,
			   "alloc_pixmap: error: not enough memory for bitplanes\n");
		      free (result);
		      result = NULL;
		    }
		}
	      else
		DBG (10,
		     "alloc_pixmap: error: not enough memory for pixmap\n");
	    }
	  else
	    DBG (10, "alloc_pixmap: error: y is out of range\n");
	}
      else
	DBG (10, "alloc_pixmap: error: x is out of range\n");
    }
  else
    DBG (10, "alloc_pixmap: error: cannot handle %d components\n", d);

  return result;
}

static void
free_pixmap (struct pixmap *p)
{
  if (p)
    {
      free (p->planes);
      free (p);
    }
}

static int
set_pixel_rgb (struct pixmap *p, int x, int y, unsigned char r,
	       unsigned char g, unsigned char b)
{
  int result = 0;

  if (p)
    {
      if (x >= 0 && x < p->width)
	{
	  if (y >= 0 && y < p->height)
	    {
	      if (p->components == 1)
		{
		  GET_R (p, x, y) = RED * r + GREEN * g + BLUE * b;
		}
	      else
		{
		  GET_R (p, x, y) = r;
		  GET_G (p, x, y) = g;
		  GET_B (p, x, y) = b;
		}
	    }
	  else
	    {
	      DBG (10, "set_pixel_rgb: error: y out of range\n");
	      result = -1;
	    }
	}
      else
	{
	  DBG (10, "set_pixel_rgb: error: x out of range\n");
	  result = -1;
	}
    }

  return result;
}

static int
zoom_x (struct pixmap *source, struct pixmap *dest)
{
  int result = 0, dest_col, row, component, src_index;
  float ratio, src_ptr, delta;
  unsigned char src_component;

  if (source && dest)
    {
      /*
       *      We could think of resizing a pixmap and changing the number of
       *      components at the same time. Maybe this will be implemented later.
       */
      if (source->height == dest->height
	  && source->components == dest->components)
	{
	  if (source->width < dest->width)
	    {
	      ratio = ((float) source->width / (float) dest->width);

	      for (src_ptr = 0, dest_col = 0; dest_col < dest->width;
		   src_ptr += ratio, dest_col++)
		{
		  /*
		   *      dest[dest_col] = source[(int)src_ptr] +
		   *        (source[((int)src_ptr) + 1] - source[(int)src_ptr])
		   *        * (src_ptr - (int)src_ptr);
		   */
		  src_index = (int) src_ptr;
		  delta = src_ptr - src_index;

		  for (row = 0; row < source->height; row++)
		    {
		      for (component = 0; component < source->components;
			   component++)
			{
			  src_component =
			    GET_COMP (source, src_index, row, component);

			  GET_COMP (dest, dest_col, row, component) =
			    src_component +
			    (GET_COMP (source, src_index + 1, row,
				       component) - src_component) * delta;
			}
		    }
		}
	    }
	  else
	    {
	      DBG (10, "zoom_x: error: can only zoom out\n");
	      result = -1;
	    }
	}
      else
	{
	  DBG (10, "zoom_x: error: incompatible pixmaps\n");
	  result = -1;
	}
    }

  return result;
}

static int
zoom_y (struct pixmap *source, struct pixmap *dest)
{
  int result = 0, dest_row, column, component, src_index;
  float ratio, src_ptr, delta;
  unsigned char src_component;

  if (source && dest)
    {
      /*
       *      We could think of resizing a pixmap and changing the number of
       *      components at the same time. Maybe this will be implemented later.
       */
      if (source->width == dest->width
	  && source->components == dest->components)
	{
	  if (source->height < dest->height)
	    {
	      ratio = ((float) source->height / (float) dest->height);

	      for (src_ptr = 0, dest_row = 0; dest_row < dest->height;
		   src_ptr += ratio, dest_row++)
		{
		  /*
		   *      dest[dest_row] = source[(int)src_ptr] +
		   *        (source[((int)src_ptr) + 1] - source[(int)src_ptr])
		   *        * (src_ptr - (int)src_ptr);
		   */
		  src_index = (int) src_ptr;
		  delta = src_ptr - src_index;

		  for (column = 0; column < source->width; column++)
		    {
		      for (component = 0; component < source->components;
			   component++)
			{
			  src_component =
			    GET_COMP (source, column, src_index, component);

			  GET_COMP (dest, column, dest_row, component) =
			    src_component +
			    (GET_COMP (source, column, src_index + 1,
				       component) - src_component) * delta;
			}
		    }
		}
	    }
	  else
	    {
	      DBG (10, "zoom_y: error: can only zoom out\n");
	      result = -1;
	    }
	}
      else
	{
	  DBG (10, "zoom_y: error: incompatible pixmaps\n");
	  result = -1;
	}
    }

  return result;
}

static unsigned char shoot_pck[] = SHOOT_PCK;

static int
shoot (int fd)
{
  struct termios tty_temp, tty_old;
  int result = 0;

  DBG (127, "shoot() called\n");

  if (write (fd, (char *) shoot_pck, 8) != 8)
    {
      DBG (3, "shoot: error: write error\n");
      return -1;
    }

  if (CameraInfo.model != 0x25)
    {
      /*
       *      WARNING: now we set the serial port to 9600 baud!
       */

      if (tcgetattr (fd, &tty_old) == -1)
	{
	  DBG (3, "shoot: error: could not get attributes\n");
	  return -1;
	}

      memcpy ((char *) &tty_temp, (char *) &tty_old, sizeof (struct termios));

      cfsetispeed (&tty_temp, B9600);
      cfsetospeed (&tty_temp, B9600);

      /*
       * Apparently there is a bug in the DC20 where the response to
       * the shoot request is always at 9600.  The DC25 does not have
       * this bug, so we skip this block.
       */
      if (tcsetattr (fd, TCSANOW, &tty_temp) == -1)
	{
	  DBG (3, "shoot: error: could not set attributes\n");
	  return -1;
	}
    }

  if (read (fd, (char *) &result, 1) != 1)
    {
      DBG (3, "shoot: error: read returned -1\n");
      result = -1;
    }
  else
    {
      result = (result == 0xD1) ? 0 : -1;
    }

  if (CameraInfo.model != 0x25)
    {
      /*
       * We reset the serial to its original speed.
       * We can skip this on the DC25 also.
       */
      if (tcsetattr (fd, TCSANOW, &tty_old) == -1)
	{
	  DBG (3, "shoot: error: could not reset attributes\n");
	  result = -1;
	}
    }

  if (result == 0)
    {
      if (CameraInfo.model == 0x25)
	{
	  /*
	   * If we don't put this in, the next read will time out
	   * and return failure.  Does the DC-20 need it too?
	   */
	  sleep (3);
	}
      if (end_of_data (fd) == -1)
	{
	  DBG (3, "shoot: error: end_of_data returned -1\n");
	  result = -1;
	}
    }

  return result;
}


static unsigned char erase_pck[] = ERASE_PCK;

static int
erase (int fd)
{
  int count = 0;

  DBG (127, "erase() called for image %d\n", dc25_opt_image_number);
  erase_pck[3] = dc25_opt_image_number;
  if (dc25_opt_erase)
    {
      erase_pck[3] = 0;
    }

  if (send_pck (fd, erase_pck) == -1)
    {
      DBG (3, "erase: error: send_pck returned -1\n");
      return -1;
    }

  if (CameraInfo.model == 0x25)
    {
      /*
       * This block may really apply to the DC20 also, but since I
       * don't have one, it's hard to say for sure.  On the DC25, erase
       * takes long enought that the read may timeout without returning
       * any data before the erase is complete.   We let this happen
       * up to 4 times, then give up.
       */
      while (count < 4)
	{
	  if (end_of_data (fd) == -1)
	    {
	      count++;
	    }
	  else
	    {
	      break;
	    }
	}
      if (count == 4)
	{
	  DBG (3, "erase: error: end_of_data returned -1\n");
	  return -1;
	}
    }
  else
    {				/* Assume DC-20 */

      if (end_of_data (fd) == -1)
	{
	  DBG (3, "erase: error: end_of_data returned -1\n");
	  return -1;
	}
    }

  return 0;
}

static unsigned char res_pck[] = RES_PCK;

static int
change_res (int fd, unsigned char res)
{
  DBG (127, "change_res called\n");
  if (res != 0 && res != 1)
    {
      DBG (3, "change_res: error: unsupported resolution\n");
      return -1;
    }

  res_pck[2] = res;

  if (send_pck (fd, res_pck) == -1)
    {
      DBG (4, "change_res: error: send_pck returned -1\n");
    }

  if (end_of_data (fd) == -1)
    {
      DBG (4, "change_res: error: end_of_data returned -1\n");
    }
  return 0;
}

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

  strcpy (tty_name, DEF_TTY_NAME);

  DBG_INIT ();

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

  fp = sanei_config_open (DC25_CONFIG_FILE);

  DBG (127,
       "sane_init() $Id$\n");

  if (!fp)
    {
      /* default to /dev/ttyS0 instead of insisting on config file */
      DBG (1, "sane_init:  missing config file '%s'\n", DC25_CONFIG_FILE);
    }
  else
    {
      while (sanei_config_read (dev_name, sizeof (dev_name), fp))
	{
	  dev_name[sizeof (dev_name) - 1] = '\0';
	  DBG (20, "sane_init:  config- %s", dev_name);

	  if (dev_name[0] == '#')
	    continue;		/* ignore line comments */
	  len = strlen (dev_name);
	  if (!len)
	    continue;		/* ignore empty lines */
	  if (strncmp (dev_name, "port=", 5) == 0)
	    {
	      p = strchr (dev_name, '/');
	      if (p)
		{
		  strcpy (tty_name, p);
		}
	      DBG (20, "Config file port=%s\n", tty_name);
	    }
	  else if (strncmp (dev_name, "baud=", 5) == 0)
	    {
	      baud = atoi (&dev_name[5]);
	      switch (baud)
		{
		case 9600:
		  tty_baud = B9600;
		  break;
		case 19200:
		  tty_baud = B19200;
		  break;
		case 38400:
		  tty_baud = B38400;
		  break;
#ifdef B57600
		case 57600:
		  tty_baud = B57600;
		  break;
#endif
#ifdef B115200
		case 115200:
		  tty_baud = B115200;
		  break;
#endif
		default:
		  DBG (20, "Unknown baud=%d\n", baud);
		  tty_baud = DEFAULT_TTY_BAUD;
		  break;
		}
	      DBG (20, "Config file baud=%lu\n", (u_long) tty_baud);
	    }
	  else if (strcmp (dev_name, "dumpinquiry") == 0)
	    {
	      dumpinquiry = SANE_TRUE;
	    }
	}
      fclose (fp);
    }

  if ((tfd = init_dc20 (tty_name, tty_baud)) == -1)
    {
      return SANE_STATUS_INVAL;
    }

  if ((dc20_info = get_info (tfd)) == NULL)
    {
      DBG (2, "error: could not get info\n");
      close_dc20 (tfd);
      return SANE_STATUS_INVAL;
    }

  if (dumpinquiry)
    {
      DBG (0, "\nCamera information:\n~~~~~~~~~~~~~~~~~\n\n");
      DBG (0, "Model...........: DC%x\n", dc20_info->model);
      DBG (0, "Firmware version: %d.%d\n", dc20_info->ver_major,
	   dc20_info->ver_minor);
      DBG (0, "Pictures........: %d/%d\n", dc20_info->pic_taken,
	   dc20_info->pic_taken + dc20_info->pic_left);
      DBG (0, "Resolution......: %s\n",
	   dc20_info->flags.low_res ? "low" : "high");
      DBG (0, "Battery state...: %s\n",
	   dc20_info->flags.low_batt ? "low" : "good");
    }

  if (CameraInfo.pic_taken == 0)
    {
/*
		sod[DC25_OPT_IMAGE_NUMBER].cap |= SANE_CAP_INACTIVE;
*/
      image_range.min = 0;
      dc25_opt_image_number = 0;

    }
  else
    {
/*
		sod[DC25_OPT_IMAGE_NUMBER].cap &= ~SANE_CAP_INACTIVE;
*/
      image_range.min = 1;
    }

  return SANE_STATUS_GOOD;
}

void
sane_exit (void)
{
}

/* Device select/open/close */

static const SANE_Device dev[] = {
  {
   "0",
   "Kodak",
   "DC-25",
   "still camera"},
};

SANE_Status
sane_get_devices (const SANE_Device *** device_list,
		  SANE_Bool __sane_unused__ local_only)
{
  static const SANE_Device *devlist[] = {
    dev + 0, 0
  };

  DBG (127, "sane_get_devices called\n");

  if (dc20_info == NULL)
    {
      return SANE_STATUS_INVAL;
    }
  *device_list = devlist;
  return SANE_STATUS_GOOD;
}

SANE_Status
sane_open (SANE_String_Const devicename, SANE_Handle * handle)
{
  int i;

  DBG (127, "sane_open for device %s\n", devicename);
  if (!devicename[0])
    {
      i = 0;
    }
  else
    {
      for (i = 0; i < NELEMS (dev); ++i)
	{
	  if (strcmp (devicename, dev[i].name) == 0)
	    {
	      break;
	    }
	}
    }

  if (i >= NELEMS (dev))
    {
      return SANE_STATUS_INVAL;
    }

  if (is_open)
    {
      return SANE_STATUS_DEVICE_BUSY;
    }

  is_open = 1;
  *handle = MAGIC;

  if (dc20_info == NULL)
    {
      DBG (1, "No device info\n");
    }

  if (tmpname == NULL)
    {
      tmpname = tmpnamebuf;
      if (mktemp (tmpname) == NULL)
	{
	  DBG (1, "Unable to make temp file %s\n", tmpname);
	  return SANE_STATUS_INVAL;
	}
    }

  DBG (3, "sane_open: pictures taken=%d\n", dc20_info->pic_taken);

  return SANE_STATUS_GOOD;
}

void
sane_close (SANE_Handle handle)
{
  DBG (127, "sane_close called\n");
  if (handle == MAGIC)
    is_open = 0;

  if (pp)
    {
      free_pixmap (pp);
      pp = NULL;
    }

  close_dc20 (tfd);

  DBG (127, "sane_close returning\n");
}

const SANE_Option_Descriptor *
sane_get_option_descriptor (SANE_Handle handle, SANE_Int option)
{
  if (handle != MAGIC || !is_open)
    return NULL;		/* wrong device */
  if (option < 0 || option >= NELEMS (sod))
    return NULL;
  return &sod[option];
}

SANE_Status
sane_control_option (SANE_Handle handle, SANE_Int option,
		     SANE_Action action, void *value, SANE_Int * info)
{
  SANE_Int myinfo = info_flags;
  SANE_Status status;

  info_flags = 0;

  DBG (127, "control_option(handle=%p,opt=%s,act=%s,val=%p,info=%p)\n",
       handle, sod[option].title,
       (action ==
	SANE_ACTION_SET_VALUE ? "SET" : (action ==
					 SANE_ACTION_GET_VALUE ? "GET" :
					 "SETAUTO")), value, (void *)info);

  if (handle != MAGIC || !is_open)
    return SANE_STATUS_INVAL;	/* Unknown handle ... */

  if (option < 0 || option >= NELEMS (sod))
    return SANE_STATUS_INVAL;	/* Unknown option ... */

  switch (action)
    {
    case SANE_ACTION_SET_VALUE:
      status = sanei_constrain_value (sod + option, value, &myinfo);
      if (status != SANE_STATUS_GOOD)
	{
	  DBG (1, "Constraint error in control_option\n");
	  return status;
	}

      switch (option)
	{
	case DC25_OPT_IMAGE_NUMBER:
	  dc25_opt_image_number = *(SANE_Word *) value;
/*			myinfo |= SANE_INFO_RELOAD_OPTIONS; */
	  break;

	case DC25_OPT_THUMBS:
	  dc25_opt_thumbnails = !!*(SANE_Word *) value;
	  myinfo |= SANE_INFO_RELOAD_PARAMS;

	  if (dc25_opt_thumbnails)
	    {
	      /*
	       * DC20 thumbnail are 80x60 grayscale, DC25
	       * thumbnails are color.
	       */
	      parms.format =
		(CameraInfo.model == 0x25) ? SANE_FRAME_RGB : SANE_FRAME_GRAY;
	      parms.bytes_per_line = 80 * 3;
	      parms.pixels_per_line = 80;
	      parms.lines = 60;
	    }
	  else
	    {
	      parms.format = SANE_FRAME_RGB;
	      if (dc20_info->flags.low_res)
		{
		  parms.bytes_per_line = 320 * 3;
		  parms.pixels_per_line = 320;
		  parms.lines = 243;
		}
	      else
		{
		  parms.bytes_per_line = 500 * 3;
		  parms.pixels_per_line = 500;
		  parms.lines = 373;
		}
	    }
	  break;

	case DC25_OPT_SNAP:
	  dc25_opt_snap = !!*(SANE_Word *) value;
	  myinfo |= SANE_INFO_RELOAD_PARAMS | SANE_INFO_RELOAD_OPTIONS;
	  if (dc25_opt_snap)
	    {
	      sod[DC25_OPT_LOWRES].cap &= ~SANE_CAP_INACTIVE;
	    }
	  else
	    {
	      sod[DC25_OPT_LOWRES].cap |= SANE_CAP_INACTIVE;
	    }
	  break;

	case DC25_OPT_LOWRES:
	  dc25_opt_lowres = !!*(SANE_Word *) value;
	  myinfo |= SANE_INFO_RELOAD_PARAMS;

	  if (!dc25_opt_thumbnails)
	    {

	      parms.format = SANE_FRAME_RGB;

	      if (dc20_info->flags.low_res)
		{
		  parms.bytes_per_line = 320 * 3;
		  parms.pixels_per_line = 320;
		  parms.lines = 243;
		}
	      else
		{
		  parms.bytes_per_line = 500 * 3;
		  parms.pixels_per_line = 500;
		  parms.lines = 373;
		}

	    }
	  break;

	case DC25_OPT_CONTRAST:
	  dc25_opt_contrast = *(SANE_Word *) value;
	  break;

	case DC25_OPT_GAMMA:
	  dc25_opt_gamma = *(SANE_Word *) value;
	  break;

	case DC25_OPT_ERASE:
	  dc25_opt_erase = !!*(SANE_Word *) value;

	  /*
	   * erase and erase_one are mutually exclusive.  If
	   * this one is turned on, the other must be off
	   */
	  if (dc25_opt_erase && dc25_opt_erase_one)
	    {
	      dc25_opt_erase_one = SANE_FALSE;
	      myinfo |= SANE_INFO_RELOAD_OPTIONS;
	    }
	  break;

	case DC25_OPT_ERASE_ONE:
	  dc25_opt_erase_one = !!*(SANE_Word *) value;

	  /*
	   * erase and erase_one are mutually exclusive.  If
	   * this one is turned on, the other must be off
	   */
	  if (dc25_opt_erase_one && dc25_opt_erase)
	    {
	      dc25_opt_erase = SANE_FALSE;
	      myinfo |= SANE_INFO_RELOAD_OPTIONS;
	    }
	  break;

	case DC25_OPT_DEFAULT:

	  dc25_opt_contrast = SANE_FIX (DC25_OPT_CONTRAST_DEFAULT);
	  dc25_opt_gamma = SANE_FIX (DC25_OPT_GAMMA_DEFAULT);
	  myinfo |= SANE_INFO_RELOAD_OPTIONS;
	  break;

	default:
	  return SANE_STATUS_INVAL;
	}
      break;

    case SANE_ACTION_GET_VALUE:
      switch (option)
	{
	case 0:
	  *(SANE_Word *) value = NELEMS (sod);
	  break;

	case DC25_OPT_IMAGE_NUMBER:
	  *(SANE_Word *) value = dc25_opt_image_number;
	  break;

	case DC25_OPT_THUMBS:
	  *(SANE_Word *) value = dc25_opt_thumbnails;
	  break;

	case DC25_OPT_SNAP:
	  *(SANE_Word *) value = dc25_opt_snap;
	  break;

	case DC25_OPT_LOWRES:
	  *(SANE_Word *) value = dc25_opt_lowres;
	  break;

	case DC25_OPT_CONTRAST:
	  *(SANE_Word *) value = dc25_opt_contrast;
	  break;

	case DC25_OPT_GAMMA:
	  *(SANE_Word *) value = dc25_opt_gamma;
	  break;

	case DC25_OPT_ERASE:
	  *(SANE_Word *) value = dc25_opt_erase;
	  break;

	case DC25_OPT_ERASE_ONE:
	  *(SANE_Word *) value = dc25_opt_erase_one;
	  break;

	default:
	  return SANE_STATUS_INVAL;
	}
      break;

    case SANE_ACTION_SET_AUTO:
      switch (option)
	{
#if 0
	case DC25_OPT_CONTRAST:
	  dc25_opt_contrast = SANE_FIX (DC25_OPT_CONTRAST_DEFAULT);
	  break;

	case DC25_OPT_GAMMA:
	  dc25_opt_gamma = SANE_FIX (DC25_OPT_GAMMA_DEFAULT);
	  break;
#endif

	default:
	  return SANE_STATUS_UNSUPPORTED;	/* We are DUMB */
	}
    }

  if (info)
    *info = myinfo;

  return SANE_STATUS_GOOD;
}

SANE_Status
sane_get_parameters (SANE_Handle handle, SANE_Parameters * params)
{
  int rc = SANE_STATUS_GOOD;

  DBG (127, "sane_get_params called\n");

  if (handle != MAGIC || !is_open)
    rc = SANE_STATUS_INVAL;	/* Unknown handle ... */


  *params = parms;
  return rc;
}

static unsigned char thumb_pck[] = THUMBS_PCK;

static unsigned char pic_pck[] = PICS_PCK;

static int bytes_in_buffer;
static int bytes_read_from_buffer;
static SANE_Byte buffer[1024];
static int total_bytes_read;
static SANE_Bool started = SANE_FALSE;
static int outbytes;

SANE_Status
sane_start (SANE_Handle handle)
{
  int n, i;
  FILE *f;

  DBG (127, "sane_start called, handle=%lx\n", (u_long) handle);

  if (handle != MAGIC || !is_open ||
      (dc25_opt_image_number == 0 && dc25_opt_snap == SANE_FALSE))
    return SANE_STATUS_INVAL;	/* Unknown handle ... */

  if (started)
    {
      return SANE_STATUS_EOF;
    }

  if (dc25_opt_snap)
    {

      /*
       * Don't allow picture unless there is room in the
       * camera.
       */
      if (CameraInfo.pic_left == 0)
	{
	  DBG (3, "No room to store new picture\n");
	  return SANE_STATUS_INVAL;
	}

      /*
       * DC-20 can only change resolution when camer is empty.
       * DC-25 can do it any time.
       */
      if (CameraInfo.model != 0x20 || CameraInfo.pic_taken == 0)
	{
	  if (change_res (tfd, dc25_opt_lowres) == -1)
	    {
	      DBG (1, "Failed to set resolution\n");
	      return SANE_STATUS_INVAL;
	    }
	}

      /*
       * Not sure why this delay is needed, but it seems to help:
       */
#ifdef HAVE_USLEEP
      usleep (10);
#else
      sleep (1);
#endif
      if (shoot (tfd) == -1)
	{
	  DBG (1, "Failed to snap new picture\n");
	  return SANE_STATUS_INVAL;
	}
      else
	{
	  info_flags |= SANE_INFO_RELOAD_OPTIONS;
	  CameraInfo.pic_taken++;
	  CameraInfo.pic_left--;
	  dc25_opt_image_number = CameraInfo.pic_taken;
	  if (image_range.min == 0)
	    image_range.min = 1;
	  image_range.max++;
	  sod[DC25_OPT_IMAGE_NUMBER].cap &= ~SANE_CAP_INACTIVE;
	}
    }

  if (dc25_opt_thumbnails)
    {

      /*
       * For thumbnails, we can do things right where we
       * start the download, and grab the first block
       * from the camera.  The reamining blocks will be
       * fetched as necessary by sane_read().
       */
      thumb_pck[3] = (unsigned char) dc25_opt_image_number;

      if (send_pck (tfd, thumb_pck) == -1)
	{
	  DBG (4, "sane_start: error: send_pck returned -1\n");
	  return SANE_STATUS_INVAL;
	}

      if (read_data (tfd, buffer, 1024) == -1)
	{
	  DBG (4, "sane_start: read_data failed\n");
	  return SANE_STATUS_INVAL;
	}

      /*
       * DC20 thumbnail are 80x60 grayscale, DC25
       * thumbnails are color.
       */
      parms.format =
	(CameraInfo.model == 0x25) ? SANE_FRAME_RGB : SANE_FRAME_GRAY;
      parms.bytes_per_line = 80 * 3;	/* 80 pixels, 3 colors */
      parms.pixels_per_line = 80;
      parms.lines = 60;

      bytes_in_buffer = 1024;
      bytes_read_from_buffer = 0;

    }
  else
    {
      /*
       * We do something a little messy, and violates the SANE
       * philosophy.  However, since it is fairly tricky to
       * convert the DC2x "comet" files on the fly, we read in
       * the entire data stream in sane_open(), and use convert_pic
       * to convert it to an in-memory pixpmap.  Then when
       * sane_read() is called, we fill the requests from
       * memory.  A good project for me (or some kind volunteer)
       * would be to rewrite this and move the actual download
       * to sane_read().  However, one argument for keeping it
       * this way is that the data comes down pretty fast, and
       * it helps to dedicate the processor to this task.  We
       * might get serial port overruns if we try to do other
       * things at the same time.
       *
       * Also, as a side note, I was constantly getting serial
       * port overruns on a 90MHz pentium until I used hdparm
       * to set the "-u1" flag on the system drives.
       */
      int fd;

      fd = open (tmpname, O_CREAT | O_EXCL | O_WRONLY, 0600);
      if (fd == -1)
	{
	  DBG (0, "Unable to open tmp file\n");
	  return SANE_STATUS_INVAL;
	}
      f = fdopen (fd, "wb");
      if (f == NULL)
	{
	  DBG (0, "Unable to fdopen tmp file\n");
	  return SANE_STATUS_INVAL;
	}

      strcpy ((char *) buffer, COMET_MAGIC);
      fwrite (buffer, 1, COMET_HEADER_SIZE, f);

      pic_pck[3] = (unsigned char) dc25_opt_image_number;

      if (send_pck (tfd, pic_pck) == -1)
	{
	  DBG (4, "sane_start: error: send_pck returned -1\n");
	  return SANE_STATUS_INVAL;
	}

      if (read_data (tfd, buffer, 1024) == -1)
	{
	  DBG (5, "sane_start: read_data failed\n");
	  return SANE_STATUS_INVAL;
	}

      if (buffer[4] == 0)
	{			/* hi-res image */
	  DBG (5, "sane_start: hi-res image\n");
	  n = 122;

	  parms.bytes_per_line = 500 * 3;	/* 3 colors */
	  parms.pixels_per_line = 500;
	  parms.lines = 373;

	  bytes_in_buffer = 1024;
	  bytes_read_from_buffer = 0;
	}
      else
	{
	  n = 61;
	  DBG (5, "sane_start: low-res image\n");

	  parms.bytes_per_line = 320 * 3;	/* 3 Colors */
	  parms.pixels_per_line = 320;
	  parms.lines = 243;

	  bytes_in_buffer = 1024;
	  bytes_read_from_buffer = 0;
	}


      fwrite (buffer, 1, 1024, f);

      for (i = 1; i < n; i++)
	{
	  if (read_data (tfd, buffer, 1024) == -1)
	    {
	      DBG (5, "sane_start: read_data failed\n");
	      return SANE_STATUS_INVAL;
	    }
	  fwrite (buffer, 1, 1024, f);
	}

      if (end_of_data (tfd) == -1)
	{
	  fclose (f);
	  DBG (4, "sane_open: end_of_data error\n");
	  return SANE_STATUS_INVAL;
	}
      else
	{
	  fclose (f);
	  if (convert_pic (tmpname, SAVE_ADJASPECT | SAVE_24BITS) == -1)
	    {
	      DBG (3, "sane_open: unable to convert\n");
	      return SANE_STATUS_INVAL;
	    }
	  unlink (tmpname);
	  outbytes = 0;
	}
    }

  started = SANE_TRUE;
  total_bytes_read = 0;

  return SANE_STATUS_GOOD;
}


SANE_Status
sane_read (SANE_Handle __sane_unused__ handle, SANE_Byte * data,
	   SANE_Int max_length, SANE_Int * length)
{
  DBG (127, "sane_read called, maxlen=%d\n", max_length);

  if ( ! started ) {
	return SANE_STATUS_INVAL;
  }

  if (dc25_opt_thumbnails)
    {
      if (total_bytes_read == THUMBSIZE)
	{
	  if (dc25_opt_erase || dc25_opt_erase_one)
	    {

	      if (erase (tfd) == -1)
		{
		  DBG (1, "Failed to erase memory\n");
		  return SANE_STATUS_INVAL;
		}

	      dc25_opt_erase = SANE_FALSE;
	      dc25_opt_erase_one = SANE_FALSE;
	      info_flags |= SANE_INFO_RELOAD_OPTIONS;

	      if (get_info (tfd) == NULL)
		{
		  DBG (2, "error: could not get info\n");
		  close_dc20 (tfd);
		  return SANE_STATUS_INVAL;
		}
	      DBG (10, "Call get_info!, image range=%d,%d\n", image_range.min,
		   image_range.max);
	    }
	  return SANE_STATUS_EOF;
	}

      *length = 0;
      if (!(bytes_in_buffer - bytes_read_from_buffer))
	{
	  if (read_data (tfd, buffer, 1024) == -1)
	    {
	      DBG (5, "sane_read: read_data failed\n");
	      return SANE_STATUS_INVAL;
	    }
	  bytes_in_buffer = 1024;
	  bytes_read_from_buffer = 0;
	}

      while (bytes_read_from_buffer < bytes_in_buffer &&
	     max_length && total_bytes_read < THUMBSIZE)
	{
	  *data++ = buffer[bytes_read_from_buffer++];
	  (*length)++;
	  max_length--;
	  total_bytes_read++;
	}

      if (total_bytes_read == THUMBSIZE)
	{
	  if (end_of_data (tfd) == -1)
	    {
	      DBG (4, "sane_read: end_of_data error\n");
	      return SANE_STATUS_INVAL;
	    }
	  else
	    {
	      return SANE_STATUS_GOOD;
	    }
	}
      else
	{
	  return SANE_STATUS_GOOD;
	}
    }
  else
    {
      int i;
      int filesize = parms.bytes_per_line * parms.lines;

      /*
       * If outbytes is zero, then this is the first time
       * we've been called, so update the contrast table.
       * The formula is something I came up with that has the
       * following prooperties:
       * 1) It's a smooth curve that provides the effect I wanted
       *    (bright pixels are made brighter, dim pixels are made
       *    dimmer)
       * 2) The contrast parameter can be adjusted to provide
       *    different amounts of contrast.
       * 3) A parameter of 1.0 can be used to pass the data
       *    through unchanged (but values around 1.75 look
       *    a lot better
       */
      if (outbytes == 0)
	{
	  double d;
	  double cont = SANE_UNFIX (dc25_opt_contrast);

	  for (i = 0; i < 256; i++)
	    {
	      d = (i * 2.0) / 255 - 1.0;
	      d =
		((-pow (1 - d, cont)) + 1) * (d >=
					      0) + (((pow (d + 1, cont)) -
						     1)) * (d < 0);
	      contrast_table[i] = (d * 127.5) + 127.5;
/*
				fprintf (stderr,"%03d %03d\n",i,contrast_table[i]);
*/
	    }
	}

      /* We're done, so return EOF */
      if (outbytes >= filesize)
	{
	  free_pixmap (pp);
	  pp = NULL;

	  if (dc25_opt_erase || dc25_opt_erase_one)
	    {
	      if (erase (tfd) == -1)
		{
		  DBG (1, "Failed to erase memory\n");
		  return SANE_STATUS_INVAL;
		}
	    }

	  if (get_info (tfd) == NULL)
	    {
	      DBG (2, "error: could not get info\n");
	      close_dc20 (tfd);
	      return SANE_STATUS_INVAL;
	    }
	  DBG (10, "Call get_info!, image range=%d,%d\n", image_range.min,
	       image_range.max);

	  get_info (tfd);

          *length=0;

	  return SANE_STATUS_EOF;
	}

      if (max_length > filesize - outbytes)
	{
	  *length = filesize - outbytes;
	}
      else
	{
	  *length = max_length;
	}

      memcpy (data, pp->planes + outbytes, *length);
      outbytes += *length;


      for (i = 0; i < *length; i++)
	{
	  data[i] = contrast_table[data[i]];
	}

      return SANE_STATUS_GOOD;

    }
}

void
sane_cancel (SANE_Handle __sane_unused__ handle)
{
  DBG (127, "sane_cancel() called\n");
  started = SANE_FALSE;
}

SANE_Status
sane_set_io_mode (SANE_Handle __sane_unused__ handle,
		  SANE_Bool __sane_unused__ non_blocking)
{
  /* sane_set_io_mode() is only valid during a scan */
  if (started)
    {
      if (non_blocking == SANE_FALSE)
	{
	  return SANE_STATUS_GOOD;
	}
      else
	{
	  return SANE_STATUS_UNSUPPORTED;
	}
    }
  else
    {
      /* We aren't currently scanning */
      return SANE_STATUS_INVAL;
    }
}

SANE_Status
sane_get_select_fd (SANE_Handle __sane_unused__ handle, SANE_Int __sane_unused__ * fd)
{
  return SANE_STATUS_UNSUPPORTED;
}