summaryrefslogtreecommitdiff
path: root/backend/plustek-usb.c
blob: 107bf9e0594c6c62106134c90dc2b560e7eb619d (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
/*.............................................................................
 * Project : SANE library for Plustek flatbed scanners.
 *.............................................................................
 */

/** @file plustek-usb.c
 *  @brief The interface functions to the USB driver stuff.
 *
 * Based on sources acquired from Plustek Inc.<br>
 * Copyright (C) 2001-2007 Gerhard Jaeger <gerhard@gjaeger.de>
 *
 * History:
 * - 0.40 - starting version of the USB support
 * - 0.41 - removed CHECK
 *        - added Canon to the manufacturer list
 * - 0.42 - added warmup stuff
 *        - added setmap function
 *        - changed detection stuff, so we first check whether
 *        - the vendor and product Ids match with the ones in our list
 * - 0.43 - cleanup
 * - 0.44 - changes to integration CIS based devices
 * - 0.45 - added skipFine assignment
 *        - added auto device name detection if only product and vendor id<br>
 *          has been specified
 *        - made 16-bit gray mode work
 *        - added special handling for Genius devices
 *        - added TPA autodetection for EPSON Photo
 *        - fixed bug that causes warmup each time autodetected<br>
 *          TPA on EPSON is used
 *        - removed Genius from PCB-Id check
 *        - added Compaq to the list
 *        - removed the scaler stuff for CIS devices
 *        - removed homeing stuff from readline function
 *        - fixed flag setting in usbDev_startScan()
 * - 0.46 - added additional branch to support alternate calibration
 * - 0.47 - added special handling with 0x400 vendor ID and model override
 *        - removed PATH_MAX
 *        - change usbDev_stopScan and usbDev_open prototype
 *        - cleanup
 * - 0.48 - added function usb_CheckAndCopyAdjs()
 * - 0.49 - changed autodetection
 *        - added support for LiDE25 (pid 0x2220)
 * - 0.50 - minor fix for startup reset
 *          removed unnecessary calls to usbio_ResetLM983x()
 *          1200DPI CIS devices don't use GrayFromColor any longer
 * - 0.51 - added Syscan to the vendor list
 *        - added SCANFLAG_Calibration handling
 * - 0.52 - added _WAF_LOFF_ON_START and _WAF_INC_DARKTGT
 *          handling in usbDev_startScan()
 *          added Visioneer
 * .
 * <hr>
 * 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.
 * <hr>
 */

/** useful for description tables
 */
typedef struct {
	int   id;
	char *desc;
	char *desc_alt;
} TabDef, *pTabDef;

/** to allow different vendors...
 */
static TabDef usbVendors[] = {

	{ 0x07B3, "Plustek",         NULL     },
	{ 0x0400, "NSC",             "Mustek" },
	{ 0x0458, "KYE/Genius",      NULL     },
	{ 0x03F0, "Hewlett-Packard", NULL     },
	{ 0x04B8, "Epson",           NULL     },
	{ 0x04A7, "Visioneer",       NULL     },
	{ 0x04A9, "Canon",           NULL     },
	{ 0x1606, "UMAX",            NULL     },
	{ 0x049F, "Compaq",          NULL     },
	{ 0x0A82, "Syscan",          NULL     },
	{ 0x0A53, "PandP Co., Ltd.", NULL     },
	{ 0xFFFF, NULL,              NULL     }
};

/** we use at least 8 megs for scanning... */
#define _SCANBUF_SIZE (8 * 1024 * 1024)

/********************** the USB scanner interface ****************************/

/** remove the slash out of the model-name to obtain a valid filename
 */
static SANE_Bool usb_normFileName( char *fname, char* buffer, u_long max_len )
{
	char *src, *dst;

	if( NULL == fname )
		return SANE_FALSE;

	if( strlen( fname ) >= max_len )
		return SANE_FALSE;

	src = fname;
	dst = buffer;
	while( *src != '\0' ) {

		if((*src == '/') || isspace(*src) || ispunct(*src))
			*dst = '_';
		else
			*dst = *src;

		dst++;
		src++;
	}
	*dst = '\0';

	return SANE_TRUE;
}

/** do some range checking and copy the adjustment values from the
 * frontend to our internal structures, so that the backend can take
 * care of them.
 */
static void usb_CheckAndCopyAdjs( Plustek_Device *dev )
{
	if( dev->adj.lampOff >= 0 )
		dev->usbDev.dwLampOnPeriod = dev->adj.lampOff;

	if( dev->adj.lampOffOnEnd >= 0 )
		dev->usbDev.bLampOffOnEnd = dev->adj.lampOffOnEnd;

	if( dev->adj.skipCalibration > 0 )
		dev->usbDev.Caps.workaroundFlag |= _WAF_BYPASS_CALIBRATION;

	if( dev->adj.skipFine > 0 )
		dev->usbDev.Caps.workaroundFlag |= _WAF_SKIP_FINE;

	if( dev->adj.skipFineWhite > 0 )
		dev->usbDev.Caps.workaroundFlag |= _WAF_SKIP_WHITEFINE;

	if( dev->adj.incDarkTgt > 0 )
		dev->usbDev.Caps.workaroundFlag |= _WAF_INC_DARKTGT;

	if( dev->adj.skipDarkStrip > 0 )
		dev->usbDev.Caps.Normal.DarkShadOrgY = -1;

	if( dev->adj.invertNegatives > 0 )
		dev->usbDev.Caps.workaroundFlag |= _WAF_INV_NEGATIVE_MAP;
}

/**
 * assign the values to the structures used by the currently found scanner
 */
static void
usb_initDev( Plustek_Device *dev, int idx, int handle, int vendor )
{
	char     *ptr;
	char      tmp_str1[PATH_MAX];
	char      tmp_str2[PATH_MAX];
	int       i;
	ScanParam sParam;
	u_short   tmp = 0;
	int       ret = 0;

	DBG( _DBG_INFO, "usb_initDev(%d,0x%04x,%i)\n",
	                idx, vendor, dev->initialized );
	/* save capability flags... */
	if( dev->initialized >= 0 ) {
		tmp = DEVCAPSFLAG_TPA;
	}

	/* copy the original values... */
	memcpy( &dev->usbDev.Caps, Settings[idx].pDevCaps, sizeof(DCapsDef));
	memcpy( &dev->usbDev.HwSetting, Settings[idx].pHwDef, sizeof(HWDef));

	/* restore capability flags... */
	if( dev->initialized >= 0 ) {
		dev->usbDev.Caps.wFlags |= tmp;
	}

	usb_CheckAndCopyAdjs( dev );
	DBG( _DBG_INFO, "Device WAF  : 0x%08lx\n", dev->usbDev.Caps.workaroundFlag );
	DBG( _DBG_INFO, "Transferrate: %lu Bytes/s\n", dev->transferRate );

	/* adjust data origin
	 */
	dev->usbDev.Caps.Positive.DataOrigin.x -= dev->adj.tpa.x;
	dev->usbDev.Caps.Positive.DataOrigin.y -= dev->adj.tpa.y;

	dev->usbDev.Caps.Negative.DataOrigin.x -= dev->adj.neg.x;
	dev->usbDev.Caps.Negative.DataOrigin.y -= dev->adj.neg.y;

	dev->usbDev.Caps.Normal.DataOrigin.x -= dev->adj.pos.x;
	dev->usbDev.Caps.Normal.DataOrigin.y -= dev->adj.pos.y;

	/** adjust shading position
	 */
	if( dev->adj.posShadingY >= 0 )
		dev->usbDev.Caps.Normal.ShadingOriginY   = dev->adj.posShadingY;

	if( dev->adj.tpaShadingY >= 0 )
		dev->usbDev.Caps.Positive.ShadingOriginY = dev->adj.tpaShadingY;

	if( dev->adj.negShadingY >= 0 )
		dev->usbDev.Caps.Negative.ShadingOriginY = dev->adj.negShadingY;

	/* adjust the gamma settings... */
	if( dev->adj.rgamma == 1.0 )
		dev->adj.rgamma = dev->usbDev.HwSetting.gamma;
	if( dev->adj.ggamma == 1.0 )
		dev->adj.ggamma = dev->usbDev.HwSetting.gamma;
	if( dev->adj.bgamma == 1.0 )
		dev->adj.bgamma = dev->usbDev.HwSetting.gamma;
	if( dev->adj.graygamma == 1.0 )
		dev->adj.graygamma = dev->usbDev.HwSetting.gamma;

	/* the following you normally get from the registry...
	 */
	bMaxITA = 0;     /* Maximum integration time adjust */

	dev->usbDev.ModelStr = Settings[idx].pModelString;

	dev->fd = handle;

	if( dev->initialized < 0 ) {
		if( usb_HasTPA( dev ))
			dev->usbDev.Caps.wFlags |= DEVCAPSFLAG_TPA;
	}
	DBG( _DBG_INFO, "Device Flags: 0x%08x\n", dev->usbDev.Caps.wFlags );

	/* well now we patch the vendor string...
	 * if not found, the default vendor will be Plustek
	 */
	for( i = 0; usbVendors[i].desc != NULL; i++ ) {

		if( usbVendors[i].id == vendor ) {
			dev->sane.vendor = usbVendors[i].desc;
			if (dev->usbDev.Caps.workaroundFlag & _WAF_USE_ALT_DESC )
				if (usbVendors[i].desc_alt )
					dev->sane.vendor = usbVendors[i].desc_alt;
			DBG( _DBG_INFO, "Vendor adjusted to: >%s<\n", dev->sane.vendor );
			break;
		}
	}

	dev->usbDev.dwTicksLampOn = 0;
	dev->usbDev.currentLamp   = usb_GetLampStatus( dev );
	usb_ResetRegisters( dev );

	if( dev->initialized >= 0 )
		return;

	usb_IsScannerReady( dev );

	sParam.bBitDepth     = 8;
	sParam.bCalibration  = PARAM_Scan;
	sParam.bChannels     = 3;
	sParam.bDataType     = SCANDATATYPE_Color;
	sParam.bSource       = SOURCE_Reflection;
	sParam.Origin.x      = 0;
	sParam.Origin.y      = 0;
	sParam.UserDpi.x     = 150;
	sParam.UserDpi.y     = 150;
	sParam.dMCLK         = 4;
	sParam.Size.dwPixels = 0;

	/* create calibration-filename */
	sprintf( tmp_str2, "%s-%s",
	         dev->sane.vendor, dev->usbDev.ModelStr );

	if( !usb_normFileName( tmp_str2, tmp_str1, PATH_MAX )) {
		strcpy( tmp_str1, "plustek-default" );
	}

	ptr = getenv ("HOME");
	ret = ( NULL == ptr )?
		snprintf( tmp_str2, sizeof(tmp_str2), "/tmp/%s", tmp_str1 ):
		snprintf( tmp_str2, sizeof(tmp_str2), "%s/.sane/%s", ptr, tmp_str1 );

	if ((ret < 0) || (ret > (int)sizeof(tmp_str2))) {
		DBG( _DBG_WARNING,
		     "Failed to generate calibration file path. Default substituted.\n" );
		snprintf(tmp_str2, sizeof(tmp_str2), "/tmp/plustek-default");
	}

	dev->calFile = strdup( tmp_str2 );
	DBG( _DBG_INFO, "Calibration file-names set to:\n" );
	DBG( _DBG_INFO, ">%s-coarse.cal<\n", dev->calFile );
	DBG( _DBG_INFO, ">%s-fine.cal<\n", dev->calFile );

	/* initialize the ASIC registers */
	usb_SetScanParameters( dev, &sParam );

	/* check and move sensor to its home position */
	usb_ModuleToHome( dev, SANE_FALSE );

	/* set the global flag, that we are initialized so far */
	dev->initialized = idx;
}

/**
 * will be used for retrieving a Plustek device
 */
static int usb_CheckForPlustekDevice( int handle, Plustek_Device *dev )
{
	char   tmp[50];
	char   pcbStr[10];
	u_char reg59[3], reg59s[3], pcbID;
	int    i, result;

	/*
	 * Plustek uses the misc IO 12 to get the PCB ID
	 * (PCB = printed circuit board), so it's possible to have one
	 * product ID and up to 7 different devices...
	 */
	DBG( _DBG_INFO, "Trying to get the pcbID of a Plustek device...\n" );

	/* get the PCB-ID */
	result = sanei_lm983x_read( handle, 0x59, reg59s, 3, SANE_TRUE );
	if( SANE_STATUS_GOOD != result ) {
		sanei_usb_close( handle );
		return -1;
	}

	reg59[0] = 0x22;	/* PIO1: Input, PIO2: Input         */
	reg59[1] = 0x02;	/* PIO3: Input, PIO4: Output as low */
	reg59[2] = 0x03;

	result = sanei_lm983x_write( handle, 0x59,  reg59, 3, SANE_TRUE );
	if( SANE_STATUS_GOOD != result ) {
		sanei_usb_close( handle );
		return -1;
	}

	result = sanei_lm983x_read ( handle, 0x02, &pcbID, 1, SANE_TRUE );
	if( SANE_STATUS_GOOD != result ) {
		sanei_usb_close( handle );
		return -1;
	}

	pcbID = (u_char)((pcbID >> 2) & 0x07);

	result = sanei_lm983x_read( handle, 0x59, reg59s, 3, SANE_TRUE );
	if( SANE_STATUS_GOOD != result ) {
		sanei_usb_close( handle );
		return -1;
	}

	DBG( _DBG_INFO, "pcbID=0x%02x\n", pcbID );

	/* now roam through the setting list... */
	strncpy( tmp, dev->usbId, 13 );
	tmp[13] = '\0';

	sprintf( pcbStr, "-%u", pcbID );
	strcat ( tmp, pcbStr );

	DBG( _DBG_INFO, "Checking for device >%s<\n", tmp );

	for( i = 0; NULL != Settings[i].pIDString; i++ ) {

		if( 0 == strcmp( Settings[i].pIDString, tmp )) {
			DBG(_DBG_INFO, "Device description for >%s< found.\n", tmp );
			usb_initDev( dev, i, handle, dev->usbDev.vendor );
			return handle;
		}
	}

	return -1;
}

/**
 * will be called upon sane_exit
 */
static void usbDev_shutdown( Plustek_Device *dev  )
{
	SANE_Int handle;

	DBG( _DBG_INFO, "Shutdown called (dev->fd=%d, %s)\n",
	                dev->fd, dev->sane.name );
	if( NULL == dev->usbDev.ModelStr ) {
		DBG( _DBG_INFO, "Function ignored!\n" );
		return;
	}

	if( SANE_STATUS_GOOD == sanei_usb_open( dev->sane.name, &handle )) {

		dev->fd = handle;

		DBG( _DBG_INFO, "Waiting for scanner-ready...\n" );
		usb_IsScannerReady( dev );

		if( 0 != dev->usbDev.bLampOffOnEnd ) {

			DBG( _DBG_INFO, "Switching lamp off...\n" );
			usb_LampOn( dev, SANE_FALSE, SANE_FALSE );
		}
		dev->fd = -1;
		sanei_usb_close( handle );
	}
	usb_StopLampTimer( dev );
}

/**
 * This function checks wether a device, described by a given
 * string(vendor and product ID), is support by this backend or not
 *
 * @param usbIdStr - sting consisting out of product and vendor ID
 *                   format: "0xVVVVx0xPPPP" VVVV = Vendor ID, PPP = Product ID
 * @returns; SANE_TRUE if supported, SANE_FALSE if not
 */
static SANE_Bool usb_IsDeviceInList( char *usbIdStr )
{
	int i;

	for( i = 0; NULL != Settings[i].pIDString; i++ ) {

		if( 0 == strncmp( Settings[i].pIDString, usbIdStr, 13 ))
			return SANE_TRUE;
	}
	return SANE_FALSE;
}

/** get last valid entry of a list
 */
static DevList*
getLast( DevList *l )
{
	if( l == NULL )
		return NULL;

	while( l->next != NULL )
		l = l->next;
	return l;
}

/** add a new entry to our internal device list, when a device is detected
 */
static SANE_Status usb_attach( SANE_String_Const dev_name )
{
	int      len;
	DevList *tmp, *last;

	/* get some memory for the entry... */
	len = sizeof(DevList) + strlen(dev_name) + 1;
	tmp = (DevList*)malloc(len);

	/* initialize and set the values */
	memset(tmp, 0, len );

	/* the device name is part of our structure space */
	tmp->dev_name = &((char*)tmp)[sizeof(DevList)];
	strcpy( tmp->dev_name, dev_name );
	tmp->attached = SANE_FALSE;

	/* root set ? */
	if( usbDevs == NULL ) {
		usbDevs = tmp;
	} else {
		last = getLast(usbDevs); /* append... */
		last->next = tmp;
	}
	return SANE_STATUS_GOOD;
}

/**
 */
static void
usbGetList( DevList **devs )
{
	int        i;
	SANE_Bool  il;
	SANE_Word  v, p;
	DevList   *tmp;

	DBG( _DBG_INFO, "Retrieving all supported and conntected devices\n" );
	for( i = 0; NULL != Settings[i].pIDString; i++ ) {

		v = strtol( &(Settings[i].pIDString)[0], 0, 0 );
		p = strtol( &(Settings[i].pIDString)[7], 0, 0 );

		/* check if this vendor- and product-ID has already been added, needed
		 * for Plustek devices - here one product-ID is used for more than one
		 * device type...
		 */
		il = SANE_FALSE;
		for( tmp = *devs; tmp ; tmp = tmp->next ) {
			if( tmp->device_id == p && tmp->vendor_id == v ) {
				il = SANE_TRUE;
				break;
			}
		}
		if( il ) {
			DBG( _DBG_INFO2, "Already in list: 0x%04x-0x%04x\n", v, p );
			continue;
		}

		/* get the last entry... */
		tmp = getLast(*devs);
		DBG( _DBG_INFO2, "Checking for 0x%04x-0x%04x\n", v, p );
		sanei_usb_find_devices( v, p, usb_attach );

		if( getLast(*devs) != tmp ) {

			if( tmp == NULL )
				tmp = *devs;
			else
				tmp = tmp->next;

			while( tmp != NULL ) {
				tmp->vendor_id = v;
				tmp->device_id = p;
				tmp = tmp->next;
			}
		}
	}

	DBG( _DBG_INFO, "Available and supported devices:\n" );
	if( *devs == NULL )
		DBG( _DBG_INFO, "NONE.\n" );

	for( tmp = *devs; tmp; tmp = tmp->next ) {
		DBG( _DBG_INFO, "Device: >%s< - 0x%04xx0x%04x\n",
			tmp->dev_name, tmp->vendor_id, tmp->device_id );
	}
}

/**
 */
static int usbDev_open( Plustek_Device *dev, DevList *devs, int keep_lock )
{
	char        dn[512];
	char        devStr[50];
	int         result;
	int         i;
	int         lc;
	SANE_Int    handle;
	SANE_Byte   version;
	SANE_Word   vendor, product;
	SANE_Bool   was_empty;
	SANE_Status status;
	DevList    *tmp;

	DBG( _DBG_INFO, "usbDev_open(%s,%s) - %p\n",
	    dev->name, dev->usbId, (void*)devs );

	/* preset our internal usb device structure */
	memset( &dev->usbDev, 0, sizeof(DeviceDef));

	/* devs is NULL, when called from sane_start */
	if( devs ) {

		dn[0] = '\0';
		if( !strcmp( dev->name, "auto" )) {

			/* use the first "unattached"... */
			for( tmp = devs; tmp; tmp = tmp->next ) {
				if( !tmp->attached ) {
					tmp->attached = SANE_TRUE;
					strcpy( dn, tmp->dev_name );
					break;
				}
			}
		} else {

			vendor  = strtol( &dev->usbId[0], 0, 0 );
			product = strtol( &dev->usbId[7], 0, 0 );

			/* check the first match... */
			for( tmp = devs; tmp; tmp = tmp->next ) {
				if( tmp->vendor_id == vendor && tmp->device_id == product ) {
					if( !tmp->attached ) {
						tmp->attached = SANE_TRUE;
						strcpy( dn, tmp->dev_name );
						break;
					}
				}
			}
		}

		if( !dn[0] ) {
			DBG( _DBG_ERROR, "No supported device found!\n" );
			return -1;
		}

		status = sanei_access_lock( dn, 5 );
		if( SANE_STATUS_GOOD != status ) {
			DBG( _DBG_ERROR, "sanei_access_lock failed: %d\n", status );
			return -1;
		}

		status = sanei_usb_open( dn, &handle );
		if( SANE_STATUS_GOOD != status ) {
			DBG( _DBG_ERROR, "sanei_usb_open failed: %s (%d)\n",
			     strerror(errno), errno);
			sanei_access_unlock( dev->sane.name );
			return -1;
		}

		/* replace the old devname, so we are able to have multiple
		 * auto-detected devices
		 */
		free( dev->name );
		dev->name      = strdup(dn);
		dev->sane.name = dev->name;

	} else {

		status = sanei_access_lock( dev->sane.name, 5 );
		if( SANE_STATUS_GOOD != status ) {
			DBG( _DBG_ERROR, "sanei_access_lock failed: %d\n", status );
			return -1;
		}

		status = sanei_usb_open( dev->name, &handle );
		if( SANE_STATUS_GOOD != status ) {
			DBG( _DBG_ERROR, "sanei_usb_open failed: %s (%d)\n",
			     strerror(errno), errno);
			sanei_access_unlock( dev->sane.name );
			return -1;
		}
	}

	was_empty = SANE_FALSE;

	result = sanei_usb_get_vendor_product( handle, &vendor, &product );

	if( SANE_STATUS_GOOD == result ) {

		sprintf( devStr, "0x%04X-0x%04X", vendor, product );

		DBG(_DBG_INFO,"Vendor ID=0x%04X, Product ID=0x%04X\n",vendor,product);

		if( dev->usbId[0] != '\0' ) {

			if( 0 != strcmp( dev->usbId, devStr )) {
				DBG( _DBG_ERROR, "Specified Vendor and Product ID "
								 "doesn't match with the ones\n"
								 "in the config file\n" );
				sanei_access_unlock( dev->sane.name );
				sanei_usb_close( handle );
				return -1;
			}
		} else {
			sprintf( dev->usbId, "0x%04X-0x%04X", vendor, product );
			was_empty = SANE_TRUE;
		}

	} else {

		DBG( _DBG_INFO, "Can't get vendor & product ID from driver...\n" );

		/* if the ioctl stuff is not supported by the kernel and we have
		 * nothing specified, we have to give up...
		 */
		if( dev->usbId[0] == '\0' ) {
			DBG( _DBG_ERROR, "Cannot autodetect Vendor an Product ID, "
							 "please specify in config file.\n" );
			sanei_access_unlock( dev->sane.name );
			sanei_usb_close( handle );
	        return -1;
		}

		vendor  = strtol( &dev->usbId[0], 0, 0 );
		product = strtol( &dev->usbId[7], 0, 0 );
		DBG( _DBG_INFO, "... using the specified: "
		                "0x%04X-0x%04X\n", vendor, product );
	}

	/* before accessing the scanner, check if supported!
	 */
	if( !usb_IsDeviceInList( dev->usbId )) {
		DBG( _DBG_ERROR, "Device >%s<, is not supported!\n", dev->usbId );
		sanei_access_unlock( dev->sane.name );
		sanei_usb_close( handle );
		return -1;
	}

	status = usbio_DetectLM983x( handle, &version );
	if( SANE_STATUS_GOOD != status ) {
		sanei_usb_close( handle );
		sanei_access_unlock( dev->sane.name );
		return -1;
	}

	if ((version < 3) || (version > 4)) {
		DBG( _DBG_ERROR, "This is not a LM9831 or LM9832 chip based scanner.\n" );
		sanei_usb_close( handle );
		sanei_access_unlock( dev->sane.name );
		return -1;
	}

	/* need to set the handle and the detected chiptype... */
	dev->fd = handle;
	dev->usbDev.HwSetting.chip = (version==3 ? _LM9831:_LM9832);
	usbio_ResetLM983x( dev );
	dev->fd = -1;

	dev->usbDev.vendor  = vendor;
	dev->usbDev.product = product;

	DBG( _DBG_INFO, "Detected vendor & product ID: "
		                "0x%04X-0x%04X\n", vendor, product );

	/*
	 * Plustek uses the misc IO 1/2 to get the PCB ID
	 * (PCB = printed circuit board), so it's possible to have one
	 * product ID and up to 7 different devices...
	 */
	if( 0x07B3 == vendor ) {

		handle = usb_CheckForPlustekDevice( handle, dev );

		if( was_empty )
			dev->usbId[0] = '\0';

		if( handle >= 0 ) {
			if( !keep_lock )
				sanei_access_unlock( dev->sane.name );
			return handle;
		}

	} else {

		/* now roam through the setting list... */
		lc = 13;
		strncpy( devStr, dev->usbId, lc );
		devStr[lc] = '\0';

		if( 0x400 == vendor ) {
			if((dev->adj.mov < 0) || (dev->adj.mov > 1)) {
				DBG(_DBG_INFO, "BearPaw MOV out of range: %d\n", dev->adj.mov);
				dev->adj.mov = 0;
			}
			sprintf( devStr, "%s-%d", dev->usbId, dev->adj.mov );
			lc = strlen(devStr);
			DBG( _DBG_INFO, "BearPaw device: %s (%d)\n", devStr, lc );
		}

		if( was_empty )
			dev->usbId[0] = '\0';

		/* if we don't use the PCD ID extension...
		 */
		for( i = 0; NULL != Settings[i].pIDString; i++ ) {

			if( 0 == strncmp( Settings[i].pIDString, devStr, lc )) {
				DBG( _DBG_INFO, "Device description for >%s< found.\n", devStr );
				usb_initDev( dev, i, handle, vendor );
				if( !keep_lock )
					sanei_access_unlock( dev->sane.name );
			    return handle;
			}
		}
	}

	sanei_access_unlock( dev->sane.name );
	sanei_usb_close( handle );
	DBG( _DBG_ERROR, "No matching device found >%s<\n", devStr );
	return -1;
}

/**
 */
static int usbDev_close( Plustek_Device *dev )
{
	DBG( _DBG_INFO, "usbDev_close()\n" );
	sanei_usb_close( dev->fd );
	dev->fd = -1;
	return 0;
}

/** convert the stuff
 */
static int usbDev_getCaps( Plustek_Device *dev )
{
	DCapsDef *scaps = &dev->usbDev.Caps;

	DBG( _DBG_INFO, "usbDev_getCaps()\n" );

	dev->caps.dwFlag = 0;

	if(((DEVCAPSFLAG_Positive & scaps->wFlags)  &&
	    (DEVCAPSFLAG_Negative & scaps->wFlags)) ||
		(DEVCAPSFLAG_TPA      & scaps->wFlags)) {
		dev->caps.dwFlag |= SFLAG_TPA;
	}

	dev->caps.wMaxExtentX = scaps->Normal.Size.x;
	dev->caps.wMaxExtentY = scaps->Normal.Size.y;
	return 0;
}

/** usbDev_getCropInfo
 * function to set the image relevant stuff
 */
static int usbDev_getCropInfo( Plustek_Device *dev, CropInfo *ci )
{
	WinInfo size;

	DBG( _DBG_INFO, "usbDev_getCropInfo()\n" );

	usb_GetImageInfo( dev, &ci->ImgDef, &size );

	ci->dwPixelsPerLine = size.dwPixels;
	ci->dwLinesPerArea  = size.dwLines;
	ci->dwBytesPerLine  = size.dwBytes;

	if( ci->ImgDef.dwFlag & SCANFLAG_DWORDBoundary )
		ci->dwBytesPerLine = (ci->dwBytesPerLine + 3UL) & 0xfffffffcUL;

	DBG( _DBG_INFO, "PPL = %lu\n",  ci->dwPixelsPerLine );
	DBG( _DBG_INFO, "LPA = %lu\n",  ci->dwLinesPerArea );
	DBG( _DBG_INFO, "BPL = %lu\n",  ci->dwBytesPerLine );

	return 0;
}

/**
 */
static int usbDev_setMap( Plustek_Device *dev, SANE_Word *map,
                          SANE_Word length, SANE_Word channel )
{
	SANE_Word i, idx;

	DBG(_DBG_INFO,"Setting map[%u] at 0x%08lx\n",channel,(unsigned long)map);

	_VAR_NOT_USED( dev );

	if( channel == _MAP_MASTER ) {

		for( i = 0; i < length; i++ ) {
			a_bMap[i]            = (SANE_Byte)map[i];
			a_bMap[length +i]    = (SANE_Byte)map[i];
			a_bMap[(length*2)+i] = (SANE_Byte)map[i];
		}

	} else {

		idx = 0;
		if( channel == _MAP_GREEN )
			idx = 1;
		if( channel == _MAP_BLUE )
			idx = 2;

		for( i = 0; i < length; i++ ) {
			a_bMap[(length * idx)+i] = (SANE_Byte)map[i];
		}
	}

	return 0;
}

/**
 */
static int
usbDev_setScanEnv( Plustek_Device *dev, ScanInfo *si )
{
	ScanDef  *scan  = &dev->scanning;
	DCapsDef *caps = &dev->usbDev.Caps;

	DBG( _DBG_INFO, "usbDev_setScanEnv()\n" );

	/* clear all the stuff */
	memset( scan, 0, sizeof(ScanDef));

	if((si->ImgDef.dwFlag & SCANDEF_Adf) &&
	   (si->ImgDef.dwFlag & SCANDEF_ContinuousScan)) {
		scan->sParam.dMCLK = dMCLK_ADF;
	}

    /* Save necessary informations */
	scan->fGrayFromColor = 0;

	/* for some devices and settings, we tweak the physical settings
	 * how to get the image - but not in calibration mode
	 */
	if((si->ImgDef.dwFlag & SCANFLAG_Calibration) == 0) {

		if( si->ImgDef.wDataType == COLOR_256GRAY ) {

			if( !(si->ImgDef.dwFlag & SCANDEF_Adf) && !usb_IsCISDevice(dev) &&
			   (caps->OpticDpi.x == 1200 && si->ImgDef.xyDpi.x <= 300)) {
				scan->fGrayFromColor = 2;
				si->ImgDef.wDataType = COLOR_TRUE24;
				DBG( _DBG_INFO, "* Gray from color set!\n" );
			}

			if( caps->workaroundFlag & _WAF_GRAY_FROM_COLOR ) {
				DBG( _DBG_INFO, "* Gray(8-bit) from color set!\n" );
				scan->fGrayFromColor = 2;
				si->ImgDef.wDataType = COLOR_TRUE24;
			}

		} else if ( si->ImgDef.wDataType == COLOR_GRAY16 ) {
			if( caps->workaroundFlag & _WAF_GRAY_FROM_COLOR ) {
				DBG( _DBG_INFO, "* Gray(16-bit) from color set!\n" );
				scan->fGrayFromColor = 2;
				si->ImgDef.wDataType = COLOR_TRUE48;
			}

		} else if ( si->ImgDef.wDataType == COLOR_BW ) {
			if( caps->workaroundFlag & _WAF_BIN_FROM_COLOR ) {
				DBG( _DBG_INFO, "* Binary from color set!\n" );
				scan->fGrayFromColor = 10;
				si->ImgDef.wDataType = COLOR_TRUE24;
			}
		}
	}

	usb_SaveImageInfo( dev, &si->ImgDef );
	usb_GetImageInfo ( dev, &si->ImgDef, &scan->sParam.Size );

	/* mask the flags */
	scan->dwFlag = si->ImgDef.dwFlag &
	              (SCANFLAG_bgr | SCANFLAG_BottomUp | SCANFLAG_Calibration |
	               SCANFLAG_DWORDBoundary | SCANFLAG_RightAlign |
	               SCANFLAG_StillModule | SCANDEF_Adf | SCANDEF_ContinuousScan);

	if( !(SCANDEF_QualityScan & si->ImgDef.dwFlag)) {
		DBG( _DBG_INFO, "* Preview Mode set!\n" );
	} else {
		DBG( _DBG_INFO, "* Preview Mode NOT set!\n" );
		scan->dwFlag |= SCANDEF_QualityScan;
	}

	scan->sParam.brightness  = si->siBrightness;
	scan->sParam.contrast    = si->siContrast;

	if( scan->sParam.bBitDepth <= 8 )
		scan->dwFlag &= ~SCANFLAG_RightAlign;

	if( scan->dwFlag & SCANFLAG_DWORDBoundary ) {
		if( scan->fGrayFromColor && scan->fGrayFromColor < 10)
			scan->dwBytesLine = (scan->sParam.Size.dwBytes / 3 + 3) & 0xfffffffcUL;
		else
			scan->dwBytesLine = (scan->sParam.Size.dwBytes + 3UL) & 0xfffffffcUL;

	} else {

		if( scan->fGrayFromColor && scan->fGrayFromColor < 10)
			scan->dwBytesLine = scan->sParam.Size.dwBytes / 3;
		else
			scan->dwBytesLine = scan->sParam.Size.dwBytes;
	}

	/* on CIS based devices we have to reconfigure the illumination
	 * settings for the gray modes
	 */
	usb_AdjustCISLampSettings( dev, SANE_TRUE );

	if( scan->dwFlag & SCANFLAG_BottomUp)
		scan->lBufAdjust = -(long)scan->dwBytesLine;
	else
		scan->lBufAdjust = scan->dwBytesLine;

	/* LM9831 has a BUG in 16-bit mode,
	 * so we generate pseudo 16-bit data from 8-bit
	 */
	if( scan->sParam.bBitDepth > 8 ) {

		if( _LM9831 == dev->usbDev.HwSetting.chip ) {

			scan->sParam.bBitDepth = 8;
			scan->dwFlag |= SCANFLAG_Pseudo48;
			scan->sParam.Size.dwBytes >>= 1;
		}
	}

	/* Source selection */
	if( scan->sParam.bSource == SOURCE_Reflection ) {

		dev->usbDev.pSource = &caps->Normal;
		scan->sParam.Origin.x += dev->usbDev.pSource->DataOrigin.x +
		                                      (u_long)dev->usbDev.Normal.lLeft;
		scan->sParam.Origin.y += dev->usbDev.pSource->DataOrigin.y +
		                                        (u_long)dev->usbDev.Normal.lUp;

	} else if( scan->sParam.bSource == SOURCE_Transparency ) {

		dev->usbDev.pSource = &caps->Positive;
		scan->sParam.Origin.x += dev->usbDev.pSource->DataOrigin.x +
		                                    (u_long)dev->usbDev.Positive.lLeft;
		scan->sParam.Origin.y += dev->usbDev.pSource->DataOrigin.y +
		                                      (u_long)dev->usbDev.Positive.lUp;

	} else if( scan->sParam.bSource == SOURCE_Negative ) {

		dev->usbDev.pSource = &caps->Negative;
		scan->sParam.Origin.x += dev->usbDev.pSource->DataOrigin.x +
		                                    (u_long)dev->usbDev.Negative.lLeft;
		scan->sParam.Origin.y += dev->usbDev.pSource->DataOrigin.y +
		                                      (u_long)dev->usbDev.Negative.lUp;

	} else {

		dev->usbDev.pSource = &dev->usbDev.Caps.Adf;
		scan->sParam.Origin.x += dev->usbDev.pSource->DataOrigin.x +
		                                      (u_long)dev->usbDev.Normal.lLeft;
		scan->sParam.Origin.y += dev->usbDev.pSource->DataOrigin.y +
		                                        (u_long)dev->usbDev.Normal.lUp;
	}

	if( scan->sParam.bSource == SOURCE_ADF ) {

		if( scan->dwFlag & SCANDEF_ContinuousScan )
			dev->usbDev.fLastScanIsAdf = SANE_TRUE;
		else
			dev->usbDev.fLastScanIsAdf = SANE_FALSE;
	}

	return 0;
}

/**
 */
static int
usbDev_stopScan( Plustek_Device *dev )
{
	DBG( _DBG_INFO, "usbDev_stopScan()\n" );

	/* in cancel-mode we first stop the motor */
	usb_ScanEnd( dev );

	dev->scanning.dwFlag = 0;

	if( NULL != dev->scanning.pScanBuffer ) {

		free( dev->scanning.pScanBuffer );
		dev->scanning.pScanBuffer = NULL;
		usb_StartLampTimer( dev );
	}
	return 0;
}

/**
 */
static int
usbDev_startScan( Plustek_Device *dev )
{
	ScanDef *scan = &dev->scanning;
	DBG( _DBG_INFO, "usbDev_startScan()\n" );

/* HEINER: Preview currently not working correctly */
#if 0
	if( scan->dwFlag & SCANDEF_QualityScan )
		dev->usbDev.a_bRegs[0x0a] = 0;
	else
		dev->usbDev.a_bRegs[0x0a] = 1;
#endif
	dev->usbDev.a_bRegs[0x0a] = 0;

	if((scan->dwFlag & SCANDEF_Adf) && (scan->dwFlag & SCANDEF_ContinuousScan)) {
		scan->fCalibrated = SANE_TRUE;
	} else {
		scan->fCalibrated = SANE_FALSE;
	}

	scan->sParam.PhyDpi.x = usb_SetAsicDpiX(dev,scan->sParam.UserDpi.x);
	scan->sParam.PhyDpi.y = usb_SetAsicDpiY(dev,scan->sParam.UserDpi.y);

	/* Allocate shading/scan buffer */
	scan->pScanBuffer = (u_long*)malloc( _SCANBUF_SIZE );

	if( scan->pScanBuffer == NULL )
		return _E_ALLOC;

	scan->dwFlag |= SCANFLAG_StartScan;

	/* some devices (esp. BearPaw) do need a lamp switch off before
	 * switching it on again. Otherwise it might happen that the lamp
	 * remains off
	 */
	if(dev->usbDev.Caps.workaroundFlag & _WAF_LOFF_ON_START) {
		if (usb_GetLampStatus(dev))
			usb_LampOn( dev, SANE_FALSE, SANE_TRUE );
	}

	usb_LampOn( dev, SANE_TRUE, SANE_TRUE );

	m_fStart    = m_fFirst = SANE_TRUE;
	m_fAutoPark = (scan->dwFlag&SCANFLAG_StillModule)?SANE_FALSE:SANE_TRUE;

	if( usb_IsSheetFedDevice(dev))
		if(usb_InCalibrationMode(dev))
			m_fAutoPark = SANE_FALSE;

	usb_StopLampTimer( dev );
	return 0;
}

/**
 * do the reading stuff here...
 * first we perform the calibration step, and then we read the image
 * line for line
 */
static int
usbDev_Prepare( Plustek_Device *dev, SANE_Byte *buf )
{
	int       result;
	SANE_Bool use_alt_cal = SANE_FALSE;
	ScanDef  *scan        = &dev->scanning;
	DCapsDef *scaps       = &dev->usbDev.Caps;
	HWDef    *hw          = &dev->usbDev.HwSetting;

	DBG( _DBG_INFO, "usbDev_PrepareScan()\n" );

	/* check the current position of the sensor and move it back
	 * to it's home position if necessary...
	 */
	if( !usb_IsSheetFedDevice(dev))
		usb_SensorStatus( dev );

	/* CIS devices need special handling... */
	if( usb_IsCISDevice(dev)) {
		use_alt_cal = SANE_TRUE;

	} else {

		if( dev->adj.altCalibrate )
			use_alt_cal = SANE_TRUE;
	}

	/* for the skip functionality use the "old" calibration functions */
	if( dev->usbDev.Caps.workaroundFlag & _WAF_BYPASS_CALIBRATION ) {
		use_alt_cal = SANE_FALSE;
	}

	if( use_alt_cal ) {
		result = cano_DoCalibration( dev );
	} else {
		result = usb_DoCalibration( dev );
	}

	if( SANE_TRUE != result ) {
		DBG( _DBG_ERROR, "calibration failed!!!\n" );
		return _E_ABORT;
	}

	if( dev->adj.cacheCalData )
		usb_SaveCalData( dev );

	DBG( _DBG_INFO, "calibration done.\n" );
	if( usb_InCalibrationMode(dev))
		return 0;

	if( !(scan->dwFlag & SCANFLAG_Scanning)) {

		usleep( 10 * 1000 );

		/* need to preset that here, as we need it during parameter setting
		 */
		scan->bLinesToSkip = (u_char)(scan->sParam.PhyDpi.y / 50);

		scan->dwLinesDiscard = 0;
		if( scan->sParam.bChannels == 3 ) {
			scan->dwLinesDiscard = (u_long)scaps->bSensorDistance *
			                       scan->sParam.PhyDpi.y / scaps->OpticDpi.y;
			scan->dwLinesDiscard <<= 1;
		}

		if( !usb_SetScanParameters( dev, &scan->sParam )) {
			DBG( _DBG_ERROR, "Setting Scan Parameters failed!\n" );
			return 0;
		}

		/* if we bypass the calibration step, we wait on lamp warmup here...
		 */
		if( scaps->workaroundFlag & _WAF_BYPASS_CALIBRATION ) {
			if( !usb_Wait4Warmup( dev )) {
				DBG( _DBG_INFO, "usbDev_Prepare() - Cancel detected...\n" );
				return 0;
			}
		}

		scan->pbScanBufBegin = (u_char*)scan->pScanBuffer;

		if((dev->caps.dwFlag & SFLAG_ADF) && (scaps->OpticDpi.x == 600))
			scan->dwLinesScanBuf = 8;
		else
			scan->dwLinesScanBuf = 32;

		scan->dwBytesScanBuf     = scan->dwLinesScanBuf *
		                           scan->sParam.Size.dwPhyBytes;

		scan->dwNumberOfScanBufs = _SCANBUF_SIZE / scan->dwBytesScanBuf;
		scan->dwLinesPerScanBufs = scan->dwNumberOfScanBufs *
		                           scan->dwLinesScanBuf;
		scan->pbScanBufEnd       = scan->pbScanBufBegin +
		                           scan->dwLinesPerScanBufs *
		                           scan->sParam.Size.dwPhyBytes;
		scan->dwRedShift   = 0;
		scan->dwBlueShift  = 0;
		scan->dwGreenShift = 0;

		/* CCD scanner */
		if( scan->sParam.bChannels == 3 ) {

			scan->dwLinesDiscard = (u_long)scaps->bSensorDistance *
			                       scan->sParam.PhyDpi.y / scaps->OpticDpi.y;

			switch( scaps->bSensorOrder ) {

			case SENSORORDER_rgb:
				scan->Red.pb   = scan->pbScanBufBegin;
				scan->Green.pb = scan->pbScanBufBegin + scan->dwLinesDiscard *
				                 scan->sParam.Size.dwPhyBytes;
				scan->Blue.pb  = scan->pbScanBufBegin + scan->dwLinesDiscard *
				                 scan->sParam.Size.dwPhyBytes * 2UL;
				break;

			case SENSORORDER_rbg:
				scan->Red.pb   = scan->pbScanBufBegin;
				scan->Blue.pb  = scan->pbScanBufBegin + scan->dwLinesDiscard *
				                 scan->sParam.Size.dwPhyBytes;
				scan->Green.pb = scan->pbScanBufBegin + scan->dwLinesDiscard *
				                 scan->sParam.Size.dwPhyBytes * 2UL;
				break;

			case SENSORORDER_gbr:
				scan->Green.pb = scan->pbScanBufBegin;
				scan->Blue.pb  = scan->pbScanBufBegin + scan->dwLinesDiscard *
				                 scan->sParam.Size.dwPhyBytes;
				scan->Red.pb   = scan->pbScanBufBegin + scan->dwLinesDiscard *
				                 scan->sParam.Size.dwPhyBytes * 2UL;
				break;

			case SENSORORDER_grb:
				scan->Green.pb = scan->pbScanBufBegin;
				scan->Red.pb   = scan->pbScanBufBegin + scan->dwLinesDiscard *
				                 scan->sParam.Size.dwPhyBytes;
				scan->Blue.pb  = scan->pbScanBufBegin + scan->dwLinesDiscard *
                                 scan->sParam.Size.dwPhyBytes * 2UL;
				break;

			case SENSORORDER_brg:
				scan->Blue.pb  = scan->pbScanBufBegin;
				scan->Red.pb   = scan->pbScanBufBegin + scan->dwLinesDiscard *
				                 scan->sParam.Size.dwPhyBytes;
				scan->Green.pb = scan->pbScanBufBegin + scan->dwLinesDiscard *
				                 scan->sParam.Size.dwPhyBytes * 2UL;
				break;

			case SENSORORDER_bgr:
				scan->Blue.pb  = scan->pbScanBufBegin;
				scan->Green.pb = scan->pbScanBufBegin + scan->dwLinesDiscard *
				                 scan->sParam.Size.dwPhyBytes;
				scan->Red.pb   = scan->pbScanBufBegin + scan->dwLinesDiscard *
				                 scan->sParam.Size.dwPhyBytes * 2UL;
			}

			/* double it for last channel */
			scan->dwLinesDiscard <<= 1;
			scan->dwGreenShift = (7UL+scan->sParam.bBitDepth) >> 3;
			scan->Green.pb += scan->dwGreenShift;
			scan->Blue.pb  += (scan->dwGreenShift * 2);

			if( scan->dwFlag & SCANFLAG_bgr) {

				u_char *pb = scan->Blue.pb;

				scan->Blue.pb = scan->Red.pb;
				scan->Red.pb  = pb;
				scan->dwBlueShift = 0;
				scan->dwRedShift  = scan->dwGreenShift << 1;
			} else {
				scan->dwRedShift  = 0;
				scan->dwBlueShift = scan->dwGreenShift << 1;
			}

		} else {

			/* CIS section */

			/* this might be a simple gray operation or AFE 1 channel op */
			scan->dwLinesDiscard = 0;
			scan->Green.pb       = scan->pbScanBufBegin;

			if(( scan->sParam.bDataType == SCANDATATYPE_Color ) &&
			   ( hw->bReg_0x26 & _ONE_CH_COLOR )) {

				u_char so;
				u_long len = scan->sParam.Size.dwPhyBytes / 3;

				so = scaps->bSensorOrder;
				if (_WAF_RESET_SO_TO_RGB & scaps->workaroundFlag) {
					if (scaps->bPCB != 0) {
						if (scan->sParam.PhyDpi.x > scaps->bPCB) {
							so = SENSORORDER_rgb;
							DBG(_DBG_INFO, "* Resetting sensororder to RGB\n");
						}
					}
				}

				switch( so ) {

				case SENSORORDER_rgb:
					scan->Red.pb   = scan->pbScanBufBegin;
					scan->Green.pb = scan->pbScanBufBegin + len;
					scan->Blue.pb  = scan->pbScanBufBegin + len * 2UL;
					break;

				case SENSORORDER_gbr:
					scan->Green.pb = scan->pbScanBufBegin;
					scan->Blue.pb  = scan->pbScanBufBegin + len;
					scan->Red.pb   = scan->pbScanBufBegin + len * 2UL;
					break;
				default:
					DBG( _DBG_ERROR, "CIS: This bSensorOrder "
					                 "is not defined\n" );
					return _E_INTERNAL;
				}
			}
		}

		/* set a funtion to process the RAW data... */
		usb_GetImageProc( dev );

		if( scan->sParam.bSource == SOURCE_ADF )
			scan->dwFlag |= SCANFLAG_StillModule;

		DBG( _DBG_INFO, "* scan->dwFlag=0x%08lx\n", scan->dwFlag );

		if( !usb_ScanBegin( dev,
			(scan->dwFlag&SCANFLAG_StillModule) ? SANE_FALSE:SANE_TRUE)) {

			return _E_INTERNAL;
		}

		scan->dwFlag |= SCANFLAG_Scanning;

		if( scan->sParam.UserDpi.y != scan->sParam.PhyDpi.y ) {

			if( scan->sParam.UserDpi.y < scan->sParam.PhyDpi.y ) {

				scan->wSumY = scan->sParam.PhyDpi.y - scan->sParam.UserDpi.y;
				scan->dwFlag |= SCANFLAG_SampleY;
				DBG( _DBG_INFO, "SampleY Flag set (%u != %u, wSumY=%u)\n",
				  scan->sParam.UserDpi.y, scan->sParam.PhyDpi.y, scan->wSumY );
			}
		}
	}

	dumpPicInit( &scan->sParam, "plustek-pic.raw" );

	/* here the NT driver uses an extra reading thread...
	 * as the SANE stuff already forked the driver to read data, I think
	 * we should only read data by using a function...
	 */
	scan->dwLinesUser = scan->sParam.Size.dwLines;
	if( !scan->dwLinesUser )
		return _E_BUFFER_TOO_SMALL;

	if( scan->sParam.Size.dwLines < scan->dwLinesUser )
		scan->dwLinesUser = scan->sParam.Size.dwLines;

	scan->sParam.Size.dwLines -= scan->dwLinesUser;
	if( scan->dwFlag & SCANFLAG_BottomUp )
		scan->UserBuf.pb = buf + (scan->dwLinesUser - 1) * scan->dwBytesLine;
	else
		scan->UserBuf.pb = buf;

	DBG(_DBG_INFO,"Reading the data now!\n" );
	DBG(_DBG_INFO,"PhyDpi.x         = %u\n", scan->sParam.PhyDpi.x  );
	DBG(_DBG_INFO,"PhyDpi.y         = %u\n", scan->sParam.PhyDpi.y  );
	DBG(_DBG_INFO,"UserDpi.x        = %u\n", scan->sParam.UserDpi.x );
	DBG(_DBG_INFO,"UserDpi.y        = %u\n", scan->sParam.UserDpi.y );
	DBG(_DBG_INFO,"NumberOfScanBufs = %lu\n",scan->dwNumberOfScanBufs);
	DBG(_DBG_INFO,"LinesPerScanBufs = %lu\n",scan->dwLinesPerScanBufs);
	DBG(_DBG_INFO,"dwPhyBytes       = %lu\n",scan->sParam.Size.dwPhyBytes);
	DBG(_DBG_INFO,"dwPhyPixels      = %lu\n",scan->sParam.Size.dwPhyPixels);
	DBG(_DBG_INFO,"dwTotalBytes     = %lu\n",scan->sParam.Size.dwTotalBytes);
	DBG(_DBG_INFO,"dwPixels         = %lu\n",scan->sParam.Size.dwPixels);
	DBG(_DBG_INFO,"dwBytes          = %lu\n",scan->sParam.Size.dwBytes);
	DBG(_DBG_INFO,"dwValidPixels    = %lu\n",scan->sParam.Size.dwValidPixels);
	DBG(_DBG_INFO,"dwBytesScanBuf   = %lu\n",scan->dwBytesScanBuf );
	DBG(_DBG_INFO,"dwLinesDiscard   = %lu\n",scan->dwLinesDiscard );
	DBG(_DBG_INFO,"dwLinesToSkip    = %u\n", scan->bLinesToSkip );
	DBG(_DBG_INFO,"dwLinesUser      = %lu\n",scan->dwLinesUser  );
	DBG(_DBG_INFO,"dwBytesLine      = %lu\n",scan->dwBytesLine  );

	scan->pbGetDataBuf = scan->pbScanBufBegin;

	scan->dwLinesToProcess = usb_ReadData( dev  );
	if( 0 == scan->dwLinesToProcess )
		return _E_DATAREAD;

	return 0;
}

/** as the name says, read one line...
 */
static int
usbDev_ReadLine( Plustek_Device *dev )
{
	int      wrap;
	u_long   cur;
	ScanDef *scan = &dev->scanning;
	HWDef   *hw   = &dev->usbDev.HwSetting;

	cur = scan->dwLinesUser;

	/* we stay within this sample loop until one line has been processed for
	 * the user...
	 */
	while( cur == scan->dwLinesUser ) {

		if( usb_IsEscPressed()) {
			DBG( _DBG_INFO, "readLine() - Cancel detected...\n" );
			return _E_ABORT;
		}

		if( !(scan->dwFlag & SCANFLAG_SampleY))	{

			scan->pfnProcess( dev );

			/* Adjust user buffer pointer */
			scan->UserBuf.pb += scan->lBufAdjust;
			scan->dwLinesUser--;

		} else {

			scan->wSumY += scan->sParam.UserDpi.y;

			if( scan->wSumY >= scan->sParam.PhyDpi.y ) {
				scan->wSumY -= scan->sParam.PhyDpi.y;

				scan->pfnProcess( dev );

				/* Adjust user buffer pointer */
				scan->UserBuf.pb += scan->lBufAdjust;
				scan->dwLinesUser--;
			}
		}

		/* Adjust get buffer pointers */
		wrap = 0;

		if( scan->sParam.bDataType == SCANDATATYPE_Color ) {

			scan->Red.pb += scan->sParam.Size.dwPhyBytes;
			if( scan->Red.pb >= scan->pbScanBufEnd ) {
				scan->Red.pb = scan->pbScanBufBegin + scan->dwRedShift;
				wrap = 1;
			}

			scan->Green.pb += scan->sParam.Size.dwPhyBytes;
			if( scan->Green.pb >= scan->pbScanBufEnd ) {
				scan->Green.pb = scan->pbScanBufBegin + scan->dwGreenShift;
				wrap = 1;
			}

			scan->Blue.pb += scan->sParam.Size.dwPhyBytes;
			if( scan->Blue.pb >= scan->pbScanBufEnd ) {
				scan->Blue.pb = scan->pbScanBufBegin + scan->dwBlueShift;
				wrap = 1;
			}
		} else {
			scan->Green.pb += scan->sParam.Size.dwPhyBytes;
			if( scan->Green.pb >= scan->pbScanBufEnd )
				scan->Green.pb = scan->pbScanBufBegin + scan->dwGreenShift;
		}

		/* on any wrap-around of the get pointers in one channel mode
		 * we have to reset them
		 */
		if( wrap ) {

			u_long len = scan->sParam.Size.dwPhyBytes;

			if( hw->bReg_0x26 & _ONE_CH_COLOR ) {

				if(scan->sParam.bDataType == SCANDATATYPE_Color) {
					len /= 3;
				}
				scan->Red.pb   = scan->pbScanBufBegin;
				scan->Green.pb = scan->pbScanBufBegin + len;
				scan->Blue.pb  = scan->pbScanBufBegin + len * 2UL;
			}
		}

		/* line processed, check if we have to get more...
		 */
		scan->dwLinesToProcess--;

		if( 0 == scan->dwLinesToProcess ) {

			scan->dwLinesToProcess = usb_ReadData( dev );
			if( 0 == scan->dwLinesToProcess ) {

				if( usb_IsEscPressed())
					return _E_ABORT;
			}
		}
	}
	return 0;
}

/* END PLUSTEK-USB.C ........................................................*/